id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_good_5845_14 | /*
* iovec manipulation routines.
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Fixes:
* Andrew Lunn : Errors in iovec copying.
* Pedro Roque : Added memcpy_fromiovecend and
* csum_..._fromiovecend.
* Andi Kleen : fixed error handling for 2.1
* Alexey Kuznetsov: 2.1 optimisations
* Andi Kleen : Fix csum*fromiovecend for IPv6.
*/
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/net.h>
#include <linux/in6.h>
#include <asm/uaccess.h>
#include <asm/byteorder.h>
#include <net/checksum.h>
#include <net/sock.h>
/*
* Verify iovec. The caller must ensure that the iovec is big enough
* to hold the message iovec.
*
* Save time not doing access_ok. copy_*_user will make this work
* in any case.
*/
int verify_iovec(struct msghdr *m, struct iovec *iov, struct sockaddr_storage *address, int mode)
{
int size, ct, err;
if (m->msg_namelen) {
if (mode == VERIFY_READ) {
void __user *namep;
namep = (void __user __force *) m->msg_name;
err = move_addr_to_kernel(namep, m->msg_namelen,
address);
if (err < 0)
return err;
}
if (m->msg_name)
m->msg_name = address;
} else {
m->msg_name = NULL;
}
size = m->msg_iovlen * sizeof(struct iovec);
if (copy_from_user(iov, (void __user __force *) m->msg_iov, size))
return -EFAULT;
m->msg_iov = iov;
err = 0;
for (ct = 0; ct < m->msg_iovlen; ct++) {
size_t len = iov[ct].iov_len;
if (len > INT_MAX - err) {
len = INT_MAX - err;
iov[ct].iov_len = len;
}
err += len;
}
return err;
}
/*
* Copy kernel to iovec. Returns -EFAULT on error.
*/
int memcpy_toiovecend(const struct iovec *iov, unsigned char *kdata,
int offset, int len)
{
int copy;
for (; len > 0; ++iov) {
/* Skip over the finished iovecs */
if (unlikely(offset >= iov->iov_len)) {
offset -= iov->iov_len;
continue;
}
copy = min_t(unsigned int, iov->iov_len - offset, len);
if (copy_to_user(iov->iov_base + offset, kdata, copy))
return -EFAULT;
offset = 0;
kdata += copy;
len -= copy;
}
return 0;
}
EXPORT_SYMBOL(memcpy_toiovecend);
/*
* Copy iovec to kernel. Returns -EFAULT on error.
*/
int memcpy_fromiovecend(unsigned char *kdata, const struct iovec *iov,
int offset, int len)
{
/* Skip over the finished iovecs */
while (offset >= iov->iov_len) {
offset -= iov->iov_len;
iov++;
}
while (len > 0) {
u8 __user *base = iov->iov_base + offset;
int copy = min_t(unsigned int, len, iov->iov_len - offset);
offset = 0;
if (copy_from_user(kdata, base, copy))
return -EFAULT;
len -= copy;
kdata += copy;
iov++;
}
return 0;
}
EXPORT_SYMBOL(memcpy_fromiovecend);
/*
* And now for the all-in-one: copy and checksum from a user iovec
* directly to a datagram
* Calls to csum_partial but the last must be in 32 bit chunks
*
* ip_build_xmit must ensure that when fragmenting only the last
* call to this function will be unaligned also.
*/
int csum_partial_copy_fromiovecend(unsigned char *kdata, struct iovec *iov,
int offset, unsigned int len, __wsum *csump)
{
__wsum csum = *csump;
int partial_cnt = 0, err = 0;
/* Skip over the finished iovecs */
while (offset >= iov->iov_len) {
offset -= iov->iov_len;
iov++;
}
while (len > 0) {
u8 __user *base = iov->iov_base + offset;
int copy = min_t(unsigned int, len, iov->iov_len - offset);
offset = 0;
/* There is a remnant from previous iov. */
if (partial_cnt) {
int par_len = 4 - partial_cnt;
/* iov component is too short ... */
if (par_len > copy) {
if (copy_from_user(kdata, base, copy))
goto out_fault;
kdata += copy;
base += copy;
partial_cnt += copy;
len -= copy;
iov++;
if (len)
continue;
*csump = csum_partial(kdata - partial_cnt,
partial_cnt, csum);
goto out;
}
if (copy_from_user(kdata, base, par_len))
goto out_fault;
csum = csum_partial(kdata - partial_cnt, 4, csum);
kdata += par_len;
base += par_len;
copy -= par_len;
len -= par_len;
partial_cnt = 0;
}
if (len > copy) {
partial_cnt = copy % 4;
if (partial_cnt) {
copy -= partial_cnt;
if (copy_from_user(kdata + copy, base + copy,
partial_cnt))
goto out_fault;
}
}
if (copy) {
csum = csum_and_copy_from_user(base, kdata, copy,
csum, &err);
if (err)
goto out;
}
len -= copy + partial_cnt;
kdata += copy + partial_cnt;
iov++;
}
*csump = csum;
out:
return err;
out_fault:
err = -EFAULT;
goto out;
}
EXPORT_SYMBOL(csum_partial_copy_fromiovecend);
unsigned long iov_pages(const struct iovec *iov, int offset,
unsigned long nr_segs)
{
unsigned long seg, base;
int pages = 0, len, size;
while (nr_segs && (offset >= iov->iov_len)) {
offset -= iov->iov_len;
++iov;
--nr_segs;
}
for (seg = 0; seg < nr_segs; seg++) {
base = (unsigned long)iov[seg].iov_base + offset;
len = iov[seg].iov_len - offset;
size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT;
pages += size;
offset = 0;
}
return pages;
}
EXPORT_SYMBOL(iov_pages);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_14 |
crossvul-cpp_data_good_1562_0 | #include <gio/gio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include "libabrt.h"
#include "abrt-polkit.h"
#include "abrt_glib.h"
#include <libreport/dump_dir.h>
#include "problem_api.h"
static GMainLoop *loop;
static guint g_timeout_source;
/* default, settable with -t: */
static unsigned g_timeout_value = 120;
/* ---------------------------------------------------------------------------------------------------- */
static GDBusNodeInfo *introspection_data = NULL;
/* Introspection data for the service we are exporting */
static const gchar introspection_xml[] =
"<node>"
" <interface name='"ABRT_DBUS_IFACE"'>"
" <method name='NewProblem'>"
" <arg type='a{ss}' name='problem_data' direction='in'/>"
" <arg type='s' name='problem_id' direction='out'/>"
" </method>"
" <method name='GetProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetAllProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetForeignProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetInfo'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='as' name='element_names' direction='in'/>"
" <arg type='a{ss}' name='response' direction='out'/>"
" </method>"
" <method name='SetElement'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" <arg type='s' name='value' direction='in'/>"
" </method>"
" <method name='DeleteElement'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" </method>"
" <method name='ChownProblemDir'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" </method>"
" <method name='DeleteProblem'>"
" <arg type='as' name='problem_dir' direction='in'/>"
" </method>"
" <method name='FindProblemByElementInTimeRange'>"
" <arg type='s' name='element' direction='in'/>"
" <arg type='s' name='value' direction='in'/>"
" <arg type='x' name='timestamp_from' direction='in'/>"
" <arg type='x' name='timestamp_to' direction='in'/>"
" <arg type='b' name='all_users' direction='in'/>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='Quit' />"
" </interface>"
"</node>";
/* ---------------------------------------------------------------------------------------------------- */
/* forward */
static gboolean on_timeout_cb(gpointer user_data);
static void reset_timeout(void)
{
if (g_timeout_source > 0)
{
log_info("Removing timeout");
g_source_remove(g_timeout_source);
}
log_info("Setting a new timeout");
g_timeout_source = g_timeout_add_seconds(g_timeout_value, on_timeout_cb, NULL);
}
static uid_t get_caller_uid(GDBusConnection *connection, GDBusMethodInvocation *invocation, const char *caller)
{
GError *error = NULL;
guint caller_uid;
GDBusProxy * proxy = g_dbus_proxy_new_sync(connection,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
NULL,
&error);
GVariant *result = g_dbus_proxy_call_sync(proxy,
"GetConnectionUnixUser",
g_variant_new ("(s)", caller),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
if (result == NULL)
{
/* we failed to get the uid, so return (uid_t) -1 to indicate the error
*/
if (error)
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidUser",
error->message);
g_error_free(error);
}
else
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidUser",
_("Unknown error"));
}
return (uid_t) -1;
}
g_variant_get(result, "(u)", &caller_uid);
g_variant_unref(result);
log_info("Caller uid: %i", caller_uid);
return caller_uid;
}
bool allowed_problem_dir(const char *dir_name)
{
if (!dir_is_in_dump_location(dir_name))
{
error_msg("Bad problem directory name '%s', should start with: '%s'", dir_name, g_settings_dump_location);
return false;
}
/* We cannot test correct permissions yet because we still need to chown
* dump directories before reporting and Chowing changes the file owner to
* the reporter, which causes this test to fail and prevents users from
* getting problem data after reporting it.
*
* Fortunately, libreport has been hardened against hard link and symbolic
* link attacks and refuses to work with such files, so this test isn't
* really necessary, however, we will use it once we get rid of the
* chowning files.
*
* abrt-server refuses to run post-create on directories that have
* incorrect owner (not "root:(abrt|root)"), incorrect permissions (other
* bits are not 0) and are complete (post-create finished). So, there is no
* way to run security sensitive event scripts (post-create) on crafted
* problem directories.
*/
#if 0
if (!dir_has_correct_permissions(dir_name))
{
error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dir_name);
return false;
}
#endif
return true;
}
static char *handle_new_problem(GVariant *problem_info, uid_t caller_uid, char **error)
{
problem_data_t *pd = problem_data_new();
GVariantIter *iter;
g_variant_get(problem_info, "a{ss}", &iter);
gchar *key, *value;
while (g_variant_iter_loop(iter, "{ss}", &key, &value))
{
problem_data_add_text_editable(pd, key, value);
}
if (caller_uid != 0 || problem_data_get_content_or_NULL(pd, FILENAME_UID) == NULL)
{ /* set uid field to caller's uid if caller is not root or root doesn't pass own uid */
log_info("Adding UID %d to problem data", caller_uid);
char buf[sizeof(uid_t) * 3 + 2];
snprintf(buf, sizeof(buf), "%d", caller_uid);
problem_data_add_text_noteditable(pd, FILENAME_UID, buf);
}
/* At least it should generate local problem identifier UUID */
problem_data_add_basics(pd);
char *problem_id = problem_data_save(pd);
if (problem_id)
notify_new_path(problem_id);
else if (error)
*error = xasprintf("Cannot create a new problem");
problem_data_free(pd);
return problem_id;
}
static void return_InvalidProblemDir_error(GDBusMethodInvocation *invocation, const char *dir_name)
{
char *msg = xasprintf(_("'%s' is not a valid problem directory"), dir_name);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidProblemDir",
msg);
free(msg);
}
/*
* Checks element's rights and does not open directory if element is protected.
* Checks problem's rights and does not open directory if user hasn't got
* access to a problem.
*
* Returns a dump directory opend for writing or NULL.
*
* If any operation from the above listed fails, immediately returns D-Bus
* error to a D-Bus caller.
*/
static struct dump_dir *open_directory_for_modification_of_element(
GDBusMethodInvocation *invocation,
uid_t caller_uid,
const char *problem_id,
const char *element)
{
static const char *const protected_elements[] = {
FILENAME_TIME,
FILENAME_UID,
NULL,
};
for (const char *const *protected = protected_elements; *protected; ++protected)
{
if (strcmp(*protected, element) == 0)
{
log_notice("'%s' element of '%s' can't be modified", element, problem_id);
char *error = xasprintf(_("'%s' element can't be modified"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ProtectedElement",
error);
free(error);
return NULL;
}
}
if (!dump_dir_accessible_by_uid(problem_id, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("'%s' is not a valid problem directory", problem_id);
return_InvalidProblemDir_error(invocation, problem_id);
}
else
{
log_notice("UID(%d) is not Authorized to access '%s'", caller_uid, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
}
return NULL;
}
struct dump_dir *dd = dd_opendir(problem_id, /* flags : */ 0);
if (!dd)
{ /* This should not happen because of the access check above */
log_notice("Can't access the problem '%s' for modification", problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("Can't access the problem for modification"));
return NULL;
}
return dd;
}
/*
* Lists problems which have given element and were seen in given time interval
*/
struct field_and_time_range {
GList *list;
const char *element;
const char *value;
unsigned long timestamp_from;
unsigned long timestamp_to;
};
static int add_dirname_to_GList_if_matches(struct dump_dir *dd, void *arg)
{
struct field_and_time_range *me = arg;
char *field_data = dd_load_text(dd, me->element);
int brk = (strcmp(field_data, me->value) != 0);
free(field_data);
if (brk)
return 0;
field_data = dd_load_text(dd, FILENAME_LAST_OCCURRENCE);
long val = atol(field_data);
free(field_data);
if (val < me->timestamp_from || val > me->timestamp_to)
return 0;
me->list = g_list_prepend(me->list, xstrdup(dd->dd_dirname));
return 0;
}
static GList *get_problem_dirs_for_element_in_time(uid_t uid,
const char *element,
const char *value,
unsigned long timestamp_from,
unsigned long timestamp_to)
{
if (timestamp_to == 0) /* not sure this is possible, but... */
timestamp_to = time(NULL);
struct field_and_time_range me = {
.list = NULL,
.element = element,
.value = value,
.timestamp_from = timestamp_from,
.timestamp_to = timestamp_to,
};
for_each_problem_in_dir(g_settings_dump_location, uid, add_dirname_to_GList_if_matches, &me);
return g_list_reverse(me.list);
}
static void handle_method_call(GDBusConnection *connection,
const gchar *caller,
const gchar *object_path,
const gchar *interface_name,
const gchar *method_name,
GVariant *parameters,
GDBusMethodInvocation *invocation,
gpointer user_data)
{
reset_timeout();
uid_t caller_uid;
GVariant *response;
caller_uid = get_caller_uid(connection, invocation, caller);
log_notice("caller_uid:%ld method:'%s'", (long)caller_uid, method_name);
if (caller_uid == (uid_t) -1)
return;
if (g_strcmp0(method_name, "NewProblem") == 0)
{
char *error = NULL;
char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error);
if (!problem_id)
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
free(error);
return;
}
/* else */
response = g_variant_new("(s)", problem_id);
g_dbus_method_invocation_return_value(invocation, response);
free(problem_id);
return;
}
if (g_strcmp0(method_name, "GetProblems") == 0)
{
GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
//I was told that g_dbus_method frees the response
//g_variant_unref(response);
return;
}
if (g_strcmp0(method_name, "GetAllProblems") == 0)
{
/*
- so, we have UID,
- if it's 0, then we don't have to check anything and just return all directories
- if uid != 0 then we want to ask for authorization
*/
if (caller_uid != 0)
{
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes)
caller_uid = 0;
}
GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "GetForeignProblems") == 0)
{
GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "ChownProblemDir") == 0)
{
const gchar *problem_dir;
g_variant_get(parameters, "(&s)", &problem_dir);
log_notice("problem_dir:'%s'", problem_dir);
if (!allowed_problem_dir(problem_dir))
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int ddstat = dump_dir_stat_for_uid(problem_dir, caller_uid);
if (ddstat < 0)
{
if (errno == ENOTDIR)
{
log_notice("requested directory does not exist '%s'", problem_dir);
}
else
{
perror_msg("can't get stat of '%s'", problem_dir);
}
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
if (ddstat & DD_STAT_OWNED_BY_UID)
{ //caller seems to be in group with access to this dir, so no action needed
log_notice("caller has access to the requested directory %s", problem_dir);
g_dbus_method_invocation_return_value(invocation, NULL);
return;
}
if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 &&
polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{
log_notice("not authorized");
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
return;
}
struct dump_dir *dd = dd_opendir(problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);
if (!dd)
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int chown_res = dd_chown(dd, caller_uid);
if (chown_res != 0)
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ChownError",
_("Chowning directory failed. Check system logs for more details."));
else
g_dbus_method_invocation_return_value(invocation, NULL);
dd_close(dd);
return;
}
if (g_strcmp0(method_name, "GetInfo") == 0)
{
/* Parameter tuple is (sas) */
/* Get 1st param - problem dir name */
const gchar *problem_dir;
g_variant_get_child(parameters, 0, "&s", &problem_dir);
log_notice("problem_dir:'%s'", problem_dir);
if (!allowed_problem_dir(problem_dir))
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
if (!dump_dir_accessible_by_uid(problem_dir, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("Requested directory does not exist '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{
log_notice("not authorized");
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
return;
}
}
struct dump_dir *dd = dd_opendir(problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);
if (!dd)
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
/* Get 2nd param - vector of element names */
GVariant *array = g_variant_get_child_value(parameters, 1);
GList *elements = string_list_from_variant(array);
g_variant_unref(array);
GVariantBuilder *builder = NULL;
for (GList *l = elements; l; l = l->next)
{
const char *element_name = (const char*)l->data;
char *value = dd_load_text_ext(dd, element_name, 0
| DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE
| DD_FAIL_QUIETLY_ENOENT
| DD_FAIL_QUIETLY_EACCES);
log_notice("element '%s' %s", element_name, value ? "fetched" : "not found");
if (value)
{
if (!builder)
builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
/* g_variant_builder_add makes a copy. No need to xstrdup here */
g_variant_builder_add(builder, "{ss}", element_name, value);
free(value);
}
}
list_free_with_free(elements);
dd_close(dd);
/* It is OK to call g_variant_new("(a{ss})", NULL) because */
/* G_VARIANT_TYPE_TUPLE allows NULL value */
GVariant *response = g_variant_new("(a{ss})", builder);
if (builder)
g_variant_builder_unref(builder);
log_info("GetInfo: returning value for '%s'", problem_dir);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "SetElement") == 0)
{
const char *problem_id;
const char *element;
const char *value;
g_variant_get(parameters, "(&s&s&s)", &problem_id, &element, &value);
if (element == NULL || element[0] == '\0' || strlen(element) > 64)
{
log_notice("'%s' is not a valid element name of '%s'", element, problem_id);
char *error = xasprintf(_("'%s' is not a valid element name"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidElement",
error);
free(error);
return;
}
struct dump_dir *dd = open_directory_for_modification_of_element(
invocation, caller_uid, problem_id, element);
if (!dd)
/* Already logged from open_directory_for_modification_of_element() */
return;
/* Is it good idea to make it static? Is it possible to change the max size while a single run? */
const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024);
const long item_size = dd_get_item_size(dd, element);
if (item_size < 0)
{
log_notice("Can't get size of '%s/%s'", problem_id, element);
char *error = xasprintf(_("Can't get size of '%s'"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
return;
}
const double requested_size = (double)strlen(value) - item_size;
/* Don't want to check the size limit in case of reducing of size */
if (requested_size > 0
&& requested_size > (max_dir_size - get_dirsize(g_settings_dump_location)))
{
log_notice("No problem space left in '%s' (requested Bytes %f)", problem_id, requested_size);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("No problem space left"));
}
else
{
dd_save_text(dd, element, value);
g_dbus_method_invocation_return_value(invocation, NULL);
}
dd_close(dd);
return;
}
if (g_strcmp0(method_name, "DeleteElement") == 0)
{
const char *problem_id;
const char *element;
g_variant_get(parameters, "(&s&s)", &problem_id, &element);
struct dump_dir *dd = open_directory_for_modification_of_element(
invocation, caller_uid, problem_id, element);
if (!dd)
/* Already logged from open_directory_for_modification_of_element() */
return;
const int res = dd_delete_item(dd, element);
dd_close(dd);
if (res != 0)
{
log_notice("Can't delete the element '%s' from the problem directory '%s'", element, problem_id);
char *error = xasprintf(_("Can't delete the element '%s' from the problem directory '%s'"), element, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
free(error);
return;
}
g_dbus_method_invocation_return_value(invocation, NULL);
return;
}
if (g_strcmp0(method_name, "DeleteProblem") == 0)
{
/* Dbus parameters are always tuples.
* In this case, it's (as) - a tuple of one element (array of strings).
* Need to fetch the array:
*/
GVariant *array = g_variant_get_child_value(parameters, 0);
GList *problem_dirs = string_list_from_variant(array);
g_variant_unref(array);
for (GList *l = problem_dirs; l; l = l->next)
{
const char *dir_name = (const char*)l->data;
log_notice("dir_name:'%s'", dir_name);
if (!allowed_problem_dir(dir_name))
{
return_InvalidProblemDir_error(invocation, dir_name);
goto ret;
}
}
for (GList *l = problem_dirs; l; l = l->next)
{
const char *dir_name = (const char*)l->data;
if (!dump_dir_accessible_by_uid(dir_name, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("Requested directory does not exist '%s'", dir_name);
continue;
}
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{ // if user didn't provide correct credentials, just move to the next dir
continue;
}
}
delete_dump_dir(dir_name);
}
g_dbus_method_invocation_return_value(invocation, NULL);
ret:
list_free_with_free(problem_dirs);
return;
}
if (g_strcmp0(method_name, "FindProblemByElementInTimeRange") == 0)
{
const gchar *element;
const gchar *value;
glong timestamp_from;
glong timestamp_to;
gboolean all;
g_variant_get_child(parameters, 0, "&s", &element);
g_variant_get_child(parameters, 1, "&s", &value);
g_variant_get_child(parameters, 2, "x", ×tamp_from);
g_variant_get_child(parameters, 3, "x", ×tamp_to);
g_variant_get_child(parameters, 4, "b", &all);
if (all && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes)
caller_uid = 0;
GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from,
timestamp_to);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "Quit") == 0)
{
g_dbus_method_invocation_return_value(invocation, NULL);
g_main_loop_quit(loop);
return;
}
}
static gboolean on_timeout_cb(gpointer user_data)
{
g_main_loop_quit(loop);
return TRUE;
}
static const GDBusInterfaceVTable interface_vtable =
{
.method_call = handle_method_call,
.get_property = NULL,
.set_property = NULL,
};
static void on_bus_acquired(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
guint registration_id;
registration_id = g_dbus_connection_register_object(connection,
ABRT_DBUS_OBJECT,
introspection_data->interfaces[0],
&interface_vtable,
NULL, /* user_data */
NULL, /* user_data_free_func */
NULL); /* GError** */
g_assert(registration_id > 0);
reset_timeout();
}
/* not used
static void on_name_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
}
*/
static void on_name_lost(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
g_print(_("The name '%s' has been lost, please check if other "
"service owning the name is not running.\n"), name);
exit(1);
}
int main(int argc, char *argv[])
{
/* I18n */
setlocale(LC_ALL, "");
#if ENABLE_NLS
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
#endif
guint owner_id;
abrt_init(argv);
const char *program_usage_string = _(
"& [options]"
);
enum {
OPT_v = 1 << 0,
OPT_t = 1 << 1,
};
/* Keep enum above and order of options below in sync! */
struct options program_options[] = {
OPT__VERBOSE(&g_verbose),
OPT_INTEGER('t', NULL, &g_timeout_value, _("Exit after NUM seconds of inactivity")),
OPT_END()
};
/*unsigned opts =*/ parse_opts(argc, argv, program_options, program_usage_string);
export_abrt_envvars(0);
/* When dbus daemon starts us, it doesn't set PATH
* (I saw it set only DBUS_STARTER_ADDRESS and DBUS_STARTER_BUS_TYPE).
* In this case, set something sane:
*/
const char *env_path = getenv("PATH");
if (!env_path || !env_path[0])
putenv((char*)"PATH=/usr/sbin:/usr/bin:/sbin:/bin");
msg_prefix = "abrt-dbus"; /* for log(), error_msg() and such */
if (getuid() != 0)
error_msg_and_die(_("This program must be run as root."));
glib_init();
/* We are lazy here - we don't want to manually provide
* the introspection data structures - so we just build
* them from XML.
*/
introspection_data = g_dbus_node_info_new_for_xml(introspection_xml, NULL);
g_assert(introspection_data != NULL);
owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
ABRT_DBUS_NAME,
G_BUS_NAME_OWNER_FLAGS_NONE,
on_bus_acquired,
NULL,
on_name_lost,
NULL,
NULL);
/* initialize the g_settings_dump_location */
load_abrt_conf();
loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(loop);
log_notice("Cleaning up");
g_bus_unown_name(owner_id);
g_dbus_node_info_unref(introspection_data);
free_abrt_conf_data();
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_1562_0 |
crossvul-cpp_data_bad_405_0 | /*
* Copyright (C) 2012,2013 - ARM Ltd
* Author: Marc Zyngier <marc.zyngier@arm.com>
*
* Derived from arch/arm/kvm/guest.c:
* Copyright (C) 2012 - Virtual Open Systems and Columbia University
* Author: Christoffer Dall <c.dall@virtualopensystems.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/kvm_host.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/fs.h>
#include <kvm/arm_psci.h>
#include <asm/cputype.h>
#include <linux/uaccess.h>
#include <asm/kvm.h>
#include <asm/kvm_emulate.h>
#include <asm/kvm_coproc.h>
#include "trace.h"
#define VM_STAT(x) { #x, offsetof(struct kvm, stat.x), KVM_STAT_VM }
#define VCPU_STAT(x) { #x, offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU }
struct kvm_stats_debugfs_item debugfs_entries[] = {
VCPU_STAT(hvc_exit_stat),
VCPU_STAT(wfe_exit_stat),
VCPU_STAT(wfi_exit_stat),
VCPU_STAT(mmio_exit_user),
VCPU_STAT(mmio_exit_kernel),
VCPU_STAT(exits),
{ NULL }
};
int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
{
return 0;
}
static u64 core_reg_offset_from_id(u64 id)
{
return id & ~(KVM_REG_ARCH_MASK | KVM_REG_SIZE_MASK | KVM_REG_ARM_CORE);
}
static int validate_core_offset(const struct kvm_one_reg *reg)
{
u64 off = core_reg_offset_from_id(reg->id);
int size;
switch (off) {
case KVM_REG_ARM_CORE_REG(regs.regs[0]) ...
KVM_REG_ARM_CORE_REG(regs.regs[30]):
case KVM_REG_ARM_CORE_REG(regs.sp):
case KVM_REG_ARM_CORE_REG(regs.pc):
case KVM_REG_ARM_CORE_REG(regs.pstate):
case KVM_REG_ARM_CORE_REG(sp_el1):
case KVM_REG_ARM_CORE_REG(elr_el1):
case KVM_REG_ARM_CORE_REG(spsr[0]) ...
KVM_REG_ARM_CORE_REG(spsr[KVM_NR_SPSR - 1]):
size = sizeof(__u64);
break;
case KVM_REG_ARM_CORE_REG(fp_regs.vregs[0]) ...
KVM_REG_ARM_CORE_REG(fp_regs.vregs[31]):
size = sizeof(__uint128_t);
break;
case KVM_REG_ARM_CORE_REG(fp_regs.fpsr):
case KVM_REG_ARM_CORE_REG(fp_regs.fpcr):
size = sizeof(__u32);
break;
default:
return -EINVAL;
}
if (KVM_REG_SIZE(reg->id) == size &&
IS_ALIGNED(off, size / sizeof(__u32)))
return 0;
return -EINVAL;
}
static int get_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
/*
* Because the kvm_regs structure is a mix of 32, 64 and
* 128bit fields, we index it as if it was a 32bit
* array. Hence below, nr_regs is the number of entries, and
* off the index in the "array".
*/
__u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr;
struct kvm_regs *regs = vcpu_gp_regs(vcpu);
int nr_regs = sizeof(*regs) / sizeof(__u32);
u32 off;
/* Our ID is an index into the kvm_regs struct. */
off = core_reg_offset_from_id(reg->id);
if (off >= nr_regs ||
(off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs)
return -ENOENT;
if (validate_core_offset(reg))
return -EINVAL;
if (copy_to_user(uaddr, ((u32 *)regs) + off, KVM_REG_SIZE(reg->id)))
return -EFAULT;
return 0;
}
static int set_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
__u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr;
struct kvm_regs *regs = vcpu_gp_regs(vcpu);
int nr_regs = sizeof(*regs) / sizeof(__u32);
__uint128_t tmp;
void *valp = &tmp;
u64 off;
int err = 0;
/* Our ID is an index into the kvm_regs struct. */
off = core_reg_offset_from_id(reg->id);
if (off >= nr_regs ||
(off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs)
return -ENOENT;
if (validate_core_offset(reg))
return -EINVAL;
if (KVM_REG_SIZE(reg->id) > sizeof(tmp))
return -EINVAL;
if (copy_from_user(valp, uaddr, KVM_REG_SIZE(reg->id))) {
err = -EFAULT;
goto out;
}
if (off == KVM_REG_ARM_CORE_REG(regs.pstate)) {
u32 mode = (*(u32 *)valp) & PSR_AA32_MODE_MASK;
switch (mode) {
case PSR_AA32_MODE_USR:
case PSR_AA32_MODE_FIQ:
case PSR_AA32_MODE_IRQ:
case PSR_AA32_MODE_SVC:
case PSR_AA32_MODE_ABT:
case PSR_AA32_MODE_UND:
case PSR_MODE_EL0t:
case PSR_MODE_EL1t:
case PSR_MODE_EL1h:
break;
default:
err = -EINVAL;
goto out;
}
}
memcpy((u32 *)regs + off, valp, KVM_REG_SIZE(reg->id));
out:
return err;
}
int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
{
return -EINVAL;
}
int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
{
return -EINVAL;
}
static unsigned long num_core_regs(void)
{
return sizeof(struct kvm_regs) / sizeof(__u32);
}
/**
* ARM64 versions of the TIMER registers, always available on arm64
*/
#define NUM_TIMER_REGS 3
static bool is_timer_reg(u64 index)
{
switch (index) {
case KVM_REG_ARM_TIMER_CTL:
case KVM_REG_ARM_TIMER_CNT:
case KVM_REG_ARM_TIMER_CVAL:
return true;
}
return false;
}
static int copy_timer_indices(struct kvm_vcpu *vcpu, u64 __user *uindices)
{
if (put_user(KVM_REG_ARM_TIMER_CTL, uindices))
return -EFAULT;
uindices++;
if (put_user(KVM_REG_ARM_TIMER_CNT, uindices))
return -EFAULT;
uindices++;
if (put_user(KVM_REG_ARM_TIMER_CVAL, uindices))
return -EFAULT;
return 0;
}
static int set_timer_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
void __user *uaddr = (void __user *)(long)reg->addr;
u64 val;
int ret;
ret = copy_from_user(&val, uaddr, KVM_REG_SIZE(reg->id));
if (ret != 0)
return -EFAULT;
return kvm_arm_timer_set_reg(vcpu, reg->id, val);
}
static int get_timer_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
void __user *uaddr = (void __user *)(long)reg->addr;
u64 val;
val = kvm_arm_timer_get_reg(vcpu, reg->id);
return copy_to_user(uaddr, &val, KVM_REG_SIZE(reg->id)) ? -EFAULT : 0;
}
/**
* kvm_arm_num_regs - how many registers do we present via KVM_GET_ONE_REG
*
* This is for all registers.
*/
unsigned long kvm_arm_num_regs(struct kvm_vcpu *vcpu)
{
return num_core_regs() + kvm_arm_num_sys_reg_descs(vcpu)
+ kvm_arm_get_fw_num_regs(vcpu) + NUM_TIMER_REGS;
}
/**
* kvm_arm_copy_reg_indices - get indices of all registers.
*
* We do core registers right here, then we append system regs.
*/
int kvm_arm_copy_reg_indices(struct kvm_vcpu *vcpu, u64 __user *uindices)
{
unsigned int i;
const u64 core_reg = KVM_REG_ARM64 | KVM_REG_SIZE_U64 | KVM_REG_ARM_CORE;
int ret;
for (i = 0; i < sizeof(struct kvm_regs) / sizeof(__u32); i++) {
if (put_user(core_reg | i, uindices))
return -EFAULT;
uindices++;
}
ret = kvm_arm_copy_fw_reg_indices(vcpu, uindices);
if (ret)
return ret;
uindices += kvm_arm_get_fw_num_regs(vcpu);
ret = copy_timer_indices(vcpu, uindices);
if (ret)
return ret;
uindices += NUM_TIMER_REGS;
return kvm_arm_copy_sys_reg_indices(vcpu, uindices);
}
int kvm_arm_get_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
/* We currently use nothing arch-specific in upper 32 bits */
if ((reg->id & ~KVM_REG_SIZE_MASK) >> 32 != KVM_REG_ARM64 >> 32)
return -EINVAL;
/* Register group 16 means we want a core register. */
if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_CORE)
return get_core_reg(vcpu, reg);
if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_FW)
return kvm_arm_get_fw_reg(vcpu, reg);
if (is_timer_reg(reg->id))
return get_timer_reg(vcpu, reg);
return kvm_arm_sys_reg_get_reg(vcpu, reg);
}
int kvm_arm_set_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
/* We currently use nothing arch-specific in upper 32 bits */
if ((reg->id & ~KVM_REG_SIZE_MASK) >> 32 != KVM_REG_ARM64 >> 32)
return -EINVAL;
/* Register group 16 means we set a core register. */
if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_CORE)
return set_core_reg(vcpu, reg);
if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_FW)
return kvm_arm_set_fw_reg(vcpu, reg);
if (is_timer_reg(reg->id))
return set_timer_reg(vcpu, reg);
return kvm_arm_sys_reg_set_reg(vcpu, reg);
}
int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
struct kvm_sregs *sregs)
{
return -EINVAL;
}
int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
struct kvm_sregs *sregs)
{
return -EINVAL;
}
int __kvm_arm_vcpu_get_events(struct kvm_vcpu *vcpu,
struct kvm_vcpu_events *events)
{
events->exception.serror_pending = !!(vcpu->arch.hcr_el2 & HCR_VSE);
events->exception.serror_has_esr = cpus_have_const_cap(ARM64_HAS_RAS_EXTN);
if (events->exception.serror_pending && events->exception.serror_has_esr)
events->exception.serror_esr = vcpu_get_vsesr(vcpu);
return 0;
}
int __kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu,
struct kvm_vcpu_events *events)
{
bool serror_pending = events->exception.serror_pending;
bool has_esr = events->exception.serror_has_esr;
if (serror_pending && has_esr) {
if (!cpus_have_const_cap(ARM64_HAS_RAS_EXTN))
return -EINVAL;
if (!((events->exception.serror_esr) & ~ESR_ELx_ISS_MASK))
kvm_set_sei_esr(vcpu, events->exception.serror_esr);
else
return -EINVAL;
} else if (serror_pending) {
kvm_inject_vabt(vcpu);
}
return 0;
}
int __attribute_const__ kvm_target_cpu(void)
{
unsigned long implementor = read_cpuid_implementor();
unsigned long part_number = read_cpuid_part_number();
switch (implementor) {
case ARM_CPU_IMP_ARM:
switch (part_number) {
case ARM_CPU_PART_AEM_V8:
return KVM_ARM_TARGET_AEM_V8;
case ARM_CPU_PART_FOUNDATION:
return KVM_ARM_TARGET_FOUNDATION_V8;
case ARM_CPU_PART_CORTEX_A53:
return KVM_ARM_TARGET_CORTEX_A53;
case ARM_CPU_PART_CORTEX_A57:
return KVM_ARM_TARGET_CORTEX_A57;
};
break;
case ARM_CPU_IMP_APM:
switch (part_number) {
case APM_CPU_PART_POTENZA:
return KVM_ARM_TARGET_XGENE_POTENZA;
};
break;
};
/* Return a default generic target */
return KVM_ARM_TARGET_GENERIC_V8;
}
int kvm_vcpu_preferred_target(struct kvm_vcpu_init *init)
{
int target = kvm_target_cpu();
if (target < 0)
return -ENODEV;
memset(init, 0, sizeof(*init));
/*
* For now, we don't return any features.
* In future, we might use features to return target
* specific features available for the preferred
* target type.
*/
init->target = (__u32)target;
return 0;
}
int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
{
return -EINVAL;
}
int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
{
return -EINVAL;
}
int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
struct kvm_translation *tr)
{
return -EINVAL;
}
#define KVM_GUESTDBG_VALID_MASK (KVM_GUESTDBG_ENABLE | \
KVM_GUESTDBG_USE_SW_BP | \
KVM_GUESTDBG_USE_HW | \
KVM_GUESTDBG_SINGLESTEP)
/**
* kvm_arch_vcpu_ioctl_set_guest_debug - set up guest debugging
* @kvm: pointer to the KVM struct
* @kvm_guest_debug: the ioctl data buffer
*
* This sets up and enables the VM for guest debugging. Userspace
* passes in a control flag to enable different debug types and
* potentially other architecture specific information in the rest of
* the structure.
*/
int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
struct kvm_guest_debug *dbg)
{
int ret = 0;
trace_kvm_set_guest_debug(vcpu, dbg->control);
if (dbg->control & ~KVM_GUESTDBG_VALID_MASK) {
ret = -EINVAL;
goto out;
}
if (dbg->control & KVM_GUESTDBG_ENABLE) {
vcpu->guest_debug = dbg->control;
/* Hardware assisted Break and Watch points */
if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW) {
vcpu->arch.external_debug_state = dbg->arch;
}
} else {
/* If not enabled clear all flags */
vcpu->guest_debug = 0;
}
out:
return ret;
}
int kvm_arm_vcpu_arch_set_attr(struct kvm_vcpu *vcpu,
struct kvm_device_attr *attr)
{
int ret;
switch (attr->group) {
case KVM_ARM_VCPU_PMU_V3_CTRL:
ret = kvm_arm_pmu_v3_set_attr(vcpu, attr);
break;
case KVM_ARM_VCPU_TIMER_CTRL:
ret = kvm_arm_timer_set_attr(vcpu, attr);
break;
default:
ret = -ENXIO;
break;
}
return ret;
}
int kvm_arm_vcpu_arch_get_attr(struct kvm_vcpu *vcpu,
struct kvm_device_attr *attr)
{
int ret;
switch (attr->group) {
case KVM_ARM_VCPU_PMU_V3_CTRL:
ret = kvm_arm_pmu_v3_get_attr(vcpu, attr);
break;
case KVM_ARM_VCPU_TIMER_CTRL:
ret = kvm_arm_timer_get_attr(vcpu, attr);
break;
default:
ret = -ENXIO;
break;
}
return ret;
}
int kvm_arm_vcpu_arch_has_attr(struct kvm_vcpu *vcpu,
struct kvm_device_attr *attr)
{
int ret;
switch (attr->group) {
case KVM_ARM_VCPU_PMU_V3_CTRL:
ret = kvm_arm_pmu_v3_has_attr(vcpu, attr);
break;
case KVM_ARM_VCPU_TIMER_CTRL:
ret = kvm_arm_timer_has_attr(vcpu, attr);
break;
default:
ret = -ENXIO;
break;
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_405_0 |
crossvul-cpp_data_bad_3988_1 | #include "clar_libgit2.h"
#include "path.h"
static char *gitmodules_altnames[] = {
".gitmodules",
/*
* Equivalent to the ".git\u200cmodules" string from git but hard-coded
* as a UTF-8 sequence
*/
".git\xe2\x80\x8cmodules",
".Gitmodules",
".gitmoduleS",
".gitmodules ",
".gitmodules.",
".gitmodules ",
".gitmodules. ",
".gitmodules .",
".gitmodules..",
".gitmodules ",
".gitmodules. ",
".gitmodules . ",
".gitmodules .",
".Gitmodules ",
".Gitmodules.",
".Gitmodules ",
".Gitmodules. ",
".Gitmodules .",
".Gitmodules..",
".Gitmodules ",
".Gitmodules. ",
".Gitmodules . ",
".Gitmodules .",
"GITMOD~1",
"gitmod~1",
"GITMOD~2",
"gitmod~3",
"GITMOD~4",
"GITMOD~1 ",
"gitmod~2.",
"GITMOD~3 ",
"gitmod~4. ",
"GITMOD~1 .",
"gitmod~2 ",
"GITMOD~3. ",
"gitmod~4 . ",
"GI7EBA~1",
"gi7eba~9",
"GI7EB~10",
"GI7EB~11",
"GI7EB~99",
"GI7EB~10",
"GI7E~100",
"GI7E~101",
"GI7E~999",
"~1000000",
"~9999999",
};
static char *gitmodules_not_altnames[] = {
".gitmodules x",
".gitmodules .x",
" .gitmodules",
"..gitmodules",
"gitmodules",
".gitmodule",
".gitmodules x ",
".gitmodules .x",
"GI7EBA~",
"GI7EBA~0",
"GI7EBA~~1",
"GI7EBA~X",
"Gx7EBA~1",
"GI7EBX~1",
"GI7EB~1",
"GI7EB~01",
"GI7EB~1",
};
void test_path_dotgit__dotgit_modules(void)
{
size_t i;
cl_assert_equal_i(1, git_path_is_gitfile(".gitmodules", strlen(".gitmodules"), GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_GENERIC));
cl_assert_equal_i(1, git_path_is_gitfile(".git\xe2\x80\x8cmodules", strlen(".git\xe2\x80\x8cmodules"), GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_GENERIC));
for (i = 0; i < ARRAY_SIZE(gitmodules_altnames); i++) {
const char *name = gitmodules_altnames[i];
if (!git_path_is_gitfile(name, strlen(name), GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_GENERIC))
cl_fail(name);
}
for (i = 0; i < ARRAY_SIZE(gitmodules_not_altnames); i++) {
const char *name = gitmodules_not_altnames[i];
if (git_path_is_gitfile(name, strlen(name), GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_GENERIC))
cl_fail(name);
}
}
void test_path_dotgit__dotgit_modules_symlink(void)
{
cl_assert_equal_b(true, git_path_isvalid(NULL, ".gitmodules", 0, GIT_PATH_REJECT_DOT_GIT_HFS|GIT_PATH_REJECT_DOT_GIT_NTFS));
cl_assert_equal_b(false, git_path_isvalid(NULL, ".gitmodules", S_IFLNK, GIT_PATH_REJECT_DOT_GIT_HFS));
cl_assert_equal_b(false, git_path_isvalid(NULL, ".gitmodules", S_IFLNK, GIT_PATH_REJECT_DOT_GIT_NTFS));
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3988_1 |
crossvul-cpp_data_bad_5819_0 | /*
* Flash Screen Video decoder
* Copyright (C) 2004 Alex Beregszaszi
* Copyright (C) 2006 Benjamin Larsson
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Flash Screen Video decoder
* @author Alex Beregszaszi
* @author Benjamin Larsson
* @author Daniel Verkamp
* @author Konstantin Shishkov
*
* A description of the bitstream format for Flash Screen Video version 1/2
* is part of the SWF File Format Specification (version 10), which can be
* downloaded from http://www.adobe.com/devnet/swf.html.
*/
#include <stdio.h>
#include <stdlib.h>
#include <zlib.h>
#include "libavutil/intreadwrite.h"
#include "avcodec.h"
#include "bytestream.h"
#include "get_bits.h"
#include "internal.h"
typedef struct BlockInfo {
uint8_t *pos;
int size;
} BlockInfo;
typedef struct FlashSVContext {
AVCodecContext *avctx;
AVFrame frame;
int image_width, image_height;
int block_width, block_height;
uint8_t *tmpblock;
int block_size;
z_stream zstream;
int ver;
const uint32_t *pal;
int is_keyframe;
uint8_t *keyframedata;
uint8_t *keyframe;
BlockInfo *blocks;
uint8_t *deflate_block;
int deflate_block_size;
int color_depth;
int zlibprime_curr, zlibprime_prev;
int diff_start, diff_height;
} FlashSVContext;
static int decode_hybrid(const uint8_t *sptr, uint8_t *dptr, int dx, int dy,
int h, int w, int stride, const uint32_t *pal)
{
int x, y;
const uint8_t *orig_src = sptr;
for (y = dx+h; y > dx; y--) {
uint8_t *dst = dptr + (y * stride) + dy * 3;
for (x = 0; x < w; x++) {
if (*sptr & 0x80) {
/* 15-bit color */
unsigned c = AV_RB16(sptr) & ~0x8000;
unsigned b = c & 0x1F;
unsigned g = (c >> 5) & 0x1F;
unsigned r = c >> 10;
/* 000aaabb -> aaabbaaa */
*dst++ = (b << 3) | (b >> 2);
*dst++ = (g << 3) | (g >> 2);
*dst++ = (r << 3) | (r >> 2);
sptr += 2;
} else {
/* palette index */
uint32_t c = pal[*sptr++];
bytestream_put_le24(&dst, c);
}
}
}
return sptr - orig_src;
}
static av_cold int flashsv_decode_init(AVCodecContext *avctx)
{
FlashSVContext *s = avctx->priv_data;
int zret; // Zlib return code
s->avctx = avctx;
s->zstream.zalloc = Z_NULL;
s->zstream.zfree = Z_NULL;
s->zstream.opaque = Z_NULL;
zret = inflateInit(&s->zstream);
if (zret != Z_OK) {
av_log(avctx, AV_LOG_ERROR, "Inflate init error: %d\n", zret);
return 1;
}
avctx->pix_fmt = AV_PIX_FMT_BGR24;
avcodec_get_frame_defaults(&s->frame);
return 0;
}
static int flashsv2_prime(FlashSVContext *s, uint8_t *src, int size)
{
z_stream zs;
int zret; // Zlib return code
if (!src)
return AVERROR_INVALIDDATA;
zs.zalloc = NULL;
zs.zfree = NULL;
zs.opaque = NULL;
s->zstream.next_in = src;
s->zstream.avail_in = size;
s->zstream.next_out = s->tmpblock;
s->zstream.avail_out = s->block_size * 3;
inflate(&s->zstream, Z_SYNC_FLUSH);
if (deflateInit(&zs, 0) != Z_OK)
return -1;
zs.next_in = s->tmpblock;
zs.avail_in = s->block_size * 3 - s->zstream.avail_out;
zs.next_out = s->deflate_block;
zs.avail_out = s->deflate_block_size;
deflate(&zs, Z_SYNC_FLUSH);
deflateEnd(&zs);
if ((zret = inflateReset(&s->zstream)) != Z_OK) {
av_log(s->avctx, AV_LOG_ERROR, "Inflate reset error: %d\n", zret);
return AVERROR_UNKNOWN;
}
s->zstream.next_in = s->deflate_block;
s->zstream.avail_in = s->deflate_block_size - zs.avail_out;
s->zstream.next_out = s->tmpblock;
s->zstream.avail_out = s->block_size * 3;
inflate(&s->zstream, Z_SYNC_FLUSH);
return 0;
}
static int flashsv_decode_block(AVCodecContext *avctx, AVPacket *avpkt,
GetBitContext *gb, int block_size,
int width, int height, int x_pos, int y_pos,
int blk_idx)
{
struct FlashSVContext *s = avctx->priv_data;
uint8_t *line = s->tmpblock;
int k;
int ret = inflateReset(&s->zstream);
if (ret != Z_OK) {
av_log(avctx, AV_LOG_ERROR, "Inflate reset error: %d\n", ret);
return AVERROR_UNKNOWN;
}
if (s->zlibprime_curr || s->zlibprime_prev) {
ret = flashsv2_prime(s,
s->blocks[blk_idx].pos,
s->blocks[blk_idx].size);
if (ret < 0)
return ret;
}
s->zstream.next_in = avpkt->data + get_bits_count(gb) / 8;
s->zstream.avail_in = block_size;
s->zstream.next_out = s->tmpblock;
s->zstream.avail_out = s->block_size * 3;
ret = inflate(&s->zstream, Z_FINISH);
if (ret == Z_DATA_ERROR) {
av_log(avctx, AV_LOG_ERROR, "Zlib resync occurred\n");
inflateSync(&s->zstream);
ret = inflate(&s->zstream, Z_FINISH);
}
if (ret != Z_OK && ret != Z_STREAM_END) {
//return -1;
}
if (s->is_keyframe) {
s->blocks[blk_idx].pos = s->keyframedata + (get_bits_count(gb) / 8);
s->blocks[blk_idx].size = block_size;
}
if (!s->color_depth) {
/* Flash Screen Video stores the image upside down, so copy
* lines to destination in reverse order. */
for (k = 1; k <= s->diff_height; k++) {
memcpy(s->frame.data[0] + x_pos * 3 +
(s->image_height - y_pos - s->diff_start - k) * s->frame.linesize[0],
line, width * 3);
/* advance source pointer to next line */
line += width * 3;
}
} else {
/* hybrid 15-bit/palette mode */
decode_hybrid(s->tmpblock, s->frame.data[0],
s->image_height - (y_pos + 1 + s->diff_start + s->diff_height),
x_pos, s->diff_height, width,
s->frame.linesize[0], s->pal);
}
skip_bits_long(gb, 8 * block_size); /* skip the consumed bits */
return 0;
}
static int calc_deflate_block_size(int tmpblock_size)
{
z_stream zstream;
int size;
zstream.zalloc = Z_NULL;
zstream.zfree = Z_NULL;
zstream.opaque = Z_NULL;
if (deflateInit(&zstream, 0) != Z_OK)
return -1;
size = deflateBound(&zstream, tmpblock_size);
deflateEnd(&zstream);
return size;
}
static int flashsv_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame, AVPacket *avpkt)
{
int buf_size = avpkt->size;
FlashSVContext *s = avctx->priv_data;
int h_blocks, v_blocks, h_part, v_part, i, j, ret;
GetBitContext gb;
int last_blockwidth = s->block_width;
int last_blockheight= s->block_height;
/* no supplementary picture */
if (buf_size == 0)
return 0;
if (buf_size < 4)
return -1;
init_get_bits(&gb, avpkt->data, buf_size * 8);
/* start to parse the bitstream */
s->block_width = 16 * (get_bits(&gb, 4) + 1);
s->image_width = get_bits(&gb, 12);
s->block_height = 16 * (get_bits(&gb, 4) + 1);
s->image_height = get_bits(&gb, 12);
if ( last_blockwidth != s->block_width
|| last_blockheight!= s->block_height)
av_freep(&s->blocks);
if (s->ver == 2) {
skip_bits(&gb, 6);
if (get_bits1(&gb)) {
avpriv_request_sample(avctx, "iframe");
return AVERROR_PATCHWELCOME;
}
if (get_bits1(&gb)) {
avpriv_request_sample(avctx, "Custom palette");
return AVERROR_PATCHWELCOME;
}
}
/* calculate number of blocks and size of border (partial) blocks */
h_blocks = s->image_width / s->block_width;
h_part = s->image_width % s->block_width;
v_blocks = s->image_height / s->block_height;
v_part = s->image_height % s->block_height;
/* the block size could change between frames, make sure the buffer
* is large enough, if not, get a larger one */
if (s->block_size < s->block_width * s->block_height) {
int tmpblock_size = 3 * s->block_width * s->block_height;
s->tmpblock = av_realloc(s->tmpblock, tmpblock_size);
if (!s->tmpblock) {
av_log(avctx, AV_LOG_ERROR, "Can't allocate decompression buffer.\n");
return AVERROR(ENOMEM);
}
if (s->ver == 2) {
s->deflate_block_size = calc_deflate_block_size(tmpblock_size);
if (s->deflate_block_size <= 0) {
av_log(avctx, AV_LOG_ERROR, "Can't determine deflate buffer size.\n");
return -1;
}
s->deflate_block = av_realloc(s->deflate_block, s->deflate_block_size);
if (!s->deflate_block) {
av_log(avctx, AV_LOG_ERROR, "Can't allocate deflate buffer.\n");
return AVERROR(ENOMEM);
}
}
}
s->block_size = s->block_width * s->block_height;
/* initialize the image size once */
if (avctx->width == 0 && avctx->height == 0) {
avcodec_set_dimensions(avctx, s->image_width, s->image_height);
}
/* check for changes of image width and image height */
if (avctx->width != s->image_width || avctx->height != s->image_height) {
av_log(avctx, AV_LOG_ERROR,
"Frame width or height differs from first frame!\n");
av_log(avctx, AV_LOG_ERROR, "fh = %d, fv %d vs ch = %d, cv = %d\n",
avctx->height, avctx->width, s->image_height, s->image_width);
return AVERROR_INVALIDDATA;
}
/* we care for keyframes only in Screen Video v2 */
s->is_keyframe = (avpkt->flags & AV_PKT_FLAG_KEY) && (s->ver == 2);
if (s->is_keyframe) {
s->keyframedata = av_realloc(s->keyframedata, avpkt->size);
memcpy(s->keyframedata, avpkt->data, avpkt->size);
}
if(s->ver == 2 && !s->blocks)
s->blocks = av_mallocz((v_blocks + !!v_part) * (h_blocks + !!h_part)
* sizeof(s->blocks[0]));
av_dlog(avctx, "image: %dx%d block: %dx%d num: %dx%d part: %dx%d\n",
s->image_width, s->image_height, s->block_width, s->block_height,
h_blocks, v_blocks, h_part, v_part);
if ((ret = ff_reget_buffer(avctx, &s->frame)) < 0)
return ret;
/* loop over all block columns */
for (j = 0; j < v_blocks + (v_part ? 1 : 0); j++) {
int y_pos = j * s->block_height; // vertical position in frame
int cur_blk_height = (j < v_blocks) ? s->block_height : v_part;
/* loop over all block rows */
for (i = 0; i < h_blocks + (h_part ? 1 : 0); i++) {
int x_pos = i * s->block_width; // horizontal position in frame
int cur_blk_width = (i < h_blocks) ? s->block_width : h_part;
int has_diff = 0;
/* get the size of the compressed zlib chunk */
int size = get_bits(&gb, 16);
s->color_depth = 0;
s->zlibprime_curr = 0;
s->zlibprime_prev = 0;
s->diff_start = 0;
s->diff_height = cur_blk_height;
if (8 * size > get_bits_left(&gb)) {
av_frame_unref(&s->frame);
return AVERROR_INVALIDDATA;
}
if (s->ver == 2 && size) {
skip_bits(&gb, 3);
s->color_depth = get_bits(&gb, 2);
has_diff = get_bits1(&gb);
s->zlibprime_curr = get_bits1(&gb);
s->zlibprime_prev = get_bits1(&gb);
if (s->color_depth != 0 && s->color_depth != 2) {
av_log(avctx, AV_LOG_ERROR,
"%dx%d invalid color depth %d\n", i, j, s->color_depth);
return AVERROR_INVALIDDATA;
}
if (has_diff) {
if (!s->keyframe) {
av_log(avctx, AV_LOG_ERROR,
"inter frame without keyframe\n");
return AVERROR_INVALIDDATA;
}
s->diff_start = get_bits(&gb, 8);
s->diff_height = get_bits(&gb, 8);
av_log(avctx, AV_LOG_DEBUG,
"%dx%d diff start %d height %d\n",
i, j, s->diff_start, s->diff_height);
size -= 2;
}
if (s->zlibprime_prev)
av_log(avctx, AV_LOG_DEBUG, "%dx%d zlibprime_prev\n", i, j);
if (s->zlibprime_curr) {
int col = get_bits(&gb, 8);
int row = get_bits(&gb, 8);
av_log(avctx, AV_LOG_DEBUG, "%dx%d zlibprime_curr %dx%d\n", i, j, col, row);
size -= 2;
avpriv_request_sample(avctx, "zlibprime_curr");
return AVERROR_PATCHWELCOME;
}
if (!s->blocks && (s->zlibprime_curr || s->zlibprime_prev)) {
av_log(avctx, AV_LOG_ERROR, "no data available for zlib "
"priming\n");
return AVERROR_INVALIDDATA;
}
size--; // account for flags byte
}
if (has_diff) {
int k;
int off = (s->image_height - y_pos - 1) * s->frame.linesize[0];
for (k = 0; k < cur_blk_height; k++)
memcpy(s->frame.data[0] + off - k*s->frame.linesize[0] + x_pos*3,
s->keyframe + off - k*s->frame.linesize[0] + x_pos*3,
cur_blk_width * 3);
}
/* skip unchanged blocks, which have size 0 */
if (size) {
if (flashsv_decode_block(avctx, avpkt, &gb, size,
cur_blk_width, cur_blk_height,
x_pos, y_pos,
i + j * (h_blocks + !!h_part)))
av_log(avctx, AV_LOG_ERROR,
"error in decompression of block %dx%d\n", i, j);
}
}
}
if (s->is_keyframe && s->ver == 2) {
if (!s->keyframe) {
s->keyframe = av_malloc(s->frame.linesize[0] * avctx->height);
if (!s->keyframe) {
av_log(avctx, AV_LOG_ERROR, "Cannot allocate image data\n");
return AVERROR(ENOMEM);
}
}
memcpy(s->keyframe, s->frame.data[0], s->frame.linesize[0] * avctx->height);
}
if ((ret = av_frame_ref(data, &s->frame)) < 0)
return ret;
*got_frame = 1;
if ((get_bits_count(&gb) / 8) != buf_size)
av_log(avctx, AV_LOG_ERROR, "buffer not fully consumed (%d != %d)\n",
buf_size, (get_bits_count(&gb) / 8));
/* report that the buffer was completely consumed */
return buf_size;
}
static av_cold int flashsv_decode_end(AVCodecContext *avctx)
{
FlashSVContext *s = avctx->priv_data;
inflateEnd(&s->zstream);
/* release the frame if needed */
av_frame_unref(&s->frame);
/* free the tmpblock */
av_free(s->tmpblock);
return 0;
}
#if CONFIG_FLASHSV_DECODER
AVCodec ff_flashsv_decoder = {
.name = "flashsv",
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_FLASHSV,
.priv_data_size = sizeof(FlashSVContext),
.init = flashsv_decode_init,
.close = flashsv_decode_end,
.decode = flashsv_decode_frame,
.capabilities = CODEC_CAP_DR1,
.pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_BGR24, AV_PIX_FMT_NONE },
.long_name = NULL_IF_CONFIG_SMALL("Flash Screen Video v1"),
};
#endif /* CONFIG_FLASHSV_DECODER */
#if CONFIG_FLASHSV2_DECODER
static const uint32_t ff_flashsv2_default_palette[128] = {
0x000000, 0x333333, 0x666666, 0x999999, 0xCCCCCC, 0xFFFFFF,
0x330000, 0x660000, 0x990000, 0xCC0000, 0xFF0000, 0x003300,
0x006600, 0x009900, 0x00CC00, 0x00FF00, 0x000033, 0x000066,
0x000099, 0x0000CC, 0x0000FF, 0x333300, 0x666600, 0x999900,
0xCCCC00, 0xFFFF00, 0x003333, 0x006666, 0x009999, 0x00CCCC,
0x00FFFF, 0x330033, 0x660066, 0x990099, 0xCC00CC, 0xFF00FF,
0xFFFF33, 0xFFFF66, 0xFFFF99, 0xFFFFCC, 0xFF33FF, 0xFF66FF,
0xFF99FF, 0xFFCCFF, 0x33FFFF, 0x66FFFF, 0x99FFFF, 0xCCFFFF,
0xCCCC33, 0xCCCC66, 0xCCCC99, 0xCCCCFF, 0xCC33CC, 0xCC66CC,
0xCC99CC, 0xCCFFCC, 0x33CCCC, 0x66CCCC, 0x99CCCC, 0xFFCCCC,
0x999933, 0x999966, 0x9999CC, 0x9999FF, 0x993399, 0x996699,
0x99CC99, 0x99FF99, 0x339999, 0x669999, 0xCC9999, 0xFF9999,
0x666633, 0x666699, 0x6666CC, 0x6666FF, 0x663366, 0x669966,
0x66CC66, 0x66FF66, 0x336666, 0x996666, 0xCC6666, 0xFF6666,
0x333366, 0x333399, 0x3333CC, 0x3333FF, 0x336633, 0x339933,
0x33CC33, 0x33FF33, 0x663333, 0x993333, 0xCC3333, 0xFF3333,
0x003366, 0x336600, 0x660033, 0x006633, 0x330066, 0x663300,
0x336699, 0x669933, 0x993366, 0x339966, 0x663399, 0x996633,
0x6699CC, 0x99CC66, 0xCC6699, 0x66CC99, 0x9966CC, 0xCC9966,
0x99CCFF, 0xCCFF99, 0xFF99CC, 0x99FFCC, 0xCC99FF, 0xFFCC99,
0x111111, 0x222222, 0x444444, 0x555555, 0xAAAAAA, 0xBBBBBB,
0xDDDDDD, 0xEEEEEE
};
static av_cold int flashsv2_decode_init(AVCodecContext *avctx)
{
FlashSVContext *s = avctx->priv_data;
flashsv_decode_init(avctx);
s->pal = ff_flashsv2_default_palette;
s->ver = 2;
return 0;
}
static av_cold int flashsv2_decode_end(AVCodecContext *avctx)
{
FlashSVContext *s = avctx->priv_data;
av_freep(&s->keyframedata);
av_freep(&s->blocks);
av_freep(&s->keyframe);
av_freep(&s->deflate_block);
flashsv_decode_end(avctx);
return 0;
}
AVCodec ff_flashsv2_decoder = {
.name = "flashsv2",
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_FLASHSV2,
.priv_data_size = sizeof(FlashSVContext),
.init = flashsv2_decode_init,
.close = flashsv2_decode_end,
.decode = flashsv_decode_frame,
.capabilities = CODEC_CAP_DR1,
.pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_BGR24, AV_PIX_FMT_NONE },
.long_name = NULL_IF_CONFIG_SMALL("Flash Screen Video v2"),
};
#endif /* CONFIG_FLASHSV2_DECODER */
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5819_0 |
crossvul-cpp_data_bad_2802_3 | /* nautilus-metadata.c - metadata utils
*
* Copyright (C) 2009 Red Hatl, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include "nautilus-metadata.h"
#include <glib.h>
static char *used_metadata_names[] =
{
NAUTILUS_METADATA_KEY_LOCATION_BACKGROUND_COLOR,
NAUTILUS_METADATA_KEY_LOCATION_BACKGROUND_IMAGE,
NAUTILUS_METADATA_KEY_ICON_VIEW_AUTO_LAYOUT,
NAUTILUS_METADATA_KEY_ICON_VIEW_SORT_BY,
NAUTILUS_METADATA_KEY_ICON_VIEW_SORT_REVERSED,
NAUTILUS_METADATA_KEY_ICON_VIEW_KEEP_ALIGNED,
NAUTILUS_METADATA_KEY_ICON_VIEW_LAYOUT_TIMESTAMP,
NAUTILUS_METADATA_KEY_DESKTOP_ICON_SIZE,
NAUTILUS_METADATA_KEY_LIST_VIEW_SORT_COLUMN,
NAUTILUS_METADATA_KEY_LIST_VIEW_SORT_REVERSED,
NAUTILUS_METADATA_KEY_LIST_VIEW_VISIBLE_COLUMNS,
NAUTILUS_METADATA_KEY_LIST_VIEW_COLUMN_ORDER,
NAUTILUS_METADATA_KEY_WINDOW_GEOMETRY,
NAUTILUS_METADATA_KEY_WINDOW_SCROLL_POSITION,
NAUTILUS_METADATA_KEY_WINDOW_SHOW_HIDDEN_FILES,
NAUTILUS_METADATA_KEY_WINDOW_MAXIMIZED,
NAUTILUS_METADATA_KEY_WINDOW_STICKY,
NAUTILUS_METADATA_KEY_WINDOW_KEEP_ABOVE,
NAUTILUS_METADATA_KEY_SIDEBAR_BACKGROUND_COLOR,
NAUTILUS_METADATA_KEY_SIDEBAR_BACKGROUND_IMAGE,
NAUTILUS_METADATA_KEY_SIDEBAR_BUTTONS,
NAUTILUS_METADATA_KEY_ANNOTATION,
NAUTILUS_METADATA_KEY_ICON_POSITION,
NAUTILUS_METADATA_KEY_ICON_POSITION_TIMESTAMP,
NAUTILUS_METADATA_KEY_ICON_SCALE,
NAUTILUS_METADATA_KEY_CUSTOM_ICON,
NAUTILUS_METADATA_KEY_CUSTOM_ICON_NAME,
NAUTILUS_METADATA_KEY_SCREEN,
NAUTILUS_METADATA_KEY_EMBLEMS,
NULL
};
guint
nautilus_metadata_get_id (const char *metadata)
{
static GHashTable *hash;
int i;
if (hash == NULL)
{
hash = g_hash_table_new (g_str_hash, g_str_equal);
for (i = 0; used_metadata_names[i] != NULL; i++)
{
g_hash_table_insert (hash,
used_metadata_names[i],
GINT_TO_POINTER (i + 1));
}
}
return GPOINTER_TO_INT (g_hash_table_lookup (hash, metadata));
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2802_3 |
crossvul-cpp_data_bad_1560_0 | /*
* Copyright (c) 1993, 1994, 1995, 1996
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <tcpdump-stdinc.h>
#include "interface.h"
#include "addrtoname.h"
#include "extract.h"
static const char tstr[] = "[|wb]";
/* XXX need to add byte-swapping macros! */
/* XXX - you mean like the ones in "extract.h"? */
/*
* Largest packet size. Everything should fit within this space.
* For instance, multiline objects are sent piecewise.
*/
#define MAXFRAMESIZE 1024
/*
* Multiple drawing ops can be sent in one packet. Each one starts on a
* an even multiple of DOP_ALIGN bytes, which must be a power of two.
*/
#define DOP_ALIGN 4
#define DOP_ROUNDUP(x) ((((int)(x)) + (DOP_ALIGN - 1)) & ~(DOP_ALIGN - 1))
#define DOP_NEXT(d)\
((struct dophdr *)((u_char *)(d) + \
DOP_ROUNDUP(EXTRACT_16BITS(&(d)->dh_len) + sizeof(*(d)))))
/*
* Format of the whiteboard packet header.
* The transport level header.
*/
struct pkt_hdr {
uint32_t ph_src; /* site id of source */
uint32_t ph_ts; /* time stamp (for skew computation) */
uint16_t ph_version; /* version number */
u_char ph_type; /* message type */
u_char ph_flags; /* message flags */
};
/* Packet types */
#define PT_DRAWOP 0 /* drawing operation */
#define PT_ID 1 /* announcement packet */
#define PT_RREQ 2 /* repair request */
#define PT_RREP 3 /* repair reply */
#define PT_KILL 4 /* terminate participation */
#define PT_PREQ 5 /* page vector request */
#define PT_PREP 7 /* page vector reply */
#ifdef PF_USER
#undef PF_USER /* {Digital,Tru64} UNIX define this, alas */
#endif
/* flags */
#define PF_USER 0x01 /* hint that packet has interactive data */
#define PF_VIS 0x02 /* only visible ops wanted */
struct PageID {
uint32_t p_sid; /* session id of initiator */
uint32_t p_uid; /* page number */
};
struct dophdr {
uint32_t dh_ts; /* sender's timestamp */
uint16_t dh_len; /* body length */
u_char dh_flags;
u_char dh_type; /* body type */
/* body follows */
};
/*
* Drawing op sub-types.
*/
#define DT_RECT 2
#define DT_LINE 3
#define DT_ML 4
#define DT_DEL 5
#define DT_XFORM 6
#define DT_ELL 7
#define DT_CHAR 8
#define DT_STR 9
#define DT_NOP 10
#define DT_PSCODE 11
#define DT_PSCOMP 12
#define DT_REF 13
#define DT_SKIP 14
#define DT_HOLE 15
#define DT_MAXTYPE 15
/*
* A drawing operation.
*/
struct pkt_dop {
struct PageID pd_page; /* page that operations apply to */
uint32_t pd_sseq; /* start sequence number */
uint32_t pd_eseq; /* end sequence number */
/* drawing ops follow */
};
/*
* A repair request.
*/
struct pkt_rreq {
uint32_t pr_id; /* source id of drawops to be repaired */
struct PageID pr_page; /* page of drawops */
uint32_t pr_sseq; /* start seqno */
uint32_t pr_eseq; /* end seqno */
};
/*
* A repair reply.
*/
struct pkt_rrep {
uint32_t pr_id; /* original site id of ops */
struct pkt_dop pr_dop;
/* drawing ops follow */
};
struct id_off {
uint32_t id;
uint32_t off;
};
struct pgstate {
uint32_t slot;
struct PageID page;
uint16_t nid;
uint16_t rsvd;
/* seqptr's */
};
/*
* An announcement packet.
*/
struct pkt_id {
uint32_t pi_mslot;
struct PageID pi_mpage; /* current page */
struct pgstate pi_ps;
/* seqptr's */
/* null-terminated site name */
};
struct pkt_preq {
struct PageID pp_page;
uint32_t pp_low;
uint32_t pp_high;
};
struct pkt_prep {
uint32_t pp_n; /* size of pageid array */
/* pgstate's follow */
};
static int
wb_id(netdissect_options *ndo,
const struct pkt_id *id, u_int len)
{
int i;
const char *cp;
const struct id_off *io;
char c;
int nid;
ND_PRINT((ndo, " wb-id:"));
if (len < sizeof(*id) || !ND_TTEST(*id))
return (-1);
len -= sizeof(*id);
ND_PRINT((ndo, " %u/%s:%u (max %u/%s:%u) ",
EXTRACT_32BITS(&id->pi_ps.slot),
ipaddr_string(ndo, &id->pi_ps.page.p_sid),
EXTRACT_32BITS(&id->pi_ps.page.p_uid),
EXTRACT_32BITS(&id->pi_mslot),
ipaddr_string(ndo, &id->pi_mpage.p_sid),
EXTRACT_32BITS(&id->pi_mpage.p_uid)));
nid = EXTRACT_16BITS(&id->pi_ps.nid);
len -= sizeof(*io) * nid;
io = (struct id_off *)(id + 1);
cp = (char *)(io + nid);
if (!ND_TTEST2(cp, len)) {
ND_PRINT((ndo, "\""));
fn_print(ndo, (u_char *)cp, (u_char *)cp + len);
ND_PRINT((ndo, "\""));
}
c = '<';
for (i = 0; i < nid && ND_TTEST(*io); ++io, ++i) {
ND_PRINT((ndo, "%c%s:%u",
c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off)));
c = ',';
}
if (i >= nid) {
ND_PRINT((ndo, ">"));
return (0);
}
return (-1);
}
static int
wb_rreq(netdissect_options *ndo,
const struct pkt_rreq *rreq, u_int len)
{
ND_PRINT((ndo, " wb-rreq:"));
if (len < sizeof(*rreq) || !ND_TTEST(*rreq))
return (-1);
ND_PRINT((ndo, " please repair %s %s:%u<%u:%u>",
ipaddr_string(ndo, &rreq->pr_id),
ipaddr_string(ndo, &rreq->pr_page.p_sid),
EXTRACT_32BITS(&rreq->pr_page.p_uid),
EXTRACT_32BITS(&rreq->pr_sseq),
EXTRACT_32BITS(&rreq->pr_eseq)));
return (0);
}
static int
wb_preq(netdissect_options *ndo,
const struct pkt_preq *preq, u_int len)
{
ND_PRINT((ndo, " wb-preq:"));
if (len < sizeof(*preq) || !ND_TTEST(*preq))
return (-1);
ND_PRINT((ndo, " need %u/%s:%u",
EXTRACT_32BITS(&preq->pp_low),
ipaddr_string(ndo, &preq->pp_page.p_sid),
EXTRACT_32BITS(&preq->pp_page.p_uid)));
return (0);
}
static int
wb_prep(netdissect_options *ndo,
const struct pkt_prep *prep, u_int len)
{
int n;
const struct pgstate *ps;
const u_char *ep = ndo->ndo_snapend;
ND_PRINT((ndo, " wb-prep:"));
if (len < sizeof(*prep)) {
return (-1);
}
n = EXTRACT_32BITS(&prep->pp_n);
ps = (const struct pgstate *)(prep + 1);
while (--n >= 0 && !ND_TTEST(*ps)) {
const struct id_off *io, *ie;
char c = '<';
ND_PRINT((ndo, " %u/%s:%u",
EXTRACT_32BITS(&ps->slot),
ipaddr_string(ndo, &ps->page.p_sid),
EXTRACT_32BITS(&ps->page.p_uid)));
io = (struct id_off *)(ps + 1);
for (ie = io + ps->nid; io < ie && !ND_TTEST(*io); ++io) {
ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id),
EXTRACT_32BITS(&io->off)));
c = ',';
}
ND_PRINT((ndo, ">"));
ps = (struct pgstate *)io;
}
return ((u_char *)ps <= ep? 0 : -1);
}
static const char *dopstr[] = {
"dop-0!",
"dop-1!",
"RECT",
"LINE",
"ML",
"DEL",
"XFORM",
"ELL",
"CHAR",
"STR",
"NOP",
"PSCODE",
"PSCOMP",
"REF",
"SKIP",
"HOLE",
};
static int
wb_dops(netdissect_options *ndo, const struct pkt_dop *dop,
uint32_t ss, uint32_t es)
{
const struct dophdr *dh = (const struct dophdr *)((const u_char *)dop + sizeof(*dop));
ND_PRINT((ndo, " <"));
for ( ; ss <= es; ++ss) {
int t;
if (!ND_TTEST(*dh)) {
ND_PRINT((ndo, "%s", tstr));
break;
}
t = dh->dh_type;
if (t > DT_MAXTYPE)
ND_PRINT((ndo, " dop-%d!", t));
else {
ND_PRINT((ndo, " %s", dopstr[t]));
if (t == DT_SKIP || t == DT_HOLE) {
uint32_t ts = EXTRACT_32BITS(&dh->dh_ts);
ND_PRINT((ndo, "%d", ts - ss + 1));
if (ss > ts || ts > es) {
ND_PRINT((ndo, "[|]"));
if (ts < ss)
return (0);
}
ss = ts;
}
}
dh = DOP_NEXT(dh);
}
ND_PRINT((ndo, " >"));
return (0);
}
static int
wb_rrep(netdissect_options *ndo,
const struct pkt_rrep *rrep, u_int len)
{
const struct pkt_dop *dop = &rrep->pr_dop;
ND_PRINT((ndo, " wb-rrep:"));
if (len < sizeof(*rrep) || !ND_TTEST(*rrep))
return (-1);
len -= sizeof(*rrep);
ND_PRINT((ndo, " for %s %s:%u<%u:%u>",
ipaddr_string(ndo, &rrep->pr_id),
ipaddr_string(ndo, &dop->pd_page.p_sid),
EXTRACT_32BITS(&dop->pd_page.p_uid),
EXTRACT_32BITS(&dop->pd_sseq),
EXTRACT_32BITS(&dop->pd_eseq)));
if (ndo->ndo_vflag)
return (wb_dops(ndo, dop,
EXTRACT_32BITS(&dop->pd_sseq),
EXTRACT_32BITS(&dop->pd_eseq)));
return (0);
}
static int
wb_drawop(netdissect_options *ndo,
const struct pkt_dop *dop, u_int len)
{
ND_PRINT((ndo, " wb-dop:"));
if (len < sizeof(*dop) || !ND_TTEST(*dop))
return (-1);
len -= sizeof(*dop);
ND_PRINT((ndo, " %s:%u<%u:%u>",
ipaddr_string(ndo, &dop->pd_page.p_sid),
EXTRACT_32BITS(&dop->pd_page.p_uid),
EXTRACT_32BITS(&dop->pd_sseq),
EXTRACT_32BITS(&dop->pd_eseq)));
if (ndo->ndo_vflag)
return (wb_dops(ndo, dop,
EXTRACT_32BITS(&dop->pd_sseq),
EXTRACT_32BITS(&dop->pd_eseq)));
return (0);
}
/*
* Print whiteboard multicast packets.
*/
void
wb_print(netdissect_options *ndo,
register const void *hdr, register u_int len)
{
register const struct pkt_hdr *ph;
ph = (const struct pkt_hdr *)hdr;
if (len < sizeof(*ph) || !ND_TTEST(*ph)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
len -= sizeof(*ph);
if (ph->ph_flags)
ND_PRINT((ndo, "*"));
switch (ph->ph_type) {
case PT_KILL:
ND_PRINT((ndo, " wb-kill"));
return;
case PT_ID:
if (wb_id(ndo, (struct pkt_id *)(ph + 1), len) >= 0)
return;
break;
case PT_RREQ:
if (wb_rreq(ndo, (struct pkt_rreq *)(ph + 1), len) >= 0)
return;
break;
case PT_RREP:
if (wb_rrep(ndo, (struct pkt_rrep *)(ph + 1), len) >= 0)
return;
break;
case PT_DRAWOP:
if (wb_drawop(ndo, (struct pkt_dop *)(ph + 1), len) >= 0)
return;
break;
case PT_PREQ:
if (wb_preq(ndo, (struct pkt_preq *)(ph + 1), len) >= 0)
return;
break;
case PT_PREP:
if (wb_prep(ndo, (struct pkt_prep *)(ph + 1), len) >= 0)
return;
break;
default:
ND_PRINT((ndo, " wb-%d!", ph->ph_type));
return;
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1560_0 |
crossvul-cpp_data_bad_3509_0 | /*
* fs/cifs/connect.c
*
* Copyright (C) International Business Machines Corp., 2002,2009
* Author(s): Steve French (sfrench@us.ibm.com)
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/fs.h>
#include <linux/net.h>
#include <linux/string.h>
#include <linux/list.h>
#include <linux/wait.h>
#include <linux/slab.h>
#include <linux/pagemap.h>
#include <linux/ctype.h>
#include <linux/utsname.h>
#include <linux/mempool.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/kthread.h>
#include <linux/pagevec.h>
#include <linux/freezer.h>
#include <linux/namei.h>
#include <asm/uaccess.h>
#include <asm/processor.h>
#include <linux/inet.h>
#include <net/ipv6.h>
#include "cifspdu.h"
#include "cifsglob.h"
#include "cifsproto.h"
#include "cifs_unicode.h"
#include "cifs_debug.h"
#include "cifs_fs_sb.h"
#include "ntlmssp.h"
#include "nterr.h"
#include "rfc1002pdu.h"
#include "fscache.h"
#define CIFS_PORT 445
#define RFC1001_PORT 139
/* SMB echo "timeout" -- FIXME: tunable? */
#define SMB_ECHO_INTERVAL (60 * HZ)
extern mempool_t *cifs_req_poolp;
struct smb_vol {
char *username;
char *password;
char *domainname;
char *UNC;
char *UNCip;
char *iocharset; /* local code page for mapping to and from Unicode */
char source_rfc1001_name[RFC1001_NAME_LEN_WITH_NULL]; /* clnt nb name */
char target_rfc1001_name[RFC1001_NAME_LEN_WITH_NULL]; /* srvr nb name */
uid_t cred_uid;
uid_t linux_uid;
gid_t linux_gid;
mode_t file_mode;
mode_t dir_mode;
unsigned secFlg;
bool retry:1;
bool intr:1;
bool setuids:1;
bool override_uid:1;
bool override_gid:1;
bool dynperm:1;
bool noperm:1;
bool no_psx_acl:1; /* set if posix acl support should be disabled */
bool cifs_acl:1;
bool no_xattr:1; /* set if xattr (EA) support should be disabled*/
bool server_ino:1; /* use inode numbers from server ie UniqueId */
bool direct_io:1;
bool strict_io:1; /* strict cache behavior */
bool remap:1; /* set to remap seven reserved chars in filenames */
bool posix_paths:1; /* unset to not ask for posix pathnames. */
bool no_linux_ext:1;
bool sfu_emul:1;
bool nullauth:1; /* attempt to authenticate with null user */
bool nocase:1; /* request case insensitive filenames */
bool nobrl:1; /* disable sending byte range locks to srv */
bool mand_lock:1; /* send mandatory not posix byte range lock reqs */
bool seal:1; /* request transport encryption on share */
bool nodfs:1; /* Do not request DFS, even if available */
bool local_lease:1; /* check leases only on local system, not remote */
bool noblocksnd:1;
bool noautotune:1;
bool nostrictsync:1; /* do not force expensive SMBflush on every sync */
bool fsc:1; /* enable fscache */
bool mfsymlinks:1; /* use Minshall+French Symlinks */
bool multiuser:1;
unsigned int rsize;
unsigned int wsize;
bool sockopt_tcp_nodelay:1;
unsigned short int port;
unsigned long actimeo; /* attribute cache timeout (jiffies) */
char *prepath;
struct sockaddr_storage srcaddr; /* allow binding to a local IP */
struct nls_table *local_nls;
};
/* FIXME: should these be tunable? */
#define TLINK_ERROR_EXPIRE (1 * HZ)
#define TLINK_IDLE_EXPIRE (600 * HZ)
static int ip_connect(struct TCP_Server_Info *server);
static int generic_ip_connect(struct TCP_Server_Info *server);
static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
static void cifs_prune_tlinks(struct work_struct *work);
/*
* cifs tcp session reconnection
*
* mark tcp session as reconnecting so temporarily locked
* mark all smb sessions as reconnecting for tcp session
* reconnect tcp session
* wake up waiters on reconnection? - (not needed currently)
*/
static int
cifs_reconnect(struct TCP_Server_Info *server)
{
int rc = 0;
struct list_head *tmp, *tmp2;
struct cifsSesInfo *ses;
struct cifsTconInfo *tcon;
struct mid_q_entry *mid_entry;
spin_lock(&GlobalMid_Lock);
if (server->tcpStatus == CifsExiting) {
/* the demux thread will exit normally
next time through the loop */
spin_unlock(&GlobalMid_Lock);
return rc;
} else
server->tcpStatus = CifsNeedReconnect;
spin_unlock(&GlobalMid_Lock);
server->maxBuf = 0;
cFYI(1, "Reconnecting tcp session");
/* before reconnecting the tcp session, mark the smb session (uid)
and the tid bad so they are not used until reconnected */
cFYI(1, "%s: marking sessions and tcons for reconnect", __func__);
spin_lock(&cifs_tcp_ses_lock);
list_for_each(tmp, &server->smb_ses_list) {
ses = list_entry(tmp, struct cifsSesInfo, smb_ses_list);
ses->need_reconnect = true;
ses->ipc_tid = 0;
list_for_each(tmp2, &ses->tcon_list) {
tcon = list_entry(tmp2, struct cifsTconInfo, tcon_list);
tcon->need_reconnect = true;
}
}
spin_unlock(&cifs_tcp_ses_lock);
/* do not want to be sending data on a socket we are freeing */
cFYI(1, "%s: tearing down socket", __func__);
mutex_lock(&server->srv_mutex);
if (server->ssocket) {
cFYI(1, "State: 0x%x Flags: 0x%lx", server->ssocket->state,
server->ssocket->flags);
kernel_sock_shutdown(server->ssocket, SHUT_WR);
cFYI(1, "Post shutdown state: 0x%x Flags: 0x%lx",
server->ssocket->state,
server->ssocket->flags);
sock_release(server->ssocket);
server->ssocket = NULL;
}
server->sequence_number = 0;
server->session_estab = false;
kfree(server->session_key.response);
server->session_key.response = NULL;
server->session_key.len = 0;
server->lstrp = jiffies;
mutex_unlock(&server->srv_mutex);
/* mark submitted MIDs for retry and issue callback */
cFYI(1, "%s: issuing mid callbacks", __func__);
spin_lock(&GlobalMid_Lock);
list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
if (mid_entry->midState == MID_REQUEST_SUBMITTED)
mid_entry->midState = MID_RETRY_NEEDED;
list_del_init(&mid_entry->qhead);
mid_entry->callback(mid_entry);
}
spin_unlock(&GlobalMid_Lock);
while ((server->tcpStatus != CifsExiting) &&
(server->tcpStatus != CifsGood)) {
try_to_freeze();
/* we should try only the port we connected to before */
rc = generic_ip_connect(server);
if (rc) {
cFYI(1, "reconnect error %d", rc);
msleep(3000);
} else {
atomic_inc(&tcpSesReconnectCount);
spin_lock(&GlobalMid_Lock);
if (server->tcpStatus != CifsExiting)
server->tcpStatus = CifsGood;
spin_unlock(&GlobalMid_Lock);
}
}
return rc;
}
/*
return codes:
0 not a transact2, or all data present
>0 transact2 with that much data missing
-EINVAL = invalid transact2
*/
static int check2ndT2(struct smb_hdr *pSMB, unsigned int maxBufSize)
{
struct smb_t2_rsp *pSMBt;
int remaining;
__u16 total_data_size, data_in_this_rsp;
if (pSMB->Command != SMB_COM_TRANSACTION2)
return 0;
/* check for plausible wct, bcc and t2 data and parm sizes */
/* check for parm and data offset going beyond end of smb */
if (pSMB->WordCount != 10) { /* coalesce_t2 depends on this */
cFYI(1, "invalid transact2 word count");
return -EINVAL;
}
pSMBt = (struct smb_t2_rsp *)pSMB;
total_data_size = get_unaligned_le16(&pSMBt->t2_rsp.TotalDataCount);
data_in_this_rsp = get_unaligned_le16(&pSMBt->t2_rsp.DataCount);
remaining = total_data_size - data_in_this_rsp;
if (remaining == 0)
return 0;
else if (remaining < 0) {
cFYI(1, "total data %d smaller than data in frame %d",
total_data_size, data_in_this_rsp);
return -EINVAL;
} else {
cFYI(1, "missing %d bytes from transact2, check next response",
remaining);
if (total_data_size > maxBufSize) {
cERROR(1, "TotalDataSize %d is over maximum buffer %d",
total_data_size, maxBufSize);
return -EINVAL;
}
return remaining;
}
}
static int coalesce_t2(struct smb_hdr *psecond, struct smb_hdr *pTargetSMB)
{
struct smb_t2_rsp *pSMB2 = (struct smb_t2_rsp *)psecond;
struct smb_t2_rsp *pSMBt = (struct smb_t2_rsp *)pTargetSMB;
char *data_area_of_target;
char *data_area_of_buf2;
int remaining;
__u16 byte_count, total_data_size, total_in_buf, total_in_buf2;
total_data_size = get_unaligned_le16(&pSMBt->t2_rsp.TotalDataCount);
if (total_data_size !=
get_unaligned_le16(&pSMB2->t2_rsp.TotalDataCount))
cFYI(1, "total data size of primary and secondary t2 differ");
total_in_buf = get_unaligned_le16(&pSMBt->t2_rsp.DataCount);
remaining = total_data_size - total_in_buf;
if (remaining < 0)
return -EINVAL;
if (remaining == 0) /* nothing to do, ignore */
return 0;
total_in_buf2 = get_unaligned_le16(&pSMB2->t2_rsp.DataCount);
if (remaining < total_in_buf2) {
cFYI(1, "transact2 2nd response contains too much data");
}
/* find end of first SMB data area */
data_area_of_target = (char *)&pSMBt->hdr.Protocol +
get_unaligned_le16(&pSMBt->t2_rsp.DataOffset);
/* validate target area */
data_area_of_buf2 = (char *)&pSMB2->hdr.Protocol +
get_unaligned_le16(&pSMB2->t2_rsp.DataOffset);
data_area_of_target += total_in_buf;
/* copy second buffer into end of first buffer */
memcpy(data_area_of_target, data_area_of_buf2, total_in_buf2);
total_in_buf += total_in_buf2;
put_unaligned_le16(total_in_buf, &pSMBt->t2_rsp.DataCount);
byte_count = get_bcc_le(pTargetSMB);
byte_count += total_in_buf2;
put_bcc_le(byte_count, pTargetSMB);
byte_count = pTargetSMB->smb_buf_length;
byte_count += total_in_buf2;
/* BB also add check that we are not beyond maximum buffer size */
pTargetSMB->smb_buf_length = byte_count;
if (remaining == total_in_buf2) {
cFYI(1, "found the last secondary response");
return 0; /* we are done */
} else /* more responses to go */
return 1;
}
static void
cifs_echo_request(struct work_struct *work)
{
int rc;
struct TCP_Server_Info *server = container_of(work,
struct TCP_Server_Info, echo.work);
/*
* We cannot send an echo until the NEGOTIATE_PROTOCOL request is
* done, which is indicated by maxBuf != 0. Also, no need to ping if
* we got a response recently
*/
if (server->maxBuf == 0 ||
time_before(jiffies, server->lstrp + SMB_ECHO_INTERVAL - HZ))
goto requeue_echo;
rc = CIFSSMBEcho(server);
if (rc)
cFYI(1, "Unable to send echo request to server: %s",
server->hostname);
requeue_echo:
queue_delayed_work(system_nrt_wq, &server->echo, SMB_ECHO_INTERVAL);
}
static int
cifs_demultiplex_thread(struct TCP_Server_Info *server)
{
int length;
unsigned int pdu_length, total_read;
struct smb_hdr *smb_buffer = NULL;
struct smb_hdr *bigbuf = NULL;
struct smb_hdr *smallbuf = NULL;
struct msghdr smb_msg;
struct kvec iov;
struct socket *csocket = server->ssocket;
struct list_head *tmp, *tmp2;
struct task_struct *task_to_wake = NULL;
struct mid_q_entry *mid_entry;
char temp;
bool isLargeBuf = false;
bool isMultiRsp;
int reconnect;
current->flags |= PF_MEMALLOC;
cFYI(1, "Demultiplex PID: %d", task_pid_nr(current));
length = atomic_inc_return(&tcpSesAllocCount);
if (length > 1)
mempool_resize(cifs_req_poolp, length + cifs_min_rcv,
GFP_KERNEL);
set_freezable();
while (server->tcpStatus != CifsExiting) {
if (try_to_freeze())
continue;
if (bigbuf == NULL) {
bigbuf = cifs_buf_get();
if (!bigbuf) {
cERROR(1, "No memory for large SMB response");
msleep(3000);
/* retry will check if exiting */
continue;
}
} else if (isLargeBuf) {
/* we are reusing a dirty large buf, clear its start */
memset(bigbuf, 0, sizeof(struct smb_hdr));
}
if (smallbuf == NULL) {
smallbuf = cifs_small_buf_get();
if (!smallbuf) {
cERROR(1, "No memory for SMB response");
msleep(1000);
/* retry will check if exiting */
continue;
}
/* beginning of smb buffer is cleared in our buf_get */
} else /* if existing small buf clear beginning */
memset(smallbuf, 0, sizeof(struct smb_hdr));
isLargeBuf = false;
isMultiRsp = false;
smb_buffer = smallbuf;
iov.iov_base = smb_buffer;
iov.iov_len = 4;
smb_msg.msg_control = NULL;
smb_msg.msg_controllen = 0;
pdu_length = 4; /* enough to get RFC1001 header */
incomplete_rcv:
if (echo_retries > 0 &&
time_after(jiffies, server->lstrp +
(echo_retries * SMB_ECHO_INTERVAL))) {
cERROR(1, "Server %s has not responded in %d seconds. "
"Reconnecting...", server->hostname,
(echo_retries * SMB_ECHO_INTERVAL / HZ));
cifs_reconnect(server);
csocket = server->ssocket;
wake_up(&server->response_q);
continue;
}
length =
kernel_recvmsg(csocket, &smb_msg,
&iov, 1, pdu_length, 0 /* BB other flags? */);
if (server->tcpStatus == CifsExiting) {
break;
} else if (server->tcpStatus == CifsNeedReconnect) {
cFYI(1, "Reconnect after server stopped responding");
cifs_reconnect(server);
cFYI(1, "call to reconnect done");
csocket = server->ssocket;
continue;
} else if (length == -ERESTARTSYS ||
length == -EAGAIN ||
length == -EINTR) {
msleep(1); /* minimum sleep to prevent looping
allowing socket to clear and app threads to set
tcpStatus CifsNeedReconnect if server hung */
if (pdu_length < 4) {
iov.iov_base = (4 - pdu_length) +
(char *)smb_buffer;
iov.iov_len = pdu_length;
smb_msg.msg_control = NULL;
smb_msg.msg_controllen = 0;
goto incomplete_rcv;
} else
continue;
} else if (length <= 0) {
cFYI(1, "Reconnect after unexpected peek error %d",
length);
cifs_reconnect(server);
csocket = server->ssocket;
wake_up(&server->response_q);
continue;
} else if (length < pdu_length) {
cFYI(1, "requested %d bytes but only got %d bytes",
pdu_length, length);
pdu_length -= length;
msleep(1);
goto incomplete_rcv;
}
/* The right amount was read from socket - 4 bytes */
/* so we can now interpret the length field */
/* the first byte big endian of the length field,
is actually not part of the length but the type
with the most common, zero, as regular data */
temp = *((char *) smb_buffer);
/* Note that FC 1001 length is big endian on the wire,
but we convert it here so it is always manipulated
as host byte order */
pdu_length = be32_to_cpu((__force __be32)smb_buffer->smb_buf_length);
smb_buffer->smb_buf_length = pdu_length;
cFYI(1, "rfc1002 length 0x%x", pdu_length+4);
if (temp == (char) RFC1002_SESSION_KEEP_ALIVE) {
continue;
} else if (temp == (char)RFC1002_POSITIVE_SESSION_RESPONSE) {
cFYI(1, "Good RFC 1002 session rsp");
continue;
} else if (temp == (char)RFC1002_NEGATIVE_SESSION_RESPONSE) {
/* we get this from Windows 98 instead of
an error on SMB negprot response */
cFYI(1, "Negative RFC1002 Session Response Error 0x%x)",
pdu_length);
/* give server a second to clean up */
msleep(1000);
/* always try 445 first on reconnect since we get NACK
* on some if we ever connected to port 139 (the NACK
* is since we do not begin with RFC1001 session
* initialize frame)
*/
cifs_set_port((struct sockaddr *)
&server->dstaddr, CIFS_PORT);
cifs_reconnect(server);
csocket = server->ssocket;
wake_up(&server->response_q);
continue;
} else if (temp != (char) 0) {
cERROR(1, "Unknown RFC 1002 frame");
cifs_dump_mem(" Received Data: ", (char *)smb_buffer,
length);
cifs_reconnect(server);
csocket = server->ssocket;
continue;
}
/* else we have an SMB response */
if ((pdu_length > CIFSMaxBufSize + MAX_CIFS_HDR_SIZE - 4) ||
(pdu_length < sizeof(struct smb_hdr) - 1 - 4)) {
cERROR(1, "Invalid size SMB length %d pdu_length %d",
length, pdu_length+4);
cifs_reconnect(server);
csocket = server->ssocket;
wake_up(&server->response_q);
continue;
}
/* else length ok */
reconnect = 0;
if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
isLargeBuf = true;
memcpy(bigbuf, smallbuf, 4);
smb_buffer = bigbuf;
}
length = 0;
iov.iov_base = 4 + (char *)smb_buffer;
iov.iov_len = pdu_length;
for (total_read = 0; total_read < pdu_length;
total_read += length) {
length = kernel_recvmsg(csocket, &smb_msg, &iov, 1,
pdu_length - total_read, 0);
if (server->tcpStatus == CifsExiting) {
/* then will exit */
reconnect = 2;
break;
} else if (server->tcpStatus == CifsNeedReconnect) {
cifs_reconnect(server);
csocket = server->ssocket;
/* Reconnect wakes up rspns q */
/* Now we will reread sock */
reconnect = 1;
break;
} else if (length == -ERESTARTSYS ||
length == -EAGAIN ||
length == -EINTR) {
msleep(1); /* minimum sleep to prevent looping,
allowing socket to clear and app
threads to set tcpStatus
CifsNeedReconnect if server hung*/
length = 0;
continue;
} else if (length <= 0) {
cERROR(1, "Received no data, expecting %d",
pdu_length - total_read);
cifs_reconnect(server);
csocket = server->ssocket;
reconnect = 1;
break;
}
}
if (reconnect == 2)
break;
else if (reconnect == 1)
continue;
total_read += 4; /* account for rfc1002 hdr */
dump_smb(smb_buffer, total_read);
/*
* We know that we received enough to get to the MID as we
* checked the pdu_length earlier. Now check to see
* if the rest of the header is OK. We borrow the length
* var for the rest of the loop to avoid a new stack var.
*
* 48 bytes is enough to display the header and a little bit
* into the payload for debugging purposes.
*/
length = checkSMB(smb_buffer, smb_buffer->Mid, total_read);
if (length != 0)
cifs_dump_mem("Bad SMB: ", smb_buffer,
min_t(unsigned int, total_read, 48));
mid_entry = NULL;
server->lstrp = jiffies;
spin_lock(&GlobalMid_Lock);
list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
if ((mid_entry->mid == smb_buffer->Mid) &&
(mid_entry->midState == MID_REQUEST_SUBMITTED) &&
(mid_entry->command == smb_buffer->Command)) {
if (length == 0 &&
check2ndT2(smb_buffer, server->maxBuf) > 0) {
/* We have a multipart transact2 resp */
isMultiRsp = true;
if (mid_entry->resp_buf) {
/* merge response - fix up 1st*/
if (coalesce_t2(smb_buffer,
mid_entry->resp_buf)) {
mid_entry->multiRsp =
true;
break;
} else {
/* all parts received */
mid_entry->multiEnd =
true;
goto multi_t2_fnd;
}
} else {
if (!isLargeBuf) {
cERROR(1, "1st trans2 resp needs bigbuf");
/* BB maybe we can fix this up, switch
to already allocated large buffer? */
} else {
/* Have first buffer */
mid_entry->resp_buf =
smb_buffer;
mid_entry->largeBuf =
true;
bigbuf = NULL;
}
}
break;
}
mid_entry->resp_buf = smb_buffer;
mid_entry->largeBuf = isLargeBuf;
multi_t2_fnd:
if (length == 0)
mid_entry->midState =
MID_RESPONSE_RECEIVED;
else
mid_entry->midState =
MID_RESPONSE_MALFORMED;
#ifdef CONFIG_CIFS_STATS2
mid_entry->when_received = jiffies;
#endif
list_del_init(&mid_entry->qhead);
mid_entry->callback(mid_entry);
break;
}
mid_entry = NULL;
}
spin_unlock(&GlobalMid_Lock);
if (mid_entry != NULL) {
/* Was previous buf put in mpx struct for multi-rsp? */
if (!isMultiRsp) {
/* smb buffer will be freed by user thread */
if (isLargeBuf)
bigbuf = NULL;
else
smallbuf = NULL;
}
} else if (length != 0) {
/* response sanity checks failed */
continue;
} else if (!is_valid_oplock_break(smb_buffer, server) &&
!isMultiRsp) {
cERROR(1, "No task to wake, unknown frame received! "
"NumMids %d", atomic_read(&midCount));
cifs_dump_mem("Received Data is: ", (char *)smb_buffer,
sizeof(struct smb_hdr));
#ifdef CONFIG_CIFS_DEBUG2
cifs_dump_detail(smb_buffer);
cifs_dump_mids(server);
#endif /* CIFS_DEBUG2 */
}
} /* end while !EXITING */
/* take it off the list, if it's not already */
spin_lock(&cifs_tcp_ses_lock);
list_del_init(&server->tcp_ses_list);
spin_unlock(&cifs_tcp_ses_lock);
spin_lock(&GlobalMid_Lock);
server->tcpStatus = CifsExiting;
spin_unlock(&GlobalMid_Lock);
wake_up_all(&server->response_q);
/* check if we have blocked requests that need to free */
/* Note that cifs_max_pending is normally 50, but
can be set at module install time to as little as two */
spin_lock(&GlobalMid_Lock);
if (atomic_read(&server->inFlight) >= cifs_max_pending)
atomic_set(&server->inFlight, cifs_max_pending - 1);
/* We do not want to set the max_pending too low or we
could end up with the counter going negative */
spin_unlock(&GlobalMid_Lock);
/* Although there should not be any requests blocked on
this queue it can not hurt to be paranoid and try to wake up requests
that may haven been blocked when more than 50 at time were on the wire
to the same server - they now will see the session is in exit state
and get out of SendReceive. */
wake_up_all(&server->request_q);
/* give those requests time to exit */
msleep(125);
if (server->ssocket) {
sock_release(csocket);
server->ssocket = NULL;
}
/* buffer usuallly freed in free_mid - need to free it here on exit */
cifs_buf_release(bigbuf);
if (smallbuf) /* no sense logging a debug message if NULL */
cifs_small_buf_release(smallbuf);
if (!list_empty(&server->pending_mid_q)) {
spin_lock(&GlobalMid_Lock);
list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
cFYI(1, "Clearing Mid 0x%x - issuing callback",
mid_entry->mid);
list_del_init(&mid_entry->qhead);
mid_entry->callback(mid_entry);
}
spin_unlock(&GlobalMid_Lock);
/* 1/8th of sec is more than enough time for them to exit */
msleep(125);
}
if (!list_empty(&server->pending_mid_q)) {
/* mpx threads have not exited yet give them
at least the smb send timeout time for long ops */
/* due to delays on oplock break requests, we need
to wait at least 45 seconds before giving up
on a request getting a response and going ahead
and killing cifsd */
cFYI(1, "Wait for exit from demultiplex thread");
msleep(46000);
/* if threads still have not exited they are probably never
coming home not much else we can do but free the memory */
}
kfree(server->hostname);
task_to_wake = xchg(&server->tsk, NULL);
kfree(server);
length = atomic_dec_return(&tcpSesAllocCount);
if (length > 0)
mempool_resize(cifs_req_poolp, length + cifs_min_rcv,
GFP_KERNEL);
/* if server->tsk was NULL then wait for a signal before exiting */
if (!task_to_wake) {
set_current_state(TASK_INTERRUPTIBLE);
while (!signal_pending(current)) {
schedule();
set_current_state(TASK_INTERRUPTIBLE);
}
set_current_state(TASK_RUNNING);
}
module_put_and_exit(0);
}
/* extract the host portion of the UNC string */
static char *
extract_hostname(const char *unc)
{
const char *src;
char *dst, *delim;
unsigned int len;
/* skip double chars at beginning of string */
/* BB: check validity of these bytes? */
src = unc + 2;
/* delimiter between hostname and sharename is always '\\' now */
delim = strchr(src, '\\');
if (!delim)
return ERR_PTR(-EINVAL);
len = delim - src;
dst = kmalloc((len + 1), GFP_KERNEL);
if (dst == NULL)
return ERR_PTR(-ENOMEM);
memcpy(dst, src, len);
dst[len] = '\0';
return dst;
}
static int
cifs_parse_mount_options(char *options, const char *devname,
struct smb_vol *vol)
{
char *value;
char *data;
unsigned int temp_len, i, j;
char separator[2];
short int override_uid = -1;
short int override_gid = -1;
bool uid_specified = false;
bool gid_specified = false;
char *nodename = utsname()->nodename;
separator[0] = ',';
separator[1] = 0;
/*
* does not have to be perfect mapping since field is
* informational, only used for servers that do not support
* port 445 and it can be overridden at mount time
*/
memset(vol->source_rfc1001_name, 0x20, RFC1001_NAME_LEN);
for (i = 0; i < strnlen(nodename, RFC1001_NAME_LEN); i++)
vol->source_rfc1001_name[i] = toupper(nodename[i]);
vol->source_rfc1001_name[RFC1001_NAME_LEN] = 0;
/* null target name indicates to use *SMBSERVR default called name
if we end up sending RFC1001 session initialize */
vol->target_rfc1001_name[0] = 0;
vol->cred_uid = current_uid();
vol->linux_uid = current_uid();
vol->linux_gid = current_gid();
/* default to only allowing write access to owner of the mount */
vol->dir_mode = vol->file_mode = S_IRUGO | S_IXUGO | S_IWUSR;
/* vol->retry default is 0 (i.e. "soft" limited retry not hard retry) */
/* default is always to request posix paths. */
vol->posix_paths = 1;
/* default to using server inode numbers where available */
vol->server_ino = 1;
vol->actimeo = CIFS_DEF_ACTIMEO;
if (!options)
return 1;
if (strncmp(options, "sep=", 4) == 0) {
if (options[4] != 0) {
separator[0] = options[4];
options += 5;
} else {
cFYI(1, "Null separator not allowed");
}
}
while ((data = strsep(&options, separator)) != NULL) {
if (!*data)
continue;
if ((value = strchr(data, '=')) != NULL)
*value++ = '\0';
/* Have to parse this before we parse for "user" */
if (strnicmp(data, "user_xattr", 10) == 0) {
vol->no_xattr = 0;
} else if (strnicmp(data, "nouser_xattr", 12) == 0) {
vol->no_xattr = 1;
} else if (strnicmp(data, "user", 4) == 0) {
if (!value) {
printk(KERN_WARNING
"CIFS: invalid or missing username\n");
return 1; /* needs_arg; */
} else if (!*value) {
/* null user, ie anonymous, authentication */
vol->nullauth = 1;
}
if (strnlen(value, MAX_USERNAME_SIZE) <
MAX_USERNAME_SIZE) {
vol->username = value;
} else {
printk(KERN_WARNING "CIFS: username too long\n");
return 1;
}
} else if (strnicmp(data, "pass", 4) == 0) {
if (!value) {
vol->password = NULL;
continue;
} else if (value[0] == 0) {
/* check if string begins with double comma
since that would mean the password really
does start with a comma, and would not
indicate an empty string */
if (value[1] != separator[0]) {
vol->password = NULL;
continue;
}
}
temp_len = strlen(value);
/* removed password length check, NTLM passwords
can be arbitrarily long */
/* if comma in password, the string will be
prematurely null terminated. Commas in password are
specified across the cifs mount interface by a double
comma ie ,, and a comma used as in other cases ie ','
as a parameter delimiter/separator is single and due
to the strsep above is temporarily zeroed. */
/* NB: password legally can have multiple commas and
the only illegal character in a password is null */
if ((value[temp_len] == 0) &&
(value[temp_len+1] == separator[0])) {
/* reinsert comma */
value[temp_len] = separator[0];
temp_len += 2; /* move after second comma */
while (value[temp_len] != 0) {
if (value[temp_len] == separator[0]) {
if (value[temp_len+1] ==
separator[0]) {
/* skip second comma */
temp_len++;
} else {
/* single comma indicating start
of next parm */
break;
}
}
temp_len++;
}
if (value[temp_len] == 0) {
options = NULL;
} else {
value[temp_len] = 0;
/* point option to start of next parm */
options = value + temp_len + 1;
}
/* go from value to value + temp_len condensing
double commas to singles. Note that this ends up
allocating a few bytes too many, which is ok */
vol->password = kzalloc(temp_len, GFP_KERNEL);
if (vol->password == NULL) {
printk(KERN_WARNING "CIFS: no memory "
"for password\n");
return 1;
}
for (i = 0, j = 0; i < temp_len; i++, j++) {
vol->password[j] = value[i];
if (value[i] == separator[0]
&& value[i+1] == separator[0]) {
/* skip second comma */
i++;
}
}
vol->password[j] = 0;
} else {
vol->password = kzalloc(temp_len+1, GFP_KERNEL);
if (vol->password == NULL) {
printk(KERN_WARNING "CIFS: no memory "
"for password\n");
return 1;
}
strcpy(vol->password, value);
}
} else if (!strnicmp(data, "ip", 2) ||
!strnicmp(data, "addr", 4)) {
if (!value || !*value) {
vol->UNCip = NULL;
} else if (strnlen(value, INET6_ADDRSTRLEN) <
INET6_ADDRSTRLEN) {
vol->UNCip = value;
} else {
printk(KERN_WARNING "CIFS: ip address "
"too long\n");
return 1;
}
} else if (strnicmp(data, "sec", 3) == 0) {
if (!value || !*value) {
cERROR(1, "no security value specified");
continue;
} else if (strnicmp(value, "krb5i", 5) == 0) {
vol->secFlg |= CIFSSEC_MAY_KRB5 |
CIFSSEC_MUST_SIGN;
} else if (strnicmp(value, "krb5p", 5) == 0) {
/* vol->secFlg |= CIFSSEC_MUST_SEAL |
CIFSSEC_MAY_KRB5; */
cERROR(1, "Krb5 cifs privacy not supported");
return 1;
} else if (strnicmp(value, "krb5", 4) == 0) {
vol->secFlg |= CIFSSEC_MAY_KRB5;
} else if (strnicmp(value, "ntlmsspi", 8) == 0) {
vol->secFlg |= CIFSSEC_MAY_NTLMSSP |
CIFSSEC_MUST_SIGN;
} else if (strnicmp(value, "ntlmssp", 7) == 0) {
vol->secFlg |= CIFSSEC_MAY_NTLMSSP;
} else if (strnicmp(value, "ntlmv2i", 7) == 0) {
vol->secFlg |= CIFSSEC_MAY_NTLMV2 |
CIFSSEC_MUST_SIGN;
} else if (strnicmp(value, "ntlmv2", 6) == 0) {
vol->secFlg |= CIFSSEC_MAY_NTLMV2;
} else if (strnicmp(value, "ntlmi", 5) == 0) {
vol->secFlg |= CIFSSEC_MAY_NTLM |
CIFSSEC_MUST_SIGN;
} else if (strnicmp(value, "ntlm", 4) == 0) {
/* ntlm is default so can be turned off too */
vol->secFlg |= CIFSSEC_MAY_NTLM;
} else if (strnicmp(value, "nontlm", 6) == 0) {
/* BB is there a better way to do this? */
vol->secFlg |= CIFSSEC_MAY_NTLMV2;
#ifdef CONFIG_CIFS_WEAK_PW_HASH
} else if (strnicmp(value, "lanman", 6) == 0) {
vol->secFlg |= CIFSSEC_MAY_LANMAN;
#endif
} else if (strnicmp(value, "none", 4) == 0) {
vol->nullauth = 1;
} else {
cERROR(1, "bad security option: %s", value);
return 1;
}
} else if ((strnicmp(data, "unc", 3) == 0)
|| (strnicmp(data, "target", 6) == 0)
|| (strnicmp(data, "path", 4) == 0)) {
if (!value || !*value) {
printk(KERN_WARNING "CIFS: invalid path to "
"network resource\n");
return 1; /* needs_arg; */
}
if ((temp_len = strnlen(value, 300)) < 300) {
vol->UNC = kmalloc(temp_len+1, GFP_KERNEL);
if (vol->UNC == NULL)
return 1;
strcpy(vol->UNC, value);
if (strncmp(vol->UNC, "//", 2) == 0) {
vol->UNC[0] = '\\';
vol->UNC[1] = '\\';
} else if (strncmp(vol->UNC, "\\\\", 2) != 0) {
printk(KERN_WARNING
"CIFS: UNC Path does not begin "
"with // or \\\\ \n");
return 1;
}
} else {
printk(KERN_WARNING "CIFS: UNC name too long\n");
return 1;
}
} else if ((strnicmp(data, "domain", 3) == 0)
|| (strnicmp(data, "workgroup", 5) == 0)) {
if (!value || !*value) {
printk(KERN_WARNING "CIFS: invalid domain name\n");
return 1; /* needs_arg; */
}
/* BB are there cases in which a comma can be valid in
a domain name and need special handling? */
if (strnlen(value, 256) < 256) {
vol->domainname = value;
cFYI(1, "Domain name set");
} else {
printk(KERN_WARNING "CIFS: domain name too "
"long\n");
return 1;
}
} else if (strnicmp(data, "srcaddr", 7) == 0) {
vol->srcaddr.ss_family = AF_UNSPEC;
if (!value || !*value) {
printk(KERN_WARNING "CIFS: srcaddr value"
" not specified.\n");
return 1; /* needs_arg; */
}
i = cifs_convert_address((struct sockaddr *)&vol->srcaddr,
value, strlen(value));
if (i == 0) {
printk(KERN_WARNING "CIFS: Could not parse"
" srcaddr: %s\n",
value);
return 1;
}
} else if (strnicmp(data, "prefixpath", 10) == 0) {
if (!value || !*value) {
printk(KERN_WARNING
"CIFS: invalid path prefix\n");
return 1; /* needs_argument */
}
if ((temp_len = strnlen(value, 1024)) < 1024) {
if (value[0] != '/')
temp_len++; /* missing leading slash */
vol->prepath = kmalloc(temp_len+1, GFP_KERNEL);
if (vol->prepath == NULL)
return 1;
if (value[0] != '/') {
vol->prepath[0] = '/';
strcpy(vol->prepath+1, value);
} else
strcpy(vol->prepath, value);
cFYI(1, "prefix path %s", vol->prepath);
} else {
printk(KERN_WARNING "CIFS: prefix too long\n");
return 1;
}
} else if (strnicmp(data, "iocharset", 9) == 0) {
if (!value || !*value) {
printk(KERN_WARNING "CIFS: invalid iocharset "
"specified\n");
return 1; /* needs_arg; */
}
if (strnlen(value, 65) < 65) {
if (strnicmp(value, "default", 7))
vol->iocharset = value;
/* if iocharset not set then load_nls_default
is used by caller */
cFYI(1, "iocharset set to %s", value);
} else {
printk(KERN_WARNING "CIFS: iocharset name "
"too long.\n");
return 1;
}
} else if (!strnicmp(data, "uid", 3) && value && *value) {
vol->linux_uid = simple_strtoul(value, &value, 0);
uid_specified = true;
} else if (!strnicmp(data, "cruid", 5) && value && *value) {
vol->cred_uid = simple_strtoul(value, &value, 0);
} else if (!strnicmp(data, "forceuid", 8)) {
override_uid = 1;
} else if (!strnicmp(data, "noforceuid", 10)) {
override_uid = 0;
} else if (!strnicmp(data, "gid", 3) && value && *value) {
vol->linux_gid = simple_strtoul(value, &value, 0);
gid_specified = true;
} else if (!strnicmp(data, "forcegid", 8)) {
override_gid = 1;
} else if (!strnicmp(data, "noforcegid", 10)) {
override_gid = 0;
} else if (strnicmp(data, "file_mode", 4) == 0) {
if (value && *value) {
vol->file_mode =
simple_strtoul(value, &value, 0);
}
} else if (strnicmp(data, "dir_mode", 4) == 0) {
if (value && *value) {
vol->dir_mode =
simple_strtoul(value, &value, 0);
}
} else if (strnicmp(data, "dirmode", 4) == 0) {
if (value && *value) {
vol->dir_mode =
simple_strtoul(value, &value, 0);
}
} else if (strnicmp(data, "port", 4) == 0) {
if (value && *value) {
vol->port =
simple_strtoul(value, &value, 0);
}
} else if (strnicmp(data, "rsize", 5) == 0) {
if (value && *value) {
vol->rsize =
simple_strtoul(value, &value, 0);
}
} else if (strnicmp(data, "wsize", 5) == 0) {
if (value && *value) {
vol->wsize =
simple_strtoul(value, &value, 0);
}
} else if (strnicmp(data, "sockopt", 5) == 0) {
if (!value || !*value) {
cERROR(1, "no socket option specified");
continue;
} else if (strnicmp(value, "TCP_NODELAY", 11) == 0) {
vol->sockopt_tcp_nodelay = 1;
}
} else if (strnicmp(data, "netbiosname", 4) == 0) {
if (!value || !*value || (*value == ' ')) {
cFYI(1, "invalid (empty) netbiosname");
} else {
memset(vol->source_rfc1001_name, 0x20,
RFC1001_NAME_LEN);
/*
* FIXME: are there cases in which a comma can
* be valid in workstation netbios name (and
* need special handling)?
*/
for (i = 0; i < RFC1001_NAME_LEN; i++) {
/* don't ucase netbiosname for user */
if (value[i] == 0)
break;
vol->source_rfc1001_name[i] = value[i];
}
/* The string has 16th byte zero still from
set at top of the function */
if (i == RFC1001_NAME_LEN && value[i] != 0)
printk(KERN_WARNING "CIFS: netbiosname"
" longer than 15 truncated.\n");
}
} else if (strnicmp(data, "servern", 7) == 0) {
/* servernetbiosname specified override *SMBSERVER */
if (!value || !*value || (*value == ' ')) {
cFYI(1, "empty server netbiosname specified");
} else {
/* last byte, type, is 0x20 for servr type */
memset(vol->target_rfc1001_name, 0x20,
RFC1001_NAME_LEN_WITH_NULL);
for (i = 0; i < 15; i++) {
/* BB are there cases in which a comma can be
valid in this workstation netbios name
(and need special handling)? */
/* user or mount helper must uppercase
the netbiosname */
if (value[i] == 0)
break;
else
vol->target_rfc1001_name[i] =
value[i];
}
/* The string has 16th byte zero still from
set at top of the function */
if (i == RFC1001_NAME_LEN && value[i] != 0)
printk(KERN_WARNING "CIFS: server net"
"biosname longer than 15 truncated.\n");
}
} else if (strnicmp(data, "actimeo", 7) == 0) {
if (value && *value) {
vol->actimeo = HZ * simple_strtoul(value,
&value, 0);
if (vol->actimeo > CIFS_MAX_ACTIMEO) {
cERROR(1, "CIFS: attribute cache"
"timeout too large");
return 1;
}
}
} else if (strnicmp(data, "credentials", 4) == 0) {
/* ignore */
} else if (strnicmp(data, "version", 3) == 0) {
/* ignore */
} else if (strnicmp(data, "guest", 5) == 0) {
/* ignore */
} else if (strnicmp(data, "rw", 2) == 0) {
/* ignore */
} else if (strnicmp(data, "ro", 2) == 0) {
/* ignore */
} else if (strnicmp(data, "noblocksend", 11) == 0) {
vol->noblocksnd = 1;
} else if (strnicmp(data, "noautotune", 10) == 0) {
vol->noautotune = 1;
} else if ((strnicmp(data, "suid", 4) == 0) ||
(strnicmp(data, "nosuid", 6) == 0) ||
(strnicmp(data, "exec", 4) == 0) ||
(strnicmp(data, "noexec", 6) == 0) ||
(strnicmp(data, "nodev", 5) == 0) ||
(strnicmp(data, "noauto", 6) == 0) ||
(strnicmp(data, "dev", 3) == 0)) {
/* The mount tool or mount.cifs helper (if present)
uses these opts to set flags, and the flags are read
by the kernel vfs layer before we get here (ie
before read super) so there is no point trying to
parse these options again and set anything and it
is ok to just ignore them */
continue;
} else if (strnicmp(data, "hard", 4) == 0) {
vol->retry = 1;
} else if (strnicmp(data, "soft", 4) == 0) {
vol->retry = 0;
} else if (strnicmp(data, "perm", 4) == 0) {
vol->noperm = 0;
} else if (strnicmp(data, "noperm", 6) == 0) {
vol->noperm = 1;
} else if (strnicmp(data, "mapchars", 8) == 0) {
vol->remap = 1;
} else if (strnicmp(data, "nomapchars", 10) == 0) {
vol->remap = 0;
} else if (strnicmp(data, "sfu", 3) == 0) {
vol->sfu_emul = 1;
} else if (strnicmp(data, "nosfu", 5) == 0) {
vol->sfu_emul = 0;
} else if (strnicmp(data, "nodfs", 5) == 0) {
vol->nodfs = 1;
} else if (strnicmp(data, "posixpaths", 10) == 0) {
vol->posix_paths = 1;
} else if (strnicmp(data, "noposixpaths", 12) == 0) {
vol->posix_paths = 0;
} else if (strnicmp(data, "nounix", 6) == 0) {
vol->no_linux_ext = 1;
} else if (strnicmp(data, "nolinux", 7) == 0) {
vol->no_linux_ext = 1;
} else if ((strnicmp(data, "nocase", 6) == 0) ||
(strnicmp(data, "ignorecase", 10) == 0)) {
vol->nocase = 1;
} else if (strnicmp(data, "mand", 4) == 0) {
/* ignore */
} else if (strnicmp(data, "nomand", 6) == 0) {
/* ignore */
} else if (strnicmp(data, "_netdev", 7) == 0) {
/* ignore */
} else if (strnicmp(data, "brl", 3) == 0) {
vol->nobrl = 0;
} else if ((strnicmp(data, "nobrl", 5) == 0) ||
(strnicmp(data, "nolock", 6) == 0)) {
vol->nobrl = 1;
/* turn off mandatory locking in mode
if remote locking is turned off since the
local vfs will do advisory */
if (vol->file_mode ==
(S_IALLUGO & ~(S_ISUID | S_IXGRP)))
vol->file_mode = S_IALLUGO;
} else if (strnicmp(data, "forcemandatorylock", 9) == 0) {
/* will take the shorter form "forcemand" as well */
/* This mount option will force use of mandatory
(DOS/Windows style) byte range locks, instead of
using posix advisory byte range locks, even if the
Unix extensions are available and posix locks would
be supported otherwise. If Unix extensions are not
negotiated this has no effect since mandatory locks
would be used (mandatory locks is all that those
those servers support) */
vol->mand_lock = 1;
} else if (strnicmp(data, "setuids", 7) == 0) {
vol->setuids = 1;
} else if (strnicmp(data, "nosetuids", 9) == 0) {
vol->setuids = 0;
} else if (strnicmp(data, "dynperm", 7) == 0) {
vol->dynperm = true;
} else if (strnicmp(data, "nodynperm", 9) == 0) {
vol->dynperm = false;
} else if (strnicmp(data, "nohard", 6) == 0) {
vol->retry = 0;
} else if (strnicmp(data, "nosoft", 6) == 0) {
vol->retry = 1;
} else if (strnicmp(data, "nointr", 6) == 0) {
vol->intr = 0;
} else if (strnicmp(data, "intr", 4) == 0) {
vol->intr = 1;
} else if (strnicmp(data, "nostrictsync", 12) == 0) {
vol->nostrictsync = 1;
} else if (strnicmp(data, "strictsync", 10) == 0) {
vol->nostrictsync = 0;
} else if (strnicmp(data, "serverino", 7) == 0) {
vol->server_ino = 1;
} else if (strnicmp(data, "noserverino", 9) == 0) {
vol->server_ino = 0;
} else if (strnicmp(data, "cifsacl", 7) == 0) {
vol->cifs_acl = 1;
} else if (strnicmp(data, "nocifsacl", 9) == 0) {
vol->cifs_acl = 0;
} else if (strnicmp(data, "acl", 3) == 0) {
vol->no_psx_acl = 0;
} else if (strnicmp(data, "noacl", 5) == 0) {
vol->no_psx_acl = 1;
} else if (strnicmp(data, "locallease", 6) == 0) {
vol->local_lease = 1;
} else if (strnicmp(data, "sign", 4) == 0) {
vol->secFlg |= CIFSSEC_MUST_SIGN;
} else if (strnicmp(data, "seal", 4) == 0) {
/* we do not do the following in secFlags because seal
is a per tree connection (mount) not a per socket
or per-smb connection option in the protocol */
/* vol->secFlg |= CIFSSEC_MUST_SEAL; */
vol->seal = 1;
} else if (strnicmp(data, "direct", 6) == 0) {
vol->direct_io = 1;
} else if (strnicmp(data, "forcedirectio", 13) == 0) {
vol->direct_io = 1;
} else if (strnicmp(data, "strictcache", 11) == 0) {
vol->strict_io = 1;
} else if (strnicmp(data, "noac", 4) == 0) {
printk(KERN_WARNING "CIFS: Mount option noac not "
"supported. Instead set "
"/proc/fs/cifs/LookupCacheEnabled to 0\n");
} else if (strnicmp(data, "fsc", 3) == 0) {
#ifndef CONFIG_CIFS_FSCACHE
cERROR(1, "FS-Cache support needs CONFIG_CIFS_FSCACHE"
"kernel config option set");
return 1;
#endif
vol->fsc = true;
} else if (strnicmp(data, "mfsymlinks", 10) == 0) {
vol->mfsymlinks = true;
} else if (strnicmp(data, "multiuser", 8) == 0) {
vol->multiuser = true;
} else
printk(KERN_WARNING "CIFS: Unknown mount option %s\n",
data);
}
if (vol->UNC == NULL) {
if (devname == NULL) {
printk(KERN_WARNING "CIFS: Missing UNC name for mount "
"target\n");
return 1;
}
if ((temp_len = strnlen(devname, 300)) < 300) {
vol->UNC = kmalloc(temp_len+1, GFP_KERNEL);
if (vol->UNC == NULL)
return 1;
strcpy(vol->UNC, devname);
if (strncmp(vol->UNC, "//", 2) == 0) {
vol->UNC[0] = '\\';
vol->UNC[1] = '\\';
} else if (strncmp(vol->UNC, "\\\\", 2) != 0) {
printk(KERN_WARNING "CIFS: UNC Path does not "
"begin with // or \\\\ \n");
return 1;
}
value = strpbrk(vol->UNC+2, "/\\");
if (value)
*value = '\\';
} else {
printk(KERN_WARNING "CIFS: UNC name too long\n");
return 1;
}
}
if (vol->multiuser && !(vol->secFlg & CIFSSEC_MAY_KRB5)) {
cERROR(1, "Multiuser mounts currently require krb5 "
"authentication!");
return 1;
}
if (vol->UNCip == NULL)
vol->UNCip = &vol->UNC[2];
if (uid_specified)
vol->override_uid = override_uid;
else if (override_uid == 1)
printk(KERN_NOTICE "CIFS: ignoring forceuid mount option "
"specified with no uid= option.\n");
if (gid_specified)
vol->override_gid = override_gid;
else if (override_gid == 1)
printk(KERN_NOTICE "CIFS: ignoring forcegid mount option "
"specified with no gid= option.\n");
return 0;
}
/** Returns true if srcaddr isn't specified and rhs isn't
* specified, or if srcaddr is specified and
* matches the IP address of the rhs argument.
*/
static bool
srcip_matches(struct sockaddr *srcaddr, struct sockaddr *rhs)
{
switch (srcaddr->sa_family) {
case AF_UNSPEC:
return (rhs->sa_family == AF_UNSPEC);
case AF_INET: {
struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
}
case AF_INET6: {
struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)&rhs;
return ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr);
}
default:
WARN_ON(1);
return false; /* don't expect to be here */
}
}
/*
* If no port is specified in addr structure, we try to match with 445 port
* and if it fails - with 139 ports. It should be called only if address
* families of server and addr are equal.
*/
static bool
match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
{
__be16 port, *sport;
switch (addr->sa_family) {
case AF_INET:
sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
port = ((struct sockaddr_in *) addr)->sin_port;
break;
case AF_INET6:
sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
port = ((struct sockaddr_in6 *) addr)->sin6_port;
break;
default:
WARN_ON(1);
return false;
}
if (!port) {
port = htons(CIFS_PORT);
if (port == *sport)
return true;
port = htons(RFC1001_PORT);
}
return port == *sport;
}
static bool
match_address(struct TCP_Server_Info *server, struct sockaddr *addr,
struct sockaddr *srcaddr)
{
switch (addr->sa_family) {
case AF_INET: {
struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
struct sockaddr_in *srv_addr4 =
(struct sockaddr_in *)&server->dstaddr;
if (addr4->sin_addr.s_addr != srv_addr4->sin_addr.s_addr)
return false;
break;
}
case AF_INET6: {
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
struct sockaddr_in6 *srv_addr6 =
(struct sockaddr_in6 *)&server->dstaddr;
if (!ipv6_addr_equal(&addr6->sin6_addr,
&srv_addr6->sin6_addr))
return false;
if (addr6->sin6_scope_id != srv_addr6->sin6_scope_id)
return false;
break;
}
default:
WARN_ON(1);
return false; /* don't expect to be here */
}
if (!srcip_matches(srcaddr, (struct sockaddr *)&server->srcaddr))
return false;
return true;
}
static bool
match_security(struct TCP_Server_Info *server, struct smb_vol *vol)
{
unsigned int secFlags;
if (vol->secFlg & (~(CIFSSEC_MUST_SIGN | CIFSSEC_MUST_SEAL)))
secFlags = vol->secFlg;
else
secFlags = global_secflags | vol->secFlg;
switch (server->secType) {
case LANMAN:
if (!(secFlags & (CIFSSEC_MAY_LANMAN|CIFSSEC_MAY_PLNTXT)))
return false;
break;
case NTLMv2:
if (!(secFlags & CIFSSEC_MAY_NTLMV2))
return false;
break;
case NTLM:
if (!(secFlags & CIFSSEC_MAY_NTLM))
return false;
break;
case Kerberos:
if (!(secFlags & CIFSSEC_MAY_KRB5))
return false;
break;
case RawNTLMSSP:
if (!(secFlags & CIFSSEC_MAY_NTLMSSP))
return false;
break;
default:
/* shouldn't happen */
return false;
}
/* now check if signing mode is acceptable */
if ((secFlags & CIFSSEC_MAY_SIGN) == 0 &&
(server->secMode & SECMODE_SIGN_REQUIRED))
return false;
else if (((secFlags & CIFSSEC_MUST_SIGN) == CIFSSEC_MUST_SIGN) &&
(server->secMode &
(SECMODE_SIGN_ENABLED|SECMODE_SIGN_REQUIRED)) == 0)
return false;
return true;
}
static struct TCP_Server_Info *
cifs_find_tcp_session(struct sockaddr *addr, struct smb_vol *vol)
{
struct TCP_Server_Info *server;
spin_lock(&cifs_tcp_ses_lock);
list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
continue;
if (!match_address(server, addr,
(struct sockaddr *)&vol->srcaddr))
continue;
if (!match_port(server, addr))
continue;
if (!match_security(server, vol))
continue;
++server->srv_count;
spin_unlock(&cifs_tcp_ses_lock);
cFYI(1, "Existing tcp session with server found");
return server;
}
spin_unlock(&cifs_tcp_ses_lock);
return NULL;
}
static void
cifs_put_tcp_session(struct TCP_Server_Info *server)
{
struct task_struct *task;
spin_lock(&cifs_tcp_ses_lock);
if (--server->srv_count > 0) {
spin_unlock(&cifs_tcp_ses_lock);
return;
}
put_net(cifs_net_ns(server));
list_del_init(&server->tcp_ses_list);
spin_unlock(&cifs_tcp_ses_lock);
cancel_delayed_work_sync(&server->echo);
spin_lock(&GlobalMid_Lock);
server->tcpStatus = CifsExiting;
spin_unlock(&GlobalMid_Lock);
cifs_crypto_shash_release(server);
cifs_fscache_release_client_cookie(server);
kfree(server->session_key.response);
server->session_key.response = NULL;
server->session_key.len = 0;
task = xchg(&server->tsk, NULL);
if (task)
force_sig(SIGKILL, task);
}
static struct TCP_Server_Info *
cifs_get_tcp_session(struct smb_vol *volume_info)
{
struct TCP_Server_Info *tcp_ses = NULL;
struct sockaddr_storage addr;
struct sockaddr_in *sin_server = (struct sockaddr_in *) &addr;
struct sockaddr_in6 *sin_server6 = (struct sockaddr_in6 *) &addr;
int rc;
memset(&addr, 0, sizeof(struct sockaddr_storage));
cFYI(1, "UNC: %s ip: %s", volume_info->UNC, volume_info->UNCip);
if (volume_info->UNCip && volume_info->UNC) {
rc = cifs_fill_sockaddr((struct sockaddr *)&addr,
volume_info->UNCip,
strlen(volume_info->UNCip),
volume_info->port);
if (!rc) {
/* we failed translating address */
rc = -EINVAL;
goto out_err;
}
} else if (volume_info->UNCip) {
/* BB using ip addr as tcp_ses name to connect to the
DFS root below */
cERROR(1, "Connecting to DFS root not implemented yet");
rc = -EINVAL;
goto out_err;
} else /* which tcp_sess DFS root would we conect to */ {
cERROR(1, "CIFS mount error: No UNC path (e.g. -o "
"unc=//192.168.1.100/public) specified");
rc = -EINVAL;
goto out_err;
}
/* see if we already have a matching tcp_ses */
tcp_ses = cifs_find_tcp_session((struct sockaddr *)&addr, volume_info);
if (tcp_ses)
return tcp_ses;
tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
if (!tcp_ses) {
rc = -ENOMEM;
goto out_err;
}
rc = cifs_crypto_shash_allocate(tcp_ses);
if (rc) {
cERROR(1, "could not setup hash structures rc %d", rc);
goto out_err;
}
cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
tcp_ses->hostname = extract_hostname(volume_info->UNC);
if (IS_ERR(tcp_ses->hostname)) {
rc = PTR_ERR(tcp_ses->hostname);
goto out_err_crypto_release;
}
tcp_ses->noblocksnd = volume_info->noblocksnd;
tcp_ses->noautotune = volume_info->noautotune;
tcp_ses->tcp_nodelay = volume_info->sockopt_tcp_nodelay;
atomic_set(&tcp_ses->inFlight, 0);
init_waitqueue_head(&tcp_ses->response_q);
init_waitqueue_head(&tcp_ses->request_q);
INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
mutex_init(&tcp_ses->srv_mutex);
memcpy(tcp_ses->workstation_RFC1001_name,
volume_info->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
memcpy(tcp_ses->server_RFC1001_name,
volume_info->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
tcp_ses->session_estab = false;
tcp_ses->sequence_number = 0;
tcp_ses->lstrp = jiffies;
INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
/*
* at this point we are the only ones with the pointer
* to the struct since the kernel thread not created yet
* no need to spinlock this init of tcpStatus or srv_count
*/
tcp_ses->tcpStatus = CifsNew;
memcpy(&tcp_ses->srcaddr, &volume_info->srcaddr,
sizeof(tcp_ses->srcaddr));
++tcp_ses->srv_count;
if (addr.ss_family == AF_INET6) {
cFYI(1, "attempting ipv6 connect");
/* BB should we allow ipv6 on port 139? */
/* other OS never observed in Wild doing 139 with v6 */
memcpy(&tcp_ses->dstaddr, sin_server6,
sizeof(struct sockaddr_in6));
} else
memcpy(&tcp_ses->dstaddr, sin_server,
sizeof(struct sockaddr_in));
rc = ip_connect(tcp_ses);
if (rc < 0) {
cERROR(1, "Error connecting to socket. Aborting operation");
goto out_err_crypto_release;
}
/*
* since we're in a cifs function already, we know that
* this will succeed. No need for try_module_get().
*/
__module_get(THIS_MODULE);
tcp_ses->tsk = kthread_run((void *)(void *)cifs_demultiplex_thread,
tcp_ses, "cifsd");
if (IS_ERR(tcp_ses->tsk)) {
rc = PTR_ERR(tcp_ses->tsk);
cERROR(1, "error %d create cifsd thread", rc);
module_put(THIS_MODULE);
goto out_err_crypto_release;
}
/* thread spawned, put it on the list */
spin_lock(&cifs_tcp_ses_lock);
list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
spin_unlock(&cifs_tcp_ses_lock);
cifs_fscache_get_client_cookie(tcp_ses);
/* queue echo request delayed work */
queue_delayed_work(system_nrt_wq, &tcp_ses->echo, SMB_ECHO_INTERVAL);
return tcp_ses;
out_err_crypto_release:
cifs_crypto_shash_release(tcp_ses);
put_net(cifs_net_ns(tcp_ses));
out_err:
if (tcp_ses) {
if (!IS_ERR(tcp_ses->hostname))
kfree(tcp_ses->hostname);
if (tcp_ses->ssocket)
sock_release(tcp_ses->ssocket);
kfree(tcp_ses);
}
return ERR_PTR(rc);
}
static struct cifsSesInfo *
cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb_vol *vol)
{
struct cifsSesInfo *ses;
spin_lock(&cifs_tcp_ses_lock);
list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
switch (server->secType) {
case Kerberos:
if (vol->cred_uid != ses->cred_uid)
continue;
break;
default:
/* anything else takes username/password */
if (ses->user_name == NULL)
continue;
if (strncmp(ses->user_name, vol->username,
MAX_USERNAME_SIZE))
continue;
if (strlen(vol->username) != 0 &&
ses->password != NULL &&
strncmp(ses->password,
vol->password ? vol->password : "",
MAX_PASSWORD_SIZE))
continue;
}
++ses->ses_count;
spin_unlock(&cifs_tcp_ses_lock);
return ses;
}
spin_unlock(&cifs_tcp_ses_lock);
return NULL;
}
static void
cifs_put_smb_ses(struct cifsSesInfo *ses)
{
int xid;
struct TCP_Server_Info *server = ses->server;
cFYI(1, "%s: ses_count=%d\n", __func__, ses->ses_count);
spin_lock(&cifs_tcp_ses_lock);
if (--ses->ses_count > 0) {
spin_unlock(&cifs_tcp_ses_lock);
return;
}
list_del_init(&ses->smb_ses_list);
spin_unlock(&cifs_tcp_ses_lock);
if (ses->status == CifsGood) {
xid = GetXid();
CIFSSMBLogoff(xid, ses);
_FreeXid(xid);
}
sesInfoFree(ses);
cifs_put_tcp_session(server);
}
static struct cifsSesInfo *
cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb_vol *volume_info)
{
int rc = -ENOMEM, xid;
struct cifsSesInfo *ses;
struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
xid = GetXid();
ses = cifs_find_smb_ses(server, volume_info);
if (ses) {
cFYI(1, "Existing smb sess found (status=%d)", ses->status);
mutex_lock(&ses->session_mutex);
rc = cifs_negotiate_protocol(xid, ses);
if (rc) {
mutex_unlock(&ses->session_mutex);
/* problem -- put our ses reference */
cifs_put_smb_ses(ses);
FreeXid(xid);
return ERR_PTR(rc);
}
if (ses->need_reconnect) {
cFYI(1, "Session needs reconnect");
rc = cifs_setup_session(xid, ses,
volume_info->local_nls);
if (rc) {
mutex_unlock(&ses->session_mutex);
/* problem -- put our reference */
cifs_put_smb_ses(ses);
FreeXid(xid);
return ERR_PTR(rc);
}
}
mutex_unlock(&ses->session_mutex);
/* existing SMB ses has a server reference already */
cifs_put_tcp_session(server);
FreeXid(xid);
return ses;
}
cFYI(1, "Existing smb sess not found");
ses = sesInfoAlloc();
if (ses == NULL)
goto get_ses_fail;
/* new SMB session uses our server ref */
ses->server = server;
if (server->dstaddr.ss_family == AF_INET6)
sprintf(ses->serverName, "%pI6", &addr6->sin6_addr);
else
sprintf(ses->serverName, "%pI4", &addr->sin_addr);
if (volume_info->username) {
ses->user_name = kstrdup(volume_info->username, GFP_KERNEL);
if (!ses->user_name)
goto get_ses_fail;
}
/* volume_info->password freed at unmount */
if (volume_info->password) {
ses->password = kstrdup(volume_info->password, GFP_KERNEL);
if (!ses->password)
goto get_ses_fail;
}
if (volume_info->domainname) {
ses->domainName = kstrdup(volume_info->domainname, GFP_KERNEL);
if (!ses->domainName)
goto get_ses_fail;
}
ses->cred_uid = volume_info->cred_uid;
ses->linux_uid = volume_info->linux_uid;
ses->overrideSecFlg = volume_info->secFlg;
mutex_lock(&ses->session_mutex);
rc = cifs_negotiate_protocol(xid, ses);
if (!rc)
rc = cifs_setup_session(xid, ses, volume_info->local_nls);
mutex_unlock(&ses->session_mutex);
if (rc)
goto get_ses_fail;
/* success, put it on the list */
spin_lock(&cifs_tcp_ses_lock);
list_add(&ses->smb_ses_list, &server->smb_ses_list);
spin_unlock(&cifs_tcp_ses_lock);
FreeXid(xid);
return ses;
get_ses_fail:
sesInfoFree(ses);
FreeXid(xid);
return ERR_PTR(rc);
}
static struct cifsTconInfo *
cifs_find_tcon(struct cifsSesInfo *ses, const char *unc)
{
struct list_head *tmp;
struct cifsTconInfo *tcon;
spin_lock(&cifs_tcp_ses_lock);
list_for_each(tmp, &ses->tcon_list) {
tcon = list_entry(tmp, struct cifsTconInfo, tcon_list);
if (tcon->tidStatus == CifsExiting)
continue;
if (strncmp(tcon->treeName, unc, MAX_TREE_SIZE))
continue;
++tcon->tc_count;
spin_unlock(&cifs_tcp_ses_lock);
return tcon;
}
spin_unlock(&cifs_tcp_ses_lock);
return NULL;
}
static void
cifs_put_tcon(struct cifsTconInfo *tcon)
{
int xid;
struct cifsSesInfo *ses = tcon->ses;
cFYI(1, "%s: tc_count=%d\n", __func__, tcon->tc_count);
spin_lock(&cifs_tcp_ses_lock);
if (--tcon->tc_count > 0) {
spin_unlock(&cifs_tcp_ses_lock);
return;
}
list_del_init(&tcon->tcon_list);
spin_unlock(&cifs_tcp_ses_lock);
xid = GetXid();
CIFSSMBTDis(xid, tcon);
_FreeXid(xid);
cifs_fscache_release_super_cookie(tcon);
tconInfoFree(tcon);
cifs_put_smb_ses(ses);
}
static struct cifsTconInfo *
cifs_get_tcon(struct cifsSesInfo *ses, struct smb_vol *volume_info)
{
int rc, xid;
struct cifsTconInfo *tcon;
tcon = cifs_find_tcon(ses, volume_info->UNC);
if (tcon) {
cFYI(1, "Found match on UNC path");
/* existing tcon already has a reference */
cifs_put_smb_ses(ses);
if (tcon->seal != volume_info->seal)
cERROR(1, "transport encryption setting "
"conflicts with existing tid");
return tcon;
}
tcon = tconInfoAlloc();
if (tcon == NULL) {
rc = -ENOMEM;
goto out_fail;
}
tcon->ses = ses;
if (volume_info->password) {
tcon->password = kstrdup(volume_info->password, GFP_KERNEL);
if (!tcon->password) {
rc = -ENOMEM;
goto out_fail;
}
}
if (strchr(volume_info->UNC + 3, '\\') == NULL
&& strchr(volume_info->UNC + 3, '/') == NULL) {
cERROR(1, "Missing share name");
rc = -ENODEV;
goto out_fail;
}
/* BB Do we need to wrap session_mutex around
* this TCon call and Unix SetFS as
* we do on SessSetup and reconnect? */
xid = GetXid();
rc = CIFSTCon(xid, ses, volume_info->UNC, tcon, volume_info->local_nls);
FreeXid(xid);
cFYI(1, "CIFS Tcon rc = %d", rc);
if (rc)
goto out_fail;
if (volume_info->nodfs) {
tcon->Flags &= ~SMB_SHARE_IS_IN_DFS;
cFYI(1, "DFS disabled (%d)", tcon->Flags);
}
tcon->seal = volume_info->seal;
/* we can have only one retry value for a connection
to a share so for resources mounted more than once
to the same server share the last value passed in
for the retry flag is used */
tcon->retry = volume_info->retry;
tcon->nocase = volume_info->nocase;
tcon->local_lease = volume_info->local_lease;
spin_lock(&cifs_tcp_ses_lock);
list_add(&tcon->tcon_list, &ses->tcon_list);
spin_unlock(&cifs_tcp_ses_lock);
cifs_fscache_get_super_cookie(tcon);
return tcon;
out_fail:
tconInfoFree(tcon);
return ERR_PTR(rc);
}
void
cifs_put_tlink(struct tcon_link *tlink)
{
if (!tlink || IS_ERR(tlink))
return;
if (!atomic_dec_and_test(&tlink->tl_count) ||
test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
tlink->tl_time = jiffies;
return;
}
if (!IS_ERR(tlink_tcon(tlink)))
cifs_put_tcon(tlink_tcon(tlink));
kfree(tlink);
return;
}
int
get_dfs_path(int xid, struct cifsSesInfo *pSesInfo, const char *old_path,
const struct nls_table *nls_codepage, unsigned int *pnum_referrals,
struct dfs_info3_param **preferrals, int remap)
{
char *temp_unc;
int rc = 0;
*pnum_referrals = 0;
*preferrals = NULL;
if (pSesInfo->ipc_tid == 0) {
temp_unc = kmalloc(2 /* for slashes */ +
strnlen(pSesInfo->serverName,
SERVER_NAME_LEN_WITH_NULL * 2)
+ 1 + 4 /* slash IPC$ */ + 2,
GFP_KERNEL);
if (temp_unc == NULL)
return -ENOMEM;
temp_unc[0] = '\\';
temp_unc[1] = '\\';
strcpy(temp_unc + 2, pSesInfo->serverName);
strcpy(temp_unc + 2 + strlen(pSesInfo->serverName), "\\IPC$");
rc = CIFSTCon(xid, pSesInfo, temp_unc, NULL, nls_codepage);
cFYI(1, "CIFS Tcon rc = %d ipc_tid = %d", rc, pSesInfo->ipc_tid);
kfree(temp_unc);
}
if (rc == 0)
rc = CIFSGetDFSRefer(xid, pSesInfo, old_path, preferrals,
pnum_referrals, nls_codepage, remap);
/* BB map targetUNCs to dfs_info3 structures, here or
in CIFSGetDFSRefer BB */
return rc;
}
#ifdef CONFIG_DEBUG_LOCK_ALLOC
static struct lock_class_key cifs_key[2];
static struct lock_class_key cifs_slock_key[2];
static inline void
cifs_reclassify_socket4(struct socket *sock)
{
struct sock *sk = sock->sk;
BUG_ON(sock_owned_by_user(sk));
sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
&cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
}
static inline void
cifs_reclassify_socket6(struct socket *sock)
{
struct sock *sk = sock->sk;
BUG_ON(sock_owned_by_user(sk));
sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
&cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
}
#else
static inline void
cifs_reclassify_socket4(struct socket *sock)
{
}
static inline void
cifs_reclassify_socket6(struct socket *sock)
{
}
#endif
/* See RFC1001 section 14 on representation of Netbios names */
static void rfc1002mangle(char *target, char *source, unsigned int length)
{
unsigned int i, j;
for (i = 0, j = 0; i < (length); i++) {
/* mask a nibble at a time and encode */
target[j] = 'A' + (0x0F & (source[i] >> 4));
target[j+1] = 'A' + (0x0F & source[i]);
j += 2;
}
}
static int
bind_socket(struct TCP_Server_Info *server)
{
int rc = 0;
if (server->srcaddr.ss_family != AF_UNSPEC) {
/* Bind to the specified local IP address */
struct socket *socket = server->ssocket;
rc = socket->ops->bind(socket,
(struct sockaddr *) &server->srcaddr,
sizeof(server->srcaddr));
if (rc < 0) {
struct sockaddr_in *saddr4;
struct sockaddr_in6 *saddr6;
saddr4 = (struct sockaddr_in *)&server->srcaddr;
saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
if (saddr6->sin6_family == AF_INET6)
cERROR(1, "cifs: "
"Failed to bind to: %pI6c, error: %d\n",
&saddr6->sin6_addr, rc);
else
cERROR(1, "cifs: "
"Failed to bind to: %pI4, error: %d\n",
&saddr4->sin_addr.s_addr, rc);
}
}
return rc;
}
static int
ip_rfc1001_connect(struct TCP_Server_Info *server)
{
int rc = 0;
/*
* some servers require RFC1001 sessinit before sending
* negprot - BB check reconnection in case where second
* sessinit is sent but no second negprot
*/
struct rfc1002_session_packet *ses_init_buf;
struct smb_hdr *smb_buf;
ses_init_buf = kzalloc(sizeof(struct rfc1002_session_packet),
GFP_KERNEL);
if (ses_init_buf) {
ses_init_buf->trailer.session_req.called_len = 32;
if (server->server_RFC1001_name &&
server->server_RFC1001_name[0] != 0)
rfc1002mangle(ses_init_buf->trailer.
session_req.called_name,
server->server_RFC1001_name,
RFC1001_NAME_LEN_WITH_NULL);
else
rfc1002mangle(ses_init_buf->trailer.
session_req.called_name,
DEFAULT_CIFS_CALLED_NAME,
RFC1001_NAME_LEN_WITH_NULL);
ses_init_buf->trailer.session_req.calling_len = 32;
/*
* calling name ends in null (byte 16) from old smb
* convention.
*/
if (server->workstation_RFC1001_name &&
server->workstation_RFC1001_name[0] != 0)
rfc1002mangle(ses_init_buf->trailer.
session_req.calling_name,
server->workstation_RFC1001_name,
RFC1001_NAME_LEN_WITH_NULL);
else
rfc1002mangle(ses_init_buf->trailer.
session_req.calling_name,
"LINUX_CIFS_CLNT",
RFC1001_NAME_LEN_WITH_NULL);
ses_init_buf->trailer.session_req.scope1 = 0;
ses_init_buf->trailer.session_req.scope2 = 0;
smb_buf = (struct smb_hdr *)ses_init_buf;
/* sizeof RFC1002_SESSION_REQUEST with no scope */
smb_buf->smb_buf_length = 0x81000044;
rc = smb_send(server, smb_buf, 0x44);
kfree(ses_init_buf);
/*
* RFC1001 layer in at least one server
* requires very short break before negprot
* presumably because not expecting negprot
* to follow so fast. This is a simple
* solution that works without
* complicating the code and causes no
* significant slowing down on mount
* for everyone else
*/
usleep_range(1000, 2000);
}
/*
* else the negprot may still work without this
* even though malloc failed
*/
return rc;
}
static int
generic_ip_connect(struct TCP_Server_Info *server)
{
int rc = 0;
__be16 sport;
int slen, sfamily;
struct socket *socket = server->ssocket;
struct sockaddr *saddr;
saddr = (struct sockaddr *) &server->dstaddr;
if (server->dstaddr.ss_family == AF_INET6) {
sport = ((struct sockaddr_in6 *) saddr)->sin6_port;
slen = sizeof(struct sockaddr_in6);
sfamily = AF_INET6;
} else {
sport = ((struct sockaddr_in *) saddr)->sin_port;
slen = sizeof(struct sockaddr_in);
sfamily = AF_INET;
}
if (socket == NULL) {
rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
IPPROTO_TCP, &socket, 1);
if (rc < 0) {
cERROR(1, "Error %d creating socket", rc);
server->ssocket = NULL;
return rc;
}
/* BB other socket options to set KEEPALIVE, NODELAY? */
cFYI(1, "Socket created");
server->ssocket = socket;
socket->sk->sk_allocation = GFP_NOFS;
if (sfamily == AF_INET6)
cifs_reclassify_socket6(socket);
else
cifs_reclassify_socket4(socket);
}
rc = bind_socket(server);
if (rc < 0)
return rc;
rc = socket->ops->connect(socket, saddr, slen, 0);
if (rc < 0) {
cFYI(1, "Error %d connecting to server", rc);
sock_release(socket);
server->ssocket = NULL;
return rc;
}
/*
* Eventually check for other socket options to change from
* the default. sock_setsockopt not used because it expects
* user space buffer
*/
socket->sk->sk_rcvtimeo = 7 * HZ;
socket->sk->sk_sndtimeo = 5 * HZ;
/* make the bufsizes depend on wsize/rsize and max requests */
if (server->noautotune) {
if (socket->sk->sk_sndbuf < (200 * 1024))
socket->sk->sk_sndbuf = 200 * 1024;
if (socket->sk->sk_rcvbuf < (140 * 1024))
socket->sk->sk_rcvbuf = 140 * 1024;
}
if (server->tcp_nodelay) {
int val = 1;
rc = kernel_setsockopt(socket, SOL_TCP, TCP_NODELAY,
(char *)&val, sizeof(val));
if (rc)
cFYI(1, "set TCP_NODELAY socket option error %d", rc);
}
cFYI(1, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx",
socket->sk->sk_sndbuf,
socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
if (sport == htons(RFC1001_PORT))
rc = ip_rfc1001_connect(server);
return rc;
}
static int
ip_connect(struct TCP_Server_Info *server)
{
__be16 *sport;
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
if (server->dstaddr.ss_family == AF_INET6)
sport = &addr6->sin6_port;
else
sport = &addr->sin_port;
if (*sport == 0) {
int rc;
/* try with 445 port at first */
*sport = htons(CIFS_PORT);
rc = generic_ip_connect(server);
if (rc >= 0)
return rc;
/* if it failed, try with 139 port */
*sport = htons(RFC1001_PORT);
}
return generic_ip_connect(server);
}
void reset_cifs_unix_caps(int xid, struct cifsTconInfo *tcon,
struct super_block *sb, struct smb_vol *vol_info)
{
/* if we are reconnecting then should we check to see if
* any requested capabilities changed locally e.g. via
* remount but we can not do much about it here
* if they have (even if we could detect it by the following)
* Perhaps we could add a backpointer to array of sb from tcon
* or if we change to make all sb to same share the same
* sb as NFS - then we only have one backpointer to sb.
* What if we wanted to mount the server share twice once with
* and once without posixacls or posix paths? */
__u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
if (vol_info && vol_info->no_linux_ext) {
tcon->fsUnixInfo.Capability = 0;
tcon->unix_ext = 0; /* Unix Extensions disabled */
cFYI(1, "Linux protocol extensions disabled");
return;
} else if (vol_info)
tcon->unix_ext = 1; /* Unix Extensions supported */
if (tcon->unix_ext == 0) {
cFYI(1, "Unix extensions disabled so not set on reconnect");
return;
}
if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
__u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
/* check for reconnect case in which we do not
want to change the mount behavior if we can avoid it */
if (vol_info == NULL) {
/* turn off POSIX ACL and PATHNAMES if not set
originally at mount time */
if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
cERROR(1, "POSIXPATH support change");
cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
} else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
cERROR(1, "possible reconnect error");
cERROR(1, "server disabled POSIX path support");
}
}
cap &= CIFS_UNIX_CAP_MASK;
if (vol_info && vol_info->no_psx_acl)
cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
cFYI(1, "negotiated posix acl support");
if (sb)
sb->s_flags |= MS_POSIXACL;
}
if (vol_info && vol_info->posix_paths == 0)
cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
cFYI(1, "negotiate posix pathnames");
if (sb)
CIFS_SB(sb)->mnt_cifs_flags |=
CIFS_MOUNT_POSIX_PATHS;
}
/* We might be setting the path sep back to a different
form if we are reconnecting and the server switched its
posix path capability for this share */
if (sb && (CIFS_SB(sb)->prepathlen > 0))
CIFS_SB(sb)->prepath[0] = CIFS_DIR_SEP(CIFS_SB(sb));
if (sb && (CIFS_SB(sb)->rsize > 127 * 1024)) {
if ((cap & CIFS_UNIX_LARGE_READ_CAP) == 0) {
CIFS_SB(sb)->rsize = 127 * 1024;
cFYI(DBG2, "larger reads not supported by srv");
}
}
cFYI(1, "Negotiate caps 0x%x", (int)cap);
#ifdef CONFIG_CIFS_DEBUG2
if (cap & CIFS_UNIX_FCNTL_CAP)
cFYI(1, "FCNTL cap");
if (cap & CIFS_UNIX_EXTATTR_CAP)
cFYI(1, "EXTATTR cap");
if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
cFYI(1, "POSIX path cap");
if (cap & CIFS_UNIX_XATTR_CAP)
cFYI(1, "XATTR cap");
if (cap & CIFS_UNIX_POSIX_ACL_CAP)
cFYI(1, "POSIX ACL cap");
if (cap & CIFS_UNIX_LARGE_READ_CAP)
cFYI(1, "very large read cap");
if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
cFYI(1, "very large write cap");
#endif /* CIFS_DEBUG2 */
if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
if (vol_info == NULL) {
cFYI(1, "resetting capabilities failed");
} else
cERROR(1, "Negotiating Unix capabilities "
"with the server failed. Consider "
"mounting with the Unix Extensions\n"
"disabled, if problems are found, "
"by specifying the nounix mount "
"option.");
}
}
}
static void
convert_delimiter(char *path, char delim)
{
int i;
char old_delim;
if (path == NULL)
return;
if (delim == '/')
old_delim = '\\';
else
old_delim = '/';
for (i = 0; path[i] != '\0'; i++) {
if (path[i] == old_delim)
path[i] = delim;
}
}
static void setup_cifs_sb(struct smb_vol *pvolume_info,
struct cifs_sb_info *cifs_sb)
{
INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
if (pvolume_info->rsize > CIFSMaxBufSize) {
cERROR(1, "rsize %d too large, using MaxBufSize",
pvolume_info->rsize);
cifs_sb->rsize = CIFSMaxBufSize;
} else if ((pvolume_info->rsize) &&
(pvolume_info->rsize <= CIFSMaxBufSize))
cifs_sb->rsize = pvolume_info->rsize;
else /* default */
cifs_sb->rsize = CIFSMaxBufSize;
if (pvolume_info->wsize > PAGEVEC_SIZE * PAGE_CACHE_SIZE) {
cERROR(1, "wsize %d too large, using 4096 instead",
pvolume_info->wsize);
cifs_sb->wsize = 4096;
} else if (pvolume_info->wsize)
cifs_sb->wsize = pvolume_info->wsize;
else
cifs_sb->wsize = min_t(const int,
PAGEVEC_SIZE * PAGE_CACHE_SIZE,
127*1024);
/* old default of CIFSMaxBufSize was too small now
that SMB Write2 can send multiple pages in kvec.
RFC1001 does not describe what happens when frame
bigger than 128K is sent so use that as max in
conjunction with 52K kvec constraint on arch with 4K
page size */
if (cifs_sb->rsize < 2048) {
cifs_sb->rsize = 2048;
/* Windows ME may prefer this */
cFYI(1, "readsize set to minimum: 2048");
}
/* calculate prepath */
cifs_sb->prepath = pvolume_info->prepath;
if (cifs_sb->prepath) {
cifs_sb->prepathlen = strlen(cifs_sb->prepath);
/* we can not convert the / to \ in the path
separators in the prefixpath yet because we do not
know (until reset_cifs_unix_caps is called later)
whether POSIX PATH CAP is available. We normalize
the / to \ after reset_cifs_unix_caps is called */
pvolume_info->prepath = NULL;
} else
cifs_sb->prepathlen = 0;
cifs_sb->mnt_uid = pvolume_info->linux_uid;
cifs_sb->mnt_gid = pvolume_info->linux_gid;
cifs_sb->mnt_file_mode = pvolume_info->file_mode;
cifs_sb->mnt_dir_mode = pvolume_info->dir_mode;
cFYI(1, "file mode: 0x%x dir mode: 0x%x",
cifs_sb->mnt_file_mode, cifs_sb->mnt_dir_mode);
cifs_sb->actimeo = pvolume_info->actimeo;
if (pvolume_info->noperm)
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_PERM;
if (pvolume_info->setuids)
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_SET_UID;
if (pvolume_info->server_ino)
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_SERVER_INUM;
if (pvolume_info->remap)
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_MAP_SPECIAL_CHR;
if (pvolume_info->no_xattr)
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_XATTR;
if (pvolume_info->sfu_emul)
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_UNX_EMUL;
if (pvolume_info->nobrl)
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_BRL;
if (pvolume_info->nostrictsync)
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NOSSYNC;
if (pvolume_info->mand_lock)
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NOPOSIXBRL;
if (pvolume_info->cifs_acl)
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_CIFS_ACL;
if (pvolume_info->override_uid)
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_OVERR_UID;
if (pvolume_info->override_gid)
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_OVERR_GID;
if (pvolume_info->dynperm)
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_DYNPERM;
if (pvolume_info->fsc)
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_FSCACHE;
if (pvolume_info->multiuser)
cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_MULTIUSER |
CIFS_MOUNT_NO_PERM);
if (pvolume_info->strict_io)
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_STRICT_IO;
if (pvolume_info->direct_io) {
cFYI(1, "mounting share using direct i/o");
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_DIRECT_IO;
}
if (pvolume_info->mfsymlinks) {
if (pvolume_info->sfu_emul) {
cERROR(1, "mount option mfsymlinks ignored if sfu "
"mount option is used");
} else {
cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_MF_SYMLINKS;
}
}
if ((pvolume_info->cifs_acl) && (pvolume_info->dynperm))
cERROR(1, "mount option dynperm ignored if cifsacl "
"mount option supported");
}
static int
is_path_accessible(int xid, struct cifsTconInfo *tcon,
struct cifs_sb_info *cifs_sb, const char *full_path)
{
int rc;
FILE_ALL_INFO *pfile_info;
pfile_info = kmalloc(sizeof(FILE_ALL_INFO), GFP_KERNEL);
if (pfile_info == NULL)
return -ENOMEM;
rc = CIFSSMBQPathInfo(xid, tcon, full_path, pfile_info,
0 /* not legacy */, cifs_sb->local_nls,
cifs_sb->mnt_cifs_flags &
CIFS_MOUNT_MAP_SPECIAL_CHR);
kfree(pfile_info);
return rc;
}
static void
cleanup_volume_info(struct smb_vol **pvolume_info)
{
struct smb_vol *volume_info;
if (!pvolume_info || !*pvolume_info)
return;
volume_info = *pvolume_info;
kzfree(volume_info->password);
kfree(volume_info->UNC);
kfree(volume_info->prepath);
kfree(volume_info);
*pvolume_info = NULL;
return;
}
#ifdef CONFIG_CIFS_DFS_UPCALL
/* build_path_to_root returns full path to root when
* we do not have an exiting connection (tcon) */
static char *
build_unc_path_to_root(const struct smb_vol *volume_info,
const struct cifs_sb_info *cifs_sb)
{
char *full_path;
int unc_len = strnlen(volume_info->UNC, MAX_TREE_SIZE + 1);
full_path = kmalloc(unc_len + cifs_sb->prepathlen + 1, GFP_KERNEL);
if (full_path == NULL)
return ERR_PTR(-ENOMEM);
strncpy(full_path, volume_info->UNC, unc_len);
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS) {
int i;
for (i = 0; i < unc_len; i++) {
if (full_path[i] == '\\')
full_path[i] = '/';
}
}
if (cifs_sb->prepathlen)
strncpy(full_path + unc_len, cifs_sb->prepath,
cifs_sb->prepathlen);
full_path[unc_len + cifs_sb->prepathlen] = 0; /* add trailing null */
return full_path;
}
#endif
int
cifs_mount(struct super_block *sb, struct cifs_sb_info *cifs_sb,
char *mount_data_global, const char *devname)
{
int rc;
int xid;
struct smb_vol *volume_info;
struct cifsSesInfo *pSesInfo;
struct cifsTconInfo *tcon;
struct TCP_Server_Info *srvTcp;
char *full_path;
char *mount_data = mount_data_global;
struct tcon_link *tlink;
#ifdef CONFIG_CIFS_DFS_UPCALL
struct dfs_info3_param *referrals = NULL;
unsigned int num_referrals = 0;
int referral_walks_count = 0;
try_mount_again:
#endif
rc = 0;
tcon = NULL;
pSesInfo = NULL;
srvTcp = NULL;
full_path = NULL;
tlink = NULL;
xid = GetXid();
volume_info = kzalloc(sizeof(struct smb_vol), GFP_KERNEL);
if (!volume_info) {
rc = -ENOMEM;
goto out;
}
if (cifs_parse_mount_options(mount_data, devname, volume_info)) {
rc = -EINVAL;
goto out;
}
if (volume_info->nullauth) {
cFYI(1, "null user");
volume_info->username = "";
} else if (volume_info->username) {
/* BB fixme parse for domain name here */
cFYI(1, "Username: %s", volume_info->username);
} else {
cifserror("No username specified");
/* In userspace mount helper we can get user name from alternate
locations such as env variables and files on disk */
rc = -EINVAL;
goto out;
}
/* this is needed for ASCII cp to Unicode converts */
if (volume_info->iocharset == NULL) {
/* load_nls_default cannot return null */
volume_info->local_nls = load_nls_default();
} else {
volume_info->local_nls = load_nls(volume_info->iocharset);
if (volume_info->local_nls == NULL) {
cERROR(1, "CIFS mount error: iocharset %s not found",
volume_info->iocharset);
rc = -ELIBACC;
goto out;
}
}
cifs_sb->local_nls = volume_info->local_nls;
/* get a reference to a tcp session */
srvTcp = cifs_get_tcp_session(volume_info);
if (IS_ERR(srvTcp)) {
rc = PTR_ERR(srvTcp);
goto out;
}
/* get a reference to a SMB session */
pSesInfo = cifs_get_smb_ses(srvTcp, volume_info);
if (IS_ERR(pSesInfo)) {
rc = PTR_ERR(pSesInfo);
pSesInfo = NULL;
goto mount_fail_check;
}
setup_cifs_sb(volume_info, cifs_sb);
if (pSesInfo->capabilities & CAP_LARGE_FILES)
sb->s_maxbytes = MAX_LFS_FILESIZE;
else
sb->s_maxbytes = MAX_NON_LFS;
/* BB FIXME fix time_gran to be larger for LANMAN sessions */
sb->s_time_gran = 100;
/* search for existing tcon to this server share */
tcon = cifs_get_tcon(pSesInfo, volume_info);
if (IS_ERR(tcon)) {
rc = PTR_ERR(tcon);
tcon = NULL;
goto remote_path_check;
}
/* do not care if following two calls succeed - informational */
if (!tcon->ipc) {
CIFSSMBQFSDeviceInfo(xid, tcon);
CIFSSMBQFSAttributeInfo(xid, tcon);
}
/* tell server which Unix caps we support */
if (tcon->ses->capabilities & CAP_UNIX)
/* reset of caps checks mount to see if unix extensions
disabled for just this mount */
reset_cifs_unix_caps(xid, tcon, sb, volume_info);
else
tcon->unix_ext = 0; /* server does not support them */
/* convert forward to back slashes in prepath here if needed */
if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS) == 0)
convert_delimiter(cifs_sb->prepath, CIFS_DIR_SEP(cifs_sb));
if ((tcon->unix_ext == 0) && (cifs_sb->rsize > (1024 * 127))) {
cifs_sb->rsize = 1024 * 127;
cFYI(DBG2, "no very large read support, rsize now 127K");
}
if (!(tcon->ses->capabilities & CAP_LARGE_WRITE_X))
cifs_sb->wsize = min(cifs_sb->wsize,
(tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE));
if (!(tcon->ses->capabilities & CAP_LARGE_READ_X))
cifs_sb->rsize = min(cifs_sb->rsize,
(tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE));
remote_path_check:
/* check if a whole path (including prepath) is not remote */
if (!rc && cifs_sb->prepathlen && tcon) {
/* build_path_to_root works only when we have a valid tcon */
full_path = cifs_build_path_to_root(cifs_sb, tcon);
if (full_path == NULL) {
rc = -ENOMEM;
goto mount_fail_check;
}
rc = is_path_accessible(xid, tcon, cifs_sb, full_path);
if (rc != 0 && rc != -EREMOTE) {
kfree(full_path);
goto mount_fail_check;
}
kfree(full_path);
}
/* get referral if needed */
if (rc == -EREMOTE) {
#ifdef CONFIG_CIFS_DFS_UPCALL
if (referral_walks_count > MAX_NESTED_LINKS) {
/*
* BB: when we implement proper loop detection,
* we will remove this check. But now we need it
* to prevent an indefinite loop if 'DFS tree' is
* misconfigured (i.e. has loops).
*/
rc = -ELOOP;
goto mount_fail_check;
}
/* convert forward to back slashes in prepath here if needed */
if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS) == 0)
convert_delimiter(cifs_sb->prepath,
CIFS_DIR_SEP(cifs_sb));
full_path = build_unc_path_to_root(volume_info, cifs_sb);
if (IS_ERR(full_path)) {
rc = PTR_ERR(full_path);
goto mount_fail_check;
}
cFYI(1, "Getting referral for: %s", full_path);
rc = get_dfs_path(xid, pSesInfo , full_path + 1,
cifs_sb->local_nls, &num_referrals, &referrals,
cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR);
if (!rc && num_referrals > 0) {
char *fake_devname = NULL;
if (mount_data != mount_data_global)
kfree(mount_data);
mount_data = cifs_compose_mount_options(
cifs_sb->mountdata, full_path + 1,
referrals, &fake_devname);
free_dfs_info_array(referrals, num_referrals);
kfree(fake_devname);
kfree(full_path);
if (IS_ERR(mount_data)) {
rc = PTR_ERR(mount_data);
mount_data = NULL;
goto mount_fail_check;
}
if (tcon)
cifs_put_tcon(tcon);
else if (pSesInfo)
cifs_put_smb_ses(pSesInfo);
cleanup_volume_info(&volume_info);
referral_walks_count++;
FreeXid(xid);
goto try_mount_again;
}
#else /* No DFS support, return error on mount */
rc = -EOPNOTSUPP;
#endif
}
if (rc)
goto mount_fail_check;
/* now, hang the tcon off of the superblock */
tlink = kzalloc(sizeof *tlink, GFP_KERNEL);
if (tlink == NULL) {
rc = -ENOMEM;
goto mount_fail_check;
}
tlink->tl_uid = pSesInfo->linux_uid;
tlink->tl_tcon = tcon;
tlink->tl_time = jiffies;
set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
cifs_sb->master_tlink = tlink;
spin_lock(&cifs_sb->tlink_tree_lock);
tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
spin_unlock(&cifs_sb->tlink_tree_lock);
queue_delayed_work(system_nrt_wq, &cifs_sb->prune_tlinks,
TLINK_IDLE_EXPIRE);
mount_fail_check:
/* on error free sesinfo and tcon struct if needed */
if (rc) {
if (mount_data != mount_data_global)
kfree(mount_data);
/* If find_unc succeeded then rc == 0 so we can not end */
/* up accidentally freeing someone elses tcon struct */
if (tcon)
cifs_put_tcon(tcon);
else if (pSesInfo)
cifs_put_smb_ses(pSesInfo);
else
cifs_put_tcp_session(srvTcp);
goto out;
}
/* volume_info->password is freed above when existing session found
(in which case it is not needed anymore) but when new sesion is created
the password ptr is put in the new session structure (in which case the
password will be freed at unmount time) */
out:
/* zero out password before freeing */
cleanup_volume_info(&volume_info);
FreeXid(xid);
return rc;
}
int
CIFSTCon(unsigned int xid, struct cifsSesInfo *ses,
const char *tree, struct cifsTconInfo *tcon,
const struct nls_table *nls_codepage)
{
struct smb_hdr *smb_buffer;
struct smb_hdr *smb_buffer_response;
TCONX_REQ *pSMB;
TCONX_RSP *pSMBr;
unsigned char *bcc_ptr;
int rc = 0;
int length;
__u16 bytes_left, count;
if (ses == NULL)
return -EIO;
smb_buffer = cifs_buf_get();
if (smb_buffer == NULL)
return -ENOMEM;
smb_buffer_response = smb_buffer;
header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
NULL /*no tid */ , 4 /*wct */ );
smb_buffer->Mid = GetNextMid(ses->server);
smb_buffer->Uid = ses->Suid;
pSMB = (TCONX_REQ *) smb_buffer;
pSMBr = (TCONX_RSP *) smb_buffer_response;
pSMB->AndXCommand = 0xFF;
pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
bcc_ptr = &pSMB->Password[0];
if ((ses->server->secMode) & SECMODE_USER) {
pSMB->PasswordLength = cpu_to_le16(1); /* minimum */
*bcc_ptr = 0; /* password is null byte */
bcc_ptr++; /* skip password */
/* already aligned so no need to do it below */
} else {
pSMB->PasswordLength = cpu_to_le16(CIFS_AUTH_RESP_SIZE);
/* BB FIXME add code to fail this if NTLMv2 or Kerberos
specified as required (when that support is added to
the vfs in the future) as only NTLM or the much
weaker LANMAN (which we do not send by default) is accepted
by Samba (not sure whether other servers allow
NTLMv2 password here) */
#ifdef CONFIG_CIFS_WEAK_PW_HASH
if ((global_secflags & CIFSSEC_MAY_LANMAN) &&
(ses->server->secType == LANMAN))
calc_lanman_hash(tcon->password, ses->server->cryptkey,
ses->server->secMode &
SECMODE_PW_ENCRYPT ? true : false,
bcc_ptr);
else
#endif /* CIFS_WEAK_PW_HASH */
rc = SMBNTencrypt(tcon->password, ses->server->cryptkey,
bcc_ptr);
bcc_ptr += CIFS_AUTH_RESP_SIZE;
if (ses->capabilities & CAP_UNICODE) {
/* must align unicode strings */
*bcc_ptr = 0; /* null byte password */
bcc_ptr++;
}
}
if (ses->server->secMode &
(SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED))
smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
if (ses->capabilities & CAP_STATUS32) {
smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
}
if (ses->capabilities & CAP_DFS) {
smb_buffer->Flags2 |= SMBFLG2_DFS;
}
if (ses->capabilities & CAP_UNICODE) {
smb_buffer->Flags2 |= SMBFLG2_UNICODE;
length =
cifs_strtoUCS((__le16 *) bcc_ptr, tree,
6 /* max utf8 char length in bytes */ *
(/* server len*/ + 256 /* share len */), nls_codepage);
bcc_ptr += 2 * length; /* convert num 16 bit words to bytes */
bcc_ptr += 2; /* skip trailing null */
} else { /* ASCII */
strcpy(bcc_ptr, tree);
bcc_ptr += strlen(tree) + 1;
}
strcpy(bcc_ptr, "?????");
bcc_ptr += strlen("?????");
bcc_ptr += 1;
count = bcc_ptr - &pSMB->Password[0];
pSMB->hdr.smb_buf_length += count;
pSMB->ByteCount = cpu_to_le16(count);
rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
0);
/* above now done in SendReceive */
if ((rc == 0) && (tcon != NULL)) {
bool is_unicode;
tcon->tidStatus = CifsGood;
tcon->need_reconnect = false;
tcon->tid = smb_buffer_response->Tid;
bcc_ptr = pByteArea(smb_buffer_response);
bytes_left = get_bcc(smb_buffer_response);
length = strnlen(bcc_ptr, bytes_left - 2);
if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
is_unicode = true;
else
is_unicode = false;
/* skip service field (NB: this field is always ASCII) */
if (length == 3) {
if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
(bcc_ptr[2] == 'C')) {
cFYI(1, "IPC connection");
tcon->ipc = 1;
}
} else if (length == 2) {
if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
/* the most common case */
cFYI(1, "disk share connection");
}
}
bcc_ptr += length + 1;
bytes_left -= (length + 1);
strncpy(tcon->treeName, tree, MAX_TREE_SIZE);
/* mostly informational -- no need to fail on error here */
kfree(tcon->nativeFileSystem);
tcon->nativeFileSystem = cifs_strndup_from_ucs(bcc_ptr,
bytes_left, is_unicode,
nls_codepage);
cFYI(1, "nativeFileSystem=%s", tcon->nativeFileSystem);
if ((smb_buffer_response->WordCount == 3) ||
(smb_buffer_response->WordCount == 7))
/* field is in same location */
tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
else
tcon->Flags = 0;
cFYI(1, "Tcon flags: 0x%x ", tcon->Flags);
} else if ((rc == 0) && tcon == NULL) {
/* all we need to save for IPC$ connection */
ses->ipc_tid = smb_buffer_response->Tid;
}
cifs_buf_release(smb_buffer);
return rc;
}
int
cifs_umount(struct super_block *sb, struct cifs_sb_info *cifs_sb)
{
struct rb_root *root = &cifs_sb->tlink_tree;
struct rb_node *node;
struct tcon_link *tlink;
char *tmp;
cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
spin_lock(&cifs_sb->tlink_tree_lock);
while ((node = rb_first(root))) {
tlink = rb_entry(node, struct tcon_link, tl_rbnode);
cifs_get_tlink(tlink);
clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
rb_erase(node, root);
spin_unlock(&cifs_sb->tlink_tree_lock);
cifs_put_tlink(tlink);
spin_lock(&cifs_sb->tlink_tree_lock);
}
spin_unlock(&cifs_sb->tlink_tree_lock);
tmp = cifs_sb->prepath;
cifs_sb->prepathlen = 0;
cifs_sb->prepath = NULL;
kfree(tmp);
return 0;
}
int cifs_negotiate_protocol(unsigned int xid, struct cifsSesInfo *ses)
{
int rc = 0;
struct TCP_Server_Info *server = ses->server;
/* only send once per connect */
if (server->maxBuf != 0)
return 0;
rc = CIFSSMBNegotiate(xid, ses);
if (rc == -EAGAIN) {
/* retry only once on 1st time connection */
rc = CIFSSMBNegotiate(xid, ses);
if (rc == -EAGAIN)
rc = -EHOSTDOWN;
}
if (rc == 0) {
spin_lock(&GlobalMid_Lock);
if (server->tcpStatus != CifsExiting)
server->tcpStatus = CifsGood;
else
rc = -EHOSTDOWN;
spin_unlock(&GlobalMid_Lock);
}
return rc;
}
int cifs_setup_session(unsigned int xid, struct cifsSesInfo *ses,
struct nls_table *nls_info)
{
int rc = 0;
struct TCP_Server_Info *server = ses->server;
ses->flags = 0;
ses->capabilities = server->capabilities;
if (linuxExtEnabled == 0)
ses->capabilities &= (~CAP_UNIX);
cFYI(1, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d",
server->secMode, server->capabilities, server->timeAdj);
rc = CIFS_SessSetup(xid, ses, nls_info);
if (rc) {
cERROR(1, "Send error in SessSetup = %d", rc);
} else {
mutex_lock(&ses->server->srv_mutex);
if (!server->session_estab) {
server->session_key.response = ses->auth_key.response;
server->session_key.len = ses->auth_key.len;
server->sequence_number = 0x2;
server->session_estab = true;
ses->auth_key.response = NULL;
}
mutex_unlock(&server->srv_mutex);
cFYI(1, "CIFS Session Established successfully");
spin_lock(&GlobalMid_Lock);
ses->status = CifsGood;
ses->need_reconnect = false;
spin_unlock(&GlobalMid_Lock);
}
kfree(ses->auth_key.response);
ses->auth_key.response = NULL;
ses->auth_key.len = 0;
kfree(ses->ntlmssp);
ses->ntlmssp = NULL;
return rc;
}
static struct cifsTconInfo *
cifs_construct_tcon(struct cifs_sb_info *cifs_sb, uid_t fsuid)
{
struct cifsTconInfo *master_tcon = cifs_sb_master_tcon(cifs_sb);
struct cifsSesInfo *ses;
struct cifsTconInfo *tcon = NULL;
struct smb_vol *vol_info;
char username[MAX_USERNAME_SIZE + 1];
vol_info = kzalloc(sizeof(*vol_info), GFP_KERNEL);
if (vol_info == NULL) {
tcon = ERR_PTR(-ENOMEM);
goto out;
}
snprintf(username, MAX_USERNAME_SIZE, "krb50x%x", fsuid);
vol_info->username = username;
vol_info->local_nls = cifs_sb->local_nls;
vol_info->linux_uid = fsuid;
vol_info->cred_uid = fsuid;
vol_info->UNC = master_tcon->treeName;
vol_info->retry = master_tcon->retry;
vol_info->nocase = master_tcon->nocase;
vol_info->local_lease = master_tcon->local_lease;
vol_info->no_linux_ext = !master_tcon->unix_ext;
/* FIXME: allow for other secFlg settings */
vol_info->secFlg = CIFSSEC_MUST_KRB5;
/* get a reference for the same TCP session */
spin_lock(&cifs_tcp_ses_lock);
++master_tcon->ses->server->srv_count;
spin_unlock(&cifs_tcp_ses_lock);
ses = cifs_get_smb_ses(master_tcon->ses->server, vol_info);
if (IS_ERR(ses)) {
tcon = (struct cifsTconInfo *)ses;
cifs_put_tcp_session(master_tcon->ses->server);
goto out;
}
tcon = cifs_get_tcon(ses, vol_info);
if (IS_ERR(tcon)) {
cifs_put_smb_ses(ses);
goto out;
}
if (ses->capabilities & CAP_UNIX)
reset_cifs_unix_caps(0, tcon, NULL, vol_info);
out:
kfree(vol_info);
return tcon;
}
static inline struct tcon_link *
cifs_sb_master_tlink(struct cifs_sb_info *cifs_sb)
{
return cifs_sb->master_tlink;
}
struct cifsTconInfo *
cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
{
return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
}
static int
cifs_sb_tcon_pending_wait(void *unused)
{
schedule();
return signal_pending(current) ? -ERESTARTSYS : 0;
}
/* find and return a tlink with given uid */
static struct tcon_link *
tlink_rb_search(struct rb_root *root, uid_t uid)
{
struct rb_node *node = root->rb_node;
struct tcon_link *tlink;
while (node) {
tlink = rb_entry(node, struct tcon_link, tl_rbnode);
if (tlink->tl_uid > uid)
node = node->rb_left;
else if (tlink->tl_uid < uid)
node = node->rb_right;
else
return tlink;
}
return NULL;
}
/* insert a tcon_link into the tree */
static void
tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
{
struct rb_node **new = &(root->rb_node), *parent = NULL;
struct tcon_link *tlink;
while (*new) {
tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
parent = *new;
if (tlink->tl_uid > new_tlink->tl_uid)
new = &((*new)->rb_left);
else
new = &((*new)->rb_right);
}
rb_link_node(&new_tlink->tl_rbnode, parent, new);
rb_insert_color(&new_tlink->tl_rbnode, root);
}
/*
* Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
* current task.
*
* If the superblock doesn't refer to a multiuser mount, then just return
* the master tcon for the mount.
*
* First, search the rbtree for an existing tcon for this fsuid. If one
* exists, then check to see if it's pending construction. If it is then wait
* for construction to complete. Once it's no longer pending, check to see if
* it failed and either return an error or retry construction, depending on
* the timeout.
*
* If one doesn't exist then insert a new tcon_link struct into the tree and
* try to construct a new one.
*/
struct tcon_link *
cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
{
int ret;
uid_t fsuid = current_fsuid();
struct tcon_link *tlink, *newtlink;
if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
spin_lock(&cifs_sb->tlink_tree_lock);
tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
if (tlink)
cifs_get_tlink(tlink);
spin_unlock(&cifs_sb->tlink_tree_lock);
if (tlink == NULL) {
newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
if (newtlink == NULL)
return ERR_PTR(-ENOMEM);
newtlink->tl_uid = fsuid;
newtlink->tl_tcon = ERR_PTR(-EACCES);
set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
cifs_get_tlink(newtlink);
spin_lock(&cifs_sb->tlink_tree_lock);
/* was one inserted after previous search? */
tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
if (tlink) {
cifs_get_tlink(tlink);
spin_unlock(&cifs_sb->tlink_tree_lock);
kfree(newtlink);
goto wait_for_construction;
}
tlink = newtlink;
tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
spin_unlock(&cifs_sb->tlink_tree_lock);
} else {
wait_for_construction:
ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
cifs_sb_tcon_pending_wait,
TASK_INTERRUPTIBLE);
if (ret) {
cifs_put_tlink(tlink);
return ERR_PTR(ret);
}
/* if it's good, return it */
if (!IS_ERR(tlink->tl_tcon))
return tlink;
/* return error if we tried this already recently */
if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
cifs_put_tlink(tlink);
return ERR_PTR(-EACCES);
}
if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
goto wait_for_construction;
}
tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
if (IS_ERR(tlink->tl_tcon)) {
cifs_put_tlink(tlink);
return ERR_PTR(-EACCES);
}
return tlink;
}
/*
* periodic workqueue job that scans tcon_tree for a superblock and closes
* out tcons.
*/
static void
cifs_prune_tlinks(struct work_struct *work)
{
struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
prune_tlinks.work);
struct rb_root *root = &cifs_sb->tlink_tree;
struct rb_node *node = rb_first(root);
struct rb_node *tmp;
struct tcon_link *tlink;
/*
* Because we drop the spinlock in the loop in order to put the tlink
* it's not guarded against removal of links from the tree. The only
* places that remove entries from the tree are this function and
* umounts. Because this function is non-reentrant and is canceled
* before umount can proceed, this is safe.
*/
spin_lock(&cifs_sb->tlink_tree_lock);
node = rb_first(root);
while (node != NULL) {
tmp = node;
node = rb_next(tmp);
tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
atomic_read(&tlink->tl_count) != 0 ||
time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
continue;
cifs_get_tlink(tlink);
clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
rb_erase(tmp, root);
spin_unlock(&cifs_sb->tlink_tree_lock);
cifs_put_tlink(tlink);
spin_lock(&cifs_sb->tlink_tree_lock);
}
spin_unlock(&cifs_sb->tlink_tree_lock);
queue_delayed_work(system_nrt_wq, &cifs_sb->prune_tlinks,
TLINK_IDLE_EXPIRE);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3509_0 |
crossvul-cpp_data_bad_2089_0 | /*
* linux/fs/nfs/write.c
*
* Write file data over NFS.
*
* Copyright (C) 1996, 1997, Olaf Kirch <okir@monad.swb.de>
*/
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/pagemap.h>
#include <linux/file.h>
#include <linux/writeback.h>
#include <linux/swap.h>
#include <linux/migrate.h>
#include <linux/sunrpc/clnt.h>
#include <linux/nfs_fs.h>
#include <linux/nfs_mount.h>
#include <linux/nfs_page.h>
#include <linux/backing-dev.h>
#include <linux/export.h>
#include <asm/uaccess.h>
#include "delegation.h"
#include "internal.h"
#include "iostat.h"
#include "nfs4_fs.h"
#include "fscache.h"
#include "pnfs.h"
#include "nfstrace.h"
#define NFSDBG_FACILITY NFSDBG_PAGECACHE
#define MIN_POOL_WRITE (32)
#define MIN_POOL_COMMIT (4)
/*
* Local function declarations
*/
static void nfs_redirty_request(struct nfs_page *req);
static const struct rpc_call_ops nfs_write_common_ops;
static const struct rpc_call_ops nfs_commit_ops;
static const struct nfs_pgio_completion_ops nfs_async_write_completion_ops;
static const struct nfs_commit_completion_ops nfs_commit_completion_ops;
static struct kmem_cache *nfs_wdata_cachep;
static mempool_t *nfs_wdata_mempool;
static struct kmem_cache *nfs_cdata_cachep;
static mempool_t *nfs_commit_mempool;
struct nfs_commit_data *nfs_commitdata_alloc(void)
{
struct nfs_commit_data *p = mempool_alloc(nfs_commit_mempool, GFP_NOIO);
if (p) {
memset(p, 0, sizeof(*p));
INIT_LIST_HEAD(&p->pages);
}
return p;
}
EXPORT_SYMBOL_GPL(nfs_commitdata_alloc);
void nfs_commit_free(struct nfs_commit_data *p)
{
mempool_free(p, nfs_commit_mempool);
}
EXPORT_SYMBOL_GPL(nfs_commit_free);
struct nfs_write_header *nfs_writehdr_alloc(void)
{
struct nfs_write_header *p = mempool_alloc(nfs_wdata_mempool, GFP_NOIO);
if (p) {
struct nfs_pgio_header *hdr = &p->header;
memset(p, 0, sizeof(*p));
INIT_LIST_HEAD(&hdr->pages);
INIT_LIST_HEAD(&hdr->rpc_list);
spin_lock_init(&hdr->lock);
atomic_set(&hdr->refcnt, 0);
hdr->verf = &p->verf;
}
return p;
}
EXPORT_SYMBOL_GPL(nfs_writehdr_alloc);
static struct nfs_write_data *nfs_writedata_alloc(struct nfs_pgio_header *hdr,
unsigned int pagecount)
{
struct nfs_write_data *data, *prealloc;
prealloc = &container_of(hdr, struct nfs_write_header, header)->rpc_data;
if (prealloc->header == NULL)
data = prealloc;
else
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (!data)
goto out;
if (nfs_pgarray_set(&data->pages, pagecount)) {
data->header = hdr;
atomic_inc(&hdr->refcnt);
} else {
if (data != prealloc)
kfree(data);
data = NULL;
}
out:
return data;
}
void nfs_writehdr_free(struct nfs_pgio_header *hdr)
{
struct nfs_write_header *whdr = container_of(hdr, struct nfs_write_header, header);
mempool_free(whdr, nfs_wdata_mempool);
}
EXPORT_SYMBOL_GPL(nfs_writehdr_free);
void nfs_writedata_release(struct nfs_write_data *wdata)
{
struct nfs_pgio_header *hdr = wdata->header;
struct nfs_write_header *write_header = container_of(hdr, struct nfs_write_header, header);
put_nfs_open_context(wdata->args.context);
if (wdata->pages.pagevec != wdata->pages.page_array)
kfree(wdata->pages.pagevec);
if (wdata == &write_header->rpc_data) {
wdata->header = NULL;
wdata = NULL;
}
if (atomic_dec_and_test(&hdr->refcnt))
hdr->completion_ops->completion(hdr);
/* Note: we only free the rpc_task after callbacks are done.
* See the comment in rpc_free_task() for why
*/
kfree(wdata);
}
EXPORT_SYMBOL_GPL(nfs_writedata_release);
static void nfs_context_set_write_error(struct nfs_open_context *ctx, int error)
{
ctx->error = error;
smp_wmb();
set_bit(NFS_CONTEXT_ERROR_WRITE, &ctx->flags);
}
static struct nfs_page *
nfs_page_find_request_locked(struct nfs_inode *nfsi, struct page *page)
{
struct nfs_page *req = NULL;
if (PagePrivate(page))
req = (struct nfs_page *)page_private(page);
else if (unlikely(PageSwapCache(page))) {
struct nfs_page *freq, *t;
/* Linearly search the commit list for the correct req */
list_for_each_entry_safe(freq, t, &nfsi->commit_info.list, wb_list) {
if (freq->wb_page == page) {
req = freq;
break;
}
}
}
if (req)
kref_get(&req->wb_kref);
return req;
}
static struct nfs_page *nfs_page_find_request(struct page *page)
{
struct inode *inode = page_file_mapping(page)->host;
struct nfs_page *req = NULL;
spin_lock(&inode->i_lock);
req = nfs_page_find_request_locked(NFS_I(inode), page);
spin_unlock(&inode->i_lock);
return req;
}
/* Adjust the file length if we're writing beyond the end */
static void nfs_grow_file(struct page *page, unsigned int offset, unsigned int count)
{
struct inode *inode = page_file_mapping(page)->host;
loff_t end, i_size;
pgoff_t end_index;
spin_lock(&inode->i_lock);
i_size = i_size_read(inode);
end_index = (i_size - 1) >> PAGE_CACHE_SHIFT;
if (i_size > 0 && page_file_index(page) < end_index)
goto out;
end = page_file_offset(page) + ((loff_t)offset+count);
if (i_size >= end)
goto out;
i_size_write(inode, end);
nfs_inc_stats(inode, NFSIOS_EXTENDWRITE);
out:
spin_unlock(&inode->i_lock);
}
/* A writeback failed: mark the page as bad, and invalidate the page cache */
static void nfs_set_pageerror(struct page *page)
{
nfs_zap_mapping(page_file_mapping(page)->host, page_file_mapping(page));
}
/* We can set the PG_uptodate flag if we see that a write request
* covers the full page.
*/
static void nfs_mark_uptodate(struct page *page, unsigned int base, unsigned int count)
{
if (PageUptodate(page))
return;
if (base != 0)
return;
if (count != nfs_page_length(page))
return;
SetPageUptodate(page);
}
static int wb_priority(struct writeback_control *wbc)
{
if (wbc->for_reclaim)
return FLUSH_HIGHPRI | FLUSH_STABLE;
if (wbc->for_kupdate || wbc->for_background)
return FLUSH_LOWPRI | FLUSH_COND_STABLE;
return FLUSH_COND_STABLE;
}
/*
* NFS congestion control
*/
int nfs_congestion_kb;
#define NFS_CONGESTION_ON_THRESH (nfs_congestion_kb >> (PAGE_SHIFT-10))
#define NFS_CONGESTION_OFF_THRESH \
(NFS_CONGESTION_ON_THRESH - (NFS_CONGESTION_ON_THRESH >> 2))
static void nfs_set_page_writeback(struct page *page)
{
struct nfs_server *nfss = NFS_SERVER(page_file_mapping(page)->host);
int ret = test_set_page_writeback(page);
WARN_ON_ONCE(ret != 0);
if (atomic_long_inc_return(&nfss->writeback) >
NFS_CONGESTION_ON_THRESH) {
set_bdi_congested(&nfss->backing_dev_info,
BLK_RW_ASYNC);
}
}
static void nfs_end_page_writeback(struct page *page)
{
struct inode *inode = page_file_mapping(page)->host;
struct nfs_server *nfss = NFS_SERVER(inode);
end_page_writeback(page);
if (atomic_long_dec_return(&nfss->writeback) < NFS_CONGESTION_OFF_THRESH)
clear_bdi_congested(&nfss->backing_dev_info, BLK_RW_ASYNC);
}
static struct nfs_page *nfs_find_and_lock_request(struct page *page, bool nonblock)
{
struct inode *inode = page_file_mapping(page)->host;
struct nfs_page *req;
int ret;
spin_lock(&inode->i_lock);
for (;;) {
req = nfs_page_find_request_locked(NFS_I(inode), page);
if (req == NULL)
break;
if (nfs_lock_request(req))
break;
/* Note: If we hold the page lock, as is the case in nfs_writepage,
* then the call to nfs_lock_request() will always
* succeed provided that someone hasn't already marked the
* request as dirty (in which case we don't care).
*/
spin_unlock(&inode->i_lock);
if (!nonblock)
ret = nfs_wait_on_request(req);
else
ret = -EAGAIN;
nfs_release_request(req);
if (ret != 0)
return ERR_PTR(ret);
spin_lock(&inode->i_lock);
}
spin_unlock(&inode->i_lock);
return req;
}
/*
* Find an associated nfs write request, and prepare to flush it out
* May return an error if the user signalled nfs_wait_on_request().
*/
static int nfs_page_async_flush(struct nfs_pageio_descriptor *pgio,
struct page *page, bool nonblock)
{
struct nfs_page *req;
int ret = 0;
req = nfs_find_and_lock_request(page, nonblock);
if (!req)
goto out;
ret = PTR_ERR(req);
if (IS_ERR(req))
goto out;
nfs_set_page_writeback(page);
WARN_ON_ONCE(test_bit(PG_CLEAN, &req->wb_flags));
ret = 0;
if (!nfs_pageio_add_request(pgio, req)) {
nfs_redirty_request(req);
ret = pgio->pg_error;
}
out:
return ret;
}
static int nfs_do_writepage(struct page *page, struct writeback_control *wbc, struct nfs_pageio_descriptor *pgio)
{
struct inode *inode = page_file_mapping(page)->host;
int ret;
nfs_inc_stats(inode, NFSIOS_VFSWRITEPAGE);
nfs_add_stats(inode, NFSIOS_WRITEPAGES, 1);
nfs_pageio_cond_complete(pgio, page_file_index(page));
ret = nfs_page_async_flush(pgio, page, wbc->sync_mode == WB_SYNC_NONE);
if (ret == -EAGAIN) {
redirty_page_for_writepage(wbc, page);
ret = 0;
}
return ret;
}
/*
* Write an mmapped page to the server.
*/
static int nfs_writepage_locked(struct page *page, struct writeback_control *wbc)
{
struct nfs_pageio_descriptor pgio;
int err;
NFS_PROTO(page_file_mapping(page)->host)->write_pageio_init(&pgio,
page->mapping->host,
wb_priority(wbc),
&nfs_async_write_completion_ops);
err = nfs_do_writepage(page, wbc, &pgio);
nfs_pageio_complete(&pgio);
if (err < 0)
return err;
if (pgio.pg_error < 0)
return pgio.pg_error;
return 0;
}
int nfs_writepage(struct page *page, struct writeback_control *wbc)
{
int ret;
ret = nfs_writepage_locked(page, wbc);
unlock_page(page);
return ret;
}
static int nfs_writepages_callback(struct page *page, struct writeback_control *wbc, void *data)
{
int ret;
ret = nfs_do_writepage(page, wbc, data);
unlock_page(page);
return ret;
}
int nfs_writepages(struct address_space *mapping, struct writeback_control *wbc)
{
struct inode *inode = mapping->host;
unsigned long *bitlock = &NFS_I(inode)->flags;
struct nfs_pageio_descriptor pgio;
int err;
/* Stop dirtying of new pages while we sync */
err = wait_on_bit_lock(bitlock, NFS_INO_FLUSHING,
nfs_wait_bit_killable, TASK_KILLABLE);
if (err)
goto out_err;
nfs_inc_stats(inode, NFSIOS_VFSWRITEPAGES);
NFS_PROTO(inode)->write_pageio_init(&pgio, inode, wb_priority(wbc), &nfs_async_write_completion_ops);
err = write_cache_pages(mapping, wbc, nfs_writepages_callback, &pgio);
nfs_pageio_complete(&pgio);
clear_bit_unlock(NFS_INO_FLUSHING, bitlock);
smp_mb__after_clear_bit();
wake_up_bit(bitlock, NFS_INO_FLUSHING);
if (err < 0)
goto out_err;
err = pgio.pg_error;
if (err < 0)
goto out_err;
return 0;
out_err:
return err;
}
/*
* Insert a write request into an inode
*/
static void nfs_inode_add_request(struct inode *inode, struct nfs_page *req)
{
struct nfs_inode *nfsi = NFS_I(inode);
/* Lock the request! */
nfs_lock_request(req);
spin_lock(&inode->i_lock);
if (!nfsi->npages && NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))
inode->i_version++;
/*
* Swap-space should not get truncated. Hence no need to plug the race
* with invalidate/truncate.
*/
if (likely(!PageSwapCache(req->wb_page))) {
set_bit(PG_MAPPED, &req->wb_flags);
SetPagePrivate(req->wb_page);
set_page_private(req->wb_page, (unsigned long)req);
}
nfsi->npages++;
kref_get(&req->wb_kref);
spin_unlock(&inode->i_lock);
}
/*
* Remove a write request from an inode
*/
static void nfs_inode_remove_request(struct nfs_page *req)
{
struct inode *inode = req->wb_context->dentry->d_inode;
struct nfs_inode *nfsi = NFS_I(inode);
spin_lock(&inode->i_lock);
if (likely(!PageSwapCache(req->wb_page))) {
set_page_private(req->wb_page, 0);
ClearPagePrivate(req->wb_page);
clear_bit(PG_MAPPED, &req->wb_flags);
}
nfsi->npages--;
spin_unlock(&inode->i_lock);
nfs_release_request(req);
}
static void
nfs_mark_request_dirty(struct nfs_page *req)
{
__set_page_dirty_nobuffers(req->wb_page);
}
#if IS_ENABLED(CONFIG_NFS_V3) || IS_ENABLED(CONFIG_NFS_V4)
/**
* nfs_request_add_commit_list - add request to a commit list
* @req: pointer to a struct nfs_page
* @dst: commit list head
* @cinfo: holds list lock and accounting info
*
* This sets the PG_CLEAN bit, updates the cinfo count of
* number of outstanding requests requiring a commit as well as
* the MM page stats.
*
* The caller must _not_ hold the cinfo->lock, but must be
* holding the nfs_page lock.
*/
void
nfs_request_add_commit_list(struct nfs_page *req, struct list_head *dst,
struct nfs_commit_info *cinfo)
{
set_bit(PG_CLEAN, &(req)->wb_flags);
spin_lock(cinfo->lock);
nfs_list_add_request(req, dst);
cinfo->mds->ncommit++;
spin_unlock(cinfo->lock);
if (!cinfo->dreq) {
inc_zone_page_state(req->wb_page, NR_UNSTABLE_NFS);
inc_bdi_stat(page_file_mapping(req->wb_page)->backing_dev_info,
BDI_RECLAIMABLE);
__mark_inode_dirty(req->wb_context->dentry->d_inode,
I_DIRTY_DATASYNC);
}
}
EXPORT_SYMBOL_GPL(nfs_request_add_commit_list);
/**
* nfs_request_remove_commit_list - Remove request from a commit list
* @req: pointer to a nfs_page
* @cinfo: holds list lock and accounting info
*
* This clears the PG_CLEAN bit, and updates the cinfo's count of
* number of outstanding requests requiring a commit
* It does not update the MM page stats.
*
* The caller _must_ hold the cinfo->lock and the nfs_page lock.
*/
void
nfs_request_remove_commit_list(struct nfs_page *req,
struct nfs_commit_info *cinfo)
{
if (!test_and_clear_bit(PG_CLEAN, &(req)->wb_flags))
return;
nfs_list_remove_request(req);
cinfo->mds->ncommit--;
}
EXPORT_SYMBOL_GPL(nfs_request_remove_commit_list);
static void nfs_init_cinfo_from_inode(struct nfs_commit_info *cinfo,
struct inode *inode)
{
cinfo->lock = &inode->i_lock;
cinfo->mds = &NFS_I(inode)->commit_info;
cinfo->ds = pnfs_get_ds_info(inode);
cinfo->dreq = NULL;
cinfo->completion_ops = &nfs_commit_completion_ops;
}
void nfs_init_cinfo(struct nfs_commit_info *cinfo,
struct inode *inode,
struct nfs_direct_req *dreq)
{
if (dreq)
nfs_init_cinfo_from_dreq(cinfo, dreq);
else
nfs_init_cinfo_from_inode(cinfo, inode);
}
EXPORT_SYMBOL_GPL(nfs_init_cinfo);
/*
* Add a request to the inode's commit list.
*/
void
nfs_mark_request_commit(struct nfs_page *req, struct pnfs_layout_segment *lseg,
struct nfs_commit_info *cinfo)
{
if (pnfs_mark_request_commit(req, lseg, cinfo))
return;
nfs_request_add_commit_list(req, &cinfo->mds->list, cinfo);
}
static void
nfs_clear_page_commit(struct page *page)
{
dec_zone_page_state(page, NR_UNSTABLE_NFS);
dec_bdi_stat(page_file_mapping(page)->backing_dev_info, BDI_RECLAIMABLE);
}
static void
nfs_clear_request_commit(struct nfs_page *req)
{
if (test_bit(PG_CLEAN, &req->wb_flags)) {
struct inode *inode = req->wb_context->dentry->d_inode;
struct nfs_commit_info cinfo;
nfs_init_cinfo_from_inode(&cinfo, inode);
if (!pnfs_clear_request_commit(req, &cinfo)) {
spin_lock(cinfo.lock);
nfs_request_remove_commit_list(req, &cinfo);
spin_unlock(cinfo.lock);
}
nfs_clear_page_commit(req->wb_page);
}
}
static inline
int nfs_write_need_commit(struct nfs_write_data *data)
{
if (data->verf.committed == NFS_DATA_SYNC)
return data->header->lseg == NULL;
return data->verf.committed != NFS_FILE_SYNC;
}
#else
static void nfs_init_cinfo_from_inode(struct nfs_commit_info *cinfo,
struct inode *inode)
{
}
void nfs_init_cinfo(struct nfs_commit_info *cinfo,
struct inode *inode,
struct nfs_direct_req *dreq)
{
}
void
nfs_mark_request_commit(struct nfs_page *req, struct pnfs_layout_segment *lseg,
struct nfs_commit_info *cinfo)
{
}
static void
nfs_clear_request_commit(struct nfs_page *req)
{
}
static inline
int nfs_write_need_commit(struct nfs_write_data *data)
{
return 0;
}
#endif
static void nfs_write_completion(struct nfs_pgio_header *hdr)
{
struct nfs_commit_info cinfo;
unsigned long bytes = 0;
if (test_bit(NFS_IOHDR_REDO, &hdr->flags))
goto out;
nfs_init_cinfo_from_inode(&cinfo, hdr->inode);
while (!list_empty(&hdr->pages)) {
struct nfs_page *req = nfs_list_entry(hdr->pages.next);
bytes += req->wb_bytes;
nfs_list_remove_request(req);
if (test_bit(NFS_IOHDR_ERROR, &hdr->flags) &&
(hdr->good_bytes < bytes)) {
nfs_set_pageerror(req->wb_page);
nfs_context_set_write_error(req->wb_context, hdr->error);
goto remove_req;
}
if (test_bit(NFS_IOHDR_NEED_RESCHED, &hdr->flags)) {
nfs_mark_request_dirty(req);
goto next;
}
if (test_bit(NFS_IOHDR_NEED_COMMIT, &hdr->flags)) {
memcpy(&req->wb_verf, &hdr->verf->verifier, sizeof(req->wb_verf));
nfs_mark_request_commit(req, hdr->lseg, &cinfo);
goto next;
}
remove_req:
nfs_inode_remove_request(req);
next:
nfs_unlock_request(req);
nfs_end_page_writeback(req->wb_page);
nfs_release_request(req);
}
out:
hdr->release(hdr);
}
#if IS_ENABLED(CONFIG_NFS_V3) || IS_ENABLED(CONFIG_NFS_V4)
static unsigned long
nfs_reqs_to_commit(struct nfs_commit_info *cinfo)
{
return cinfo->mds->ncommit;
}
/* cinfo->lock held by caller */
int
nfs_scan_commit_list(struct list_head *src, struct list_head *dst,
struct nfs_commit_info *cinfo, int max)
{
struct nfs_page *req, *tmp;
int ret = 0;
list_for_each_entry_safe(req, tmp, src, wb_list) {
if (!nfs_lock_request(req))
continue;
kref_get(&req->wb_kref);
if (cond_resched_lock(cinfo->lock))
list_safe_reset_next(req, tmp, wb_list);
nfs_request_remove_commit_list(req, cinfo);
nfs_list_add_request(req, dst);
ret++;
if ((ret == max) && !cinfo->dreq)
break;
}
return ret;
}
/*
* nfs_scan_commit - Scan an inode for commit requests
* @inode: NFS inode to scan
* @dst: mds destination list
* @cinfo: mds and ds lists of reqs ready to commit
*
* Moves requests from the inode's 'commit' request list.
* The requests are *not* checked to ensure that they form a contiguous set.
*/
int
nfs_scan_commit(struct inode *inode, struct list_head *dst,
struct nfs_commit_info *cinfo)
{
int ret = 0;
spin_lock(cinfo->lock);
if (cinfo->mds->ncommit > 0) {
const int max = INT_MAX;
ret = nfs_scan_commit_list(&cinfo->mds->list, dst,
cinfo, max);
ret += pnfs_scan_commit_lists(inode, cinfo, max - ret);
}
spin_unlock(cinfo->lock);
return ret;
}
#else
static unsigned long nfs_reqs_to_commit(struct nfs_commit_info *cinfo)
{
return 0;
}
int nfs_scan_commit(struct inode *inode, struct list_head *dst,
struct nfs_commit_info *cinfo)
{
return 0;
}
#endif
/*
* Search for an existing write request, and attempt to update
* it to reflect a new dirty region on a given page.
*
* If the attempt fails, then the existing request is flushed out
* to disk.
*/
static struct nfs_page *nfs_try_to_update_request(struct inode *inode,
struct page *page,
unsigned int offset,
unsigned int bytes)
{
struct nfs_page *req;
unsigned int rqend;
unsigned int end;
int error;
if (!PagePrivate(page))
return NULL;
end = offset + bytes;
spin_lock(&inode->i_lock);
for (;;) {
req = nfs_page_find_request_locked(NFS_I(inode), page);
if (req == NULL)
goto out_unlock;
rqend = req->wb_offset + req->wb_bytes;
/*
* Tell the caller to flush out the request if
* the offsets are non-contiguous.
* Note: nfs_flush_incompatible() will already
* have flushed out requests having wrong owners.
*/
if (offset > rqend
|| end < req->wb_offset)
goto out_flushme;
if (nfs_lock_request(req))
break;
/* The request is locked, so wait and then retry */
spin_unlock(&inode->i_lock);
error = nfs_wait_on_request(req);
nfs_release_request(req);
if (error != 0)
goto out_err;
spin_lock(&inode->i_lock);
}
/* Okay, the request matches. Update the region */
if (offset < req->wb_offset) {
req->wb_offset = offset;
req->wb_pgbase = offset;
}
if (end > rqend)
req->wb_bytes = end - req->wb_offset;
else
req->wb_bytes = rqend - req->wb_offset;
out_unlock:
spin_unlock(&inode->i_lock);
if (req)
nfs_clear_request_commit(req);
return req;
out_flushme:
spin_unlock(&inode->i_lock);
nfs_release_request(req);
error = nfs_wb_page(inode, page);
out_err:
return ERR_PTR(error);
}
/*
* Try to update an existing write request, or create one if there is none.
*
* Note: Should always be called with the Page Lock held to prevent races
* if we have to add a new request. Also assumes that the caller has
* already called nfs_flush_incompatible() if necessary.
*/
static struct nfs_page * nfs_setup_write_request(struct nfs_open_context* ctx,
struct page *page, unsigned int offset, unsigned int bytes)
{
struct inode *inode = page_file_mapping(page)->host;
struct nfs_page *req;
req = nfs_try_to_update_request(inode, page, offset, bytes);
if (req != NULL)
goto out;
req = nfs_create_request(ctx, inode, page, offset, bytes);
if (IS_ERR(req))
goto out;
nfs_inode_add_request(inode, req);
out:
return req;
}
static int nfs_writepage_setup(struct nfs_open_context *ctx, struct page *page,
unsigned int offset, unsigned int count)
{
struct nfs_page *req;
req = nfs_setup_write_request(ctx, page, offset, count);
if (IS_ERR(req))
return PTR_ERR(req);
/* Update file length */
nfs_grow_file(page, offset, count);
nfs_mark_uptodate(page, req->wb_pgbase, req->wb_bytes);
nfs_mark_request_dirty(req);
nfs_unlock_and_release_request(req);
return 0;
}
int nfs_flush_incompatible(struct file *file, struct page *page)
{
struct nfs_open_context *ctx = nfs_file_open_context(file);
struct nfs_lock_context *l_ctx;
struct nfs_page *req;
int do_flush, status;
/*
* Look for a request corresponding to this page. If there
* is one, and it belongs to another file, we flush it out
* before we try to copy anything into the page. Do this
* due to the lack of an ACCESS-type call in NFSv2.
* Also do the same if we find a request from an existing
* dropped page.
*/
do {
req = nfs_page_find_request(page);
if (req == NULL)
return 0;
l_ctx = req->wb_lock_context;
do_flush = req->wb_page != page || req->wb_context != ctx;
if (l_ctx && ctx->dentry->d_inode->i_flock != NULL) {
do_flush |= l_ctx->lockowner.l_owner != current->files
|| l_ctx->lockowner.l_pid != current->tgid;
}
nfs_release_request(req);
if (!do_flush)
return 0;
status = nfs_wb_page(page_file_mapping(page)->host, page);
} while (status == 0);
return status;
}
/*
* Avoid buffered writes when a open context credential's key would
* expire soon.
*
* Returns -EACCES if the key will expire within RPC_KEY_EXPIRE_FAIL.
*
* Return 0 and set a credential flag which triggers the inode to flush
* and performs NFS_FILE_SYNC writes if the key will expired within
* RPC_KEY_EXPIRE_TIMEO.
*/
int
nfs_key_timeout_notify(struct file *filp, struct inode *inode)
{
struct nfs_open_context *ctx = nfs_file_open_context(filp);
struct rpc_auth *auth = NFS_SERVER(inode)->client->cl_auth;
return rpcauth_key_timeout_notify(auth, ctx->cred);
}
/*
* Test if the open context credential key is marked to expire soon.
*/
bool nfs_ctx_key_to_expire(struct nfs_open_context *ctx)
{
return rpcauth_cred_key_to_expire(ctx->cred);
}
/*
* If the page cache is marked as unsafe or invalid, then we can't rely on
* the PageUptodate() flag. In this case, we will need to turn off
* write optimisations that depend on the page contents being correct.
*/
static bool nfs_write_pageuptodate(struct page *page, struct inode *inode)
{
if (nfs_have_delegated_attributes(inode))
goto out;
if (NFS_I(inode)->cache_validity & (NFS_INO_INVALID_DATA|NFS_INO_REVAL_PAGECACHE))
return false;
out:
return PageUptodate(page) != 0;
}
/* If we know the page is up to date, and we're not using byte range locks (or
* if we have the whole file locked for writing), it may be more efficient to
* extend the write to cover the entire page in order to avoid fragmentation
* inefficiencies.
*
* If the file is opened for synchronous writes or if we have a write delegation
* from the server then we can just skip the rest of the checks.
*/
static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode)
{
if (file->f_flags & O_DSYNC)
return 0;
if (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))
return 1;
if (nfs_write_pageuptodate(page, inode) && (inode->i_flock == NULL ||
(inode->i_flock->fl_start == 0 &&
inode->i_flock->fl_end == OFFSET_MAX &&
inode->i_flock->fl_type != F_RDLCK)))
return 1;
return 0;
}
/*
* Update and possibly write a cached page of an NFS file.
*
* XXX: Keep an eye on generic_file_read to make sure it doesn't do bad
* things with a page scheduled for an RPC call (e.g. invalidate it).
*/
int nfs_updatepage(struct file *file, struct page *page,
unsigned int offset, unsigned int count)
{
struct nfs_open_context *ctx = nfs_file_open_context(file);
struct inode *inode = page_file_mapping(page)->host;
int status = 0;
nfs_inc_stats(inode, NFSIOS_VFSUPDATEPAGE);
dprintk("NFS: nfs_updatepage(%pD2 %d@%lld)\n",
file, count, (long long)(page_file_offset(page) + offset));
if (nfs_can_extend_write(file, page, inode)) {
count = max(count + offset, nfs_page_length(page));
offset = 0;
}
status = nfs_writepage_setup(ctx, page, offset, count);
if (status < 0)
nfs_set_pageerror(page);
else
__set_page_dirty_nobuffers(page);
dprintk("NFS: nfs_updatepage returns %d (isize %lld)\n",
status, (long long)i_size_read(inode));
return status;
}
static int flush_task_priority(int how)
{
switch (how & (FLUSH_HIGHPRI|FLUSH_LOWPRI)) {
case FLUSH_HIGHPRI:
return RPC_PRIORITY_HIGH;
case FLUSH_LOWPRI:
return RPC_PRIORITY_LOW;
}
return RPC_PRIORITY_NORMAL;
}
int nfs_initiate_write(struct rpc_clnt *clnt,
struct nfs_write_data *data,
const struct rpc_call_ops *call_ops,
int how, int flags)
{
struct inode *inode = data->header->inode;
int priority = flush_task_priority(how);
struct rpc_task *task;
struct rpc_message msg = {
.rpc_argp = &data->args,
.rpc_resp = &data->res,
.rpc_cred = data->header->cred,
};
struct rpc_task_setup task_setup_data = {
.rpc_client = clnt,
.task = &data->task,
.rpc_message = &msg,
.callback_ops = call_ops,
.callback_data = data,
.workqueue = nfsiod_workqueue,
.flags = RPC_TASK_ASYNC | flags,
.priority = priority,
};
int ret = 0;
/* Set up the initial task struct. */
NFS_PROTO(inode)->write_setup(data, &msg);
dprintk("NFS: %5u initiated write call "
"(req %s/%llu, %u bytes @ offset %llu)\n",
data->task.tk_pid,
inode->i_sb->s_id,
(unsigned long long)NFS_FILEID(inode),
data->args.count,
(unsigned long long)data->args.offset);
nfs4_state_protect_write(NFS_SERVER(inode)->nfs_client,
&task_setup_data.rpc_client, &msg, data);
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task)) {
ret = PTR_ERR(task);
goto out;
}
if (how & FLUSH_SYNC) {
ret = rpc_wait_for_completion_task(task);
if (ret == 0)
ret = task->tk_status;
}
rpc_put_task(task);
out:
return ret;
}
EXPORT_SYMBOL_GPL(nfs_initiate_write);
/*
* Set up the argument/result storage required for the RPC call.
*/
static void nfs_write_rpcsetup(struct nfs_write_data *data,
unsigned int count, unsigned int offset,
int how, struct nfs_commit_info *cinfo)
{
struct nfs_page *req = data->header->req;
/* Set up the RPC argument and reply structs
* NB: take care not to mess about with data->commit et al. */
data->args.fh = NFS_FH(data->header->inode);
data->args.offset = req_offset(req) + offset;
/* pnfs_set_layoutcommit needs this */
data->mds_offset = data->args.offset;
data->args.pgbase = req->wb_pgbase + offset;
data->args.pages = data->pages.pagevec;
data->args.count = count;
data->args.context = get_nfs_open_context(req->wb_context);
data->args.lock_context = req->wb_lock_context;
data->args.stable = NFS_UNSTABLE;
switch (how & (FLUSH_STABLE | FLUSH_COND_STABLE)) {
case 0:
break;
case FLUSH_COND_STABLE:
if (nfs_reqs_to_commit(cinfo))
break;
default:
data->args.stable = NFS_FILE_SYNC;
}
data->res.fattr = &data->fattr;
data->res.count = count;
data->res.verf = &data->verf;
nfs_fattr_init(&data->fattr);
}
static int nfs_do_write(struct nfs_write_data *data,
const struct rpc_call_ops *call_ops,
int how)
{
struct inode *inode = data->header->inode;
return nfs_initiate_write(NFS_CLIENT(inode), data, call_ops, how, 0);
}
static int nfs_do_multiple_writes(struct list_head *head,
const struct rpc_call_ops *call_ops,
int how)
{
struct nfs_write_data *data;
int ret = 0;
while (!list_empty(head)) {
int ret2;
data = list_first_entry(head, struct nfs_write_data, list);
list_del_init(&data->list);
ret2 = nfs_do_write(data, call_ops, how);
if (ret == 0)
ret = ret2;
}
return ret;
}
/* If a nfs_flush_* function fails, it should remove reqs from @head and
* call this on each, which will prepare them to be retried on next
* writeback using standard nfs.
*/
static void nfs_redirty_request(struct nfs_page *req)
{
nfs_mark_request_dirty(req);
nfs_unlock_request(req);
nfs_end_page_writeback(req->wb_page);
nfs_release_request(req);
}
static void nfs_async_write_error(struct list_head *head)
{
struct nfs_page *req;
while (!list_empty(head)) {
req = nfs_list_entry(head->next);
nfs_list_remove_request(req);
nfs_redirty_request(req);
}
}
static const struct nfs_pgio_completion_ops nfs_async_write_completion_ops = {
.error_cleanup = nfs_async_write_error,
.completion = nfs_write_completion,
};
static void nfs_flush_error(struct nfs_pageio_descriptor *desc,
struct nfs_pgio_header *hdr)
{
set_bit(NFS_IOHDR_REDO, &hdr->flags);
while (!list_empty(&hdr->rpc_list)) {
struct nfs_write_data *data = list_first_entry(&hdr->rpc_list,
struct nfs_write_data, list);
list_del(&data->list);
nfs_writedata_release(data);
}
desc->pg_completion_ops->error_cleanup(&desc->pg_list);
}
/*
* Generate multiple small requests to write out a single
* contiguous dirty area on one page.
*/
static int nfs_flush_multi(struct nfs_pageio_descriptor *desc,
struct nfs_pgio_header *hdr)
{
struct nfs_page *req = hdr->req;
struct page *page = req->wb_page;
struct nfs_write_data *data;
size_t wsize = desc->pg_bsize, nbytes;
unsigned int offset;
int requests = 0;
struct nfs_commit_info cinfo;
nfs_init_cinfo(&cinfo, desc->pg_inode, desc->pg_dreq);
if ((desc->pg_ioflags & FLUSH_COND_STABLE) &&
(desc->pg_moreio || nfs_reqs_to_commit(&cinfo) ||
desc->pg_count > wsize))
desc->pg_ioflags &= ~FLUSH_COND_STABLE;
offset = 0;
nbytes = desc->pg_count;
do {
size_t len = min(nbytes, wsize);
data = nfs_writedata_alloc(hdr, 1);
if (!data) {
nfs_flush_error(desc, hdr);
return -ENOMEM;
}
data->pages.pagevec[0] = page;
nfs_write_rpcsetup(data, len, offset, desc->pg_ioflags, &cinfo);
list_add(&data->list, &hdr->rpc_list);
requests++;
nbytes -= len;
offset += len;
} while (nbytes != 0);
nfs_list_remove_request(req);
nfs_list_add_request(req, &hdr->pages);
desc->pg_rpc_callops = &nfs_write_common_ops;
return 0;
}
/*
* Create an RPC task for the given write request and kick it.
* The page must have been locked by the caller.
*
* It may happen that the page we're passed is not marked dirty.
* This is the case if nfs_updatepage detects a conflicting request
* that has been written but not committed.
*/
static int nfs_flush_one(struct nfs_pageio_descriptor *desc,
struct nfs_pgio_header *hdr)
{
struct nfs_page *req;
struct page **pages;
struct nfs_write_data *data;
struct list_head *head = &desc->pg_list;
struct nfs_commit_info cinfo;
data = nfs_writedata_alloc(hdr, nfs_page_array_len(desc->pg_base,
desc->pg_count));
if (!data) {
nfs_flush_error(desc, hdr);
return -ENOMEM;
}
nfs_init_cinfo(&cinfo, desc->pg_inode, desc->pg_dreq);
pages = data->pages.pagevec;
while (!list_empty(head)) {
req = nfs_list_entry(head->next);
nfs_list_remove_request(req);
nfs_list_add_request(req, &hdr->pages);
*pages++ = req->wb_page;
}
if ((desc->pg_ioflags & FLUSH_COND_STABLE) &&
(desc->pg_moreio || nfs_reqs_to_commit(&cinfo)))
desc->pg_ioflags &= ~FLUSH_COND_STABLE;
/* Set up the argument struct */
nfs_write_rpcsetup(data, desc->pg_count, 0, desc->pg_ioflags, &cinfo);
list_add(&data->list, &hdr->rpc_list);
desc->pg_rpc_callops = &nfs_write_common_ops;
return 0;
}
int nfs_generic_flush(struct nfs_pageio_descriptor *desc,
struct nfs_pgio_header *hdr)
{
if (desc->pg_bsize < PAGE_CACHE_SIZE)
return nfs_flush_multi(desc, hdr);
return nfs_flush_one(desc, hdr);
}
EXPORT_SYMBOL_GPL(nfs_generic_flush);
static int nfs_generic_pg_writepages(struct nfs_pageio_descriptor *desc)
{
struct nfs_write_header *whdr;
struct nfs_pgio_header *hdr;
int ret;
whdr = nfs_writehdr_alloc();
if (!whdr) {
desc->pg_completion_ops->error_cleanup(&desc->pg_list);
return -ENOMEM;
}
hdr = &whdr->header;
nfs_pgheader_init(desc, hdr, nfs_writehdr_free);
atomic_inc(&hdr->refcnt);
ret = nfs_generic_flush(desc, hdr);
if (ret == 0)
ret = nfs_do_multiple_writes(&hdr->rpc_list,
desc->pg_rpc_callops,
desc->pg_ioflags);
if (atomic_dec_and_test(&hdr->refcnt))
hdr->completion_ops->completion(hdr);
return ret;
}
static const struct nfs_pageio_ops nfs_pageio_write_ops = {
.pg_test = nfs_generic_pg_test,
.pg_doio = nfs_generic_pg_writepages,
};
void nfs_pageio_init_write(struct nfs_pageio_descriptor *pgio,
struct inode *inode, int ioflags,
const struct nfs_pgio_completion_ops *compl_ops)
{
nfs_pageio_init(pgio, inode, &nfs_pageio_write_ops, compl_ops,
NFS_SERVER(inode)->wsize, ioflags);
}
EXPORT_SYMBOL_GPL(nfs_pageio_init_write);
void nfs_pageio_reset_write_mds(struct nfs_pageio_descriptor *pgio)
{
pgio->pg_ops = &nfs_pageio_write_ops;
pgio->pg_bsize = NFS_SERVER(pgio->pg_inode)->wsize;
}
EXPORT_SYMBOL_GPL(nfs_pageio_reset_write_mds);
void nfs_write_prepare(struct rpc_task *task, void *calldata)
{
struct nfs_write_data *data = calldata;
int err;
err = NFS_PROTO(data->header->inode)->write_rpc_prepare(task, data);
if (err)
rpc_exit(task, err);
}
void nfs_commit_prepare(struct rpc_task *task, void *calldata)
{
struct nfs_commit_data *data = calldata;
NFS_PROTO(data->inode)->commit_rpc_prepare(task, data);
}
/*
* Handle a write reply that flushes a whole page.
*
* FIXME: There is an inherent race with invalidate_inode_pages and
* writebacks since the page->count is kept > 1 for as long
* as the page has a write request pending.
*/
static void nfs_writeback_done_common(struct rpc_task *task, void *calldata)
{
struct nfs_write_data *data = calldata;
nfs_writeback_done(task, data);
}
static void nfs_writeback_release_common(void *calldata)
{
struct nfs_write_data *data = calldata;
struct nfs_pgio_header *hdr = data->header;
int status = data->task.tk_status;
if ((status >= 0) && nfs_write_need_commit(data)) {
spin_lock(&hdr->lock);
if (test_bit(NFS_IOHDR_NEED_RESCHED, &hdr->flags))
; /* Do nothing */
else if (!test_and_set_bit(NFS_IOHDR_NEED_COMMIT, &hdr->flags))
memcpy(hdr->verf, &data->verf, sizeof(*hdr->verf));
else if (memcmp(hdr->verf, &data->verf, sizeof(*hdr->verf)))
set_bit(NFS_IOHDR_NEED_RESCHED, &hdr->flags);
spin_unlock(&hdr->lock);
}
nfs_writedata_release(data);
}
static const struct rpc_call_ops nfs_write_common_ops = {
.rpc_call_prepare = nfs_write_prepare,
.rpc_call_done = nfs_writeback_done_common,
.rpc_release = nfs_writeback_release_common,
};
/*
* This function is called when the WRITE call is complete.
*/
void nfs_writeback_done(struct rpc_task *task, struct nfs_write_data *data)
{
struct nfs_writeargs *argp = &data->args;
struct nfs_writeres *resp = &data->res;
struct inode *inode = data->header->inode;
int status;
dprintk("NFS: %5u nfs_writeback_done (status %d)\n",
task->tk_pid, task->tk_status);
/*
* ->write_done will attempt to use post-op attributes to detect
* conflicting writes by other clients. A strict interpretation
* of close-to-open would allow us to continue caching even if
* another writer had changed the file, but some applications
* depend on tighter cache coherency when writing.
*/
status = NFS_PROTO(inode)->write_done(task, data);
if (status != 0)
return;
nfs_add_stats(inode, NFSIOS_SERVERWRITTENBYTES, resp->count);
#if IS_ENABLED(CONFIG_NFS_V3) || IS_ENABLED(CONFIG_NFS_V4)
if (resp->verf->committed < argp->stable && task->tk_status >= 0) {
/* We tried a write call, but the server did not
* commit data to stable storage even though we
* requested it.
* Note: There is a known bug in Tru64 < 5.0 in which
* the server reports NFS_DATA_SYNC, but performs
* NFS_FILE_SYNC. We therefore implement this checking
* as a dprintk() in order to avoid filling syslog.
*/
static unsigned long complain;
/* Note this will print the MDS for a DS write */
if (time_before(complain, jiffies)) {
dprintk("NFS: faulty NFS server %s:"
" (committed = %d) != (stable = %d)\n",
NFS_SERVER(inode)->nfs_client->cl_hostname,
resp->verf->committed, argp->stable);
complain = jiffies + 300 * HZ;
}
}
#endif
if (task->tk_status < 0)
nfs_set_pgio_error(data->header, task->tk_status, argp->offset);
else if (resp->count < argp->count) {
static unsigned long complain;
/* This a short write! */
nfs_inc_stats(inode, NFSIOS_SHORTWRITE);
/* Has the server at least made some progress? */
if (resp->count == 0) {
if (time_before(complain, jiffies)) {
printk(KERN_WARNING
"NFS: Server wrote zero bytes, expected %u.\n",
argp->count);
complain = jiffies + 300 * HZ;
}
nfs_set_pgio_error(data->header, -EIO, argp->offset);
task->tk_status = -EIO;
return;
}
/* Was this an NFSv2 write or an NFSv3 stable write? */
if (resp->verf->committed != NFS_UNSTABLE) {
/* Resend from where the server left off */
data->mds_offset += resp->count;
argp->offset += resp->count;
argp->pgbase += resp->count;
argp->count -= resp->count;
} else {
/* Resend as a stable write in order to avoid
* headaches in the case of a server crash.
*/
argp->stable = NFS_FILE_SYNC;
}
rpc_restart_call_prepare(task);
}
}
#if IS_ENABLED(CONFIG_NFS_V3) || IS_ENABLED(CONFIG_NFS_V4)
static int nfs_commit_set_lock(struct nfs_inode *nfsi, int may_wait)
{
int ret;
if (!test_and_set_bit(NFS_INO_COMMIT, &nfsi->flags))
return 1;
if (!may_wait)
return 0;
ret = out_of_line_wait_on_bit_lock(&nfsi->flags,
NFS_INO_COMMIT,
nfs_wait_bit_killable,
TASK_KILLABLE);
return (ret < 0) ? ret : 1;
}
static void nfs_commit_clear_lock(struct nfs_inode *nfsi)
{
clear_bit(NFS_INO_COMMIT, &nfsi->flags);
smp_mb__after_clear_bit();
wake_up_bit(&nfsi->flags, NFS_INO_COMMIT);
}
void nfs_commitdata_release(struct nfs_commit_data *data)
{
put_nfs_open_context(data->context);
nfs_commit_free(data);
}
EXPORT_SYMBOL_GPL(nfs_commitdata_release);
int nfs_initiate_commit(struct rpc_clnt *clnt, struct nfs_commit_data *data,
const struct rpc_call_ops *call_ops,
int how, int flags)
{
struct rpc_task *task;
int priority = flush_task_priority(how);
struct rpc_message msg = {
.rpc_argp = &data->args,
.rpc_resp = &data->res,
.rpc_cred = data->cred,
};
struct rpc_task_setup task_setup_data = {
.task = &data->task,
.rpc_client = clnt,
.rpc_message = &msg,
.callback_ops = call_ops,
.callback_data = data,
.workqueue = nfsiod_workqueue,
.flags = RPC_TASK_ASYNC | flags,
.priority = priority,
};
/* Set up the initial task struct. */
NFS_PROTO(data->inode)->commit_setup(data, &msg);
dprintk("NFS: %5u initiated commit call\n", data->task.tk_pid);
nfs4_state_protect(NFS_SERVER(data->inode)->nfs_client,
NFS_SP4_MACH_CRED_COMMIT, &task_setup_data.rpc_client, &msg);
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task))
return PTR_ERR(task);
if (how & FLUSH_SYNC)
rpc_wait_for_completion_task(task);
rpc_put_task(task);
return 0;
}
EXPORT_SYMBOL_GPL(nfs_initiate_commit);
/*
* Set up the argument/result storage required for the RPC call.
*/
void nfs_init_commit(struct nfs_commit_data *data,
struct list_head *head,
struct pnfs_layout_segment *lseg,
struct nfs_commit_info *cinfo)
{
struct nfs_page *first = nfs_list_entry(head->next);
struct inode *inode = first->wb_context->dentry->d_inode;
/* Set up the RPC argument and reply structs
* NB: take care not to mess about with data->commit et al. */
list_splice_init(head, &data->pages);
data->inode = inode;
data->cred = first->wb_context->cred;
data->lseg = lseg; /* reference transferred */
data->mds_ops = &nfs_commit_ops;
data->completion_ops = cinfo->completion_ops;
data->dreq = cinfo->dreq;
data->args.fh = NFS_FH(data->inode);
/* Note: we always request a commit of the entire inode */
data->args.offset = 0;
data->args.count = 0;
data->context = get_nfs_open_context(first->wb_context);
data->res.fattr = &data->fattr;
data->res.verf = &data->verf;
nfs_fattr_init(&data->fattr);
}
EXPORT_SYMBOL_GPL(nfs_init_commit);
void nfs_retry_commit(struct list_head *page_list,
struct pnfs_layout_segment *lseg,
struct nfs_commit_info *cinfo)
{
struct nfs_page *req;
while (!list_empty(page_list)) {
req = nfs_list_entry(page_list->next);
nfs_list_remove_request(req);
nfs_mark_request_commit(req, lseg, cinfo);
if (!cinfo->dreq) {
dec_zone_page_state(req->wb_page, NR_UNSTABLE_NFS);
dec_bdi_stat(page_file_mapping(req->wb_page)->backing_dev_info,
BDI_RECLAIMABLE);
}
nfs_unlock_and_release_request(req);
}
}
EXPORT_SYMBOL_GPL(nfs_retry_commit);
/*
* Commit dirty pages
*/
static int
nfs_commit_list(struct inode *inode, struct list_head *head, int how,
struct nfs_commit_info *cinfo)
{
struct nfs_commit_data *data;
data = nfs_commitdata_alloc();
if (!data)
goto out_bad;
/* Set up the argument struct */
nfs_init_commit(data, head, NULL, cinfo);
atomic_inc(&cinfo->mds->rpcs_out);
return nfs_initiate_commit(NFS_CLIENT(inode), data, data->mds_ops,
how, 0);
out_bad:
nfs_retry_commit(head, NULL, cinfo);
cinfo->completion_ops->error_cleanup(NFS_I(inode));
return -ENOMEM;
}
/*
* COMMIT call returned
*/
static void nfs_commit_done(struct rpc_task *task, void *calldata)
{
struct nfs_commit_data *data = calldata;
dprintk("NFS: %5u nfs_commit_done (status %d)\n",
task->tk_pid, task->tk_status);
/* Call the NFS version-specific code */
NFS_PROTO(data->inode)->commit_done(task, data);
}
static void nfs_commit_release_pages(struct nfs_commit_data *data)
{
struct nfs_page *req;
int status = data->task.tk_status;
struct nfs_commit_info cinfo;
while (!list_empty(&data->pages)) {
req = nfs_list_entry(data->pages.next);
nfs_list_remove_request(req);
nfs_clear_page_commit(req->wb_page);
dprintk("NFS: commit (%s/%llu %d@%lld)",
req->wb_context->dentry->d_sb->s_id,
(unsigned long long)NFS_FILEID(req->wb_context->dentry->d_inode),
req->wb_bytes,
(long long)req_offset(req));
if (status < 0) {
nfs_context_set_write_error(req->wb_context, status);
nfs_inode_remove_request(req);
dprintk(", error = %d\n", status);
goto next;
}
/* Okay, COMMIT succeeded, apparently. Check the verifier
* returned by the server against all stored verfs. */
if (!memcmp(&req->wb_verf, &data->verf.verifier, sizeof(req->wb_verf))) {
/* We have a match */
nfs_inode_remove_request(req);
dprintk(" OK\n");
goto next;
}
/* We have a mismatch. Write the page again */
dprintk(" mismatch\n");
nfs_mark_request_dirty(req);
set_bit(NFS_CONTEXT_RESEND_WRITES, &req->wb_context->flags);
next:
nfs_unlock_and_release_request(req);
}
nfs_init_cinfo(&cinfo, data->inode, data->dreq);
if (atomic_dec_and_test(&cinfo.mds->rpcs_out))
nfs_commit_clear_lock(NFS_I(data->inode));
}
static void nfs_commit_release(void *calldata)
{
struct nfs_commit_data *data = calldata;
data->completion_ops->completion(data);
nfs_commitdata_release(calldata);
}
static const struct rpc_call_ops nfs_commit_ops = {
.rpc_call_prepare = nfs_commit_prepare,
.rpc_call_done = nfs_commit_done,
.rpc_release = nfs_commit_release,
};
static const struct nfs_commit_completion_ops nfs_commit_completion_ops = {
.completion = nfs_commit_release_pages,
.error_cleanup = nfs_commit_clear_lock,
};
int nfs_generic_commit_list(struct inode *inode, struct list_head *head,
int how, struct nfs_commit_info *cinfo)
{
int status;
status = pnfs_commit_list(inode, head, how, cinfo);
if (status == PNFS_NOT_ATTEMPTED)
status = nfs_commit_list(inode, head, how, cinfo);
return status;
}
int nfs_commit_inode(struct inode *inode, int how)
{
LIST_HEAD(head);
struct nfs_commit_info cinfo;
int may_wait = how & FLUSH_SYNC;
int res;
res = nfs_commit_set_lock(NFS_I(inode), may_wait);
if (res <= 0)
goto out_mark_dirty;
nfs_init_cinfo_from_inode(&cinfo, inode);
res = nfs_scan_commit(inode, &head, &cinfo);
if (res) {
int error;
error = nfs_generic_commit_list(inode, &head, how, &cinfo);
if (error < 0)
return error;
if (!may_wait)
goto out_mark_dirty;
error = wait_on_bit(&NFS_I(inode)->flags,
NFS_INO_COMMIT,
nfs_wait_bit_killable,
TASK_KILLABLE);
if (error < 0)
return error;
} else
nfs_commit_clear_lock(NFS_I(inode));
return res;
/* Note: If we exit without ensuring that the commit is complete,
* we must mark the inode as dirty. Otherwise, future calls to
* sync_inode() with the WB_SYNC_ALL flag set will fail to ensure
* that the data is on the disk.
*/
out_mark_dirty:
__mark_inode_dirty(inode, I_DIRTY_DATASYNC);
return res;
}
static int nfs_commit_unstable_pages(struct inode *inode, struct writeback_control *wbc)
{
struct nfs_inode *nfsi = NFS_I(inode);
int flags = FLUSH_SYNC;
int ret = 0;
/* no commits means nothing needs to be done */
if (!nfsi->commit_info.ncommit)
return ret;
if (wbc->sync_mode == WB_SYNC_NONE) {
/* Don't commit yet if this is a non-blocking flush and there
* are a lot of outstanding writes for this mapping.
*/
if (nfsi->commit_info.ncommit <= (nfsi->npages >> 1))
goto out_mark_dirty;
/* don't wait for the COMMIT response */
flags = 0;
}
ret = nfs_commit_inode(inode, flags);
if (ret >= 0) {
if (wbc->sync_mode == WB_SYNC_NONE) {
if (ret < wbc->nr_to_write)
wbc->nr_to_write -= ret;
else
wbc->nr_to_write = 0;
}
return 0;
}
out_mark_dirty:
__mark_inode_dirty(inode, I_DIRTY_DATASYNC);
return ret;
}
#else
static int nfs_commit_unstable_pages(struct inode *inode, struct writeback_control *wbc)
{
return 0;
}
#endif
int nfs_write_inode(struct inode *inode, struct writeback_control *wbc)
{
return nfs_commit_unstable_pages(inode, wbc);
}
EXPORT_SYMBOL_GPL(nfs_write_inode);
/*
* flush the inode to disk.
*/
int nfs_wb_all(struct inode *inode)
{
struct writeback_control wbc = {
.sync_mode = WB_SYNC_ALL,
.nr_to_write = LONG_MAX,
.range_start = 0,
.range_end = LLONG_MAX,
};
int ret;
trace_nfs_writeback_inode_enter(inode);
ret = sync_inode(inode, &wbc);
trace_nfs_writeback_inode_exit(inode, ret);
return ret;
}
EXPORT_SYMBOL_GPL(nfs_wb_all);
int nfs_wb_page_cancel(struct inode *inode, struct page *page)
{
struct nfs_page *req;
int ret = 0;
for (;;) {
wait_on_page_writeback(page);
req = nfs_page_find_request(page);
if (req == NULL)
break;
if (nfs_lock_request(req)) {
nfs_clear_request_commit(req);
nfs_inode_remove_request(req);
/*
* In case nfs_inode_remove_request has marked the
* page as being dirty
*/
cancel_dirty_page(page, PAGE_CACHE_SIZE);
nfs_unlock_and_release_request(req);
break;
}
ret = nfs_wait_on_request(req);
nfs_release_request(req);
if (ret < 0)
break;
}
return ret;
}
/*
* Write back all requests on one page - we do this before reading it.
*/
int nfs_wb_page(struct inode *inode, struct page *page)
{
loff_t range_start = page_file_offset(page);
loff_t range_end = range_start + (loff_t)(PAGE_CACHE_SIZE - 1);
struct writeback_control wbc = {
.sync_mode = WB_SYNC_ALL,
.nr_to_write = 0,
.range_start = range_start,
.range_end = range_end,
};
int ret;
trace_nfs_writeback_page_enter(inode);
for (;;) {
wait_on_page_writeback(page);
if (clear_page_dirty_for_io(page)) {
ret = nfs_writepage_locked(page, &wbc);
if (ret < 0)
goto out_error;
continue;
}
ret = 0;
if (!PagePrivate(page))
break;
ret = nfs_commit_inode(inode, FLUSH_SYNC);
if (ret < 0)
goto out_error;
}
out_error:
trace_nfs_writeback_page_exit(inode, ret);
return ret;
}
#ifdef CONFIG_MIGRATION
int nfs_migrate_page(struct address_space *mapping, struct page *newpage,
struct page *page, enum migrate_mode mode)
{
/*
* If PagePrivate is set, then the page is currently associated with
* an in-progress read or write request. Don't try to migrate it.
*
* FIXME: we could do this in principle, but we'll need a way to ensure
* that we can safely release the inode reference while holding
* the page lock.
*/
if (PagePrivate(page))
return -EBUSY;
if (!nfs_fscache_release_page(page, GFP_KERNEL))
return -EBUSY;
return migrate_page(mapping, newpage, page, mode);
}
#endif
int __init nfs_init_writepagecache(void)
{
nfs_wdata_cachep = kmem_cache_create("nfs_write_data",
sizeof(struct nfs_write_header),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (nfs_wdata_cachep == NULL)
return -ENOMEM;
nfs_wdata_mempool = mempool_create_slab_pool(MIN_POOL_WRITE,
nfs_wdata_cachep);
if (nfs_wdata_mempool == NULL)
goto out_destroy_write_cache;
nfs_cdata_cachep = kmem_cache_create("nfs_commit_data",
sizeof(struct nfs_commit_data),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (nfs_cdata_cachep == NULL)
goto out_destroy_write_mempool;
nfs_commit_mempool = mempool_create_slab_pool(MIN_POOL_COMMIT,
nfs_cdata_cachep);
if (nfs_commit_mempool == NULL)
goto out_destroy_commit_cache;
/*
* NFS congestion size, scale with available memory.
*
* 64MB: 8192k
* 128MB: 11585k
* 256MB: 16384k
* 512MB: 23170k
* 1GB: 32768k
* 2GB: 46340k
* 4GB: 65536k
* 8GB: 92681k
* 16GB: 131072k
*
* This allows larger machines to have larger/more transfers.
* Limit the default to 256M
*/
nfs_congestion_kb = (16*int_sqrt(totalram_pages)) << (PAGE_SHIFT-10);
if (nfs_congestion_kb > 256*1024)
nfs_congestion_kb = 256*1024;
return 0;
out_destroy_commit_cache:
kmem_cache_destroy(nfs_cdata_cachep);
out_destroy_write_mempool:
mempool_destroy(nfs_wdata_mempool);
out_destroy_write_cache:
kmem_cache_destroy(nfs_wdata_cachep);
return -ENOMEM;
}
void nfs_destroy_writepagecache(void)
{
mempool_destroy(nfs_commit_mempool);
kmem_cache_destroy(nfs_cdata_cachep);
mempool_destroy(nfs_wdata_mempool);
kmem_cache_destroy(nfs_wdata_cachep);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2089_0 |
crossvul-cpp_data_good_5845_9 | /*
BlueZ - Bluetooth protocol stack for Linux
Copyright (C) 2000-2001 Qualcomm Incorporated
Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
/* Bluetooth HCI sockets. */
#include <linux/export.h>
#include <asm/unaligned.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include <net/bluetooth/hci_mon.h>
static atomic_t monitor_promisc = ATOMIC_INIT(0);
/* ----- HCI socket interface ----- */
static inline int hci_test_bit(int nr, void *addr)
{
return *((__u32 *) addr + (nr >> 5)) & ((__u32) 1 << (nr & 31));
}
/* Security filter */
static struct hci_sec_filter hci_sec_filter = {
/* Packet types */
0x10,
/* Events */
{ 0x1000d9fe, 0x0000b00c },
/* Commands */
{
{ 0x0 },
/* OGF_LINK_CTL */
{ 0xbe000006, 0x00000001, 0x00000000, 0x00 },
/* OGF_LINK_POLICY */
{ 0x00005200, 0x00000000, 0x00000000, 0x00 },
/* OGF_HOST_CTL */
{ 0xaab00200, 0x2b402aaa, 0x05220154, 0x00 },
/* OGF_INFO_PARAM */
{ 0x000002be, 0x00000000, 0x00000000, 0x00 },
/* OGF_STATUS_PARAM */
{ 0x000000ea, 0x00000000, 0x00000000, 0x00 }
}
};
static struct bt_sock_list hci_sk_list = {
.lock = __RW_LOCK_UNLOCKED(hci_sk_list.lock)
};
static bool is_filtered_packet(struct sock *sk, struct sk_buff *skb)
{
struct hci_filter *flt;
int flt_type, flt_event;
/* Apply filter */
flt = &hci_pi(sk)->filter;
if (bt_cb(skb)->pkt_type == HCI_VENDOR_PKT)
flt_type = 0;
else
flt_type = bt_cb(skb)->pkt_type & HCI_FLT_TYPE_BITS;
if (!test_bit(flt_type, &flt->type_mask))
return true;
/* Extra filter for event packets only */
if (bt_cb(skb)->pkt_type != HCI_EVENT_PKT)
return false;
flt_event = (*(__u8 *)skb->data & HCI_FLT_EVENT_BITS);
if (!hci_test_bit(flt_event, &flt->event_mask))
return true;
/* Check filter only when opcode is set */
if (!flt->opcode)
return false;
if (flt_event == HCI_EV_CMD_COMPLETE &&
flt->opcode != get_unaligned((__le16 *)(skb->data + 3)))
return true;
if (flt_event == HCI_EV_CMD_STATUS &&
flt->opcode != get_unaligned((__le16 *)(skb->data + 4)))
return true;
return false;
}
/* Send frame to RAW socket */
void hci_send_to_sock(struct hci_dev *hdev, struct sk_buff *skb)
{
struct sock *sk;
struct sk_buff *skb_copy = NULL;
BT_DBG("hdev %p len %d", hdev, skb->len);
read_lock(&hci_sk_list.lock);
sk_for_each(sk, &hci_sk_list.head) {
struct sk_buff *nskb;
if (sk->sk_state != BT_BOUND || hci_pi(sk)->hdev != hdev)
continue;
/* Don't send frame to the socket it came from */
if (skb->sk == sk)
continue;
if (hci_pi(sk)->channel == HCI_CHANNEL_RAW) {
if (is_filtered_packet(sk, skb))
continue;
} else if (hci_pi(sk)->channel == HCI_CHANNEL_USER) {
if (!bt_cb(skb)->incoming)
continue;
if (bt_cb(skb)->pkt_type != HCI_EVENT_PKT &&
bt_cb(skb)->pkt_type != HCI_ACLDATA_PKT &&
bt_cb(skb)->pkt_type != HCI_SCODATA_PKT)
continue;
} else {
/* Don't send frame to other channel types */
continue;
}
if (!skb_copy) {
/* Create a private copy with headroom */
skb_copy = __pskb_copy(skb, 1, GFP_ATOMIC);
if (!skb_copy)
continue;
/* Put type byte before the data */
memcpy(skb_push(skb_copy, 1), &bt_cb(skb)->pkt_type, 1);
}
nskb = skb_clone(skb_copy, GFP_ATOMIC);
if (!nskb)
continue;
if (sock_queue_rcv_skb(sk, nskb))
kfree_skb(nskb);
}
read_unlock(&hci_sk_list.lock);
kfree_skb(skb_copy);
}
/* Send frame to control socket */
void hci_send_to_control(struct sk_buff *skb, struct sock *skip_sk)
{
struct sock *sk;
BT_DBG("len %d", skb->len);
read_lock(&hci_sk_list.lock);
sk_for_each(sk, &hci_sk_list.head) {
struct sk_buff *nskb;
/* Skip the original socket */
if (sk == skip_sk)
continue;
if (sk->sk_state != BT_BOUND)
continue;
if (hci_pi(sk)->channel != HCI_CHANNEL_CONTROL)
continue;
nskb = skb_clone(skb, GFP_ATOMIC);
if (!nskb)
continue;
if (sock_queue_rcv_skb(sk, nskb))
kfree_skb(nskb);
}
read_unlock(&hci_sk_list.lock);
}
/* Send frame to monitor socket */
void hci_send_to_monitor(struct hci_dev *hdev, struct sk_buff *skb)
{
struct sock *sk;
struct sk_buff *skb_copy = NULL;
__le16 opcode;
if (!atomic_read(&monitor_promisc))
return;
BT_DBG("hdev %p len %d", hdev, skb->len);
switch (bt_cb(skb)->pkt_type) {
case HCI_COMMAND_PKT:
opcode = __constant_cpu_to_le16(HCI_MON_COMMAND_PKT);
break;
case HCI_EVENT_PKT:
opcode = __constant_cpu_to_le16(HCI_MON_EVENT_PKT);
break;
case HCI_ACLDATA_PKT:
if (bt_cb(skb)->incoming)
opcode = __constant_cpu_to_le16(HCI_MON_ACL_RX_PKT);
else
opcode = __constant_cpu_to_le16(HCI_MON_ACL_TX_PKT);
break;
case HCI_SCODATA_PKT:
if (bt_cb(skb)->incoming)
opcode = __constant_cpu_to_le16(HCI_MON_SCO_RX_PKT);
else
opcode = __constant_cpu_to_le16(HCI_MON_SCO_TX_PKT);
break;
default:
return;
}
read_lock(&hci_sk_list.lock);
sk_for_each(sk, &hci_sk_list.head) {
struct sk_buff *nskb;
if (sk->sk_state != BT_BOUND)
continue;
if (hci_pi(sk)->channel != HCI_CHANNEL_MONITOR)
continue;
if (!skb_copy) {
struct hci_mon_hdr *hdr;
/* Create a private copy with headroom */
skb_copy = __pskb_copy(skb, HCI_MON_HDR_SIZE,
GFP_ATOMIC);
if (!skb_copy)
continue;
/* Put header before the data */
hdr = (void *) skb_push(skb_copy, HCI_MON_HDR_SIZE);
hdr->opcode = opcode;
hdr->index = cpu_to_le16(hdev->id);
hdr->len = cpu_to_le16(skb->len);
}
nskb = skb_clone(skb_copy, GFP_ATOMIC);
if (!nskb)
continue;
if (sock_queue_rcv_skb(sk, nskb))
kfree_skb(nskb);
}
read_unlock(&hci_sk_list.lock);
kfree_skb(skb_copy);
}
static void send_monitor_event(struct sk_buff *skb)
{
struct sock *sk;
BT_DBG("len %d", skb->len);
read_lock(&hci_sk_list.lock);
sk_for_each(sk, &hci_sk_list.head) {
struct sk_buff *nskb;
if (sk->sk_state != BT_BOUND)
continue;
if (hci_pi(sk)->channel != HCI_CHANNEL_MONITOR)
continue;
nskb = skb_clone(skb, GFP_ATOMIC);
if (!nskb)
continue;
if (sock_queue_rcv_skb(sk, nskb))
kfree_skb(nskb);
}
read_unlock(&hci_sk_list.lock);
}
static struct sk_buff *create_monitor_event(struct hci_dev *hdev, int event)
{
struct hci_mon_hdr *hdr;
struct hci_mon_new_index *ni;
struct sk_buff *skb;
__le16 opcode;
switch (event) {
case HCI_DEV_REG:
skb = bt_skb_alloc(HCI_MON_NEW_INDEX_SIZE, GFP_ATOMIC);
if (!skb)
return NULL;
ni = (void *) skb_put(skb, HCI_MON_NEW_INDEX_SIZE);
ni->type = hdev->dev_type;
ni->bus = hdev->bus;
bacpy(&ni->bdaddr, &hdev->bdaddr);
memcpy(ni->name, hdev->name, 8);
opcode = __constant_cpu_to_le16(HCI_MON_NEW_INDEX);
break;
case HCI_DEV_UNREG:
skb = bt_skb_alloc(0, GFP_ATOMIC);
if (!skb)
return NULL;
opcode = __constant_cpu_to_le16(HCI_MON_DEL_INDEX);
break;
default:
return NULL;
}
__net_timestamp(skb);
hdr = (void *) skb_push(skb, HCI_MON_HDR_SIZE);
hdr->opcode = opcode;
hdr->index = cpu_to_le16(hdev->id);
hdr->len = cpu_to_le16(skb->len - HCI_MON_HDR_SIZE);
return skb;
}
static void send_monitor_replay(struct sock *sk)
{
struct hci_dev *hdev;
read_lock(&hci_dev_list_lock);
list_for_each_entry(hdev, &hci_dev_list, list) {
struct sk_buff *skb;
skb = create_monitor_event(hdev, HCI_DEV_REG);
if (!skb)
continue;
if (sock_queue_rcv_skb(sk, skb))
kfree_skb(skb);
}
read_unlock(&hci_dev_list_lock);
}
/* Generate internal stack event */
static void hci_si_event(struct hci_dev *hdev, int type, int dlen, void *data)
{
struct hci_event_hdr *hdr;
struct hci_ev_stack_internal *ev;
struct sk_buff *skb;
skb = bt_skb_alloc(HCI_EVENT_HDR_SIZE + sizeof(*ev) + dlen, GFP_ATOMIC);
if (!skb)
return;
hdr = (void *) skb_put(skb, HCI_EVENT_HDR_SIZE);
hdr->evt = HCI_EV_STACK_INTERNAL;
hdr->plen = sizeof(*ev) + dlen;
ev = (void *) skb_put(skb, sizeof(*ev) + dlen);
ev->type = type;
memcpy(ev->data, data, dlen);
bt_cb(skb)->incoming = 1;
__net_timestamp(skb);
bt_cb(skb)->pkt_type = HCI_EVENT_PKT;
hci_send_to_sock(hdev, skb);
kfree_skb(skb);
}
void hci_sock_dev_event(struct hci_dev *hdev, int event)
{
struct hci_ev_si_device ev;
BT_DBG("hdev %s event %d", hdev->name, event);
/* Send event to monitor */
if (atomic_read(&monitor_promisc)) {
struct sk_buff *skb;
skb = create_monitor_event(hdev, event);
if (skb) {
send_monitor_event(skb);
kfree_skb(skb);
}
}
/* Send event to sockets */
ev.event = event;
ev.dev_id = hdev->id;
hci_si_event(NULL, HCI_EV_SI_DEVICE, sizeof(ev), &ev);
if (event == HCI_DEV_UNREG) {
struct sock *sk;
/* Detach sockets from device */
read_lock(&hci_sk_list.lock);
sk_for_each(sk, &hci_sk_list.head) {
bh_lock_sock_nested(sk);
if (hci_pi(sk)->hdev == hdev) {
hci_pi(sk)->hdev = NULL;
sk->sk_err = EPIPE;
sk->sk_state = BT_OPEN;
sk->sk_state_change(sk);
hci_dev_put(hdev);
}
bh_unlock_sock(sk);
}
read_unlock(&hci_sk_list.lock);
}
}
static int hci_sock_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct hci_dev *hdev;
BT_DBG("sock %p sk %p", sock, sk);
if (!sk)
return 0;
hdev = hci_pi(sk)->hdev;
if (hci_pi(sk)->channel == HCI_CHANNEL_MONITOR)
atomic_dec(&monitor_promisc);
bt_sock_unlink(&hci_sk_list, sk);
if (hdev) {
if (hci_pi(sk)->channel == HCI_CHANNEL_USER) {
mgmt_index_added(hdev);
clear_bit(HCI_USER_CHANNEL, &hdev->dev_flags);
hci_dev_close(hdev->id);
}
atomic_dec(&hdev->promisc);
hci_dev_put(hdev);
}
sock_orphan(sk);
skb_queue_purge(&sk->sk_receive_queue);
skb_queue_purge(&sk->sk_write_queue);
sock_put(sk);
return 0;
}
static int hci_sock_blacklist_add(struct hci_dev *hdev, void __user *arg)
{
bdaddr_t bdaddr;
int err;
if (copy_from_user(&bdaddr, arg, sizeof(bdaddr)))
return -EFAULT;
hci_dev_lock(hdev);
err = hci_blacklist_add(hdev, &bdaddr, BDADDR_BREDR);
hci_dev_unlock(hdev);
return err;
}
static int hci_sock_blacklist_del(struct hci_dev *hdev, void __user *arg)
{
bdaddr_t bdaddr;
int err;
if (copy_from_user(&bdaddr, arg, sizeof(bdaddr)))
return -EFAULT;
hci_dev_lock(hdev);
err = hci_blacklist_del(hdev, &bdaddr, BDADDR_BREDR);
hci_dev_unlock(hdev);
return err;
}
/* Ioctls that require bound socket */
static int hci_sock_bound_ioctl(struct sock *sk, unsigned int cmd,
unsigned long arg)
{
struct hci_dev *hdev = hci_pi(sk)->hdev;
if (!hdev)
return -EBADFD;
if (test_bit(HCI_USER_CHANNEL, &hdev->dev_flags))
return -EBUSY;
if (hdev->dev_type != HCI_BREDR)
return -EOPNOTSUPP;
switch (cmd) {
case HCISETRAW:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (test_bit(HCI_QUIRK_RAW_DEVICE, &hdev->quirks))
return -EPERM;
if (arg)
set_bit(HCI_RAW, &hdev->flags);
else
clear_bit(HCI_RAW, &hdev->flags);
return 0;
case HCIGETCONNINFO:
return hci_get_conn_info(hdev, (void __user *) arg);
case HCIGETAUTHINFO:
return hci_get_auth_info(hdev, (void __user *) arg);
case HCIBLOCKADDR:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return hci_sock_blacklist_add(hdev, (void __user *) arg);
case HCIUNBLOCKADDR:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return hci_sock_blacklist_del(hdev, (void __user *) arg);
}
return -ENOIOCTLCMD;
}
static int hci_sock_ioctl(struct socket *sock, unsigned int cmd,
unsigned long arg)
{
void __user *argp = (void __user *) arg;
struct sock *sk = sock->sk;
int err;
BT_DBG("cmd %x arg %lx", cmd, arg);
lock_sock(sk);
if (hci_pi(sk)->channel != HCI_CHANNEL_RAW) {
err = -EBADFD;
goto done;
}
release_sock(sk);
switch (cmd) {
case HCIGETDEVLIST:
return hci_get_dev_list(argp);
case HCIGETDEVINFO:
return hci_get_dev_info(argp);
case HCIGETCONNLIST:
return hci_get_conn_list(argp);
case HCIDEVUP:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return hci_dev_open(arg);
case HCIDEVDOWN:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return hci_dev_close(arg);
case HCIDEVRESET:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return hci_dev_reset(arg);
case HCIDEVRESTAT:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return hci_dev_reset_stat(arg);
case HCISETSCAN:
case HCISETAUTH:
case HCISETENCRYPT:
case HCISETPTYPE:
case HCISETLINKPOL:
case HCISETLINKMODE:
case HCISETACLMTU:
case HCISETSCOMTU:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return hci_dev_cmd(cmd, argp);
case HCIINQUIRY:
return hci_inquiry(argp);
}
lock_sock(sk);
err = hci_sock_bound_ioctl(sk, cmd, arg);
done:
release_sock(sk);
return err;
}
static int hci_sock_bind(struct socket *sock, struct sockaddr *addr,
int addr_len)
{
struct sockaddr_hci haddr;
struct sock *sk = sock->sk;
struct hci_dev *hdev = NULL;
int len, err = 0;
BT_DBG("sock %p sk %p", sock, sk);
if (!addr)
return -EINVAL;
memset(&haddr, 0, sizeof(haddr));
len = min_t(unsigned int, sizeof(haddr), addr_len);
memcpy(&haddr, addr, len);
if (haddr.hci_family != AF_BLUETOOTH)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state == BT_BOUND) {
err = -EALREADY;
goto done;
}
switch (haddr.hci_channel) {
case HCI_CHANNEL_RAW:
if (hci_pi(sk)->hdev) {
err = -EALREADY;
goto done;
}
if (haddr.hci_dev != HCI_DEV_NONE) {
hdev = hci_dev_get(haddr.hci_dev);
if (!hdev) {
err = -ENODEV;
goto done;
}
atomic_inc(&hdev->promisc);
}
hci_pi(sk)->hdev = hdev;
break;
case HCI_CHANNEL_USER:
if (hci_pi(sk)->hdev) {
err = -EALREADY;
goto done;
}
if (haddr.hci_dev == HCI_DEV_NONE) {
err = -EINVAL;
goto done;
}
if (!capable(CAP_NET_ADMIN)) {
err = -EPERM;
goto done;
}
hdev = hci_dev_get(haddr.hci_dev);
if (!hdev) {
err = -ENODEV;
goto done;
}
if (test_bit(HCI_UP, &hdev->flags) ||
test_bit(HCI_INIT, &hdev->flags) ||
test_bit(HCI_SETUP, &hdev->dev_flags)) {
err = -EBUSY;
hci_dev_put(hdev);
goto done;
}
if (test_and_set_bit(HCI_USER_CHANNEL, &hdev->dev_flags)) {
err = -EUSERS;
hci_dev_put(hdev);
goto done;
}
mgmt_index_removed(hdev);
err = hci_dev_open(hdev->id);
if (err) {
clear_bit(HCI_USER_CHANNEL, &hdev->dev_flags);
hci_dev_put(hdev);
goto done;
}
atomic_inc(&hdev->promisc);
hci_pi(sk)->hdev = hdev;
break;
case HCI_CHANNEL_CONTROL:
if (haddr.hci_dev != HCI_DEV_NONE) {
err = -EINVAL;
goto done;
}
if (!capable(CAP_NET_ADMIN)) {
err = -EPERM;
goto done;
}
break;
case HCI_CHANNEL_MONITOR:
if (haddr.hci_dev != HCI_DEV_NONE) {
err = -EINVAL;
goto done;
}
if (!capable(CAP_NET_RAW)) {
err = -EPERM;
goto done;
}
send_monitor_replay(sk);
atomic_inc(&monitor_promisc);
break;
default:
err = -EINVAL;
goto done;
}
hci_pi(sk)->channel = haddr.hci_channel;
sk->sk_state = BT_BOUND;
done:
release_sock(sk);
return err;
}
static int hci_sock_getname(struct socket *sock, struct sockaddr *addr,
int *addr_len, int peer)
{
struct sockaddr_hci *haddr = (struct sockaddr_hci *) addr;
struct sock *sk = sock->sk;
struct hci_dev *hdev;
int err = 0;
BT_DBG("sock %p sk %p", sock, sk);
if (peer)
return -EOPNOTSUPP;
lock_sock(sk);
hdev = hci_pi(sk)->hdev;
if (!hdev) {
err = -EBADFD;
goto done;
}
*addr_len = sizeof(*haddr);
haddr->hci_family = AF_BLUETOOTH;
haddr->hci_dev = hdev->id;
haddr->hci_channel= hci_pi(sk)->channel;
done:
release_sock(sk);
return err;
}
static void hci_sock_cmsg(struct sock *sk, struct msghdr *msg,
struct sk_buff *skb)
{
__u32 mask = hci_pi(sk)->cmsg_mask;
if (mask & HCI_CMSG_DIR) {
int incoming = bt_cb(skb)->incoming;
put_cmsg(msg, SOL_HCI, HCI_CMSG_DIR, sizeof(incoming),
&incoming);
}
if (mask & HCI_CMSG_TSTAMP) {
#ifdef CONFIG_COMPAT
struct compat_timeval ctv;
#endif
struct timeval tv;
void *data;
int len;
skb_get_timestamp(skb, &tv);
data = &tv;
len = sizeof(tv);
#ifdef CONFIG_COMPAT
if (!COMPAT_USE_64BIT_TIME &&
(msg->msg_flags & MSG_CMSG_COMPAT)) {
ctv.tv_sec = tv.tv_sec;
ctv.tv_usec = tv.tv_usec;
data = &ctv;
len = sizeof(ctv);
}
#endif
put_cmsg(msg, SOL_HCI, HCI_CMSG_TSTAMP, len, data);
}
}
static int hci_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
int noblock = flags & MSG_DONTWAIT;
struct sock *sk = sock->sk;
struct sk_buff *skb;
int copied, err;
BT_DBG("sock %p, sk %p", sock, sk);
if (flags & (MSG_OOB))
return -EOPNOTSUPP;
if (sk->sk_state == BT_CLOSED)
return 0;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
return err;
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
skb_reset_transport_header(skb);
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
switch (hci_pi(sk)->channel) {
case HCI_CHANNEL_RAW:
hci_sock_cmsg(sk, msg, skb);
break;
case HCI_CHANNEL_USER:
case HCI_CHANNEL_CONTROL:
case HCI_CHANNEL_MONITOR:
sock_recv_timestamp(msg, sk, skb);
break;
}
skb_free_datagram(sk, skb);
return err ? : copied;
}
static int hci_sock_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct hci_dev *hdev;
struct sk_buff *skb;
int err;
BT_DBG("sock %p sk %p", sock, sk);
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_NOSIGNAL|MSG_ERRQUEUE))
return -EINVAL;
if (len < 4 || len > HCI_MAX_FRAME_SIZE)
return -EINVAL;
lock_sock(sk);
switch (hci_pi(sk)->channel) {
case HCI_CHANNEL_RAW:
case HCI_CHANNEL_USER:
break;
case HCI_CHANNEL_CONTROL:
err = mgmt_control(sk, msg, len);
goto done;
case HCI_CHANNEL_MONITOR:
err = -EOPNOTSUPP;
goto done;
default:
err = -EINVAL;
goto done;
}
hdev = hci_pi(sk)->hdev;
if (!hdev) {
err = -EBADFD;
goto done;
}
if (!test_bit(HCI_UP, &hdev->flags)) {
err = -ENETDOWN;
goto done;
}
skb = bt_skb_send_alloc(sk, len, msg->msg_flags & MSG_DONTWAIT, &err);
if (!skb)
goto done;
if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {
err = -EFAULT;
goto drop;
}
bt_cb(skb)->pkt_type = *((unsigned char *) skb->data);
skb_pull(skb, 1);
if (hci_pi(sk)->channel == HCI_CHANNEL_RAW &&
bt_cb(skb)->pkt_type == HCI_COMMAND_PKT) {
u16 opcode = get_unaligned_le16(skb->data);
u16 ogf = hci_opcode_ogf(opcode);
u16 ocf = hci_opcode_ocf(opcode);
if (((ogf > HCI_SFLT_MAX_OGF) ||
!hci_test_bit(ocf & HCI_FLT_OCF_BITS,
&hci_sec_filter.ocf_mask[ogf])) &&
!capable(CAP_NET_RAW)) {
err = -EPERM;
goto drop;
}
if (test_bit(HCI_RAW, &hdev->flags) || (ogf == 0x3f)) {
skb_queue_tail(&hdev->raw_q, skb);
queue_work(hdev->workqueue, &hdev->tx_work);
} else {
/* Stand-alone HCI commands must be flaged as
* single-command requests.
*/
bt_cb(skb)->req.start = true;
skb_queue_tail(&hdev->cmd_q, skb);
queue_work(hdev->workqueue, &hdev->cmd_work);
}
} else {
if (!capable(CAP_NET_RAW)) {
err = -EPERM;
goto drop;
}
if (hci_pi(sk)->channel == HCI_CHANNEL_USER &&
bt_cb(skb)->pkt_type != HCI_COMMAND_PKT &&
bt_cb(skb)->pkt_type != HCI_ACLDATA_PKT &&
bt_cb(skb)->pkt_type != HCI_SCODATA_PKT) {
err = -EINVAL;
goto drop;
}
skb_queue_tail(&hdev->raw_q, skb);
queue_work(hdev->workqueue, &hdev->tx_work);
}
err = len;
done:
release_sock(sk);
return err;
drop:
kfree_skb(skb);
goto done;
}
static int hci_sock_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int len)
{
struct hci_ufilter uf = { .opcode = 0 };
struct sock *sk = sock->sk;
int err = 0, opt = 0;
BT_DBG("sk %p, opt %d", sk, optname);
lock_sock(sk);
if (hci_pi(sk)->channel != HCI_CHANNEL_RAW) {
err = -EBADFD;
goto done;
}
switch (optname) {
case HCI_DATA_DIR:
if (get_user(opt, (int __user *)optval)) {
err = -EFAULT;
break;
}
if (opt)
hci_pi(sk)->cmsg_mask |= HCI_CMSG_DIR;
else
hci_pi(sk)->cmsg_mask &= ~HCI_CMSG_DIR;
break;
case HCI_TIME_STAMP:
if (get_user(opt, (int __user *)optval)) {
err = -EFAULT;
break;
}
if (opt)
hci_pi(sk)->cmsg_mask |= HCI_CMSG_TSTAMP;
else
hci_pi(sk)->cmsg_mask &= ~HCI_CMSG_TSTAMP;
break;
case HCI_FILTER:
{
struct hci_filter *f = &hci_pi(sk)->filter;
uf.type_mask = f->type_mask;
uf.opcode = f->opcode;
uf.event_mask[0] = *((u32 *) f->event_mask + 0);
uf.event_mask[1] = *((u32 *) f->event_mask + 1);
}
len = min_t(unsigned int, len, sizeof(uf));
if (copy_from_user(&uf, optval, len)) {
err = -EFAULT;
break;
}
if (!capable(CAP_NET_RAW)) {
uf.type_mask &= hci_sec_filter.type_mask;
uf.event_mask[0] &= *((u32 *) hci_sec_filter.event_mask + 0);
uf.event_mask[1] &= *((u32 *) hci_sec_filter.event_mask + 1);
}
{
struct hci_filter *f = &hci_pi(sk)->filter;
f->type_mask = uf.type_mask;
f->opcode = uf.opcode;
*((u32 *) f->event_mask + 0) = uf.event_mask[0];
*((u32 *) f->event_mask + 1) = uf.event_mask[1];
}
break;
default:
err = -ENOPROTOOPT;
break;
}
done:
release_sock(sk);
return err;
}
static int hci_sock_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct hci_ufilter uf;
struct sock *sk = sock->sk;
int len, opt, err = 0;
BT_DBG("sk %p, opt %d", sk, optname);
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
if (hci_pi(sk)->channel != HCI_CHANNEL_RAW) {
err = -EBADFD;
goto done;
}
switch (optname) {
case HCI_DATA_DIR:
if (hci_pi(sk)->cmsg_mask & HCI_CMSG_DIR)
opt = 1;
else
opt = 0;
if (put_user(opt, optval))
err = -EFAULT;
break;
case HCI_TIME_STAMP:
if (hci_pi(sk)->cmsg_mask & HCI_CMSG_TSTAMP)
opt = 1;
else
opt = 0;
if (put_user(opt, optval))
err = -EFAULT;
break;
case HCI_FILTER:
{
struct hci_filter *f = &hci_pi(sk)->filter;
memset(&uf, 0, sizeof(uf));
uf.type_mask = f->type_mask;
uf.opcode = f->opcode;
uf.event_mask[0] = *((u32 *) f->event_mask + 0);
uf.event_mask[1] = *((u32 *) f->event_mask + 1);
}
len = min_t(unsigned int, len, sizeof(uf));
if (copy_to_user(optval, &uf, len))
err = -EFAULT;
break;
default:
err = -ENOPROTOOPT;
break;
}
done:
release_sock(sk);
return err;
}
static const struct proto_ops hci_sock_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.release = hci_sock_release,
.bind = hci_sock_bind,
.getname = hci_sock_getname,
.sendmsg = hci_sock_sendmsg,
.recvmsg = hci_sock_recvmsg,
.ioctl = hci_sock_ioctl,
.poll = datagram_poll,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = hci_sock_setsockopt,
.getsockopt = hci_sock_getsockopt,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.mmap = sock_no_mmap
};
static struct proto hci_sk_proto = {
.name = "HCI",
.owner = THIS_MODULE,
.obj_size = sizeof(struct hci_pinfo)
};
static int hci_sock_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
BT_DBG("sock %p", sock);
if (sock->type != SOCK_RAW)
return -ESOCKTNOSUPPORT;
sock->ops = &hci_sock_ops;
sk = sk_alloc(net, PF_BLUETOOTH, GFP_ATOMIC, &hci_sk_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
sock_reset_flag(sk, SOCK_ZAPPED);
sk->sk_protocol = protocol;
sock->state = SS_UNCONNECTED;
sk->sk_state = BT_OPEN;
bt_sock_link(&hci_sk_list, sk);
return 0;
}
static const struct net_proto_family hci_sock_family_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.create = hci_sock_create,
};
int __init hci_sock_init(void)
{
int err;
err = proto_register(&hci_sk_proto, 0);
if (err < 0)
return err;
err = bt_sock_register(BTPROTO_HCI, &hci_sock_family_ops);
if (err < 0) {
BT_ERR("HCI socket registration failed");
goto error;
}
err = bt_procfs_init(&init_net, "hci", &hci_sk_list, NULL);
if (err < 0) {
BT_ERR("Failed to create HCI proc file");
bt_sock_unregister(BTPROTO_HCI);
goto error;
}
BT_INFO("HCI socket layer initialized");
return 0;
error:
proto_unregister(&hci_sk_proto);
return err;
}
void hci_sock_cleanup(void)
{
bt_procfs_cleanup(&init_net, "hci");
bt_sock_unregister(BTPROTO_HCI);
proto_unregister(&hci_sk_proto);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_9 |
crossvul-cpp_data_good_1762_1 | /* Request a key from userspace
*
* Copyright (C) 2004-2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* See Documentation/security/keys-request-key.txt
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/kmod.h>
#include <linux/err.h>
#include <linux/keyctl.h>
#include <linux/slab.h>
#include "internal.h"
#define key_negative_timeout 60 /* default timeout on a negative key's existence */
/**
* complete_request_key - Complete the construction of a key.
* @cons: The key construction record.
* @error: The success or failute of the construction.
*
* Complete the attempt to construct a key. The key will be negated
* if an error is indicated. The authorisation key will be revoked
* unconditionally.
*/
void complete_request_key(struct key_construction *cons, int error)
{
kenter("{%d,%d},%d", cons->key->serial, cons->authkey->serial, error);
if (error < 0)
key_negate_and_link(cons->key, key_negative_timeout, NULL,
cons->authkey);
else
key_revoke(cons->authkey);
key_put(cons->key);
key_put(cons->authkey);
kfree(cons);
}
EXPORT_SYMBOL(complete_request_key);
/*
* Initialise a usermode helper that is going to have a specific session
* keyring.
*
* This is called in context of freshly forked kthread before kernel_execve(),
* so we can simply install the desired session_keyring at this point.
*/
static int umh_keys_init(struct subprocess_info *info, struct cred *cred)
{
struct key *keyring = info->data;
return install_session_keyring_to_cred(cred, keyring);
}
/*
* Clean up a usermode helper with session keyring.
*/
static void umh_keys_cleanup(struct subprocess_info *info)
{
struct key *keyring = info->data;
key_put(keyring);
}
/*
* Call a usermode helper with a specific session keyring.
*/
static int call_usermodehelper_keys(char *path, char **argv, char **envp,
struct key *session_keyring, int wait)
{
struct subprocess_info *info;
info = call_usermodehelper_setup(path, argv, envp, GFP_KERNEL,
umh_keys_init, umh_keys_cleanup,
session_keyring);
if (!info)
return -ENOMEM;
key_get(session_keyring);
return call_usermodehelper_exec(info, wait);
}
/*
* Request userspace finish the construction of a key
* - execute "/sbin/request-key <op> <key> <uid> <gid> <keyring> <keyring> <keyring>"
*/
static int call_sbin_request_key(struct key_construction *cons,
const char *op,
void *aux)
{
const struct cred *cred = current_cred();
key_serial_t prkey, sskey;
struct key *key = cons->key, *authkey = cons->authkey, *keyring,
*session;
char *argv[9], *envp[3], uid_str[12], gid_str[12];
char key_str[12], keyring_str[3][12];
char desc[20];
int ret, i;
kenter("{%d},{%d},%s", key->serial, authkey->serial, op);
ret = install_user_keyrings();
if (ret < 0)
goto error_alloc;
/* allocate a new session keyring */
sprintf(desc, "_req.%u", key->serial);
cred = get_current_cred();
keyring = keyring_alloc(desc, cred->fsuid, cred->fsgid, cred,
KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ,
KEY_ALLOC_QUOTA_OVERRUN, NULL);
put_cred(cred);
if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto error_alloc;
}
/* attach the auth key to the session keyring */
ret = key_link(keyring, authkey);
if (ret < 0)
goto error_link;
/* record the UID and GID */
sprintf(uid_str, "%d", from_kuid(&init_user_ns, cred->fsuid));
sprintf(gid_str, "%d", from_kgid(&init_user_ns, cred->fsgid));
/* we say which key is under construction */
sprintf(key_str, "%d", key->serial);
/* we specify the process's default keyrings */
sprintf(keyring_str[0], "%d",
cred->thread_keyring ? cred->thread_keyring->serial : 0);
prkey = 0;
if (cred->process_keyring)
prkey = cred->process_keyring->serial;
sprintf(keyring_str[1], "%d", prkey);
rcu_read_lock();
session = rcu_dereference(cred->session_keyring);
if (!session)
session = cred->user->session_keyring;
sskey = session->serial;
rcu_read_unlock();
sprintf(keyring_str[2], "%d", sskey);
/* set up a minimal environment */
i = 0;
envp[i++] = "HOME=/";
envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
envp[i] = NULL;
/* set up the argument list */
i = 0;
argv[i++] = "/sbin/request-key";
argv[i++] = (char *) op;
argv[i++] = key_str;
argv[i++] = uid_str;
argv[i++] = gid_str;
argv[i++] = keyring_str[0];
argv[i++] = keyring_str[1];
argv[i++] = keyring_str[2];
argv[i] = NULL;
/* do it */
ret = call_usermodehelper_keys(argv[0], argv, envp, keyring,
UMH_WAIT_PROC);
kdebug("usermode -> 0x%x", ret);
if (ret >= 0) {
/* ret is the exit/wait code */
if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags) ||
key_validate(key) < 0)
ret = -ENOKEY;
else
/* ignore any errors from userspace if the key was
* instantiated */
ret = 0;
}
error_link:
key_put(keyring);
error_alloc:
complete_request_key(cons, ret);
kleave(" = %d", ret);
return ret;
}
/*
* Call out to userspace for key construction.
*
* Program failure is ignored in favour of key status.
*/
static int construct_key(struct key *key, const void *callout_info,
size_t callout_len, void *aux,
struct key *dest_keyring)
{
struct key_construction *cons;
request_key_actor_t actor;
struct key *authkey;
int ret;
kenter("%d,%p,%zu,%p", key->serial, callout_info, callout_len, aux);
cons = kmalloc(sizeof(*cons), GFP_KERNEL);
if (!cons)
return -ENOMEM;
/* allocate an authorisation key */
authkey = request_key_auth_new(key, callout_info, callout_len,
dest_keyring);
if (IS_ERR(authkey)) {
kfree(cons);
ret = PTR_ERR(authkey);
authkey = NULL;
} else {
cons->authkey = key_get(authkey);
cons->key = key_get(key);
/* make the call */
actor = call_sbin_request_key;
if (key->type->request_key)
actor = key->type->request_key;
ret = actor(cons, "create", aux);
/* check that the actor called complete_request_key() prior to
* returning an error */
WARN_ON(ret < 0 &&
!test_bit(KEY_FLAG_REVOKED, &authkey->flags));
key_put(authkey);
}
kleave(" = %d", ret);
return ret;
}
/*
* Get the appropriate destination keyring for the request.
*
* The keyring selected is returned with an extra reference upon it which the
* caller must release.
*/
static void construct_get_dest_keyring(struct key **_dest_keyring)
{
struct request_key_auth *rka;
const struct cred *cred = current_cred();
struct key *dest_keyring = *_dest_keyring, *authkey;
kenter("%p", dest_keyring);
/* find the appropriate keyring */
if (dest_keyring) {
/* the caller supplied one */
key_get(dest_keyring);
} else {
/* use a default keyring; falling through the cases until we
* find one that we actually have */
switch (cred->jit_keyring) {
case KEY_REQKEY_DEFL_DEFAULT:
case KEY_REQKEY_DEFL_REQUESTOR_KEYRING:
if (cred->request_key_auth) {
authkey = cred->request_key_auth;
down_read(&authkey->sem);
rka = authkey->payload.data;
if (!test_bit(KEY_FLAG_REVOKED,
&authkey->flags))
dest_keyring =
key_get(rka->dest_keyring);
up_read(&authkey->sem);
if (dest_keyring)
break;
}
case KEY_REQKEY_DEFL_THREAD_KEYRING:
dest_keyring = key_get(cred->thread_keyring);
if (dest_keyring)
break;
case KEY_REQKEY_DEFL_PROCESS_KEYRING:
dest_keyring = key_get(cred->process_keyring);
if (dest_keyring)
break;
case KEY_REQKEY_DEFL_SESSION_KEYRING:
rcu_read_lock();
dest_keyring = key_get(
rcu_dereference(cred->session_keyring));
rcu_read_unlock();
if (dest_keyring)
break;
case KEY_REQKEY_DEFL_USER_SESSION_KEYRING:
dest_keyring =
key_get(cred->user->session_keyring);
break;
case KEY_REQKEY_DEFL_USER_KEYRING:
dest_keyring = key_get(cred->user->uid_keyring);
break;
case KEY_REQKEY_DEFL_GROUP_KEYRING:
default:
BUG();
}
}
*_dest_keyring = dest_keyring;
kleave(" [dk %d]", key_serial(dest_keyring));
return;
}
/*
* Allocate a new key in under-construction state and attempt to link it in to
* the requested keyring.
*
* May return a key that's already under construction instead if there was a
* race between two thread calling request_key().
*/
static int construct_alloc_key(struct keyring_search_context *ctx,
struct key *dest_keyring,
unsigned long flags,
struct key_user *user,
struct key **_key)
{
struct assoc_array_edit *edit;
struct key *key;
key_perm_t perm;
key_ref_t key_ref;
int ret;
kenter("%s,%s,,,",
ctx->index_key.type->name, ctx->index_key.description);
*_key = NULL;
mutex_lock(&user->cons_lock);
perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
perm |= KEY_USR_VIEW;
if (ctx->index_key.type->read)
perm |= KEY_POS_READ;
if (ctx->index_key.type == &key_type_keyring ||
ctx->index_key.type->update)
perm |= KEY_POS_WRITE;
key = key_alloc(ctx->index_key.type, ctx->index_key.description,
ctx->cred->fsuid, ctx->cred->fsgid, ctx->cred,
perm, flags);
if (IS_ERR(key))
goto alloc_failed;
set_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags);
if (dest_keyring) {
ret = __key_link_begin(dest_keyring, &ctx->index_key, &edit);
if (ret < 0)
goto link_prealloc_failed;
}
/* attach the key to the destination keyring under lock, but we do need
* to do another check just in case someone beat us to it whilst we
* waited for locks */
mutex_lock(&key_construction_mutex);
key_ref = search_process_keyrings(ctx);
if (!IS_ERR(key_ref))
goto key_already_present;
if (dest_keyring)
__key_link(key, &edit);
mutex_unlock(&key_construction_mutex);
if (dest_keyring)
__key_link_end(dest_keyring, &ctx->index_key, edit);
mutex_unlock(&user->cons_lock);
*_key = key;
kleave(" = 0 [%d]", key_serial(key));
return 0;
/* the key is now present - we tell the caller that we found it by
* returning -EINPROGRESS */
key_already_present:
key_put(key);
mutex_unlock(&key_construction_mutex);
key = key_ref_to_ptr(key_ref);
if (dest_keyring) {
ret = __key_link_check_live_key(dest_keyring, key);
if (ret == 0)
__key_link(key, &edit);
__key_link_end(dest_keyring, &ctx->index_key, edit);
if (ret < 0)
goto link_check_failed;
}
mutex_unlock(&user->cons_lock);
*_key = key;
kleave(" = -EINPROGRESS [%d]", key_serial(key));
return -EINPROGRESS;
link_check_failed:
mutex_unlock(&user->cons_lock);
key_put(key);
kleave(" = %d [linkcheck]", ret);
return ret;
link_prealloc_failed:
mutex_unlock(&user->cons_lock);
key_put(key);
kleave(" = %d [prelink]", ret);
return ret;
alloc_failed:
mutex_unlock(&user->cons_lock);
kleave(" = %ld", PTR_ERR(key));
return PTR_ERR(key);
}
/*
* Commence key construction.
*/
static struct key *construct_key_and_link(struct keyring_search_context *ctx,
const char *callout_info,
size_t callout_len,
void *aux,
struct key *dest_keyring,
unsigned long flags)
{
struct key_user *user;
struct key *key;
int ret;
kenter("");
if (ctx->index_key.type == &key_type_keyring)
return ERR_PTR(-EPERM);
user = key_user_lookup(current_fsuid());
if (!user)
return ERR_PTR(-ENOMEM);
construct_get_dest_keyring(&dest_keyring);
ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key);
key_user_put(user);
if (ret == 0) {
ret = construct_key(key, callout_info, callout_len, aux,
dest_keyring);
if (ret < 0) {
kdebug("cons failed");
goto construction_failed;
}
} else if (ret == -EINPROGRESS) {
ret = 0;
} else {
goto couldnt_alloc_key;
}
key_put(dest_keyring);
kleave(" = key %d", key_serial(key));
return key;
construction_failed:
key_negate_and_link(key, key_negative_timeout, NULL, NULL);
key_put(key);
couldnt_alloc_key:
key_put(dest_keyring);
kleave(" = %d", ret);
return ERR_PTR(ret);
}
/**
* request_key_and_link - Request a key and cache it in a keyring.
* @type: The type of key we want.
* @description: The searchable description of the key.
* @callout_info: The data to pass to the instantiation upcall (or NULL).
* @callout_len: The length of callout_info.
* @aux: Auxiliary data for the upcall.
* @dest_keyring: Where to cache the key.
* @flags: Flags to key_alloc().
*
* A key matching the specified criteria is searched for in the process's
* keyrings and returned with its usage count incremented if found. Otherwise,
* if callout_info is not NULL, a key will be allocated and some service
* (probably in userspace) will be asked to instantiate it.
*
* If successfully found or created, the key will be linked to the destination
* keyring if one is provided.
*
* Returns a pointer to the key if successful; -EACCES, -ENOKEY, -EKEYREVOKED
* or -EKEYEXPIRED if an inaccessible, negative, revoked or expired key was
* found; -ENOKEY if no key was found and no @callout_info was given; -EDQUOT
* if insufficient key quota was available to create a new key; or -ENOMEM if
* insufficient memory was available.
*
* If the returned key was created, then it may still be under construction,
* and wait_for_key_construction() should be used to wait for that to complete.
*/
struct key *request_key_and_link(struct key_type *type,
const char *description,
const void *callout_info,
size_t callout_len,
void *aux,
struct key *dest_keyring,
unsigned long flags)
{
struct keyring_search_context ctx = {
.index_key.type = type,
.index_key.description = description,
.cred = current_cred(),
.match_data.cmp = key_default_cmp,
.match_data.raw_data = description,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
.flags = (KEYRING_SEARCH_DO_STATE_CHECK |
KEYRING_SEARCH_SKIP_EXPIRED),
};
struct key *key;
key_ref_t key_ref;
int ret;
kenter("%s,%s,%p,%zu,%p,%p,%lx",
ctx.index_key.type->name, ctx.index_key.description,
callout_info, callout_len, aux, dest_keyring, flags);
if (type->match_preparse) {
ret = type->match_preparse(&ctx.match_data);
if (ret < 0) {
key = ERR_PTR(ret);
goto error;
}
}
/* search all the process keyrings for a key */
key_ref = search_process_keyrings(&ctx);
if (!IS_ERR(key_ref)) {
key = key_ref_to_ptr(key_ref);
if (dest_keyring) {
construct_get_dest_keyring(&dest_keyring);
ret = key_link(dest_keyring, key);
key_put(dest_keyring);
if (ret < 0) {
key_put(key);
key = ERR_PTR(ret);
goto error_free;
}
}
} else if (PTR_ERR(key_ref) != -EAGAIN) {
key = ERR_CAST(key_ref);
} else {
/* the search failed, but the keyrings were searchable, so we
* should consult userspace if we can */
key = ERR_PTR(-ENOKEY);
if (!callout_info)
goto error_free;
key = construct_key_and_link(&ctx, callout_info, callout_len,
aux, dest_keyring, flags);
}
error_free:
if (type->match_free)
type->match_free(&ctx.match_data);
error:
kleave(" = %p", key);
return key;
}
/**
* wait_for_key_construction - Wait for construction of a key to complete
* @key: The key being waited for.
* @intr: Whether to wait interruptibly.
*
* Wait for a key to finish being constructed.
*
* Returns 0 if successful; -ERESTARTSYS if the wait was interrupted; -ENOKEY
* if the key was negated; or -EKEYREVOKED or -EKEYEXPIRED if the key was
* revoked or expired.
*/
int wait_for_key_construction(struct key *key, bool intr)
{
int ret;
ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT,
intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE);
if (ret)
return -ERESTARTSYS;
if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) {
smp_rmb();
return key->type_data.reject_error;
}
return key_validate(key);
}
EXPORT_SYMBOL(wait_for_key_construction);
/**
* request_key - Request a key and wait for construction
* @type: Type of key.
* @description: The searchable description of the key.
* @callout_info: The data to pass to the instantiation upcall (or NULL).
*
* As for request_key_and_link() except that it does not add the returned key
* to a keyring if found, new keys are always allocated in the user's quota,
* the callout_info must be a NUL-terminated string and no auxiliary data can
* be passed.
*
* Furthermore, it then works as wait_for_key_construction() to wait for the
* completion of keys undergoing construction with a non-interruptible wait.
*/
struct key *request_key(struct key_type *type,
const char *description,
const char *callout_info)
{
struct key *key;
size_t callout_len = 0;
int ret;
if (callout_info)
callout_len = strlen(callout_info);
key = request_key_and_link(type, description, callout_info, callout_len,
NULL, NULL, KEY_ALLOC_IN_QUOTA);
if (!IS_ERR(key)) {
ret = wait_for_key_construction(key, false);
if (ret < 0) {
key_put(key);
return ERR_PTR(ret);
}
}
return key;
}
EXPORT_SYMBOL(request_key);
/**
* request_key_with_auxdata - Request a key with auxiliary data for the upcaller
* @type: The type of key we want.
* @description: The searchable description of the key.
* @callout_info: The data to pass to the instantiation upcall (or NULL).
* @callout_len: The length of callout_info.
* @aux: Auxiliary data for the upcall.
*
* As for request_key_and_link() except that it does not add the returned key
* to a keyring if found and new keys are always allocated in the user's quota.
*
* Furthermore, it then works as wait_for_key_construction() to wait for the
* completion of keys undergoing construction with a non-interruptible wait.
*/
struct key *request_key_with_auxdata(struct key_type *type,
const char *description,
const void *callout_info,
size_t callout_len,
void *aux)
{
struct key *key;
int ret;
key = request_key_and_link(type, description, callout_info, callout_len,
aux, NULL, KEY_ALLOC_IN_QUOTA);
if (!IS_ERR(key)) {
ret = wait_for_key_construction(key, false);
if (ret < 0) {
key_put(key);
return ERR_PTR(ret);
}
}
return key;
}
EXPORT_SYMBOL(request_key_with_auxdata);
/*
* request_key_async - Request a key (allow async construction)
* @type: Type of key.
* @description: The searchable description of the key.
* @callout_info: The data to pass to the instantiation upcall (or NULL).
* @callout_len: The length of callout_info.
*
* As for request_key_and_link() except that it does not add the returned key
* to a keyring if found, new keys are always allocated in the user's quota and
* no auxiliary data can be passed.
*
* The caller should call wait_for_key_construction() to wait for the
* completion of the returned key if it is still undergoing construction.
*/
struct key *request_key_async(struct key_type *type,
const char *description,
const void *callout_info,
size_t callout_len)
{
return request_key_and_link(type, description, callout_info,
callout_len, NULL, NULL,
KEY_ALLOC_IN_QUOTA);
}
EXPORT_SYMBOL(request_key_async);
/*
* request a key with auxiliary data for the upcaller (allow async construction)
* @type: Type of key.
* @description: The searchable description of the key.
* @callout_info: The data to pass to the instantiation upcall (or NULL).
* @callout_len: The length of callout_info.
* @aux: Auxiliary data for the upcall.
*
* As for request_key_and_link() except that it does not add the returned key
* to a keyring if found and new keys are always allocated in the user's quota.
*
* The caller should call wait_for_key_construction() to wait for the
* completion of the returned key if it is still undergoing construction.
*/
struct key *request_key_async_with_auxdata(struct key_type *type,
const char *description,
const void *callout_info,
size_t callout_len,
void *aux)
{
return request_key_and_link(type, description, callout_info,
callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA);
}
EXPORT_SYMBOL(request_key_async_with_auxdata);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_1762_1 |
crossvul-cpp_data_good_1745_0 | /*
* linux/fs/ext4/namei.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/namei.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller (davem@caip.rutgers.edu), 1995
* Directory entry file type support and forward compatibility hooks
* for B-tree directories by Theodore Ts'o (tytso@mit.edu), 1998
* Hash Tree Directory indexing (c)
* Daniel Phillips, 2001
* Hash Tree Directory indexing porting
* Christopher Li, 2002
* Hash Tree Directory indexing cleanup
* Theodore Ts'o, 2002
*/
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/jbd2.h>
#include <linux/time.h>
#include <linux/fcntl.h>
#include <linux/stat.h>
#include <linux/string.h>
#include <linux/quotaops.h>
#include <linux/buffer_head.h>
#include <linux/bio.h>
#include "ext4.h"
#include "ext4_jbd2.h"
#include "xattr.h"
#include "acl.h"
#include <trace/events/ext4.h>
/*
* define how far ahead to read directories while searching them.
*/
#define NAMEI_RA_CHUNKS 2
#define NAMEI_RA_BLOCKS 4
#define NAMEI_RA_SIZE (NAMEI_RA_CHUNKS * NAMEI_RA_BLOCKS)
#define NAMEI_RA_INDEX(c,b) (((c) * NAMEI_RA_BLOCKS) + (b))
static struct buffer_head *ext4_append(handle_t *handle,
struct inode *inode,
ext4_lblk_t *block, int *err)
{
struct buffer_head *bh;
if (unlikely(EXT4_SB(inode->i_sb)->s_max_dir_size_kb &&
((inode->i_size >> 10) >=
EXT4_SB(inode->i_sb)->s_max_dir_size_kb))) {
*err = -ENOSPC;
return NULL;
}
*block = inode->i_size >> inode->i_sb->s_blocksize_bits;
bh = ext4_bread(handle, inode, *block, 1, err);
if (bh) {
inode->i_size += inode->i_sb->s_blocksize;
EXT4_I(inode)->i_disksize = inode->i_size;
*err = ext4_journal_get_write_access(handle, bh);
if (*err) {
brelse(bh);
bh = NULL;
}
}
return bh;
}
#ifndef assert
#define assert(test) J_ASSERT(test)
#endif
#ifdef DX_DEBUG
#define dxtrace(command) command
#else
#define dxtrace(command)
#endif
struct fake_dirent
{
__le32 inode;
__le16 rec_len;
u8 name_len;
u8 file_type;
};
struct dx_countlimit
{
__le16 limit;
__le16 count;
};
struct dx_entry
{
__le32 hash;
__le32 block;
};
/*
* dx_root_info is laid out so that if it should somehow get overlaid by a
* dirent the two low bits of the hash version will be zero. Therefore, the
* hash version mod 4 should never be 0. Sincerely, the paranoia department.
*/
struct dx_root
{
struct fake_dirent dot;
char dot_name[4];
struct fake_dirent dotdot;
char dotdot_name[4];
struct dx_root_info
{
__le32 reserved_zero;
u8 hash_version;
u8 info_length; /* 8 */
u8 indirect_levels;
u8 unused_flags;
}
info;
struct dx_entry entries[0];
};
struct dx_node
{
struct fake_dirent fake;
struct dx_entry entries[0];
};
struct dx_frame
{
struct buffer_head *bh;
struct dx_entry *entries;
struct dx_entry *at;
};
struct dx_map_entry
{
u32 hash;
u16 offs;
u16 size;
};
/*
* This goes at the end of each htree block.
*/
struct dx_tail {
u32 dt_reserved;
__le32 dt_checksum; /* crc32c(uuid+inum+dirblock) */
};
static inline ext4_lblk_t dx_get_block(struct dx_entry *entry);
static void dx_set_block(struct dx_entry *entry, ext4_lblk_t value);
static inline unsigned dx_get_hash(struct dx_entry *entry);
static void dx_set_hash(struct dx_entry *entry, unsigned value);
static unsigned dx_get_count(struct dx_entry *entries);
static unsigned dx_get_limit(struct dx_entry *entries);
static void dx_set_count(struct dx_entry *entries, unsigned value);
static void dx_set_limit(struct dx_entry *entries, unsigned value);
static unsigned dx_root_limit(struct inode *dir, unsigned infosize);
static unsigned dx_node_limit(struct inode *dir);
static struct dx_frame *dx_probe(const struct qstr *d_name,
struct inode *dir,
struct dx_hash_info *hinfo,
struct dx_frame *frame,
int *err);
static void dx_release(struct dx_frame *frames);
static int dx_make_map(struct ext4_dir_entry_2 *de, unsigned blocksize,
struct dx_hash_info *hinfo, struct dx_map_entry map[]);
static void dx_sort_map(struct dx_map_entry *map, unsigned count);
static struct ext4_dir_entry_2 *dx_move_dirents(char *from, char *to,
struct dx_map_entry *offsets, int count, unsigned blocksize);
static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize);
static void dx_insert_block(struct dx_frame *frame,
u32 hash, ext4_lblk_t block);
static int ext4_htree_next_block(struct inode *dir, __u32 hash,
struct dx_frame *frame,
struct dx_frame *frames,
__u32 *start_hash);
static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
const struct qstr *d_name,
struct ext4_dir_entry_2 **res_dir,
int *err);
static int ext4_dx_add_entry(handle_t *handle, struct dentry *dentry,
struct inode *inode);
/* checksumming functions */
#define EXT4_DIRENT_TAIL(block, blocksize) \
((struct ext4_dir_entry_tail *)(((void *)(block)) + \
((blocksize) - \
sizeof(struct ext4_dir_entry_tail))))
static void initialize_dirent_tail(struct ext4_dir_entry_tail *t,
unsigned int blocksize)
{
memset(t, 0, sizeof(struct ext4_dir_entry_tail));
t->det_rec_len = ext4_rec_len_to_disk(
sizeof(struct ext4_dir_entry_tail), blocksize);
t->det_reserved_ft = EXT4_FT_DIR_CSUM;
}
/* Walk through a dirent block to find a checksum "dirent" at the tail */
static struct ext4_dir_entry_tail *get_dirent_tail(struct inode *inode,
struct ext4_dir_entry *de)
{
struct ext4_dir_entry_tail *t;
#ifdef PARANOID
struct ext4_dir_entry *d, *top;
d = de;
top = (struct ext4_dir_entry *)(((void *)de) +
(EXT4_BLOCK_SIZE(inode->i_sb) -
sizeof(struct ext4_dir_entry_tail)));
while (d < top && d->rec_len)
d = (struct ext4_dir_entry *)(((void *)d) +
le16_to_cpu(d->rec_len));
if (d != top)
return NULL;
t = (struct ext4_dir_entry_tail *)d;
#else
t = EXT4_DIRENT_TAIL(de, EXT4_BLOCK_SIZE(inode->i_sb));
#endif
if (t->det_reserved_zero1 ||
le16_to_cpu(t->det_rec_len) != sizeof(struct ext4_dir_entry_tail) ||
t->det_reserved_zero2 ||
t->det_reserved_ft != EXT4_FT_DIR_CSUM)
return NULL;
return t;
}
static __le32 ext4_dirent_csum(struct inode *inode,
struct ext4_dir_entry *dirent, int size)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_inode_info *ei = EXT4_I(inode);
__u32 csum;
csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
return cpu_to_le32(csum);
}
int ext4_dirent_csum_verify(struct inode *inode, struct ext4_dir_entry *dirent)
{
struct ext4_dir_entry_tail *t;
if (!EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
return 1;
t = get_dirent_tail(inode, dirent);
if (!t) {
EXT4_ERROR_INODE(inode, "metadata_csum set but no space in dir "
"leaf for checksum. Please run e2fsck -D.");
return 0;
}
if (t->det_checksum != ext4_dirent_csum(inode, dirent,
(void *)t - (void *)dirent))
return 0;
return 1;
}
static void ext4_dirent_csum_set(struct inode *inode,
struct ext4_dir_entry *dirent)
{
struct ext4_dir_entry_tail *t;
if (!EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
return;
t = get_dirent_tail(inode, dirent);
if (!t) {
EXT4_ERROR_INODE(inode, "metadata_csum set but no space in dir "
"leaf for checksum. Please run e2fsck -D.");
return;
}
t->det_checksum = ext4_dirent_csum(inode, dirent,
(void *)t - (void *)dirent);
}
static inline int ext4_handle_dirty_dirent_node(handle_t *handle,
struct inode *inode,
struct buffer_head *bh)
{
ext4_dirent_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
return ext4_handle_dirty_metadata(handle, inode, bh);
}
static struct dx_countlimit *get_dx_countlimit(struct inode *inode,
struct ext4_dir_entry *dirent,
int *offset)
{
struct ext4_dir_entry *dp;
struct dx_root_info *root;
int count_offset;
if (le16_to_cpu(dirent->rec_len) == EXT4_BLOCK_SIZE(inode->i_sb))
count_offset = 8;
else if (le16_to_cpu(dirent->rec_len) == 12) {
dp = (struct ext4_dir_entry *)(((void *)dirent) + 12);
if (le16_to_cpu(dp->rec_len) !=
EXT4_BLOCK_SIZE(inode->i_sb) - 12)
return NULL;
root = (struct dx_root_info *)(((void *)dp + 12));
if (root->reserved_zero ||
root->info_length != sizeof(struct dx_root_info))
return NULL;
count_offset = 32;
} else
return NULL;
if (offset)
*offset = count_offset;
return (struct dx_countlimit *)(((void *)dirent) + count_offset);
}
static __le32 ext4_dx_csum(struct inode *inode, struct ext4_dir_entry *dirent,
int count_offset, int count, struct dx_tail *t)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_inode_info *ei = EXT4_I(inode);
__u32 csum, old_csum;
int size;
size = count_offset + (count * sizeof(struct dx_entry));
old_csum = t->dt_checksum;
t->dt_checksum = 0;
csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
csum = ext4_chksum(sbi, csum, (__u8 *)t, sizeof(struct dx_tail));
t->dt_checksum = old_csum;
return cpu_to_le32(csum);
}
static int ext4_dx_csum_verify(struct inode *inode,
struct ext4_dir_entry *dirent)
{
struct dx_countlimit *c;
struct dx_tail *t;
int count_offset, limit, count;
if (!EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
return 1;
c = get_dx_countlimit(inode, dirent, &count_offset);
if (!c) {
EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
return 1;
}
limit = le16_to_cpu(c->limit);
count = le16_to_cpu(c->count);
if (count_offset + (limit * sizeof(struct dx_entry)) >
EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
EXT4_ERROR_INODE(inode, "metadata_csum set but no space for "
"tree checksum found. Run e2fsck -D.");
return 1;
}
t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
if (t->dt_checksum != ext4_dx_csum(inode, dirent, count_offset,
count, t))
return 0;
return 1;
}
static void ext4_dx_csum_set(struct inode *inode, struct ext4_dir_entry *dirent)
{
struct dx_countlimit *c;
struct dx_tail *t;
int count_offset, limit, count;
if (!EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
return;
c = get_dx_countlimit(inode, dirent, &count_offset);
if (!c) {
EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
return;
}
limit = le16_to_cpu(c->limit);
count = le16_to_cpu(c->count);
if (count_offset + (limit * sizeof(struct dx_entry)) >
EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
EXT4_ERROR_INODE(inode, "metadata_csum set but no space for "
"tree checksum. Run e2fsck -D.");
return;
}
t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
t->dt_checksum = ext4_dx_csum(inode, dirent, count_offset, count, t);
}
static inline int ext4_handle_dirty_dx_node(handle_t *handle,
struct inode *inode,
struct buffer_head *bh)
{
ext4_dx_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
return ext4_handle_dirty_metadata(handle, inode, bh);
}
/*
* p is at least 6 bytes before the end of page
*/
static inline struct ext4_dir_entry_2 *
ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize)
{
return (struct ext4_dir_entry_2 *)((char *)p +
ext4_rec_len_from_disk(p->rec_len, blocksize));
}
/*
* Future: use high four bits of block for coalesce-on-delete flags
* Mask them off for now.
*/
static inline ext4_lblk_t dx_get_block(struct dx_entry *entry)
{
return le32_to_cpu(entry->block) & 0x00ffffff;
}
static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value)
{
entry->block = cpu_to_le32(value);
}
static inline unsigned dx_get_hash(struct dx_entry *entry)
{
return le32_to_cpu(entry->hash);
}
static inline void dx_set_hash(struct dx_entry *entry, unsigned value)
{
entry->hash = cpu_to_le32(value);
}
static inline unsigned dx_get_count(struct dx_entry *entries)
{
return le16_to_cpu(((struct dx_countlimit *) entries)->count);
}
static inline unsigned dx_get_limit(struct dx_entry *entries)
{
return le16_to_cpu(((struct dx_countlimit *) entries)->limit);
}
static inline void dx_set_count(struct dx_entry *entries, unsigned value)
{
((struct dx_countlimit *) entries)->count = cpu_to_le16(value);
}
static inline void dx_set_limit(struct dx_entry *entries, unsigned value)
{
((struct dx_countlimit *) entries)->limit = cpu_to_le16(value);
}
static inline unsigned dx_root_limit(struct inode *dir, unsigned infosize)
{
unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(1) -
EXT4_DIR_REC_LEN(2) - infosize;
if (EXT4_HAS_RO_COMPAT_FEATURE(dir->i_sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
entry_space -= sizeof(struct dx_tail);
return entry_space / sizeof(struct dx_entry);
}
static inline unsigned dx_node_limit(struct inode *dir)
{
unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(0);
if (EXT4_HAS_RO_COMPAT_FEATURE(dir->i_sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
entry_space -= sizeof(struct dx_tail);
return entry_space / sizeof(struct dx_entry);
}
/*
* Debug
*/
#ifdef DX_DEBUG
static void dx_show_index(char * label, struct dx_entry *entries)
{
int i, n = dx_get_count (entries);
printk(KERN_DEBUG "%s index ", label);
for (i = 0; i < n; i++) {
printk("%x->%lu ", i ? dx_get_hash(entries + i) :
0, (unsigned long)dx_get_block(entries + i));
}
printk("\n");
}
struct stats
{
unsigned names;
unsigned space;
unsigned bcount;
};
static struct stats dx_show_leaf(struct dx_hash_info *hinfo, struct ext4_dir_entry_2 *de,
int size, int show_names)
{
unsigned names = 0, space = 0;
char *base = (char *) de;
struct dx_hash_info h = *hinfo;
printk("names: ");
while ((char *) de < base + size)
{
if (de->inode)
{
if (show_names)
{
int len = de->name_len;
char *name = de->name;
while (len--) printk("%c", *name++);
ext4fs_dirhash(de->name, de->name_len, &h);
printk(":%x.%u ", h.hash,
(unsigned) ((char *) de - base));
}
space += EXT4_DIR_REC_LEN(de->name_len);
names++;
}
de = ext4_next_entry(de, size);
}
printk("(%i)\n", names);
return (struct stats) { names, space, 1 };
}
struct stats dx_show_entries(struct dx_hash_info *hinfo, struct inode *dir,
struct dx_entry *entries, int levels)
{
unsigned blocksize = dir->i_sb->s_blocksize;
unsigned count = dx_get_count(entries), names = 0, space = 0, i;
unsigned bcount = 0;
struct buffer_head *bh;
int err;
printk("%i indexed blocks...\n", count);
for (i = 0; i < count; i++, entries++)
{
ext4_lblk_t block = dx_get_block(entries);
ext4_lblk_t hash = i ? dx_get_hash(entries): 0;
u32 range = i < count - 1? (dx_get_hash(entries + 1) - hash): ~hash;
struct stats stats;
printk("%s%3u:%03u hash %8x/%8x ",levels?"":" ", i, block, hash, range);
if (!(bh = ext4_bread (NULL,dir, block, 0,&err))) continue;
stats = levels?
dx_show_entries(hinfo, dir, ((struct dx_node *) bh->b_data)->entries, levels - 1):
dx_show_leaf(hinfo, (struct ext4_dir_entry_2 *) bh->b_data, blocksize, 0);
names += stats.names;
space += stats.space;
bcount += stats.bcount;
brelse(bh);
}
if (bcount)
printk(KERN_DEBUG "%snames %u, fullness %u (%u%%)\n",
levels ? "" : " ", names, space/bcount,
(space/bcount)*100/blocksize);
return (struct stats) { names, space, bcount};
}
#endif /* DX_DEBUG */
/*
* Probe for a directory leaf block to search.
*
* dx_probe can return ERR_BAD_DX_DIR, which means there was a format
* error in the directory index, and the caller should fall back to
* searching the directory normally. The callers of dx_probe **MUST**
* check for this error code, and make sure it never gets reflected
* back to userspace.
*/
static struct dx_frame *
dx_probe(const struct qstr *d_name, struct inode *dir,
struct dx_hash_info *hinfo, struct dx_frame *frame_in, int *err)
{
unsigned count, indirect;
struct dx_entry *at, *entries, *p, *q, *m;
struct dx_root *root;
struct buffer_head *bh;
struct dx_frame *frame = frame_in;
u32 hash;
frame->bh = NULL;
if (!(bh = ext4_bread (NULL,dir, 0, 0, err)))
goto fail;
root = (struct dx_root *) bh->b_data;
if (root->info.hash_version != DX_HASH_TEA &&
root->info.hash_version != DX_HASH_HALF_MD4 &&
root->info.hash_version != DX_HASH_LEGACY) {
ext4_warning(dir->i_sb, "Unrecognised inode hash code %d",
root->info.hash_version);
brelse(bh);
*err = ERR_BAD_DX_DIR;
goto fail;
}
hinfo->hash_version = root->info.hash_version;
if (hinfo->hash_version <= DX_HASH_TEA)
hinfo->hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
hinfo->seed = EXT4_SB(dir->i_sb)->s_hash_seed;
if (d_name)
ext4fs_dirhash(d_name->name, d_name->len, hinfo);
hash = hinfo->hash;
if (root->info.unused_flags & 1) {
ext4_warning(dir->i_sb, "Unimplemented inode hash flags: %#06x",
root->info.unused_flags);
brelse(bh);
*err = ERR_BAD_DX_DIR;
goto fail;
}
if ((indirect = root->info.indirect_levels) > 1) {
ext4_warning(dir->i_sb, "Unimplemented inode hash depth: %#06x",
root->info.indirect_levels);
brelse(bh);
*err = ERR_BAD_DX_DIR;
goto fail;
}
if (!buffer_verified(bh) &&
!ext4_dx_csum_verify(dir, (struct ext4_dir_entry *)bh->b_data)) {
ext4_warning(dir->i_sb, "Root failed checksum");
brelse(bh);
*err = ERR_BAD_DX_DIR;
goto fail;
}
set_buffer_verified(bh);
entries = (struct dx_entry *) (((char *)&root->info) +
root->info.info_length);
if (dx_get_limit(entries) != dx_root_limit(dir,
root->info.info_length)) {
ext4_warning(dir->i_sb, "dx entry: limit != root limit");
brelse(bh);
*err = ERR_BAD_DX_DIR;
goto fail;
}
dxtrace(printk("Look up %x", hash));
while (1)
{
count = dx_get_count(entries);
if (!count || count > dx_get_limit(entries)) {
ext4_warning(dir->i_sb,
"dx entry: no count or count > limit");
brelse(bh);
*err = ERR_BAD_DX_DIR;
goto fail2;
}
p = entries + 1;
q = entries + count - 1;
while (p <= q)
{
m = p + (q - p)/2;
dxtrace(printk("."));
if (dx_get_hash(m) > hash)
q = m - 1;
else
p = m + 1;
}
if (0) // linear search cross check
{
unsigned n = count - 1;
at = entries;
while (n--)
{
dxtrace(printk(","));
if (dx_get_hash(++at) > hash)
{
at--;
break;
}
}
assert (at == p - 1);
}
at = p - 1;
dxtrace(printk(" %x->%u\n", at == entries? 0: dx_get_hash(at), dx_get_block(at)));
frame->bh = bh;
frame->entries = entries;
frame->at = at;
if (!indirect--) return frame;
if (!(bh = ext4_bread (NULL,dir, dx_get_block(at), 0, err)))
goto fail2;
at = entries = ((struct dx_node *) bh->b_data)->entries;
if (!buffer_verified(bh) &&
!ext4_dx_csum_verify(dir,
(struct ext4_dir_entry *)bh->b_data)) {
ext4_warning(dir->i_sb, "Node failed checksum");
brelse(bh);
*err = ERR_BAD_DX_DIR;
goto fail;
}
set_buffer_verified(bh);
if (dx_get_limit(entries) != dx_node_limit (dir)) {
ext4_warning(dir->i_sb,
"dx entry: limit != node limit");
brelse(bh);
*err = ERR_BAD_DX_DIR;
goto fail2;
}
frame++;
frame->bh = NULL;
}
fail2:
while (frame >= frame_in) {
brelse(frame->bh);
frame--;
}
fail:
if (*err == ERR_BAD_DX_DIR)
ext4_warning(dir->i_sb,
"Corrupt dir inode %lu, running e2fsck is "
"recommended.", dir->i_ino);
return NULL;
}
static void dx_release (struct dx_frame *frames)
{
if (frames[0].bh == NULL)
return;
if (((struct dx_root *) frames[0].bh->b_data)->info.indirect_levels)
brelse(frames[1].bh);
brelse(frames[0].bh);
}
/*
* This function increments the frame pointer to search the next leaf
* block, and reads in the necessary intervening nodes if the search
* should be necessary. Whether or not the search is necessary is
* controlled by the hash parameter. If the hash value is even, then
* the search is only continued if the next block starts with that
* hash value. This is used if we are searching for a specific file.
*
* If the hash value is HASH_NB_ALWAYS, then always go to the next block.
*
* This function returns 1 if the caller should continue to search,
* or 0 if it should not. If there is an error reading one of the
* index blocks, it will a negative error code.
*
* If start_hash is non-null, it will be filled in with the starting
* hash of the next page.
*/
static int ext4_htree_next_block(struct inode *dir, __u32 hash,
struct dx_frame *frame,
struct dx_frame *frames,
__u32 *start_hash)
{
struct dx_frame *p;
struct buffer_head *bh;
int err, num_frames = 0;
__u32 bhash;
p = frame;
/*
* Find the next leaf page by incrementing the frame pointer.
* If we run out of entries in the interior node, loop around and
* increment pointer in the parent node. When we break out of
* this loop, num_frames indicates the number of interior
* nodes need to be read.
*/
while (1) {
if (++(p->at) < p->entries + dx_get_count(p->entries))
break;
if (p == frames)
return 0;
num_frames++;
p--;
}
/*
* If the hash is 1, then continue only if the next page has a
* continuation hash of any value. This is used for readdir
* handling. Otherwise, check to see if the hash matches the
* desired contiuation hash. If it doesn't, return since
* there's no point to read in the successive index pages.
*/
bhash = dx_get_hash(p->at);
if (start_hash)
*start_hash = bhash;
if ((hash & 1) == 0) {
if ((bhash & ~1) != hash)
return 0;
}
/*
* If the hash is HASH_NB_ALWAYS, we always go to the next
* block so no check is necessary
*/
while (num_frames--) {
if (!(bh = ext4_bread(NULL, dir, dx_get_block(p->at),
0, &err)))
return err; /* Failure */
if (!buffer_verified(bh) &&
!ext4_dx_csum_verify(dir,
(struct ext4_dir_entry *)bh->b_data)) {
ext4_warning(dir->i_sb, "Node failed checksum");
return -EIO;
}
set_buffer_verified(bh);
p++;
brelse(p->bh);
p->bh = bh;
p->at = p->entries = ((struct dx_node *) bh->b_data)->entries;
}
return 1;
}
/*
* This function fills a red-black tree with information from a
* directory block. It returns the number directory entries loaded
* into the tree. If there is an error it is returned in err.
*/
static int htree_dirblock_to_tree(struct file *dir_file,
struct inode *dir, ext4_lblk_t block,
struct dx_hash_info *hinfo,
__u32 start_hash, __u32 start_minor_hash)
{
struct buffer_head *bh;
struct ext4_dir_entry_2 *de, *top;
int err = 0, count = 0;
dxtrace(printk(KERN_INFO "In htree dirblock_to_tree: block %lu\n",
(unsigned long)block));
if (!(bh = ext4_bread (NULL, dir, block, 0, &err)))
return err;
if (!buffer_verified(bh) &&
!ext4_dirent_csum_verify(dir, (struct ext4_dir_entry *)bh->b_data))
return -EIO;
set_buffer_verified(bh);
de = (struct ext4_dir_entry_2 *) bh->b_data;
top = (struct ext4_dir_entry_2 *) ((char *) de +
dir->i_sb->s_blocksize -
EXT4_DIR_REC_LEN(0));
for (; de < top; de = ext4_next_entry(de, dir->i_sb->s_blocksize)) {
if (ext4_check_dir_entry(dir, NULL, de, bh,
(block<<EXT4_BLOCK_SIZE_BITS(dir->i_sb))
+ ((char *)de - bh->b_data))) {
/* On error, skip the f_pos to the next block. */
dir_file->f_pos = (dir_file->f_pos |
(dir->i_sb->s_blocksize - 1)) + 1;
brelse(bh);
return count;
}
ext4fs_dirhash(de->name, de->name_len, hinfo);
if ((hinfo->hash < start_hash) ||
((hinfo->hash == start_hash) &&
(hinfo->minor_hash < start_minor_hash)))
continue;
if (de->inode == 0)
continue;
if ((err = ext4_htree_store_dirent(dir_file,
hinfo->hash, hinfo->minor_hash, de)) != 0) {
brelse(bh);
return err;
}
count++;
}
brelse(bh);
return count;
}
/*
* This function fills a red-black tree with information from a
* directory. We start scanning the directory in hash order, starting
* at start_hash and start_minor_hash.
*
* This function returns the number of entries inserted into the tree,
* or a negative error code.
*/
int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash,
__u32 start_minor_hash, __u32 *next_hash)
{
struct dx_hash_info hinfo;
struct ext4_dir_entry_2 *de;
struct dx_frame frames[2], *frame;
struct inode *dir;
ext4_lblk_t block;
int count = 0;
int ret, err;
__u32 hashval;
dxtrace(printk(KERN_DEBUG "In htree_fill_tree, start hash: %x:%x\n",
start_hash, start_minor_hash));
dir = dir_file->f_path.dentry->d_inode;
if (!(ext4_test_inode_flag(dir, EXT4_INODE_INDEX))) {
hinfo.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
if (hinfo.hash_version <= DX_HASH_TEA)
hinfo.hash_version +=
EXT4_SB(dir->i_sb)->s_hash_unsigned;
hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
count = htree_dirblock_to_tree(dir_file, dir, 0, &hinfo,
start_hash, start_minor_hash);
*next_hash = ~0;
return count;
}
hinfo.hash = start_hash;
hinfo.minor_hash = 0;
frame = dx_probe(NULL, dir, &hinfo, frames, &err);
if (!frame)
return err;
/* Add '.' and '..' from the htree header */
if (!start_hash && !start_minor_hash) {
de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
if ((err = ext4_htree_store_dirent(dir_file, 0, 0, de)) != 0)
goto errout;
count++;
}
if (start_hash < 2 || (start_hash ==2 && start_minor_hash==0)) {
de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
de = ext4_next_entry(de, dir->i_sb->s_blocksize);
if ((err = ext4_htree_store_dirent(dir_file, 2, 0, de)) != 0)
goto errout;
count++;
}
while (1) {
block = dx_get_block(frame->at);
ret = htree_dirblock_to_tree(dir_file, dir, block, &hinfo,
start_hash, start_minor_hash);
if (ret < 0) {
err = ret;
goto errout;
}
count += ret;
hashval = ~0;
ret = ext4_htree_next_block(dir, HASH_NB_ALWAYS,
frame, frames, &hashval);
*next_hash = hashval;
if (ret < 0) {
err = ret;
goto errout;
}
/*
* Stop if: (a) there are no more entries, or
* (b) we have inserted at least one entry and the
* next hash value is not a continuation
*/
if ((ret == 0) ||
(count && ((hashval & 1) == 0)))
break;
}
dx_release(frames);
dxtrace(printk(KERN_DEBUG "Fill tree: returned %d entries, "
"next hash: %x\n", count, *next_hash));
return count;
errout:
dx_release(frames);
return (err);
}
/*
* Directory block splitting, compacting
*/
/*
* Create map of hash values, offsets, and sizes, stored at end of block.
* Returns number of entries mapped.
*/
static int dx_make_map(struct ext4_dir_entry_2 *de, unsigned blocksize,
struct dx_hash_info *hinfo,
struct dx_map_entry *map_tail)
{
int count = 0;
char *base = (char *) de;
struct dx_hash_info h = *hinfo;
while ((char *) de < base + blocksize) {
if (de->name_len && de->inode) {
ext4fs_dirhash(de->name, de->name_len, &h);
map_tail--;
map_tail->hash = h.hash;
map_tail->offs = ((char *) de - base)>>2;
map_tail->size = le16_to_cpu(de->rec_len);
count++;
cond_resched();
}
/* XXX: do we need to check rec_len == 0 case? -Chris */
de = ext4_next_entry(de, blocksize);
}
return count;
}
/* Sort map by hash value */
static void dx_sort_map (struct dx_map_entry *map, unsigned count)
{
struct dx_map_entry *p, *q, *top = map + count - 1;
int more;
/* Combsort until bubble sort doesn't suck */
while (count > 2) {
count = count*10/13;
if (count - 9 < 2) /* 9, 10 -> 11 */
count = 11;
for (p = top, q = p - count; q >= map; p--, q--)
if (p->hash < q->hash)
swap(*p, *q);
}
/* Garden variety bubble sort */
do {
more = 0;
q = top;
while (q-- > map) {
if (q[1].hash >= q[0].hash)
continue;
swap(*(q+1), *q);
more = 1;
}
} while(more);
}
static void dx_insert_block(struct dx_frame *frame, u32 hash, ext4_lblk_t block)
{
struct dx_entry *entries = frame->entries;
struct dx_entry *old = frame->at, *new = old + 1;
int count = dx_get_count(entries);
assert(count < dx_get_limit(entries));
assert(old < entries + count);
memmove(new + 1, new, (char *)(entries + count) - (char *)(new));
dx_set_hash(new, hash);
dx_set_block(new, block);
dx_set_count(entries, count + 1);
}
static void ext4_update_dx_flag(struct inode *inode)
{
if (!EXT4_HAS_COMPAT_FEATURE(inode->i_sb,
EXT4_FEATURE_COMPAT_DIR_INDEX))
ext4_clear_inode_flag(inode, EXT4_INODE_INDEX);
}
/*
* NOTE! unlike strncmp, ext4_match returns 1 for success, 0 for failure.
*
* `len <= EXT4_NAME_LEN' is guaranteed by caller.
* `de != NULL' is guaranteed by caller.
*/
static inline int ext4_match (int len, const char * const name,
struct ext4_dir_entry_2 * de)
{
if (len != de->name_len)
return 0;
if (!de->inode)
return 0;
return !memcmp(name, de->name, len);
}
/*
* Returns 0 if not found, -1 on failure, and 1 on success
*/
static inline int search_dirblock(struct buffer_head *bh,
struct inode *dir,
const struct qstr *d_name,
unsigned int offset,
struct ext4_dir_entry_2 ** res_dir)
{
struct ext4_dir_entry_2 * de;
char * dlimit;
int de_len;
const char *name = d_name->name;
int namelen = d_name->len;
de = (struct ext4_dir_entry_2 *) bh->b_data;
dlimit = bh->b_data + dir->i_sb->s_blocksize;
while ((char *) de < dlimit) {
/* this code is executed quadratically often */
/* do minimal checking `by hand' */
if ((char *) de + namelen <= dlimit &&
ext4_match (namelen, name, de)) {
/* found a match - just to be sure, do a full check */
if (ext4_check_dir_entry(dir, NULL, de, bh, offset))
return -1;
*res_dir = de;
return 1;
}
/* prevent looping on a bad block */
de_len = ext4_rec_len_from_disk(de->rec_len,
dir->i_sb->s_blocksize);
if (de_len <= 0)
return -1;
offset += de_len;
de = (struct ext4_dir_entry_2 *) ((char *) de + de_len);
}
return 0;
}
/*
* ext4_find_entry()
*
* finds an entry in the specified directory with the wanted name. It
* returns the cache buffer in which the entry was found, and the entry
* itself (as a parameter - res_dir). It does NOT read the inode of the
* entry - you'll have to do that yourself if you want to.
*
* The returned buffer_head has ->b_count elevated. The caller is expected
* to brelse() it when appropriate.
*/
static struct buffer_head * ext4_find_entry (struct inode *dir,
const struct qstr *d_name,
struct ext4_dir_entry_2 ** res_dir)
{
struct super_block *sb;
struct buffer_head *bh_use[NAMEI_RA_SIZE];
struct buffer_head *bh, *ret = NULL;
ext4_lblk_t start, block, b;
const u8 *name = d_name->name;
int ra_max = 0; /* Number of bh's in the readahead
buffer, bh_use[] */
int ra_ptr = 0; /* Current index into readahead
buffer */
int num = 0;
ext4_lblk_t nblocks;
int i, err;
int namelen;
*res_dir = NULL;
sb = dir->i_sb;
namelen = d_name->len;
if (namelen > EXT4_NAME_LEN)
return NULL;
if ((namelen <= 2) && (name[0] == '.') &&
(name[1] == '.' || name[1] == '\0')) {
/*
* "." or ".." will only be in the first block
* NFS may look up ".."; "." should be handled by the VFS
*/
block = start = 0;
nblocks = 1;
goto restart;
}
if (is_dx(dir)) {
bh = ext4_dx_find_entry(dir, d_name, res_dir, &err);
/*
* On success, or if the error was file not found,
* return. Otherwise, fall back to doing a search the
* old fashioned way.
*/
if (bh || (err != ERR_BAD_DX_DIR))
return bh;
dxtrace(printk(KERN_DEBUG "ext4_find_entry: dx failed, "
"falling back\n"));
}
nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
start = EXT4_I(dir)->i_dir_start_lookup;
if (start >= nblocks)
start = 0;
block = start;
restart:
do {
/*
* We deal with the read-ahead logic here.
*/
if (ra_ptr >= ra_max) {
/* Refill the readahead buffer */
ra_ptr = 0;
b = block;
for (ra_max = 0; ra_max < NAMEI_RA_SIZE; ra_max++) {
/*
* Terminate if we reach the end of the
* directory and must wrap, or if our
* search has finished at this block.
*/
if (b >= nblocks || (num && block == start)) {
bh_use[ra_max] = NULL;
break;
}
num++;
bh = ext4_getblk(NULL, dir, b++, 0, &err);
bh_use[ra_max] = bh;
if (bh)
ll_rw_block(READ | REQ_META | REQ_PRIO,
1, &bh);
}
}
if ((bh = bh_use[ra_ptr++]) == NULL)
goto next;
wait_on_buffer(bh);
if (!buffer_uptodate(bh)) {
/* read error, skip block & hope for the best */
EXT4_ERROR_INODE(dir, "reading directory lblock %lu",
(unsigned long) block);
brelse(bh);
goto next;
}
if (!buffer_verified(bh) &&
!ext4_dirent_csum_verify(dir,
(struct ext4_dir_entry *)bh->b_data)) {
EXT4_ERROR_INODE(dir, "checksumming directory "
"block %lu", (unsigned long)block);
brelse(bh);
goto next;
}
set_buffer_verified(bh);
i = search_dirblock(bh, dir, d_name,
block << EXT4_BLOCK_SIZE_BITS(sb), res_dir);
if (i == 1) {
EXT4_I(dir)->i_dir_start_lookup = block;
ret = bh;
goto cleanup_and_exit;
} else {
brelse(bh);
if (i < 0)
goto cleanup_and_exit;
}
next:
if (++block >= nblocks)
block = 0;
} while (block != start);
/*
* If the directory has grown while we were searching, then
* search the last part of the directory before giving up.
*/
block = nblocks;
nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
if (block < nblocks) {
start = 0;
goto restart;
}
cleanup_and_exit:
/* Clean up the read-ahead blocks */
for (; ra_ptr < ra_max; ra_ptr++)
brelse(bh_use[ra_ptr]);
return ret;
}
static struct buffer_head * ext4_dx_find_entry(struct inode *dir, const struct qstr *d_name,
struct ext4_dir_entry_2 **res_dir, int *err)
{
struct super_block * sb = dir->i_sb;
struct dx_hash_info hinfo;
struct dx_frame frames[2], *frame;
struct buffer_head *bh;
ext4_lblk_t block;
int retval;
if (!(frame = dx_probe(d_name, dir, &hinfo, frames, err)))
return NULL;
do {
block = dx_get_block(frame->at);
if (!(bh = ext4_bread(NULL, dir, block, 0, err)))
goto errout;
if (!buffer_verified(bh) &&
!ext4_dirent_csum_verify(dir,
(struct ext4_dir_entry *)bh->b_data)) {
EXT4_ERROR_INODE(dir, "checksumming directory "
"block %lu", (unsigned long)block);
brelse(bh);
*err = -EIO;
goto errout;
}
set_buffer_verified(bh);
retval = search_dirblock(bh, dir, d_name,
block << EXT4_BLOCK_SIZE_BITS(sb),
res_dir);
if (retval == 1) { /* Success! */
dx_release(frames);
return bh;
}
brelse(bh);
if (retval == -1) {
*err = ERR_BAD_DX_DIR;
goto errout;
}
/* Check to see if we should continue to search */
retval = ext4_htree_next_block(dir, hinfo.hash, frame,
frames, NULL);
if (retval < 0) {
ext4_warning(sb,
"error reading index page in directory #%lu",
dir->i_ino);
*err = retval;
goto errout;
}
} while (retval == 1);
*err = -ENOENT;
errout:
dxtrace(printk(KERN_DEBUG "%s not found\n", d_name->name));
dx_release (frames);
return NULL;
}
static struct dentry *ext4_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
{
struct inode *inode;
struct ext4_dir_entry_2 *de;
struct buffer_head *bh;
if (dentry->d_name.len > EXT4_NAME_LEN)
return ERR_PTR(-ENAMETOOLONG);
bh = ext4_find_entry(dir, &dentry->d_name, &de);
inode = NULL;
if (bh) {
__u32 ino = le32_to_cpu(de->inode);
brelse(bh);
if (!ext4_valid_inum(dir->i_sb, ino)) {
EXT4_ERROR_INODE(dir, "bad inode number: %u", ino);
return ERR_PTR(-EIO);
}
if (unlikely(ino == dir->i_ino)) {
EXT4_ERROR_INODE(dir, "'%.*s' linked to parent dir",
dentry->d_name.len,
dentry->d_name.name);
return ERR_PTR(-EIO);
}
inode = ext4_iget(dir->i_sb, ino);
if (inode == ERR_PTR(-ESTALE)) {
EXT4_ERROR_INODE(dir,
"deleted inode referenced: %u",
ino);
return ERR_PTR(-EIO);
}
}
return d_splice_alias(inode, dentry);
}
struct dentry *ext4_get_parent(struct dentry *child)
{
__u32 ino;
static const struct qstr dotdot = QSTR_INIT("..", 2);
struct ext4_dir_entry_2 * de;
struct buffer_head *bh;
bh = ext4_find_entry(child->d_inode, &dotdot, &de);
if (!bh)
return ERR_PTR(-ENOENT);
ino = le32_to_cpu(de->inode);
brelse(bh);
if (!ext4_valid_inum(child->d_inode->i_sb, ino)) {
EXT4_ERROR_INODE(child->d_inode,
"bad parent inode number: %u", ino);
return ERR_PTR(-EIO);
}
return d_obtain_alias(ext4_iget(child->d_inode->i_sb, ino));
}
#define S_SHIFT 12
static unsigned char ext4_type_by_mode[S_IFMT >> S_SHIFT] = {
[S_IFREG >> S_SHIFT] = EXT4_FT_REG_FILE,
[S_IFDIR >> S_SHIFT] = EXT4_FT_DIR,
[S_IFCHR >> S_SHIFT] = EXT4_FT_CHRDEV,
[S_IFBLK >> S_SHIFT] = EXT4_FT_BLKDEV,
[S_IFIFO >> S_SHIFT] = EXT4_FT_FIFO,
[S_IFSOCK >> S_SHIFT] = EXT4_FT_SOCK,
[S_IFLNK >> S_SHIFT] = EXT4_FT_SYMLINK,
};
static inline void ext4_set_de_type(struct super_block *sb,
struct ext4_dir_entry_2 *de,
umode_t mode) {
if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FILETYPE))
de->file_type = ext4_type_by_mode[(mode & S_IFMT)>>S_SHIFT];
}
/*
* Move count entries from end of map between two memory locations.
* Returns pointer to last entry moved.
*/
static struct ext4_dir_entry_2 *
dx_move_dirents(char *from, char *to, struct dx_map_entry *map, int count,
unsigned blocksize)
{
unsigned rec_len = 0;
while (count--) {
struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)
(from + (map->offs<<2));
rec_len = EXT4_DIR_REC_LEN(de->name_len);
memcpy (to, de, rec_len);
((struct ext4_dir_entry_2 *) to)->rec_len =
ext4_rec_len_to_disk(rec_len, blocksize);
de->inode = 0;
map++;
to += rec_len;
}
return (struct ext4_dir_entry_2 *) (to - rec_len);
}
/*
* Compact each dir entry in the range to the minimal rec_len.
* Returns pointer to last entry in range.
*/
static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize)
{
struct ext4_dir_entry_2 *next, *to, *prev, *de = (struct ext4_dir_entry_2 *) base;
unsigned rec_len = 0;
prev = to = de;
while ((char*)de < base + blocksize) {
next = ext4_next_entry(de, blocksize);
if (de->inode && de->name_len) {
rec_len = EXT4_DIR_REC_LEN(de->name_len);
if (de > to)
memmove(to, de, rec_len);
to->rec_len = ext4_rec_len_to_disk(rec_len, blocksize);
prev = to;
to = (struct ext4_dir_entry_2 *) (((char *) to) + rec_len);
}
de = next;
}
return prev;
}
/*
* Split a full leaf block to make room for a new dir entry.
* Allocate a new block, and move entries so that they are approx. equally full.
* Returns pointer to de in block into which the new entry will be inserted.
*/
static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,
struct buffer_head **bh,struct dx_frame *frame,
struct dx_hash_info *hinfo, int *error)
{
unsigned blocksize = dir->i_sb->s_blocksize;
unsigned count, continued;
struct buffer_head *bh2;
ext4_lblk_t newblock;
u32 hash2;
struct dx_map_entry *map;
char *data1 = (*bh)->b_data, *data2;
unsigned split, move, size;
struct ext4_dir_entry_2 *de = NULL, *de2;
struct ext4_dir_entry_tail *t;
int csum_size = 0;
int err = 0, i;
if (EXT4_HAS_RO_COMPAT_FEATURE(dir->i_sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
csum_size = sizeof(struct ext4_dir_entry_tail);
bh2 = ext4_append (handle, dir, &newblock, &err);
if (!(bh2)) {
brelse(*bh);
*bh = NULL;
goto errout;
}
BUFFER_TRACE(*bh, "get_write_access");
err = ext4_journal_get_write_access(handle, *bh);
if (err)
goto journal_error;
BUFFER_TRACE(frame->bh, "get_write_access");
err = ext4_journal_get_write_access(handle, frame->bh);
if (err)
goto journal_error;
data2 = bh2->b_data;
/* create map in the end of data2 block */
map = (struct dx_map_entry *) (data2 + blocksize);
count = dx_make_map((struct ext4_dir_entry_2 *) data1,
blocksize, hinfo, map);
map -= count;
dx_sort_map(map, count);
/* Split the existing block in the middle, size-wise */
size = 0;
move = 0;
for (i = count-1; i >= 0; i--) {
/* is more than half of this entry in 2nd half of the block? */
if (size + map[i].size/2 > blocksize/2)
break;
size += map[i].size;
move++;
}
/* map index at which we will split */
split = count - move;
hash2 = map[split].hash;
continued = hash2 == map[split - 1].hash;
dxtrace(printk(KERN_INFO "Split block %lu at %x, %i/%i\n",
(unsigned long)dx_get_block(frame->at),
hash2, split, count-split));
/* Fancy dance to stay within two buffers */
de2 = dx_move_dirents(data1, data2, map + split, count - split, blocksize);
de = dx_pack_dirents(data1, blocksize);
de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
(char *) de,
blocksize);
de2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -
(char *) de2,
blocksize);
if (csum_size) {
t = EXT4_DIRENT_TAIL(data2, blocksize);
initialize_dirent_tail(t, blocksize);
t = EXT4_DIRENT_TAIL(data1, blocksize);
initialize_dirent_tail(t, blocksize);
}
dxtrace(dx_show_leaf (hinfo, (struct ext4_dir_entry_2 *) data1, blocksize, 1));
dxtrace(dx_show_leaf (hinfo, (struct ext4_dir_entry_2 *) data2, blocksize, 1));
/* Which block gets the new entry? */
if (hinfo->hash >= hash2)
{
swap(*bh, bh2);
de = de2;
}
dx_insert_block(frame, hash2 + continued, newblock);
err = ext4_handle_dirty_dirent_node(handle, dir, bh2);
if (err)
goto journal_error;
err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
if (err)
goto journal_error;
brelse(bh2);
dxtrace(dx_show_index("frame", frame->entries));
return de;
journal_error:
brelse(*bh);
brelse(bh2);
*bh = NULL;
ext4_std_error(dir->i_sb, err);
errout:
*error = err;
return NULL;
}
/*
* Add a new entry into a directory (leaf) block. If de is non-NULL,
* it points to a directory entry which is guaranteed to be large
* enough for new directory entry. If de is NULL, then
* add_dirent_to_buf will attempt search the directory block for
* space. It will return -ENOSPC if no space is available, and -EIO
* and -EEXIST if directory entry already exists.
*/
static int add_dirent_to_buf(handle_t *handle, struct dentry *dentry,
struct inode *inode, struct ext4_dir_entry_2 *de,
struct buffer_head *bh)
{
struct inode *dir = dentry->d_parent->d_inode;
const char *name = dentry->d_name.name;
int namelen = dentry->d_name.len;
unsigned int offset = 0;
unsigned int blocksize = dir->i_sb->s_blocksize;
unsigned short reclen;
int nlen, rlen, err;
char *top;
int csum_size = 0;
if (EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
csum_size = sizeof(struct ext4_dir_entry_tail);
reclen = EXT4_DIR_REC_LEN(namelen);
if (!de) {
de = (struct ext4_dir_entry_2 *)bh->b_data;
top = bh->b_data + (blocksize - csum_size) - reclen;
while ((char *) de <= top) {
if (ext4_check_dir_entry(dir, NULL, de, bh, offset))
return -EIO;
if (ext4_match(namelen, name, de))
return -EEXIST;
nlen = EXT4_DIR_REC_LEN(de->name_len);
rlen = ext4_rec_len_from_disk(de->rec_len, blocksize);
if ((de->inode? rlen - nlen: rlen) >= reclen)
break;
de = (struct ext4_dir_entry_2 *)((char *)de + rlen);
offset += rlen;
}
if ((char *) de > top)
return -ENOSPC;
}
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, bh);
if (err) {
ext4_std_error(dir->i_sb, err);
return err;
}
/* By now the buffer is marked for journaling */
nlen = EXT4_DIR_REC_LEN(de->name_len);
rlen = ext4_rec_len_from_disk(de->rec_len, blocksize);
if (de->inode) {
struct ext4_dir_entry_2 *de1 = (struct ext4_dir_entry_2 *)((char *)de + nlen);
de1->rec_len = ext4_rec_len_to_disk(rlen - nlen, blocksize);
de->rec_len = ext4_rec_len_to_disk(nlen, blocksize);
de = de1;
}
de->file_type = EXT4_FT_UNKNOWN;
de->inode = cpu_to_le32(inode->i_ino);
ext4_set_de_type(dir->i_sb, de, inode->i_mode);
de->name_len = namelen;
memcpy(de->name, name, namelen);
/*
* XXX shouldn't update any times until successful
* completion of syscall, but too many callers depend
* on this.
*
* XXX similarly, too many callers depend on
* ext4_new_inode() setting the times, but error
* recovery deletes the inode, so the worst that can
* happen is that the times are slightly out of date
* and/or different from the directory change time.
*/
dir->i_mtime = dir->i_ctime = ext4_current_time(dir);
ext4_update_dx_flag(dir);
dir->i_version++;
ext4_mark_inode_dirty(handle, dir);
BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_dirent_node(handle, dir, bh);
if (err)
ext4_std_error(dir->i_sb, err);
return 0;
}
/*
* This converts a one block unindexed directory to a 3 block indexed
* directory, and adds the dentry to the indexed directory.
*/
static int make_indexed_dir(handle_t *handle, struct dentry *dentry,
struct inode *inode, struct buffer_head *bh)
{
struct inode *dir = dentry->d_parent->d_inode;
const char *name = dentry->d_name.name;
int namelen = dentry->d_name.len;
struct buffer_head *bh2;
struct dx_root *root;
struct dx_frame frames[2], *frame;
struct dx_entry *entries;
struct ext4_dir_entry_2 *de, *de2;
struct ext4_dir_entry_tail *t;
char *data1, *top;
unsigned len;
int retval;
unsigned blocksize;
struct dx_hash_info hinfo;
ext4_lblk_t block;
struct fake_dirent *fde;
int csum_size = 0;
if (EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
csum_size = sizeof(struct ext4_dir_entry_tail);
blocksize = dir->i_sb->s_blocksize;
dxtrace(printk(KERN_DEBUG "Creating index: inode %lu\n", dir->i_ino));
retval = ext4_journal_get_write_access(handle, bh);
if (retval) {
ext4_std_error(dir->i_sb, retval);
brelse(bh);
return retval;
}
root = (struct dx_root *) bh->b_data;
/* The 0th block becomes the root, move the dirents out */
fde = &root->dotdot;
de = (struct ext4_dir_entry_2 *)((char *)fde +
ext4_rec_len_from_disk(fde->rec_len, blocksize));
if ((char *) de >= (((char *) root) + blocksize)) {
EXT4_ERROR_INODE(dir, "invalid rec_len for '..'");
brelse(bh);
return -EIO;
}
len = ((char *) root) + (blocksize - csum_size) - (char *) de;
/* Allocate new block for the 0th block's dirents */
bh2 = ext4_append(handle, dir, &block, &retval);
if (!(bh2)) {
brelse(bh);
return retval;
}
ext4_set_inode_flag(dir, EXT4_INODE_INDEX);
data1 = bh2->b_data;
memcpy (data1, de, len);
de = (struct ext4_dir_entry_2 *) data1;
top = data1 + len;
while ((char *)(de2 = ext4_next_entry(de, blocksize)) < top)
de = de2;
de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
(char *) de,
blocksize);
if (csum_size) {
t = EXT4_DIRENT_TAIL(data1, blocksize);
initialize_dirent_tail(t, blocksize);
}
/* Initialize the root; the dot dirents already exist */
de = (struct ext4_dir_entry_2 *) (&root->dotdot);
de->rec_len = ext4_rec_len_to_disk(blocksize - EXT4_DIR_REC_LEN(2),
blocksize);
memset (&root->info, 0, sizeof(root->info));
root->info.info_length = sizeof(root->info);
root->info.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
entries = root->entries;
dx_set_block(entries, 1);
dx_set_count(entries, 1);
dx_set_limit(entries, dx_root_limit(dir, sizeof(root->info)));
/* Initialize as for dx_probe */
hinfo.hash_version = root->info.hash_version;
if (hinfo.hash_version <= DX_HASH_TEA)
hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
ext4fs_dirhash(name, namelen, &hinfo);
frame = frames;
frame->entries = entries;
frame->at = entries;
frame->bh = bh;
bh = bh2;
ext4_handle_dirty_dx_node(handle, dir, frame->bh);
ext4_handle_dirty_dirent_node(handle, dir, bh);
de = do_split(handle,dir, &bh, frame, &hinfo, &retval);
if (!de) {
/*
* Even if the block split failed, we have to properly write
* out all the changes we did so far. Otherwise we can end up
* with corrupted filesystem.
*/
ext4_mark_inode_dirty(handle, dir);
dx_release(frames);
return retval;
}
dx_release(frames);
retval = add_dirent_to_buf(handle, dentry, inode, de, bh);
brelse(bh);
return retval;
}
/*
* ext4_add_entry()
*
* adds a file entry to the specified directory, using the same
* semantics as ext4_find_entry(). It returns NULL if it failed.
*
* NOTE!! The inode part of 'de' is left at 0 - which means you
* may not sleep between calling this and putting something into
* the entry, as someone else might have used it while you slept.
*/
static int ext4_add_entry(handle_t *handle, struct dentry *dentry,
struct inode *inode)
{
struct inode *dir = dentry->d_parent->d_inode;
struct buffer_head *bh;
struct ext4_dir_entry_2 *de;
struct ext4_dir_entry_tail *t;
struct super_block *sb;
int retval;
int dx_fallback=0;
unsigned blocksize;
ext4_lblk_t block, blocks;
int csum_size = 0;
if (EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
csum_size = sizeof(struct ext4_dir_entry_tail);
sb = dir->i_sb;
blocksize = sb->s_blocksize;
if (!dentry->d_name.len)
return -EINVAL;
if (is_dx(dir)) {
retval = ext4_dx_add_entry(handle, dentry, inode);
if (!retval || (retval != ERR_BAD_DX_DIR))
return retval;
ext4_clear_inode_flag(dir, EXT4_INODE_INDEX);
dx_fallback++;
ext4_mark_inode_dirty(handle, dir);
}
blocks = dir->i_size >> sb->s_blocksize_bits;
for (block = 0; block < blocks; block++) {
bh = ext4_bread(handle, dir, block, 0, &retval);
if(!bh)
return retval;
if (!buffer_verified(bh) &&
!ext4_dirent_csum_verify(dir,
(struct ext4_dir_entry *)bh->b_data))
return -EIO;
set_buffer_verified(bh);
retval = add_dirent_to_buf(handle, dentry, inode, NULL, bh);
if (retval != -ENOSPC) {
brelse(bh);
return retval;
}
if (blocks == 1 && !dx_fallback &&
EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_DIR_INDEX))
return make_indexed_dir(handle, dentry, inode, bh);
brelse(bh);
}
bh = ext4_append(handle, dir, &block, &retval);
if (!bh)
return retval;
de = (struct ext4_dir_entry_2 *) bh->b_data;
de->inode = 0;
de->rec_len = ext4_rec_len_to_disk(blocksize - csum_size, blocksize);
if (csum_size) {
t = EXT4_DIRENT_TAIL(bh->b_data, blocksize);
initialize_dirent_tail(t, blocksize);
}
retval = add_dirent_to_buf(handle, dentry, inode, de, bh);
brelse(bh);
if (retval == 0)
ext4_set_inode_state(inode, EXT4_STATE_NEWENTRY);
return retval;
}
/*
* Returns 0 for success, or a negative error value
*/
static int ext4_dx_add_entry(handle_t *handle, struct dentry *dentry,
struct inode *inode)
{
struct dx_frame frames[2], *frame;
struct dx_entry *entries, *at;
struct dx_hash_info hinfo;
struct buffer_head *bh;
struct inode *dir = dentry->d_parent->d_inode;
struct super_block *sb = dir->i_sb;
struct ext4_dir_entry_2 *de;
int err;
frame = dx_probe(&dentry->d_name, dir, &hinfo, frames, &err);
if (!frame)
return err;
entries = frame->entries;
at = frame->at;
if (!(bh = ext4_bread(handle,dir, dx_get_block(frame->at), 0, &err)))
goto cleanup;
if (!buffer_verified(bh) &&
!ext4_dirent_csum_verify(dir, (struct ext4_dir_entry *)bh->b_data))
goto journal_error;
set_buffer_verified(bh);
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, bh);
if (err)
goto journal_error;
err = add_dirent_to_buf(handle, dentry, inode, NULL, bh);
if (err != -ENOSPC)
goto cleanup;
/* Block full, should compress but for now just split */
dxtrace(printk(KERN_DEBUG "using %u of %u node entries\n",
dx_get_count(entries), dx_get_limit(entries)));
/* Need to split index? */
if (dx_get_count(entries) == dx_get_limit(entries)) {
ext4_lblk_t newblock;
unsigned icount = dx_get_count(entries);
int levels = frame - frames;
struct dx_entry *entries2;
struct dx_node *node2;
struct buffer_head *bh2;
if (levels && (dx_get_count(frames->entries) ==
dx_get_limit(frames->entries))) {
ext4_warning(sb, "Directory index full!");
err = -ENOSPC;
goto cleanup;
}
bh2 = ext4_append (handle, dir, &newblock, &err);
if (!(bh2))
goto cleanup;
node2 = (struct dx_node *)(bh2->b_data);
entries2 = node2->entries;
memset(&node2->fake, 0, sizeof(struct fake_dirent));
node2->fake.rec_len = ext4_rec_len_to_disk(sb->s_blocksize,
sb->s_blocksize);
BUFFER_TRACE(frame->bh, "get_write_access");
err = ext4_journal_get_write_access(handle, frame->bh);
if (err)
goto journal_error;
if (levels) {
unsigned icount1 = icount/2, icount2 = icount - icount1;
unsigned hash2 = dx_get_hash(entries + icount1);
dxtrace(printk(KERN_DEBUG "Split index %i/%i\n",
icount1, icount2));
BUFFER_TRACE(frame->bh, "get_write_access"); /* index root */
err = ext4_journal_get_write_access(handle,
frames[0].bh);
if (err)
goto journal_error;
memcpy((char *) entries2, (char *) (entries + icount1),
icount2 * sizeof(struct dx_entry));
dx_set_count(entries, icount1);
dx_set_count(entries2, icount2);
dx_set_limit(entries2, dx_node_limit(dir));
/* Which index block gets the new entry? */
if (at - entries >= icount1) {
frame->at = at = at - entries - icount1 + entries2;
frame->entries = entries = entries2;
swap(frame->bh, bh2);
}
dx_insert_block(frames + 0, hash2, newblock);
dxtrace(dx_show_index("node", frames[1].entries));
dxtrace(dx_show_index("node",
((struct dx_node *) bh2->b_data)->entries));
err = ext4_handle_dirty_dx_node(handle, dir, bh2);
if (err)
goto journal_error;
brelse (bh2);
} else {
dxtrace(printk(KERN_DEBUG
"Creating second level index...\n"));
memcpy((char *) entries2, (char *) entries,
icount * sizeof(struct dx_entry));
dx_set_limit(entries2, dx_node_limit(dir));
/* Set up root */
dx_set_count(entries, 1);
dx_set_block(entries + 0, newblock);
((struct dx_root *) frames[0].bh->b_data)->info.indirect_levels = 1;
/* Add new access path frame */
frame = frames + 1;
frame->at = at = at - entries + entries2;
frame->entries = entries = entries2;
frame->bh = bh2;
err = ext4_journal_get_write_access(handle,
frame->bh);
if (err)
goto journal_error;
}
err = ext4_handle_dirty_dx_node(handle, dir, frames[0].bh);
if (err) {
ext4_std_error(inode->i_sb, err);
goto cleanup;
}
}
de = do_split(handle, dir, &bh, frame, &hinfo, &err);
if (!de)
goto cleanup;
err = add_dirent_to_buf(handle, dentry, inode, de, bh);
goto cleanup;
journal_error:
ext4_std_error(dir->i_sb, err);
cleanup:
if (bh)
brelse(bh);
dx_release(frames);
return err;
}
/*
* ext4_delete_entry deletes a directory entry by merging it with the
* previous entry
*/
static int ext4_delete_entry(handle_t *handle,
struct inode *dir,
struct ext4_dir_entry_2 *de_del,
struct buffer_head *bh)
{
struct ext4_dir_entry_2 *de, *pde;
unsigned int blocksize = dir->i_sb->s_blocksize;
int csum_size = 0;
int i, err;
if (EXT4_HAS_RO_COMPAT_FEATURE(dir->i_sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
csum_size = sizeof(struct ext4_dir_entry_tail);
i = 0;
pde = NULL;
de = (struct ext4_dir_entry_2 *) bh->b_data;
while (i < bh->b_size - csum_size) {
if (ext4_check_dir_entry(dir, NULL, de, bh, i))
return -EIO;
if (de == de_del) {
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, bh);
if (unlikely(err)) {
ext4_std_error(dir->i_sb, err);
return err;
}
if (pde)
pde->rec_len = ext4_rec_len_to_disk(
ext4_rec_len_from_disk(pde->rec_len,
blocksize) +
ext4_rec_len_from_disk(de->rec_len,
blocksize),
blocksize);
else
de->inode = 0;
dir->i_version++;
BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_dirent_node(handle, dir, bh);
if (unlikely(err)) {
ext4_std_error(dir->i_sb, err);
return err;
}
return 0;
}
i += ext4_rec_len_from_disk(de->rec_len, blocksize);
pde = de;
de = ext4_next_entry(de, blocksize);
}
return -ENOENT;
}
/*
* DIR_NLINK feature is set if 1) nlinks > EXT4_LINK_MAX or 2) nlinks == 2,
* since this indicates that nlinks count was previously 1.
*/
static void ext4_inc_count(handle_t *handle, struct inode *inode)
{
inc_nlink(inode);
if (is_dx(inode) && inode->i_nlink > 1) {
/* limit is 16-bit i_links_count */
if (inode->i_nlink >= EXT4_LINK_MAX || inode->i_nlink == 2) {
set_nlink(inode, 1);
EXT4_SET_RO_COMPAT_FEATURE(inode->i_sb,
EXT4_FEATURE_RO_COMPAT_DIR_NLINK);
}
}
}
/*
* If a directory had nlink == 1, then we should let it be 1. This indicates
* directory has >EXT4_LINK_MAX subdirs.
*/
static void ext4_dec_count(handle_t *handle, struct inode *inode)
{
if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 2)
drop_nlink(inode);
}
static int ext4_add_nondir(handle_t *handle,
struct dentry *dentry, struct inode *inode)
{
int err = ext4_add_entry(handle, dentry, inode);
if (!err) {
ext4_mark_inode_dirty(handle, inode);
unlock_new_inode(inode);
d_instantiate(dentry, inode);
return 0;
}
drop_nlink(inode);
unlock_new_inode(inode);
iput(inode);
return err;
}
/*
* By the time this is called, we already have created
* the directory cache entry for the new file, but it
* is so far negative - it has no inode.
*
* If the create succeeds, we fill in the inode information
* with d_instantiate().
*/
static int ext4_create(struct inode *dir, struct dentry *dentry, umode_t mode,
bool excl)
{
handle_t *handle;
struct inode *inode;
int err, retries = 0;
dquot_initialize(dir);
retry:
handle = ext4_journal_start(dir, EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3 +
EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
if (IS_DIRSYNC(dir))
ext4_handle_sync(handle);
inode = ext4_new_inode(handle, dir, mode, &dentry->d_name, 0, NULL);
err = PTR_ERR(inode);
if (!IS_ERR(inode)) {
inode->i_op = &ext4_file_inode_operations;
inode->i_fop = &ext4_file_operations;
ext4_set_aops(inode);
err = ext4_add_nondir(handle, dentry, inode);
}
ext4_journal_stop(handle);
if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
goto retry;
return err;
}
static int ext4_mknod(struct inode *dir, struct dentry *dentry,
umode_t mode, dev_t rdev)
{
handle_t *handle;
struct inode *inode;
int err, retries = 0;
if (!new_valid_dev(rdev))
return -EINVAL;
dquot_initialize(dir);
retry:
handle = ext4_journal_start(dir, EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3 +
EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
if (IS_DIRSYNC(dir))
ext4_handle_sync(handle);
inode = ext4_new_inode(handle, dir, mode, &dentry->d_name, 0, NULL);
err = PTR_ERR(inode);
if (!IS_ERR(inode)) {
init_special_inode(inode, inode->i_mode, rdev);
#ifdef CONFIG_EXT4_FS_XATTR
inode->i_op = &ext4_special_inode_operations;
#endif
err = ext4_add_nondir(handle, dentry, inode);
}
ext4_journal_stop(handle);
if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
goto retry;
return err;
}
static int ext4_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
{
handle_t *handle;
struct inode *inode;
struct buffer_head *dir_block = NULL;
struct ext4_dir_entry_2 *de;
struct ext4_dir_entry_tail *t;
unsigned int blocksize = dir->i_sb->s_blocksize;
int csum_size = 0;
int err, retries = 0;
if (EXT4_HAS_RO_COMPAT_FEATURE(dir->i_sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
csum_size = sizeof(struct ext4_dir_entry_tail);
if (EXT4_DIR_LINK_MAX(dir))
return -EMLINK;
dquot_initialize(dir);
retry:
handle = ext4_journal_start(dir, EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3 +
EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
if (IS_DIRSYNC(dir))
ext4_handle_sync(handle);
inode = ext4_new_inode(handle, dir, S_IFDIR | mode,
&dentry->d_name, 0, NULL);
err = PTR_ERR(inode);
if (IS_ERR(inode))
goto out_stop;
inode->i_op = &ext4_dir_inode_operations;
inode->i_fop = &ext4_dir_operations;
inode->i_size = EXT4_I(inode)->i_disksize = inode->i_sb->s_blocksize;
dir_block = ext4_bread(handle, inode, 0, 1, &err);
if (!dir_block)
goto out_clear_inode;
BUFFER_TRACE(dir_block, "get_write_access");
err = ext4_journal_get_write_access(handle, dir_block);
if (err)
goto out_clear_inode;
de = (struct ext4_dir_entry_2 *) dir_block->b_data;
de->inode = cpu_to_le32(inode->i_ino);
de->name_len = 1;
de->rec_len = ext4_rec_len_to_disk(EXT4_DIR_REC_LEN(de->name_len),
blocksize);
strcpy(de->name, ".");
ext4_set_de_type(dir->i_sb, de, S_IFDIR);
de = ext4_next_entry(de, blocksize);
de->inode = cpu_to_le32(dir->i_ino);
de->rec_len = ext4_rec_len_to_disk(blocksize -
(csum_size + EXT4_DIR_REC_LEN(1)),
blocksize);
de->name_len = 2;
strcpy(de->name, "..");
ext4_set_de_type(dir->i_sb, de, S_IFDIR);
set_nlink(inode, 2);
if (csum_size) {
t = EXT4_DIRENT_TAIL(dir_block->b_data, blocksize);
initialize_dirent_tail(t, blocksize);
}
BUFFER_TRACE(dir_block, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_dirent_node(handle, inode, dir_block);
if (err)
goto out_clear_inode;
set_buffer_verified(dir_block);
err = ext4_mark_inode_dirty(handle, inode);
if (!err)
err = ext4_add_entry(handle, dentry, inode);
if (err) {
out_clear_inode:
clear_nlink(inode);
unlock_new_inode(inode);
ext4_mark_inode_dirty(handle, inode);
iput(inode);
goto out_stop;
}
ext4_inc_count(handle, dir);
ext4_update_dx_flag(dir);
err = ext4_mark_inode_dirty(handle, dir);
if (err)
goto out_clear_inode;
unlock_new_inode(inode);
d_instantiate(dentry, inode);
out_stop:
brelse(dir_block);
ext4_journal_stop(handle);
if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
goto retry;
return err;
}
/*
* routine to check that the specified directory is empty (for rmdir)
*/
static int empty_dir(struct inode *inode)
{
unsigned int offset;
struct buffer_head *bh;
struct ext4_dir_entry_2 *de, *de1;
struct super_block *sb;
int err = 0;
sb = inode->i_sb;
if (inode->i_size < EXT4_DIR_REC_LEN(1) + EXT4_DIR_REC_LEN(2) ||
!(bh = ext4_bread(NULL, inode, 0, 0, &err))) {
if (err)
EXT4_ERROR_INODE(inode,
"error %d reading directory lblock 0", err);
else
ext4_warning(inode->i_sb,
"bad directory (dir #%lu) - no data block",
inode->i_ino);
return 1;
}
if (!buffer_verified(bh) &&
!ext4_dirent_csum_verify(inode,
(struct ext4_dir_entry *)bh->b_data)) {
EXT4_ERROR_INODE(inode, "checksum error reading directory "
"lblock 0");
return -EIO;
}
set_buffer_verified(bh);
de = (struct ext4_dir_entry_2 *) bh->b_data;
de1 = ext4_next_entry(de, sb->s_blocksize);
if (le32_to_cpu(de->inode) != inode->i_ino ||
!le32_to_cpu(de1->inode) ||
strcmp(".", de->name) ||
strcmp("..", de1->name)) {
ext4_warning(inode->i_sb,
"bad directory (dir #%lu) - no `.' or `..'",
inode->i_ino);
brelse(bh);
return 1;
}
offset = ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) +
ext4_rec_len_from_disk(de1->rec_len, sb->s_blocksize);
de = ext4_next_entry(de1, sb->s_blocksize);
while (offset < inode->i_size) {
if (!bh ||
(void *) de >= (void *) (bh->b_data+sb->s_blocksize)) {
unsigned int lblock;
err = 0;
brelse(bh);
lblock = offset >> EXT4_BLOCK_SIZE_BITS(sb);
bh = ext4_bread(NULL, inode, lblock, 0, &err);
if (!bh) {
if (err)
EXT4_ERROR_INODE(inode,
"error %d reading directory "
"lblock %u", err, lblock);
offset += sb->s_blocksize;
continue;
}
if (!buffer_verified(bh) &&
!ext4_dirent_csum_verify(inode,
(struct ext4_dir_entry *)bh->b_data)) {
EXT4_ERROR_INODE(inode, "checksum error "
"reading directory lblock 0");
return -EIO;
}
set_buffer_verified(bh);
de = (struct ext4_dir_entry_2 *) bh->b_data;
}
if (ext4_check_dir_entry(inode, NULL, de, bh, offset)) {
de = (struct ext4_dir_entry_2 *)(bh->b_data +
sb->s_blocksize);
offset = (offset | (sb->s_blocksize - 1)) + 1;
continue;
}
if (le32_to_cpu(de->inode)) {
brelse(bh);
return 0;
}
offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
de = ext4_next_entry(de, sb->s_blocksize);
}
brelse(bh);
return 1;
}
/* ext4_orphan_add() links an unlinked or truncated inode into a list of
* such inodes, starting at the superblock, in case we crash before the
* file is closed/deleted, or in case the inode truncate spans multiple
* transactions and the last transaction is not recovered after a crash.
*
* At filesystem recovery time, we walk this list deleting unlinked
* inodes and truncating linked inodes in ext4_orphan_cleanup().
*/
int ext4_orphan_add(handle_t *handle, struct inode *inode)
{
struct super_block *sb = inode->i_sb;
struct ext4_iloc iloc;
int err = 0, rc;
if (!EXT4_SB(sb)->s_journal)
return 0;
mutex_lock(&EXT4_SB(sb)->s_orphan_lock);
if (!list_empty(&EXT4_I(inode)->i_orphan))
goto out_unlock;
/*
* Orphan handling is only valid for files with data blocks
* being truncated, or files being unlinked. Note that we either
* hold i_mutex, or the inode can not be referenced from outside,
* so i_nlink should not be bumped due to race
*/
J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
S_ISLNK(inode->i_mode)) || inode->i_nlink == 0);
BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
if (err)
goto out_unlock;
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto out_unlock;
/*
* Due to previous errors inode may be already a part of on-disk
* orphan list. If so skip on-disk list modification.
*/
if (NEXT_ORPHAN(inode) && NEXT_ORPHAN(inode) <=
(le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count)))
goto mem_insert;
/* Insert this inode at the head of the on-disk orphan list... */
NEXT_ORPHAN(inode) = le32_to_cpu(EXT4_SB(sb)->s_es->s_last_orphan);
EXT4_SB(sb)->s_es->s_last_orphan = cpu_to_le32(inode->i_ino);
err = ext4_handle_dirty_super(handle, sb);
rc = ext4_mark_iloc_dirty(handle, inode, &iloc);
if (!err)
err = rc;
/* Only add to the head of the in-memory list if all the
* previous operations succeeded. If the orphan_add is going to
* fail (possibly taking the journal offline), we can't risk
* leaving the inode on the orphan list: stray orphan-list
* entries can cause panics at unmount time.
*
* This is safe: on error we're going to ignore the orphan list
* anyway on the next recovery. */
mem_insert:
if (!err)
list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan);
jbd_debug(4, "superblock will point to %lu\n", inode->i_ino);
jbd_debug(4, "orphan inode %lu will point to %d\n",
inode->i_ino, NEXT_ORPHAN(inode));
out_unlock:
mutex_unlock(&EXT4_SB(sb)->s_orphan_lock);
ext4_std_error(inode->i_sb, err);
return err;
}
/*
* ext4_orphan_del() removes an unlinked or truncated inode from the list
* of such inodes stored on disk, because it is finally being cleaned up.
*/
int ext4_orphan_del(handle_t *handle, struct inode *inode)
{
struct list_head *prev;
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi;
__u32 ino_next;
struct ext4_iloc iloc;
int err = 0;
if (!EXT4_SB(inode->i_sb)->s_journal)
return 0;
mutex_lock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
if (list_empty(&ei->i_orphan))
goto out;
ino_next = NEXT_ORPHAN(inode);
prev = ei->i_orphan.prev;
sbi = EXT4_SB(inode->i_sb);
jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
list_del_init(&ei->i_orphan);
/* If we're on an error path, we may not have a valid
* transaction handle with which to update the orphan list on
* disk, but we still need to remove the inode from the linked
* list in memory. */
if (!handle)
goto out;
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto out_err;
if (prev == &sbi->s_orphan) {
jbd_debug(4, "superblock will point to %u\n", ino_next);
BUFFER_TRACE(sbi->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, sbi->s_sbh);
if (err)
goto out_brelse;
sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
err = ext4_handle_dirty_super(handle, inode->i_sb);
} else {
struct ext4_iloc iloc2;
struct inode *i_prev =
&list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
jbd_debug(4, "orphan inode %lu will point to %u\n",
i_prev->i_ino, ino_next);
err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
if (err)
goto out_brelse;
NEXT_ORPHAN(i_prev) = ino_next;
err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
}
if (err)
goto out_brelse;
NEXT_ORPHAN(inode) = 0;
err = ext4_mark_iloc_dirty(handle, inode, &iloc);
out_err:
ext4_std_error(inode->i_sb, err);
out:
mutex_unlock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
return err;
out_brelse:
brelse(iloc.bh);
goto out_err;
}
static int ext4_rmdir(struct inode *dir, struct dentry *dentry)
{
int retval;
struct inode *inode;
struct buffer_head *bh;
struct ext4_dir_entry_2 *de;
handle_t *handle;
/* Initialize quotas before so that eventual writes go in
* separate transaction */
dquot_initialize(dir);
dquot_initialize(dentry->d_inode);
handle = ext4_journal_start(dir, EXT4_DELETE_TRANS_BLOCKS(dir->i_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
retval = -ENOENT;
bh = ext4_find_entry(dir, &dentry->d_name, &de);
if (!bh)
goto end_rmdir;
if (IS_DIRSYNC(dir))
ext4_handle_sync(handle);
inode = dentry->d_inode;
retval = -EIO;
if (le32_to_cpu(de->inode) != inode->i_ino)
goto end_rmdir;
retval = -ENOTEMPTY;
if (!empty_dir(inode))
goto end_rmdir;
retval = ext4_delete_entry(handle, dir, de, bh);
if (retval)
goto end_rmdir;
if (!EXT4_DIR_LINK_EMPTY(inode))
ext4_warning(inode->i_sb,
"empty directory has too many links (%d)",
inode->i_nlink);
inode->i_version++;
clear_nlink(inode);
/* There's no need to set i_disksize: the fact that i_nlink is
* zero will ensure that the right thing happens during any
* recovery. */
inode->i_size = 0;
ext4_orphan_add(handle, inode);
inode->i_ctime = dir->i_ctime = dir->i_mtime = ext4_current_time(inode);
ext4_mark_inode_dirty(handle, inode);
ext4_dec_count(handle, dir);
ext4_update_dx_flag(dir);
ext4_mark_inode_dirty(handle, dir);
end_rmdir:
ext4_journal_stop(handle);
brelse(bh);
return retval;
}
static int ext4_unlink(struct inode *dir, struct dentry *dentry)
{
int retval;
struct inode *inode;
struct buffer_head *bh;
struct ext4_dir_entry_2 *de;
handle_t *handle;
trace_ext4_unlink_enter(dir, dentry);
/* Initialize quotas before so that eventual writes go
* in separate transaction */
dquot_initialize(dir);
dquot_initialize(dentry->d_inode);
handle = ext4_journal_start(dir, EXT4_DELETE_TRANS_BLOCKS(dir->i_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
if (IS_DIRSYNC(dir))
ext4_handle_sync(handle);
retval = -ENOENT;
bh = ext4_find_entry(dir, &dentry->d_name, &de);
if (!bh)
goto end_unlink;
inode = dentry->d_inode;
retval = -EIO;
if (le32_to_cpu(de->inode) != inode->i_ino)
goto end_unlink;
if (!inode->i_nlink) {
ext4_warning(inode->i_sb,
"Deleting nonexistent file (%lu), %d",
inode->i_ino, inode->i_nlink);
set_nlink(inode, 1);
}
retval = ext4_delete_entry(handle, dir, de, bh);
if (retval)
goto end_unlink;
dir->i_ctime = dir->i_mtime = ext4_current_time(dir);
ext4_update_dx_flag(dir);
ext4_mark_inode_dirty(handle, dir);
drop_nlink(inode);
if (!inode->i_nlink)
ext4_orphan_add(handle, inode);
inode->i_ctime = ext4_current_time(inode);
ext4_mark_inode_dirty(handle, inode);
retval = 0;
end_unlink:
ext4_journal_stop(handle);
brelse(bh);
trace_ext4_unlink_exit(dentry, retval);
return retval;
}
static int ext4_symlink(struct inode *dir,
struct dentry *dentry, const char *symname)
{
handle_t *handle;
struct inode *inode;
int l, err, retries = 0;
int credits;
l = strlen(symname)+1;
if (l > dir->i_sb->s_blocksize)
return -ENAMETOOLONG;
dquot_initialize(dir);
if (l > EXT4_N_BLOCKS * 4) {
/*
* For non-fast symlinks, we just allocate inode and put it on
* orphan list in the first transaction => we need bitmap,
* group descriptor, sb, inode block, quota blocks, and
* possibly selinux xattr blocks.
*/
credits = 4 + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
EXT4_XATTR_TRANS_BLOCKS;
} else {
/*
* Fast symlink. We have to add entry to directory
* (EXT4_DATA_TRANS_BLOCKS + EXT4_INDEX_EXTRA_TRANS_BLOCKS),
* allocate new inode (bitmap, group descriptor, inode block,
* quota blocks, sb is already counted in previous macros).
*/
credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3 +
EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb);
}
retry:
handle = ext4_journal_start(dir, credits);
if (IS_ERR(handle))
return PTR_ERR(handle);
if (IS_DIRSYNC(dir))
ext4_handle_sync(handle);
inode = ext4_new_inode(handle, dir, S_IFLNK|S_IRWXUGO,
&dentry->d_name, 0, NULL);
err = PTR_ERR(inode);
if (IS_ERR(inode))
goto out_stop;
if (l > EXT4_N_BLOCKS * 4) {
inode->i_op = &ext4_symlink_inode_operations;
ext4_set_aops(inode);
/*
* We cannot call page_symlink() with transaction started
* because it calls into ext4_write_begin() which can wait
* for transaction commit if we are running out of space
* and thus we deadlock. So we have to stop transaction now
* and restart it when symlink contents is written.
*
* To keep fs consistent in case of crash, we have to put inode
* to orphan list in the mean time.
*/
drop_nlink(inode);
err = ext4_orphan_add(handle, inode);
ext4_journal_stop(handle);
if (err)
goto err_drop_inode;
err = __page_symlink(inode, symname, l, 1);
if (err)
goto err_drop_inode;
/*
* Now inode is being linked into dir (EXT4_DATA_TRANS_BLOCKS
* + EXT4_INDEX_EXTRA_TRANS_BLOCKS), inode is also modified
*/
handle = ext4_journal_start(dir,
EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 1);
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
goto err_drop_inode;
}
set_nlink(inode, 1);
err = ext4_orphan_del(handle, inode);
if (err) {
ext4_journal_stop(handle);
clear_nlink(inode);
goto err_drop_inode;
}
} else {
/* clear the extent format for fast symlink */
ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS);
inode->i_op = &ext4_fast_symlink_inode_operations;
memcpy((char *)&EXT4_I(inode)->i_data, symname, l);
inode->i_size = l-1;
}
EXT4_I(inode)->i_disksize = inode->i_size;
err = ext4_add_nondir(handle, dentry, inode);
out_stop:
ext4_journal_stop(handle);
if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
goto retry;
return err;
err_drop_inode:
unlock_new_inode(inode);
iput(inode);
return err;
}
static int ext4_link(struct dentry *old_dentry,
struct inode *dir, struct dentry *dentry)
{
handle_t *handle;
struct inode *inode = old_dentry->d_inode;
int err, retries = 0;
if (inode->i_nlink >= EXT4_LINK_MAX)
return -EMLINK;
dquot_initialize(dir);
retry:
handle = ext4_journal_start(dir, EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS);
if (IS_ERR(handle))
return PTR_ERR(handle);
if (IS_DIRSYNC(dir))
ext4_handle_sync(handle);
inode->i_ctime = ext4_current_time(inode);
ext4_inc_count(handle, inode);
ihold(inode);
err = ext4_add_entry(handle, dentry, inode);
if (!err) {
ext4_mark_inode_dirty(handle, inode);
d_instantiate(dentry, inode);
} else {
drop_nlink(inode);
iput(inode);
}
ext4_journal_stop(handle);
if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
goto retry;
return err;
}
#define PARENT_INO(buffer, size) \
(ext4_next_entry((struct ext4_dir_entry_2 *)(buffer), size)->inode)
/*
* Anybody can rename anything with this: the permission checks are left to the
* higher-level routines.
*/
static int ext4_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
handle_t *handle;
struct inode *old_inode, *new_inode;
struct buffer_head *old_bh, *new_bh, *dir_bh;
struct ext4_dir_entry_2 *old_de, *new_de;
int retval, force_da_alloc = 0;
dquot_initialize(old_dir);
dquot_initialize(new_dir);
old_bh = new_bh = dir_bh = NULL;
/* Initialize quotas before so that eventual writes go
* in separate transaction */
if (new_dentry->d_inode)
dquot_initialize(new_dentry->d_inode);
handle = ext4_journal_start(old_dir, 2 *
EXT4_DATA_TRANS_BLOCKS(old_dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2);
if (IS_ERR(handle))
return PTR_ERR(handle);
if (IS_DIRSYNC(old_dir) || IS_DIRSYNC(new_dir))
ext4_handle_sync(handle);
old_bh = ext4_find_entry(old_dir, &old_dentry->d_name, &old_de);
/*
* Check for inode number is _not_ due to possible IO errors.
* We might rmdir the source, keep it as pwd of some process
* and merrily kill the link to whatever was created under the
* same name. Goodbye sticky bit ;-<
*/
old_inode = old_dentry->d_inode;
retval = -ENOENT;
if (!old_bh || le32_to_cpu(old_de->inode) != old_inode->i_ino)
goto end_rename;
new_inode = new_dentry->d_inode;
new_bh = ext4_find_entry(new_dir, &new_dentry->d_name, &new_de);
if (new_bh) {
if (!new_inode) {
brelse(new_bh);
new_bh = NULL;
}
}
if (S_ISDIR(old_inode->i_mode)) {
if (new_inode) {
retval = -ENOTEMPTY;
if (!empty_dir(new_inode))
goto end_rename;
}
retval = -EIO;
dir_bh = ext4_bread(handle, old_inode, 0, 0, &retval);
if (!dir_bh)
goto end_rename;
if (!buffer_verified(dir_bh) &&
!ext4_dirent_csum_verify(old_inode,
(struct ext4_dir_entry *)dir_bh->b_data))
goto end_rename;
set_buffer_verified(dir_bh);
if (le32_to_cpu(PARENT_INO(dir_bh->b_data,
old_dir->i_sb->s_blocksize)) != old_dir->i_ino)
goto end_rename;
retval = -EMLINK;
if (!new_inode && new_dir != old_dir &&
EXT4_DIR_LINK_MAX(new_dir))
goto end_rename;
BUFFER_TRACE(dir_bh, "get_write_access");
retval = ext4_journal_get_write_access(handle, dir_bh);
if (retval)
goto end_rename;
}
if (!new_bh) {
retval = ext4_add_entry(handle, new_dentry, old_inode);
if (retval)
goto end_rename;
} else {
BUFFER_TRACE(new_bh, "get write access");
retval = ext4_journal_get_write_access(handle, new_bh);
if (retval)
goto end_rename;
new_de->inode = cpu_to_le32(old_inode->i_ino);
if (EXT4_HAS_INCOMPAT_FEATURE(new_dir->i_sb,
EXT4_FEATURE_INCOMPAT_FILETYPE))
new_de->file_type = old_de->file_type;
new_dir->i_version++;
new_dir->i_ctime = new_dir->i_mtime =
ext4_current_time(new_dir);
ext4_mark_inode_dirty(handle, new_dir);
BUFFER_TRACE(new_bh, "call ext4_handle_dirty_metadata");
retval = ext4_handle_dirty_dirent_node(handle, new_dir, new_bh);
if (unlikely(retval)) {
ext4_std_error(new_dir->i_sb, retval);
goto end_rename;
}
brelse(new_bh);
new_bh = NULL;
}
/*
* Like most other Unix systems, set the ctime for inodes on a
* rename.
*/
old_inode->i_ctime = ext4_current_time(old_inode);
ext4_mark_inode_dirty(handle, old_inode);
/*
* ok, that's it
*/
if (le32_to_cpu(old_de->inode) != old_inode->i_ino ||
old_de->name_len != old_dentry->d_name.len ||
strncmp(old_de->name, old_dentry->d_name.name, old_de->name_len) ||
(retval = ext4_delete_entry(handle, old_dir,
old_de, old_bh)) == -ENOENT) {
/* old_de could have moved from under us during htree split, so
* make sure that we are deleting the right entry. We might
* also be pointing to a stale entry in the unused part of
* old_bh so just checking inum and the name isn't enough. */
struct buffer_head *old_bh2;
struct ext4_dir_entry_2 *old_de2;
old_bh2 = ext4_find_entry(old_dir, &old_dentry->d_name, &old_de2);
if (old_bh2) {
retval = ext4_delete_entry(handle, old_dir,
old_de2, old_bh2);
brelse(old_bh2);
}
}
if (retval) {
ext4_warning(old_dir->i_sb,
"Deleting old file (%lu), %d, error=%d",
old_dir->i_ino, old_dir->i_nlink, retval);
}
if (new_inode) {
ext4_dec_count(handle, new_inode);
new_inode->i_ctime = ext4_current_time(new_inode);
}
old_dir->i_ctime = old_dir->i_mtime = ext4_current_time(old_dir);
ext4_update_dx_flag(old_dir);
if (dir_bh) {
PARENT_INO(dir_bh->b_data, new_dir->i_sb->s_blocksize) =
cpu_to_le32(new_dir->i_ino);
BUFFER_TRACE(dir_bh, "call ext4_handle_dirty_metadata");
if (is_dx(old_inode)) {
retval = ext4_handle_dirty_dx_node(handle,
old_inode,
dir_bh);
} else {
retval = ext4_handle_dirty_dirent_node(handle,
old_inode,
dir_bh);
}
if (retval) {
ext4_std_error(old_dir->i_sb, retval);
goto end_rename;
}
ext4_dec_count(handle, old_dir);
if (new_inode) {
/* checked empty_dir above, can't have another parent,
* ext4_dec_count() won't work for many-linked dirs */
clear_nlink(new_inode);
} else {
ext4_inc_count(handle, new_dir);
ext4_update_dx_flag(new_dir);
ext4_mark_inode_dirty(handle, new_dir);
}
}
ext4_mark_inode_dirty(handle, old_dir);
if (new_inode) {
ext4_mark_inode_dirty(handle, new_inode);
if (!new_inode->i_nlink)
ext4_orphan_add(handle, new_inode);
if (!test_opt(new_dir->i_sb, NO_AUTO_DA_ALLOC))
force_da_alloc = 1;
}
retval = 0;
end_rename:
brelse(dir_bh);
brelse(old_bh);
brelse(new_bh);
ext4_journal_stop(handle);
if (retval == 0 && force_da_alloc)
ext4_alloc_da_blocks(old_inode);
return retval;
}
/*
* directories can handle most operations...
*/
const struct inode_operations ext4_dir_inode_operations = {
.create = ext4_create,
.lookup = ext4_lookup,
.link = ext4_link,
.unlink = ext4_unlink,
.symlink = ext4_symlink,
.mkdir = ext4_mkdir,
.rmdir = ext4_rmdir,
.mknod = ext4_mknod,
.rename = ext4_rename,
.setattr = ext4_setattr,
#ifdef CONFIG_EXT4_FS_XATTR
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.listxattr = ext4_listxattr,
.removexattr = generic_removexattr,
#endif
.get_acl = ext4_get_acl,
.fiemap = ext4_fiemap,
};
const struct inode_operations ext4_special_inode_operations = {
.setattr = ext4_setattr,
#ifdef CONFIG_EXT4_FS_XATTR
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.listxattr = ext4_listxattr,
.removexattr = generic_removexattr,
#endif
.get_acl = ext4_get_acl,
};
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_1745_0 |
crossvul-cpp_data_good_5185_0 | /* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@file rsa_verify_hash.c
RSA PKCS #1 v1.5 or v2 PSS signature verification, Tom St Denis and Andreas Lange
*/
#ifdef LTC_MRSA
/**
PKCS #1 de-sign then v1.5 or PSS depad
@param sig The signature data
@param siglen The length of the signature data (octets)
@param hash The hash of the message that was signed
@param hashlen The length of the hash of the message that was signed (octets)
@param padding Type of padding (LTC_PKCS_1_PSS or LTC_PKCS_1_V1_5)
@param hash_idx The index of the desired hash
@param saltlen The length of the salt used during signature
@param stat [out] The result of the signature comparison, 1==valid, 0==invalid
@param key The public RSA key corresponding to the key that performed the signature
@return CRYPT_OK on success (even if the signature is invalid)
*/
int rsa_verify_hash_ex(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long hashlen,
int padding,
int hash_idx, unsigned long saltlen,
int *stat, rsa_key *key)
{
unsigned long modulus_bitlen, modulus_bytelen, x;
int err;
unsigned char *tmpbuf;
LTC_ARGCHK(hash != NULL);
LTC_ARGCHK(sig != NULL);
LTC_ARGCHK(stat != NULL);
LTC_ARGCHK(key != NULL);
/* default to invalid */
*stat = 0;
/* valid padding? */
if ((padding != LTC_PKCS_1_V1_5) &&
(padding != LTC_PKCS_1_PSS)) {
return CRYPT_PK_INVALID_PADDING;
}
if (padding == LTC_PKCS_1_PSS) {
/* valid hash ? */
if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
return err;
}
}
/* get modulus len in bits */
modulus_bitlen = mp_count_bits( (key->N));
/* outlen must be at least the size of the modulus */
modulus_bytelen = mp_unsigned_bin_size( (key->N));
if (modulus_bytelen != siglen) {
return CRYPT_INVALID_PACKET;
}
/* allocate temp buffer for decoded sig */
tmpbuf = XMALLOC(siglen);
if (tmpbuf == NULL) {
return CRYPT_MEM;
}
/* RSA decode it */
x = siglen;
if ((err = ltc_mp.rsa_me(sig, siglen, tmpbuf, &x, PK_PUBLIC, key)) != CRYPT_OK) {
XFREE(tmpbuf);
return err;
}
/* make sure the output is the right size */
if (x != siglen) {
XFREE(tmpbuf);
return CRYPT_INVALID_PACKET;
}
if (padding == LTC_PKCS_1_PSS) {
/* PSS decode and verify it */
if(modulus_bitlen%8 == 1){
err = pkcs_1_pss_decode(hash, hashlen, tmpbuf+1, x-1, saltlen, hash_idx, modulus_bitlen, stat);
}
else{
err = pkcs_1_pss_decode(hash, hashlen, tmpbuf, x, saltlen, hash_idx, modulus_bitlen, stat);
}
} else {
/* PKCS #1 v1.5 decode it */
unsigned char *out;
unsigned long outlen, loid[16], reallen;
int decoded;
ltc_asn1_list digestinfo[2], siginfo[2];
/* not all hashes have OIDs... so sad */
if (hash_descriptor[hash_idx].OIDlen == 0) {
err = CRYPT_INVALID_ARG;
goto bail_2;
}
/* allocate temp buffer for decoded hash */
outlen = ((modulus_bitlen >> 3) + (modulus_bitlen & 7 ? 1 : 0)) - 3;
out = XMALLOC(outlen);
if (out == NULL) {
err = CRYPT_MEM;
goto bail_2;
}
if ((err = pkcs_1_v1_5_decode(tmpbuf, x, LTC_PKCS_1_EMSA, modulus_bitlen, out, &outlen, &decoded)) != CRYPT_OK) {
XFREE(out);
goto bail_2;
}
/* now we must decode out[0...outlen-1] using ASN.1, test the OID and then test the hash */
/* construct the SEQUENCE
SEQUENCE {
SEQUENCE {hashoid OID
blah NULL
}
hash OCTET STRING
}
*/
LTC_SET_ASN1(digestinfo, 0, LTC_ASN1_OBJECT_IDENTIFIER, loid, sizeof(loid)/sizeof(loid[0]));
LTC_SET_ASN1(digestinfo, 1, LTC_ASN1_NULL, NULL, 0);
LTC_SET_ASN1(siginfo, 0, LTC_ASN1_SEQUENCE, digestinfo, 2);
LTC_SET_ASN1(siginfo, 1, LTC_ASN1_OCTET_STRING, tmpbuf, siglen);
if ((err = der_decode_sequence(out, outlen, siginfo, 2)) != CRYPT_OK) {
XFREE(out);
goto bail_2;
}
if ((err = der_length_sequence(siginfo, 2, &reallen)) != CRYPT_OK) {
XFREE(out);
goto bail_2;
}
/* test OID */
if ((reallen == outlen) &&
(digestinfo[0].size == hash_descriptor[hash_idx].OIDlen) &&
(XMEMCMP(digestinfo[0].data, hash_descriptor[hash_idx].OID, sizeof(unsigned long) * hash_descriptor[hash_idx].OIDlen) == 0) &&
(siginfo[1].size == hashlen) &&
(XMEMCMP(siginfo[1].data, hash, hashlen) == 0)) {
*stat = 1;
}
#ifdef LTC_CLEAN_STACK
zeromem(out, outlen);
#endif
XFREE(out);
}
bail_2:
#ifdef LTC_CLEAN_STACK
zeromem(tmpbuf, siglen);
#endif
XFREE(tmpbuf);
return err;
}
#endif /* LTC_MRSA */
/* $Source$ */
/* $Revision$ */
/* $Date$ */
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5185_0 |
crossvul-cpp_data_bad_3480_0 | // TODO some minor issues
/*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 2001 - 2007 Tensilica Inc.
*
* Joe Taylor <joe@tensilica.com, joetylr@yahoo.com>
* Chris Zankel <chris@zankel.net>
* Scott Foehner<sfoehner@yahoo.com>,
* Kevin Chea
* Marc Gauthier<marc@tensilica.com> <marc@alumni.uwaterloo.ca>
*/
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <linux/ptrace.h>
#include <linux/smp.h>
#include <linux/security.h>
#include <linux/signal.h>
#include <asm/pgtable.h>
#include <asm/page.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include <asm/ptrace.h>
#include <asm/elf.h>
#include <asm/coprocessor.h>
void user_enable_single_step(struct task_struct *child)
{
child->ptrace |= PT_SINGLESTEP;
}
void user_disable_single_step(struct task_struct *child)
{
child->ptrace &= ~PT_SINGLESTEP;
}
/*
* Called by kernel/ptrace.c when detaching to disable single stepping.
*/
void ptrace_disable(struct task_struct *child)
{
/* Nothing to do.. */
}
int ptrace_getregs(struct task_struct *child, void __user *uregs)
{
struct pt_regs *regs = task_pt_regs(child);
xtensa_gregset_t __user *gregset = uregs;
unsigned long wm = regs->wmask;
unsigned long wb = regs->windowbase;
int live, i;
if (!access_ok(VERIFY_WRITE, uregs, sizeof(xtensa_gregset_t)))
return -EIO;
__put_user(regs->pc, &gregset->pc);
__put_user(regs->ps & ~(1 << PS_EXCM_BIT), &gregset->ps);
__put_user(regs->lbeg, &gregset->lbeg);
__put_user(regs->lend, &gregset->lend);
__put_user(regs->lcount, &gregset->lcount);
__put_user(regs->windowstart, &gregset->windowstart);
__put_user(regs->windowbase, &gregset->windowbase);
live = (wm & 2) ? 4 : (wm & 4) ? 8 : (wm & 8) ? 12 : 16;
for (i = 0; i < live; i++)
__put_user(regs->areg[i],gregset->a+((wb*4+i)%XCHAL_NUM_AREGS));
for (i = XCHAL_NUM_AREGS - (wm >> 4) * 4; i < XCHAL_NUM_AREGS; i++)
__put_user(regs->areg[i],gregset->a+((wb*4+i)%XCHAL_NUM_AREGS));
return 0;
}
int ptrace_setregs(struct task_struct *child, void __user *uregs)
{
struct pt_regs *regs = task_pt_regs(child);
xtensa_gregset_t *gregset = uregs;
const unsigned long ps_mask = PS_CALLINC_MASK | PS_OWB_MASK;
unsigned long ps;
unsigned long wb;
if (!access_ok(VERIFY_WRITE, uregs, sizeof(xtensa_gregset_t)))
return -EIO;
__get_user(regs->pc, &gregset->pc);
__get_user(ps, &gregset->ps);
__get_user(regs->lbeg, &gregset->lbeg);
__get_user(regs->lend, &gregset->lend);
__get_user(regs->lcount, &gregset->lcount);
__get_user(regs->windowstart, &gregset->windowstart);
__get_user(wb, &gregset->windowbase);
regs->ps = (regs->ps & ~ps_mask) | (ps & ps_mask) | (1 << PS_EXCM_BIT);
if (wb >= XCHAL_NUM_AREGS / 4)
return -EFAULT;
regs->windowbase = wb;
if (wb != 0 && __copy_from_user(regs->areg + XCHAL_NUM_AREGS - wb * 4,
gregset->a, wb * 16))
return -EFAULT;
if (__copy_from_user(regs->areg, gregset->a + wb*4, (WSBITS-wb) * 16))
return -EFAULT;
return 0;
}
int ptrace_getxregs(struct task_struct *child, void __user *uregs)
{
struct pt_regs *regs = task_pt_regs(child);
struct thread_info *ti = task_thread_info(child);
elf_xtregs_t __user *xtregs = uregs;
int ret = 0;
if (!access_ok(VERIFY_WRITE, uregs, sizeof(elf_xtregs_t)))
return -EIO;
#if XTENSA_HAVE_COPROCESSORS
/* Flush all coprocessor registers to memory. */
coprocessor_flush_all(ti);
ret |= __copy_to_user(&xtregs->cp0, &ti->xtregs_cp,
sizeof(xtregs_coprocessor_t));
#endif
ret |= __copy_to_user(&xtregs->opt, ®s->xtregs_opt,
sizeof(xtregs->opt));
ret |= __copy_to_user(&xtregs->user,&ti->xtregs_user,
sizeof(xtregs->user));
return ret ? -EFAULT : 0;
}
int ptrace_setxregs(struct task_struct *child, void __user *uregs)
{
struct thread_info *ti = task_thread_info(child);
struct pt_regs *regs = task_pt_regs(child);
elf_xtregs_t *xtregs = uregs;
int ret = 0;
#if XTENSA_HAVE_COPROCESSORS
/* Flush all coprocessors before we overwrite them. */
coprocessor_flush_all(ti);
coprocessor_release_all(ti);
ret |= __copy_from_user(&ti->xtregs_cp, &xtregs->cp0,
sizeof(xtregs_coprocessor_t));
#endif
ret |= __copy_from_user(®s->xtregs_opt, &xtregs->opt,
sizeof(xtregs->opt));
ret |= __copy_from_user(&ti->xtregs_user, &xtregs->user,
sizeof(xtregs->user));
return ret ? -EFAULT : 0;
}
int ptrace_peekusr(struct task_struct *child, long regno, long __user *ret)
{
struct pt_regs *regs;
unsigned long tmp;
regs = task_pt_regs(child);
tmp = 0; /* Default return value. */
switch(regno) {
case REG_AR_BASE ... REG_AR_BASE + XCHAL_NUM_AREGS - 1:
tmp = regs->areg[regno - REG_AR_BASE];
break;
case REG_A_BASE ... REG_A_BASE + 15:
tmp = regs->areg[regno - REG_A_BASE];
break;
case REG_PC:
tmp = regs->pc;
break;
case REG_PS:
/* Note: PS.EXCM is not set while user task is running;
* its being set in regs is for exception handling
* convenience. */
tmp = (regs->ps & ~(1 << PS_EXCM_BIT));
break;
case REG_WB:
break; /* tmp = 0 */
case REG_WS:
{
unsigned long wb = regs->windowbase;
unsigned long ws = regs->windowstart;
tmp = ((ws>>wb) | (ws<<(WSBITS-wb))) & ((1<<WSBITS)-1);
break;
}
case REG_LBEG:
tmp = regs->lbeg;
break;
case REG_LEND:
tmp = regs->lend;
break;
case REG_LCOUNT:
tmp = regs->lcount;
break;
case REG_SAR:
tmp = regs->sar;
break;
case SYSCALL_NR:
tmp = regs->syscall;
break;
default:
return -EIO;
}
return put_user(tmp, ret);
}
int ptrace_pokeusr(struct task_struct *child, long regno, long val)
{
struct pt_regs *regs;
regs = task_pt_regs(child);
switch (regno) {
case REG_AR_BASE ... REG_AR_BASE + XCHAL_NUM_AREGS - 1:
regs->areg[regno - REG_AR_BASE] = val;
break;
case REG_A_BASE ... REG_A_BASE + 15:
regs->areg[regno - REG_A_BASE] = val;
break;
case REG_PC:
regs->pc = val;
break;
case SYSCALL_NR:
regs->syscall = val;
break;
default:
return -EIO;
}
return 0;
}
long arch_ptrace(struct task_struct *child, long request,
unsigned long addr, unsigned long data)
{
int ret = -EPERM;
void __user *datap = (void __user *) data;
switch (request) {
case PTRACE_PEEKTEXT: /* read word at location addr. */
case PTRACE_PEEKDATA:
ret = generic_ptrace_peekdata(child, addr, data);
break;
case PTRACE_PEEKUSR: /* read register specified by addr. */
ret = ptrace_peekusr(child, addr, datap);
break;
case PTRACE_POKETEXT: /* write the word at location addr. */
case PTRACE_POKEDATA:
ret = generic_ptrace_pokedata(child, addr, data);
break;
case PTRACE_POKEUSR: /* write register specified by addr. */
ret = ptrace_pokeusr(child, addr, data);
break;
case PTRACE_GETREGS:
ret = ptrace_getregs(child, datap);
break;
case PTRACE_SETREGS:
ret = ptrace_setregs(child, datap);
break;
case PTRACE_GETXTREGS:
ret = ptrace_getxregs(child, datap);
break;
case PTRACE_SETXTREGS:
ret = ptrace_setxregs(child, datap);
break;
default:
ret = ptrace_request(child, request, addr, data);
break;
}
return ret;
}
void do_syscall_trace(void)
{
/*
* The 0x80 provides a way for the tracing parent to distinguish
* between a syscall stop and SIGTRAP delivery
*/
ptrace_notify(SIGTRAP|((current->ptrace & PT_TRACESYSGOOD) ? 0x80 : 0));
/*
* this isn't the same as continuing with a signal, but it will do
* for normal use. strace only continues with a signal if the
* stopping signal is not SIGTRAP. -brl
*/
if (current->exit_code) {
send_sig(current->exit_code, current, 1);
current->exit_code = 0;
}
}
void do_syscall_trace_enter(struct pt_regs *regs)
{
if (test_thread_flag(TIF_SYSCALL_TRACE)
&& (current->ptrace & PT_PTRACED))
do_syscall_trace();
#if 0
if (unlikely(current->audit_context))
audit_syscall_entry(current, AUDIT_ARCH_XTENSA..);
#endif
}
void do_syscall_trace_leave(struct pt_regs *regs)
{
if ((test_thread_flag(TIF_SYSCALL_TRACE))
&& (current->ptrace & PT_PTRACED))
do_syscall_trace();
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3480_0 |
crossvul-cpp_data_good_1053_0 | /* $OpenBSD: doas.c,v 1.57 2016/06/19 19:29:43 martijn Exp $ */
/*
* Copyright (c) 2015 Ted Unangst <tedu@openbsd.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#if defined(HAVE_INTTYPES_H)
#include <inttypes.h>
#endif
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <syslog.h>
#include <errno.h>
#include <fcntl.h>
#if defined(HAVE_LOGIN_CAP_H)
#include <login_cap.h>
#endif
#if defined(USE_BSD_AUTH)
#include <bsd_auth.h>
#include <readpassphrase.h>
#endif
#if defined(USE_PAM)
#include <security/pam_appl.h>
#if defined(OPENPAM) /* BSD, MacOS & certain Linux distros */
#include <security/openpam.h>
static struct pam_conv pamc = { openpam_ttyconv, NULL };
#elif defined(__LINUX_PAM__) /* Linux */
#include <security/pam_misc.h>
static struct pam_conv pamc = { misc_conv, NULL };
#elif defined(SOLARIS_PAM) /* illumos & Solaris */
#include "pm_pam_conv.h"
static struct pam_conv pamc = { pam_tty_conv, NULL };
#endif /* OPENPAM */
#endif /* USE_PAM */
#include "doas.h"
static void
usage(void)
{
fprintf(stderr, "usage: doas [-ns] [-a style] [-C config] [-u user]"
" command [args]\n");
exit(1);
}
#ifdef linux
void
errc(int eval, int code, const char *format)
{
fprintf(stderr, "%s", format);
exit(code);
}
#endif
static int
parseuid(const char *s, uid_t *uid)
{
struct passwd *pw;
const char *errstr;
if ((pw = getpwnam(s)) != NULL) {
*uid = pw->pw_uid;
return 0;
}
#if !defined(__linux__) && !defined(__NetBSD__)
*uid = strtonum(s, 0, UID_MAX, &errstr);
#else
sscanf(s, "%d", uid);
#endif
if (errstr)
return -1;
return 0;
}
static int
uidcheck(const char *s, uid_t desired)
{
uid_t uid;
if (parseuid(s, &uid) != 0)
return -1;
if (uid != desired)
return -1;
return 0;
}
static int
parsegid(const char *s, gid_t *gid)
{
struct group *gr;
const char *errstr;
if ((gr = getgrnam(s)) != NULL) {
*gid = gr->gr_gid;
return 0;
}
#if !defined(__linux__) && !defined(__NetBSD__)
*gid = strtonum(s, 0, GID_MAX, &errstr);
#else
sscanf(s, "%d", gid);
#endif
if (errstr)
return -1;
return 0;
}
static int
match(uid_t uid, gid_t *groups, int ngroups, uid_t target, const char *cmd,
const char **cmdargs, struct rule *r)
{
int i;
if (r->ident[0] == ':') {
gid_t rgid;
if (parsegid(r->ident + 1, &rgid) == -1)
return 0;
for (i = 0; i < ngroups; i++) {
if (rgid == groups[i])
break;
}
if (i == ngroups)
return 0;
} else {
if (uidcheck(r->ident, uid) != 0)
return 0;
}
if (r->target && uidcheck(r->target, target) != 0)
return 0;
if (r->cmd) {
if (strcmp(r->cmd, cmd))
return 0;
if (r->cmdargs) {
/* if arguments were given, they should match explicitly */
for (i = 0; r->cmdargs[i]; i++) {
if (!cmdargs[i])
return 0;
if (strcmp(r->cmdargs[i], cmdargs[i]))
return 0;
}
if (cmdargs[i])
return 0;
}
}
return 1;
}
static int
permit(uid_t uid, gid_t *groups, int ngroups, struct rule **lastr,
uid_t target, const char *cmd, const char **cmdargs)
{
int i;
*lastr = NULL;
for (i = 0; i < nrules; i++) {
if (match(uid, groups, ngroups, target, cmd,
cmdargs, rules[i]))
*lastr = rules[i];
}
if (!*lastr)
return 0;
return (*lastr)->action == PERMIT;
}
static void
parseconfig(const char *filename, int checkperms)
{
extern FILE *yyfp;
extern int yyparse(void);
struct stat sb;
yyfp = fopen(filename, "r");
if (!yyfp)
err(1, checkperms ? "doas is not enabled, %s" :
"could not open config file %s", filename);
if (checkperms) {
if (fstat(fileno(yyfp), &sb) != 0)
err(1, "fstat(\"%s\")", filename);
if ((sb.st_mode & (S_IWGRP|S_IWOTH)) != 0)
errx(1, "%s is writable by group or other", filename);
if (sb.st_uid != 0)
errx(1, "%s is not owned by root", filename);
}
yyparse();
fclose(yyfp);
if (parse_errors)
exit(1);
}
static void
checkconfig(const char *confpath, int argc, char **argv,
uid_t uid, gid_t *groups, int ngroups, uid_t target)
{
struct rule *rule;
int status;
#if defined(__linux__) || defined(__FreeBSD__)
status = setresuid(uid, uid, uid);
#else
status = setreuid(uid, uid);
#endif
if (status == -1)
{
printf("doas: Unable to set UID\n");
exit(1);
}
parseconfig(confpath, 0);
if (!argc)
exit(0);
if (permit(uid, groups, ngroups, &rule, target, argv[0],
(const char **)argv + 1)) {
printf("permit%s\n", (rule->options & NOPASS) ? " nopass" : "");
exit(0);
} else {
printf("deny\n");
exit(1);
}
}
#if defined(USE_BSD_AUTH)
static void
authuser(char *myname, char *login_style, int persist)
{
char *challenge = NULL, *response, rbuf[1024], cbuf[128];
auth_session_t *as;
int fd = -1;
if (persist)
fd = open("/dev/tty", O_RDWR);
if (fd != -1) {
if (ioctl(fd, TIOCCHKVERAUTH) == 0)
goto good;
}
if (!(as = auth_userchallenge(myname, login_style, "auth-doas",
&challenge)))
errx(1, "Authorization failed");
if (!challenge) {
char host[HOST_NAME_MAX + 1];
if (gethostname(host, sizeof(host)))
snprintf(host, sizeof(host), "?");
snprintf(cbuf, sizeof(cbuf),
"\rdoas (%.32s@%.32s) password: ", myname, host);
challenge = cbuf;
}
response = readpassphrase(challenge, rbuf, sizeof(rbuf),
RPP_REQUIRE_TTY);
if (response == NULL && errno == ENOTTY) {
syslog(LOG_AUTHPRIV | LOG_NOTICE,
"tty required for %s", myname);
errx(1, "a tty is required");
}
if (!auth_userresponse(as, response, 0)) {
syslog(LOG_AUTHPRIV | LOG_NOTICE,
"failed auth for %s", myname);
errc(1, EPERM, NULL);
}
explicit_bzero(rbuf, sizeof(rbuf));
good:
if (fd != -1) {
int secs = 5 * 60;
ioctl(fd, TIOCSETVERAUTH, &secs);
close(fd);
}
}
#endif
int
main(int argc, char **argv)
{
const char *safepath = SAFE_PATH;
const char *confpath = NULL;
char *shargv[] = { NULL, NULL };
char *sh;
const char *cmd;
char cmdline[LINE_MAX];
char myname[_PW_NAME_LEN + 1];
struct passwd *original_pw, *target_pw;
struct rule *rule;
uid_t uid;
uid_t target = 0;
gid_t groups[NGROUPS_MAX + 1];
int ngroups;
int i, ch;
int sflag = 0;
int nflag = 0;
char cwdpath[PATH_MAX];
const char *cwd;
char *login_style = NULL;
char **envp;
#ifndef linux
setprogname("doas");
#endif
#ifndef linux
closefrom(STDERR_FILENO + 1);
#endif
uid = getuid();
while ((ch = getopt(argc, argv, "a:C:nsu:")) != -1) {
/* while ((ch = getopt(argc, argv, "a:C:Lnsu:")) != -1) { */
switch (ch) {
case 'a':
login_style = optarg;
break;
case 'C':
confpath = optarg;
break;
/* case 'L':
i = open("/dev/tty", O_RDWR);
if (i != -1)
ioctl(i, TIOCCLRVERAUTH);
exit(i != -1);
*/
case 'u':
if (parseuid(optarg, &target) != 0)
errx(1, "unknown user");
break;
case 'n':
nflag = 1;
break;
case 's':
sflag = 1;
break;
default:
usage();
break;
}
}
argv += optind;
argc -= optind;
if (confpath) {
if (sflag)
usage();
} else if ((!sflag && !argc) || (sflag && argc))
usage();
original_pw = getpwuid(uid);
if (! original_pw)
err(1, "getpwuid failed");
if (strlcpy(myname, original_pw->pw_name, sizeof(myname)) >= sizeof(myname))
errx(1, "pw_name too long");
ngroups = getgroups(NGROUPS_MAX, groups);
if (ngroups == -1)
err(1, "can't get groups");
groups[ngroups++] = getgid();
if (sflag) {
sh = getenv("SHELL");
if (sh == NULL || *sh == '\0') {
shargv[0] = strdup(original_pw->pw_shell);
if (shargv[0] == NULL)
err(1, NULL);
} else
shargv[0] = sh;
argv = shargv;
argc = 1;
}
if (confpath) {
checkconfig(confpath, argc, argv, uid, groups, ngroups,
target);
exit(1); /* fail safe */
}
if (geteuid())
errx(1, "not installed setuid");
parseconfig(DOAS_CONF, 1);
/* cmdline is used only for logging, no need to abort on truncate */
(void)strlcpy(cmdline, argv[0], sizeof(cmdline));
for (i = 1; i < argc; i++) {
if (strlcat(cmdline, " ", sizeof(cmdline)) >= sizeof(cmdline))
break;
if (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline))
break;
}
cmd = argv[0];
if (!permit(uid, groups, ngroups, &rule, target, cmd,
(const char **)argv + 1)) {
syslog(LOG_AUTHPRIV | LOG_NOTICE,
"failed command for %s: %s", myname, cmdline);
errc(1, EPERM, NULL);
}
if (!(rule->options & NOPASS)) {
if (nflag)
errx(1, "Authorization required");
#if defined(USE_BSD_AUTH)
authuser(myname, login_style, rule->options & PERSIST);
#elif defined(USE_PAM)
#define PAM_END(msg) do { \
syslog(LOG_ERR, "%s: %s", msg, pam_strerror(pamh, pam_err)); \
warnx("%s: %s", msg, pam_strerror(pamh, pam_err)); \
pam_end(pamh, pam_err); \
exit(EXIT_FAILURE); \
} while (/*CONSTCOND*/0)
pam_handle_t *pamh = NULL;
int pam_err;
/* #ifndef linux */
int temp_stdin;
/* openpam_ttyconv checks if stdin is a terminal and
* if it is then does not bother to open /dev/tty.
* The result is that PAM writes the password prompt
* directly to stdout. In scenarios where stdin is a
* terminal, but stdout is redirected to a file
* e.g. by running doas ls &> ls.out interactively,
* the password prompt gets written to ls.out as well.
* By closing stdin first we forces PAM to read/write
* to/from the terminal directly. We restore stdin
* after authenticating. */
temp_stdin = dup(STDIN_FILENO);
if (temp_stdin == -1)
err(1, "dup");
close(STDIN_FILENO);
/* #else */
/* force password prompt to display on stderr, not stdout */
int temp_stdout = dup(1);
if (temp_stdout == -1)
err(1, "dup");
close(1);
if (dup2(2, 1) == -1)
err(1, "dup2");
/* #endif */
pam_err = pam_start("doas", myname, &pamc, &pamh);
if (pam_err != PAM_SUCCESS) {
if (pamh != NULL)
PAM_END("pam_start");
syslog(LOG_ERR, "pam_start failed: %s",
pam_strerror(pamh, pam_err));
errx(EXIT_FAILURE, "pam_start failed");
}
switch (pam_err = pam_authenticate(pamh, PAM_SILENT)) {
case PAM_SUCCESS:
switch (pam_err = pam_acct_mgmt(pamh, PAM_SILENT)) {
case PAM_SUCCESS:
break;
case PAM_NEW_AUTHTOK_REQD:
pam_err = pam_chauthtok(pamh,
PAM_SILENT|PAM_CHANGE_EXPIRED_AUTHTOK);
if (pam_err != PAM_SUCCESS)
PAM_END("pam_chauthtok");
break;
case PAM_AUTH_ERR:
case PAM_USER_UNKNOWN:
case PAM_MAXTRIES:
syslog(LOG_AUTHPRIV | LOG_NOTICE,
"failed auth for %s", myname);
errx(EXIT_FAILURE, "second authentication failed");
break;
default:
PAM_END("pam_acct_mgmt");
break;
}
break;
case PAM_AUTH_ERR:
case PAM_USER_UNKNOWN:
case PAM_MAXTRIES:
syslog(LOG_AUTHPRIV | LOG_NOTICE,
"failed auth for %s", myname);
errx(EXIT_FAILURE, "authentication failed");
break;
default:
PAM_END("pam_authenticate");
break;
}
pam_end(pamh, pam_err);
#ifndef linux
/* Re-establish stdin */
if (dup2(temp_stdin, STDIN_FILENO) == -1)
err(1, "dup2");
close(temp_stdin);
#else
/* Re-establish stdout */
close(1);
if (dup2(temp_stdout, 1) == -1)
err(1, "dup2");
#endif
#else
#error No auth module!
#endif
}
/*
if (pledge("stdio rpath getpw exec id", NULL) == -1)
err(1, "pledge");
*/
target_pw = getpwuid(target);
if (! target_pw)
errx(1, "no passwd entry for target");
#if defined(HAVE_LOGIN_CAP_H)
if (setusercontext(NULL, target_pw, target, LOGIN_SETGROUP |
LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK |
LOGIN_SETUSER) != 0)
errx(1, "failed to set user context for target");
#else
#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
if (setresgid(target_pw->pw_gid, target_pw->pw_gid, target_pw->pw_gid) == -1)
err(1, "setresgid");
#else
if (setregid(target_pw->pw_gid, target_pw->pw_gid) == -1)
err(1, "setregid");
#endif
if (initgroups(target_pw->pw_name, target_pw->pw_gid) == -1)
err(1, "initgroups");
#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
if (setresuid(target, target, target) == -1)
err(1, "setresuid");
#else
if (setreuid(target, target) == -1)
err(1, "setreuid");
#endif
#endif
/*
if (pledge("stdio rpath exec", NULL) == -1)
err(1, "pledge");
*/
if (getcwd(cwdpath, sizeof(cwdpath)) == NULL)
cwd = "(failed)";
else
cwd = cwdpath;
/*
if (pledge("stdio exec", NULL) == -1)
err(1, "pledge");
*/
syslog(LOG_AUTHPRIV | LOG_INFO, "%s ran command %s as %s from %s",
myname, cmdline, target_pw->pw_name, cwd);
envp = prepenv(rule, original_pw, target_pw);
if (rule->cmd) {
if (setenv("PATH", safepath, 1) == -1)
err(1, "failed to set PATH '%s'", safepath);
}
execvpe(cmd, argv, envp);
if (errno == ENOENT)
errx(1, "%s: command not found", cmd);
err(1, "%s", cmd);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_1053_0 |
crossvul-cpp_data_bad_5653_0 | /*
* Per core/cpu state
*
* Used to coordinate shared registers between HT threads or
* among events on a single PMU.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/stddef.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <asm/hardirq.h>
#include <asm/apic.h>
#include "perf_event.h"
/*
* Intel PerfMon, used on Core and later.
*/
static u64 intel_perfmon_event_map[PERF_COUNT_HW_MAX] __read_mostly =
{
[PERF_COUNT_HW_CPU_CYCLES] = 0x003c,
[PERF_COUNT_HW_INSTRUCTIONS] = 0x00c0,
[PERF_COUNT_HW_CACHE_REFERENCES] = 0x4f2e,
[PERF_COUNT_HW_CACHE_MISSES] = 0x412e,
[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0x00c4,
[PERF_COUNT_HW_BRANCH_MISSES] = 0x00c5,
[PERF_COUNT_HW_BUS_CYCLES] = 0x013c,
[PERF_COUNT_HW_REF_CPU_CYCLES] = 0x0300, /* pseudo-encoding */
};
static struct event_constraint intel_core_event_constraints[] __read_mostly =
{
INTEL_EVENT_CONSTRAINT(0x11, 0x2), /* FP_ASSIST */
INTEL_EVENT_CONSTRAINT(0x12, 0x2), /* MUL */
INTEL_EVENT_CONSTRAINT(0x13, 0x2), /* DIV */
INTEL_EVENT_CONSTRAINT(0x14, 0x1), /* CYCLES_DIV_BUSY */
INTEL_EVENT_CONSTRAINT(0x19, 0x2), /* DELAYED_BYPASS */
INTEL_EVENT_CONSTRAINT(0xc1, 0x1), /* FP_COMP_INSTR_RET */
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_core2_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
INTEL_EVENT_CONSTRAINT(0x10, 0x1), /* FP_COMP_OPS_EXE */
INTEL_EVENT_CONSTRAINT(0x11, 0x2), /* FP_ASSIST */
INTEL_EVENT_CONSTRAINT(0x12, 0x2), /* MUL */
INTEL_EVENT_CONSTRAINT(0x13, 0x2), /* DIV */
INTEL_EVENT_CONSTRAINT(0x14, 0x1), /* CYCLES_DIV_BUSY */
INTEL_EVENT_CONSTRAINT(0x18, 0x1), /* IDLE_DURING_DIV */
INTEL_EVENT_CONSTRAINT(0x19, 0x2), /* DELAYED_BYPASS */
INTEL_EVENT_CONSTRAINT(0xa1, 0x1), /* RS_UOPS_DISPATCH_CYCLES */
INTEL_EVENT_CONSTRAINT(0xc9, 0x1), /* ITLB_MISS_RETIRED (T30-9) */
INTEL_EVENT_CONSTRAINT(0xcb, 0x1), /* MEM_LOAD_RETIRED */
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_nehalem_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
INTEL_EVENT_CONSTRAINT(0x40, 0x3), /* L1D_CACHE_LD */
INTEL_EVENT_CONSTRAINT(0x41, 0x3), /* L1D_CACHE_ST */
INTEL_EVENT_CONSTRAINT(0x42, 0x3), /* L1D_CACHE_LOCK */
INTEL_EVENT_CONSTRAINT(0x43, 0x3), /* L1D_ALL_REF */
INTEL_EVENT_CONSTRAINT(0x48, 0x3), /* L1D_PEND_MISS */
INTEL_EVENT_CONSTRAINT(0x4e, 0x3), /* L1D_PREFETCH */
INTEL_EVENT_CONSTRAINT(0x51, 0x3), /* L1D */
INTEL_EVENT_CONSTRAINT(0x63, 0x3), /* CACHE_LOCK_CYCLES */
EVENT_CONSTRAINT_END
};
static struct extra_reg intel_nehalem_extra_regs[] __read_mostly =
{
INTEL_EVENT_EXTRA_REG(0xb7, MSR_OFFCORE_RSP_0, 0xffff, RSP_0),
EVENT_EXTRA_END
};
static struct event_constraint intel_westmere_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
INTEL_EVENT_CONSTRAINT(0x51, 0x3), /* L1D */
INTEL_EVENT_CONSTRAINT(0x60, 0x1), /* OFFCORE_REQUESTS_OUTSTANDING */
INTEL_EVENT_CONSTRAINT(0x63, 0x3), /* CACHE_LOCK_CYCLES */
INTEL_EVENT_CONSTRAINT(0xb3, 0x1), /* SNOOPQ_REQUEST_OUTSTANDING */
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_snb_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
INTEL_UEVENT_CONSTRAINT(0x04a3, 0xf), /* CYCLE_ACTIVITY.CYCLES_NO_DISPATCH */
INTEL_UEVENT_CONSTRAINT(0x05a3, 0xf), /* CYCLE_ACTIVITY.STALLS_L2_PENDING */
INTEL_UEVENT_CONSTRAINT(0x02a3, 0x4), /* CYCLE_ACTIVITY.CYCLES_L1D_PENDING */
INTEL_UEVENT_CONSTRAINT(0x06a3, 0x4), /* CYCLE_ACTIVITY.STALLS_L1D_PENDING */
INTEL_EVENT_CONSTRAINT(0x48, 0x4), /* L1D_PEND_MISS.PENDING */
INTEL_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PREC_DIST */
INTEL_EVENT_CONSTRAINT(0xcd, 0x8), /* MEM_TRANS_RETIRED.LOAD_LATENCY */
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_ivb_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
INTEL_UEVENT_CONSTRAINT(0x0148, 0x4), /* L1D_PEND_MISS.PENDING */
INTEL_UEVENT_CONSTRAINT(0x0279, 0xf), /* IDQ.EMTPY */
INTEL_UEVENT_CONSTRAINT(0x019c, 0xf), /* IDQ_UOPS_NOT_DELIVERED.CORE */
INTEL_UEVENT_CONSTRAINT(0x04a3, 0xf), /* CYCLE_ACTIVITY.CYCLES_NO_EXECUTE */
INTEL_UEVENT_CONSTRAINT(0x05a3, 0xf), /* CYCLE_ACTIVITY.STALLS_L2_PENDING */
INTEL_UEVENT_CONSTRAINT(0x06a3, 0xf), /* CYCLE_ACTIVITY.STALLS_LDM_PENDING */
INTEL_UEVENT_CONSTRAINT(0x08a3, 0x4), /* CYCLE_ACTIVITY.CYCLES_L1D_PENDING */
INTEL_UEVENT_CONSTRAINT(0x0ca3, 0x4), /* CYCLE_ACTIVITY.STALLS_L1D_PENDING */
INTEL_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PREC_DIST */
INTEL_EVENT_CONSTRAINT(0xd0, 0xf), /* MEM_UOPS_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0xd1, 0xf), /* MEM_LOAD_UOPS_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0xd2, 0xf), /* MEM_LOAD_UOPS_LLC_HIT_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0xd3, 0xf), /* MEM_LOAD_UOPS_LLC_MISS_RETIRED.* */
EVENT_CONSTRAINT_END
};
static struct extra_reg intel_westmere_extra_regs[] __read_mostly =
{
INTEL_EVENT_EXTRA_REG(0xb7, MSR_OFFCORE_RSP_0, 0xffff, RSP_0),
INTEL_EVENT_EXTRA_REG(0xbb, MSR_OFFCORE_RSP_1, 0xffff, RSP_1),
EVENT_EXTRA_END
};
static struct event_constraint intel_v1_event_constraints[] __read_mostly =
{
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_gen_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
EVENT_CONSTRAINT_END
};
static struct extra_reg intel_snb_extra_regs[] __read_mostly = {
INTEL_EVENT_EXTRA_REG(0xb7, MSR_OFFCORE_RSP_0, 0x3fffffffffull, RSP_0),
INTEL_EVENT_EXTRA_REG(0xbb, MSR_OFFCORE_RSP_1, 0x3fffffffffull, RSP_1),
EVENT_EXTRA_END
};
static u64 intel_pmu_event_map(int hw_event)
{
return intel_perfmon_event_map[hw_event];
}
#define SNB_DMND_DATA_RD (1ULL << 0)
#define SNB_DMND_RFO (1ULL << 1)
#define SNB_DMND_IFETCH (1ULL << 2)
#define SNB_DMND_WB (1ULL << 3)
#define SNB_PF_DATA_RD (1ULL << 4)
#define SNB_PF_RFO (1ULL << 5)
#define SNB_PF_IFETCH (1ULL << 6)
#define SNB_LLC_DATA_RD (1ULL << 7)
#define SNB_LLC_RFO (1ULL << 8)
#define SNB_LLC_IFETCH (1ULL << 9)
#define SNB_BUS_LOCKS (1ULL << 10)
#define SNB_STRM_ST (1ULL << 11)
#define SNB_OTHER (1ULL << 15)
#define SNB_RESP_ANY (1ULL << 16)
#define SNB_NO_SUPP (1ULL << 17)
#define SNB_LLC_HITM (1ULL << 18)
#define SNB_LLC_HITE (1ULL << 19)
#define SNB_LLC_HITS (1ULL << 20)
#define SNB_LLC_HITF (1ULL << 21)
#define SNB_LOCAL (1ULL << 22)
#define SNB_REMOTE (0xffULL << 23)
#define SNB_SNP_NONE (1ULL << 31)
#define SNB_SNP_NOT_NEEDED (1ULL << 32)
#define SNB_SNP_MISS (1ULL << 33)
#define SNB_NO_FWD (1ULL << 34)
#define SNB_SNP_FWD (1ULL << 35)
#define SNB_HITM (1ULL << 36)
#define SNB_NON_DRAM (1ULL << 37)
#define SNB_DMND_READ (SNB_DMND_DATA_RD|SNB_LLC_DATA_RD)
#define SNB_DMND_WRITE (SNB_DMND_RFO|SNB_LLC_RFO)
#define SNB_DMND_PREFETCH (SNB_PF_DATA_RD|SNB_PF_RFO)
#define SNB_SNP_ANY (SNB_SNP_NONE|SNB_SNP_NOT_NEEDED| \
SNB_SNP_MISS|SNB_NO_FWD|SNB_SNP_FWD| \
SNB_HITM)
#define SNB_DRAM_ANY (SNB_LOCAL|SNB_REMOTE|SNB_SNP_ANY)
#define SNB_DRAM_REMOTE (SNB_REMOTE|SNB_SNP_ANY)
#define SNB_L3_ACCESS SNB_RESP_ANY
#define SNB_L3_MISS (SNB_DRAM_ANY|SNB_NON_DRAM)
static __initconst const u64 snb_hw_cache_extra_regs
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(LL ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = SNB_DMND_READ|SNB_L3_ACCESS,
[ C(RESULT_MISS) ] = SNB_DMND_READ|SNB_L3_MISS,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = SNB_DMND_WRITE|SNB_L3_ACCESS,
[ C(RESULT_MISS) ] = SNB_DMND_WRITE|SNB_L3_MISS,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = SNB_DMND_PREFETCH|SNB_L3_ACCESS,
[ C(RESULT_MISS) ] = SNB_DMND_PREFETCH|SNB_L3_MISS,
},
},
[ C(NODE) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = SNB_DMND_READ|SNB_DRAM_ANY,
[ C(RESULT_MISS) ] = SNB_DMND_READ|SNB_DRAM_REMOTE,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = SNB_DMND_WRITE|SNB_DRAM_ANY,
[ C(RESULT_MISS) ] = SNB_DMND_WRITE|SNB_DRAM_REMOTE,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = SNB_DMND_PREFETCH|SNB_DRAM_ANY,
[ C(RESULT_MISS) ] = SNB_DMND_PREFETCH|SNB_DRAM_REMOTE,
},
},
};
static __initconst const u64 snb_hw_cache_event_ids
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(L1D) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0xf1d0, /* MEM_UOP_RETIRED.LOADS */
[ C(RESULT_MISS) ] = 0x0151, /* L1D.REPLACEMENT */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0xf2d0, /* MEM_UOP_RETIRED.STORES */
[ C(RESULT_MISS) ] = 0x0851, /* L1D.ALL_M_REPLACEMENT */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x024e, /* HW_PRE_REQ.DL1_MISS */
},
},
[ C(L1I ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0280, /* ICACHE.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(LL ) ] = {
[ C(OP_READ) ] = {
/* OFFCORE_RESPONSE.ANY_DATA.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_DATA.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_WRITE) ] = {
/* OFFCORE_RESPONSE.ANY_RFO.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_RFO.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
/* OFFCORE_RESPONSE.PREFETCH.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.PREFETCH.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
},
[ C(DTLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x81d0, /* MEM_UOP_RETIRED.ALL_LOADS */
[ C(RESULT_MISS) ] = 0x0108, /* DTLB_LOAD_MISSES.CAUSES_A_WALK */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x82d0, /* MEM_UOP_RETIRED.ALL_STORES */
[ C(RESULT_MISS) ] = 0x0149, /* DTLB_STORE_MISSES.MISS_CAUSES_A_WALK */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(ITLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x1085, /* ITLB_MISSES.STLB_HIT */
[ C(RESULT_MISS) ] = 0x0185, /* ITLB_MISSES.CAUSES_A_WALK */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(BPU ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ALL_BRANCHES */
[ C(RESULT_MISS) ] = 0x00c5, /* BR_MISP_RETIRED.ALL_BRANCHES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(NODE) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
},
};
static __initconst const u64 westmere_hw_cache_event_ids
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(L1D) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x010b, /* MEM_INST_RETIRED.LOADS */
[ C(RESULT_MISS) ] = 0x0151, /* L1D.REPL */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x020b, /* MEM_INST_RETURED.STORES */
[ C(RESULT_MISS) ] = 0x0251, /* L1D.M_REPL */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x014e, /* L1D_PREFETCH.REQUESTS */
[ C(RESULT_MISS) ] = 0x024e, /* L1D_PREFETCH.MISS */
},
},
[ C(L1I ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0380, /* L1I.READS */
[ C(RESULT_MISS) ] = 0x0280, /* L1I.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(LL ) ] = {
[ C(OP_READ) ] = {
/* OFFCORE_RESPONSE.ANY_DATA.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_DATA.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
/*
* Use RFO, not WRITEBACK, because a write miss would typically occur
* on RFO.
*/
[ C(OP_WRITE) ] = {
/* OFFCORE_RESPONSE.ANY_RFO.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_RFO.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
/* OFFCORE_RESPONSE.PREFETCH.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.PREFETCH.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
},
[ C(DTLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x010b, /* MEM_INST_RETIRED.LOADS */
[ C(RESULT_MISS) ] = 0x0108, /* DTLB_LOAD_MISSES.ANY */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x020b, /* MEM_INST_RETURED.STORES */
[ C(RESULT_MISS) ] = 0x010c, /* MEM_STORE_RETIRED.DTLB_MISS */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(ITLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x01c0, /* INST_RETIRED.ANY_P */
[ C(RESULT_MISS) ] = 0x0185, /* ITLB_MISSES.ANY */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(BPU ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ALL_BRANCHES */
[ C(RESULT_MISS) ] = 0x03e8, /* BPU_CLEARS.ANY */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(NODE) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
},
};
/*
* Nehalem/Westmere MSR_OFFCORE_RESPONSE bits;
* See IA32 SDM Vol 3B 30.6.1.3
*/
#define NHM_DMND_DATA_RD (1 << 0)
#define NHM_DMND_RFO (1 << 1)
#define NHM_DMND_IFETCH (1 << 2)
#define NHM_DMND_WB (1 << 3)
#define NHM_PF_DATA_RD (1 << 4)
#define NHM_PF_DATA_RFO (1 << 5)
#define NHM_PF_IFETCH (1 << 6)
#define NHM_OFFCORE_OTHER (1 << 7)
#define NHM_UNCORE_HIT (1 << 8)
#define NHM_OTHER_CORE_HIT_SNP (1 << 9)
#define NHM_OTHER_CORE_HITM (1 << 10)
/* reserved */
#define NHM_REMOTE_CACHE_FWD (1 << 12)
#define NHM_REMOTE_DRAM (1 << 13)
#define NHM_LOCAL_DRAM (1 << 14)
#define NHM_NON_DRAM (1 << 15)
#define NHM_LOCAL (NHM_LOCAL_DRAM|NHM_REMOTE_CACHE_FWD)
#define NHM_REMOTE (NHM_REMOTE_DRAM)
#define NHM_DMND_READ (NHM_DMND_DATA_RD)
#define NHM_DMND_WRITE (NHM_DMND_RFO|NHM_DMND_WB)
#define NHM_DMND_PREFETCH (NHM_PF_DATA_RD|NHM_PF_DATA_RFO)
#define NHM_L3_HIT (NHM_UNCORE_HIT|NHM_OTHER_CORE_HIT_SNP|NHM_OTHER_CORE_HITM)
#define NHM_L3_MISS (NHM_NON_DRAM|NHM_LOCAL_DRAM|NHM_REMOTE_DRAM|NHM_REMOTE_CACHE_FWD)
#define NHM_L3_ACCESS (NHM_L3_HIT|NHM_L3_MISS)
static __initconst const u64 nehalem_hw_cache_extra_regs
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(LL ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_READ|NHM_L3_ACCESS,
[ C(RESULT_MISS) ] = NHM_DMND_READ|NHM_L3_MISS,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_WRITE|NHM_L3_ACCESS,
[ C(RESULT_MISS) ] = NHM_DMND_WRITE|NHM_L3_MISS,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_PREFETCH|NHM_L3_ACCESS,
[ C(RESULT_MISS) ] = NHM_DMND_PREFETCH|NHM_L3_MISS,
},
},
[ C(NODE) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_READ|NHM_LOCAL|NHM_REMOTE,
[ C(RESULT_MISS) ] = NHM_DMND_READ|NHM_REMOTE,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_WRITE|NHM_LOCAL|NHM_REMOTE,
[ C(RESULT_MISS) ] = NHM_DMND_WRITE|NHM_REMOTE,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_PREFETCH|NHM_LOCAL|NHM_REMOTE,
[ C(RESULT_MISS) ] = NHM_DMND_PREFETCH|NHM_REMOTE,
},
},
};
static __initconst const u64 nehalem_hw_cache_event_ids
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(L1D) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x010b, /* MEM_INST_RETIRED.LOADS */
[ C(RESULT_MISS) ] = 0x0151, /* L1D.REPL */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x020b, /* MEM_INST_RETURED.STORES */
[ C(RESULT_MISS) ] = 0x0251, /* L1D.M_REPL */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x014e, /* L1D_PREFETCH.REQUESTS */
[ C(RESULT_MISS) ] = 0x024e, /* L1D_PREFETCH.MISS */
},
},
[ C(L1I ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0380, /* L1I.READS */
[ C(RESULT_MISS) ] = 0x0280, /* L1I.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(LL ) ] = {
[ C(OP_READ) ] = {
/* OFFCORE_RESPONSE.ANY_DATA.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_DATA.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
/*
* Use RFO, not WRITEBACK, because a write miss would typically occur
* on RFO.
*/
[ C(OP_WRITE) ] = {
/* OFFCORE_RESPONSE.ANY_RFO.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_RFO.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
/* OFFCORE_RESPONSE.PREFETCH.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.PREFETCH.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
},
[ C(DTLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0f40, /* L1D_CACHE_LD.MESI (alias) */
[ C(RESULT_MISS) ] = 0x0108, /* DTLB_LOAD_MISSES.ANY */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x0f41, /* L1D_CACHE_ST.MESI (alias) */
[ C(RESULT_MISS) ] = 0x010c, /* MEM_STORE_RETIRED.DTLB_MISS */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(ITLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x01c0, /* INST_RETIRED.ANY_P */
[ C(RESULT_MISS) ] = 0x20c8, /* ITLB_MISS_RETIRED */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(BPU ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ALL_BRANCHES */
[ C(RESULT_MISS) ] = 0x03e8, /* BPU_CLEARS.ANY */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(NODE) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
},
};
static __initconst const u64 core2_hw_cache_event_ids
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(L1D) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0f40, /* L1D_CACHE_LD.MESI */
[ C(RESULT_MISS) ] = 0x0140, /* L1D_CACHE_LD.I_STATE */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x0f41, /* L1D_CACHE_ST.MESI */
[ C(RESULT_MISS) ] = 0x0141, /* L1D_CACHE_ST.I_STATE */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x104e, /* L1D_PREFETCH.REQUESTS */
[ C(RESULT_MISS) ] = 0,
},
},
[ C(L1I ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0080, /* L1I.READS */
[ C(RESULT_MISS) ] = 0x0081, /* L1I.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(LL ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x4f29, /* L2_LD.MESI */
[ C(RESULT_MISS) ] = 0x4129, /* L2_LD.ISTATE */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x4f2A, /* L2_ST.MESI */
[ C(RESULT_MISS) ] = 0x412A, /* L2_ST.ISTATE */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(DTLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0f40, /* L1D_CACHE_LD.MESI (alias) */
[ C(RESULT_MISS) ] = 0x0208, /* DTLB_MISSES.MISS_LD */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x0f41, /* L1D_CACHE_ST.MESI (alias) */
[ C(RESULT_MISS) ] = 0x0808, /* DTLB_MISSES.MISS_ST */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(ITLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c0, /* INST_RETIRED.ANY_P */
[ C(RESULT_MISS) ] = 0x1282, /* ITLBMISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(BPU ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ANY */
[ C(RESULT_MISS) ] = 0x00c5, /* BP_INST_RETIRED.MISPRED */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
};
static __initconst const u64 atom_hw_cache_event_ids
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(L1D) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x2140, /* L1D_CACHE.LD */
[ C(RESULT_MISS) ] = 0,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x2240, /* L1D_CACHE.ST */
[ C(RESULT_MISS) ] = 0,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(L1I ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0380, /* L1I.READS */
[ C(RESULT_MISS) ] = 0x0280, /* L1I.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(LL ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x4f29, /* L2_LD.MESI */
[ C(RESULT_MISS) ] = 0x4129, /* L2_LD.ISTATE */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x4f2A, /* L2_ST.MESI */
[ C(RESULT_MISS) ] = 0x412A, /* L2_ST.ISTATE */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(DTLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x2140, /* L1D_CACHE_LD.MESI (alias) */
[ C(RESULT_MISS) ] = 0x0508, /* DTLB_MISSES.MISS_LD */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x2240, /* L1D_CACHE_ST.MESI (alias) */
[ C(RESULT_MISS) ] = 0x0608, /* DTLB_MISSES.MISS_ST */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(ITLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c0, /* INST_RETIRED.ANY_P */
[ C(RESULT_MISS) ] = 0x0282, /* ITLB.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(BPU ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ANY */
[ C(RESULT_MISS) ] = 0x00c5, /* BP_INST_RETIRED.MISPRED */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
};
static inline bool intel_pmu_needs_lbr_smpl(struct perf_event *event)
{
/* user explicitly requested branch sampling */
if (has_branch_stack(event))
return true;
/* implicit branch sampling to correct PEBS skid */
if (x86_pmu.intel_cap.pebs_trap && event->attr.precise_ip > 1)
return true;
return false;
}
static void intel_pmu_disable_all(void)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0);
if (test_bit(INTEL_PMC_IDX_FIXED_BTS, cpuc->active_mask))
intel_pmu_disable_bts();
intel_pmu_pebs_disable_all();
intel_pmu_lbr_disable_all();
}
static void intel_pmu_enable_all(int added)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
intel_pmu_pebs_enable_all();
intel_pmu_lbr_enable_all();
wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL,
x86_pmu.intel_ctrl & ~cpuc->intel_ctrl_guest_mask);
if (test_bit(INTEL_PMC_IDX_FIXED_BTS, cpuc->active_mask)) {
struct perf_event *event =
cpuc->events[INTEL_PMC_IDX_FIXED_BTS];
if (WARN_ON_ONCE(!event))
return;
intel_pmu_enable_bts(event->hw.config);
}
}
/*
* Workaround for:
* Intel Errata AAK100 (model 26)
* Intel Errata AAP53 (model 30)
* Intel Errata BD53 (model 44)
*
* The official story:
* These chips need to be 'reset' when adding counters by programming the
* magic three (non-counting) events 0x4300B5, 0x4300D2, and 0x4300B1 either
* in sequence on the same PMC or on different PMCs.
*
* In practise it appears some of these events do in fact count, and
* we need to programm all 4 events.
*/
static void intel_pmu_nhm_workaround(void)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
static const unsigned long nhm_magic[4] = {
0x4300B5,
0x4300D2,
0x4300B1,
0x4300B1
};
struct perf_event *event;
int i;
/*
* The Errata requires below steps:
* 1) Clear MSR_IA32_PEBS_ENABLE and MSR_CORE_PERF_GLOBAL_CTRL;
* 2) Configure 4 PERFEVTSELx with the magic events and clear
* the corresponding PMCx;
* 3) set bit0~bit3 of MSR_CORE_PERF_GLOBAL_CTRL;
* 4) Clear MSR_CORE_PERF_GLOBAL_CTRL;
* 5) Clear 4 pairs of ERFEVTSELx and PMCx;
*/
/*
* The real steps we choose are a little different from above.
* A) To reduce MSR operations, we don't run step 1) as they
* are already cleared before this function is called;
* B) Call x86_perf_event_update to save PMCx before configuring
* PERFEVTSELx with magic number;
* C) With step 5), we do clear only when the PERFEVTSELx is
* not used currently.
* D) Call x86_perf_event_set_period to restore PMCx;
*/
/* We always operate 4 pairs of PERF Counters */
for (i = 0; i < 4; i++) {
event = cpuc->events[i];
if (event)
x86_perf_event_update(event);
}
for (i = 0; i < 4; i++) {
wrmsrl(MSR_ARCH_PERFMON_EVENTSEL0 + i, nhm_magic[i]);
wrmsrl(MSR_ARCH_PERFMON_PERFCTR0 + i, 0x0);
}
wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0xf);
wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0x0);
for (i = 0; i < 4; i++) {
event = cpuc->events[i];
if (event) {
x86_perf_event_set_period(event);
__x86_pmu_enable_event(&event->hw,
ARCH_PERFMON_EVENTSEL_ENABLE);
} else
wrmsrl(MSR_ARCH_PERFMON_EVENTSEL0 + i, 0x0);
}
}
static void intel_pmu_nhm_enable_all(int added)
{
if (added)
intel_pmu_nhm_workaround();
intel_pmu_enable_all(added);
}
static inline u64 intel_pmu_get_status(void)
{
u64 status;
rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
return status;
}
static inline void intel_pmu_ack_status(u64 ack)
{
wrmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, ack);
}
static void intel_pmu_disable_fixed(struct hw_perf_event *hwc)
{
int idx = hwc->idx - INTEL_PMC_IDX_FIXED;
u64 ctrl_val, mask;
mask = 0xfULL << (idx * 4);
rdmsrl(hwc->config_base, ctrl_val);
ctrl_val &= ~mask;
wrmsrl(hwc->config_base, ctrl_val);
}
static void intel_pmu_disable_event(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
if (unlikely(hwc->idx == INTEL_PMC_IDX_FIXED_BTS)) {
intel_pmu_disable_bts();
intel_pmu_drain_bts_buffer();
return;
}
cpuc->intel_ctrl_guest_mask &= ~(1ull << hwc->idx);
cpuc->intel_ctrl_host_mask &= ~(1ull << hwc->idx);
/*
* must disable before any actual event
* because any event may be combined with LBR
*/
if (intel_pmu_needs_lbr_smpl(event))
intel_pmu_lbr_disable(event);
if (unlikely(hwc->config_base == MSR_ARCH_PERFMON_FIXED_CTR_CTRL)) {
intel_pmu_disable_fixed(hwc);
return;
}
x86_pmu_disable_event(event);
if (unlikely(event->attr.precise_ip))
intel_pmu_pebs_disable(event);
}
static void intel_pmu_enable_fixed(struct hw_perf_event *hwc)
{
int idx = hwc->idx - INTEL_PMC_IDX_FIXED;
u64 ctrl_val, bits, mask;
/*
* Enable IRQ generation (0x8),
* and enable ring-3 counting (0x2) and ring-0 counting (0x1)
* if requested:
*/
bits = 0x8ULL;
if (hwc->config & ARCH_PERFMON_EVENTSEL_USR)
bits |= 0x2;
if (hwc->config & ARCH_PERFMON_EVENTSEL_OS)
bits |= 0x1;
/*
* ANY bit is supported in v3 and up
*/
if (x86_pmu.version > 2 && hwc->config & ARCH_PERFMON_EVENTSEL_ANY)
bits |= 0x4;
bits <<= (idx * 4);
mask = 0xfULL << (idx * 4);
rdmsrl(hwc->config_base, ctrl_val);
ctrl_val &= ~mask;
ctrl_val |= bits;
wrmsrl(hwc->config_base, ctrl_val);
}
static void intel_pmu_enable_event(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
if (unlikely(hwc->idx == INTEL_PMC_IDX_FIXED_BTS)) {
if (!__this_cpu_read(cpu_hw_events.enabled))
return;
intel_pmu_enable_bts(hwc->config);
return;
}
/*
* must enabled before any actual event
* because any event may be combined with LBR
*/
if (intel_pmu_needs_lbr_smpl(event))
intel_pmu_lbr_enable(event);
if (event->attr.exclude_host)
cpuc->intel_ctrl_guest_mask |= (1ull << hwc->idx);
if (event->attr.exclude_guest)
cpuc->intel_ctrl_host_mask |= (1ull << hwc->idx);
if (unlikely(hwc->config_base == MSR_ARCH_PERFMON_FIXED_CTR_CTRL)) {
intel_pmu_enable_fixed(hwc);
return;
}
if (unlikely(event->attr.precise_ip))
intel_pmu_pebs_enable(event);
__x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
}
/*
* Save and restart an expired event. Called by NMI contexts,
* so it has to be careful about preempting normal event ops:
*/
int intel_pmu_save_and_restart(struct perf_event *event)
{
x86_perf_event_update(event);
return x86_perf_event_set_period(event);
}
static void intel_pmu_reset(void)
{
struct debug_store *ds = __this_cpu_read(cpu_hw_events.ds);
unsigned long flags;
int idx;
if (!x86_pmu.num_counters)
return;
local_irq_save(flags);
pr_info("clearing PMU state on CPU#%d\n", smp_processor_id());
for (idx = 0; idx < x86_pmu.num_counters; idx++) {
wrmsrl_safe(x86_pmu_config_addr(idx), 0ull);
wrmsrl_safe(x86_pmu_event_addr(idx), 0ull);
}
for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++)
wrmsrl_safe(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, 0ull);
if (ds)
ds->bts_index = ds->bts_buffer_base;
local_irq_restore(flags);
}
/*
* This handler is triggered by the local APIC, so the APIC IRQ handling
* rules apply:
*/
static int intel_pmu_handle_irq(struct pt_regs *regs)
{
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
int bit, loops;
u64 status;
int handled;
cpuc = &__get_cpu_var(cpu_hw_events);
/*
* Some chipsets need to unmask the LVTPC in a particular spot
* inside the nmi handler. As a result, the unmasking was pushed
* into all the nmi handlers.
*
* This handler doesn't seem to have any issues with the unmasking
* so it was left at the top.
*/
apic_write(APIC_LVTPC, APIC_DM_NMI);
intel_pmu_disable_all();
handled = intel_pmu_drain_bts_buffer();
status = intel_pmu_get_status();
if (!status) {
intel_pmu_enable_all(0);
return handled;
}
loops = 0;
again:
intel_pmu_ack_status(status);
if (++loops > 100) {
WARN_ONCE(1, "perfevents: irq loop stuck!\n");
perf_event_print_debug();
intel_pmu_reset();
goto done;
}
inc_irq_stat(apic_perf_irqs);
intel_pmu_lbr_read();
/*
* PEBS overflow sets bit 62 in the global status register
*/
if (__test_and_clear_bit(62, (unsigned long *)&status)) {
handled++;
x86_pmu.drain_pebs(regs);
}
for_each_set_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) {
struct perf_event *event = cpuc->events[bit];
handled++;
if (!test_bit(bit, cpuc->active_mask))
continue;
if (!intel_pmu_save_and_restart(event))
continue;
perf_sample_data_init(&data, 0, event->hw.last_period);
if (has_branch_stack(event))
data.br_stack = &cpuc->lbr_stack;
if (perf_event_overflow(event, &data, regs))
x86_pmu_stop(event, 0);
}
/*
* Repeat if there is more work to be done:
*/
status = intel_pmu_get_status();
if (status)
goto again;
done:
intel_pmu_enable_all(0);
return handled;
}
static struct event_constraint *
intel_bts_constraints(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
unsigned int hw_event, bts_event;
if (event->attr.freq)
return NULL;
hw_event = hwc->config & INTEL_ARCH_EVENT_MASK;
bts_event = x86_pmu.event_map(PERF_COUNT_HW_BRANCH_INSTRUCTIONS);
if (unlikely(hw_event == bts_event && hwc->sample_period == 1))
return &bts_constraint;
return NULL;
}
static int intel_alt_er(int idx)
{
if (!(x86_pmu.er_flags & ERF_HAS_RSP_1))
return idx;
if (idx == EXTRA_REG_RSP_0)
return EXTRA_REG_RSP_1;
if (idx == EXTRA_REG_RSP_1)
return EXTRA_REG_RSP_0;
return idx;
}
static void intel_fixup_er(struct perf_event *event, int idx)
{
event->hw.extra_reg.idx = idx;
if (idx == EXTRA_REG_RSP_0) {
event->hw.config &= ~INTEL_ARCH_EVENT_MASK;
event->hw.config |= 0x01b7;
event->hw.extra_reg.reg = MSR_OFFCORE_RSP_0;
} else if (idx == EXTRA_REG_RSP_1) {
event->hw.config &= ~INTEL_ARCH_EVENT_MASK;
event->hw.config |= 0x01bb;
event->hw.extra_reg.reg = MSR_OFFCORE_RSP_1;
}
}
/*
* manage allocation of shared extra msr for certain events
*
* sharing can be:
* per-cpu: to be shared between the various events on a single PMU
* per-core: per-cpu + shared by HT threads
*/
static struct event_constraint *
__intel_shared_reg_get_constraints(struct cpu_hw_events *cpuc,
struct perf_event *event,
struct hw_perf_event_extra *reg)
{
struct event_constraint *c = &emptyconstraint;
struct er_account *era;
unsigned long flags;
int idx = reg->idx;
/*
* reg->alloc can be set due to existing state, so for fake cpuc we
* need to ignore this, otherwise we might fail to allocate proper fake
* state for this extra reg constraint. Also see the comment below.
*/
if (reg->alloc && !cpuc->is_fake)
return NULL; /* call x86_get_event_constraint() */
again:
era = &cpuc->shared_regs->regs[idx];
/*
* we use spin_lock_irqsave() to avoid lockdep issues when
* passing a fake cpuc
*/
raw_spin_lock_irqsave(&era->lock, flags);
if (!atomic_read(&era->ref) || era->config == reg->config) {
/*
* If its a fake cpuc -- as per validate_{group,event}() we
* shouldn't touch event state and we can avoid doing so
* since both will only call get_event_constraints() once
* on each event, this avoids the need for reg->alloc.
*
* Not doing the ER fixup will only result in era->reg being
* wrong, but since we won't actually try and program hardware
* this isn't a problem either.
*/
if (!cpuc->is_fake) {
if (idx != reg->idx)
intel_fixup_er(event, idx);
/*
* x86_schedule_events() can call get_event_constraints()
* multiple times on events in the case of incremental
* scheduling(). reg->alloc ensures we only do the ER
* allocation once.
*/
reg->alloc = 1;
}
/* lock in msr value */
era->config = reg->config;
era->reg = reg->reg;
/* one more user */
atomic_inc(&era->ref);
/*
* need to call x86_get_event_constraint()
* to check if associated event has constraints
*/
c = NULL;
} else {
idx = intel_alt_er(idx);
if (idx != reg->idx) {
raw_spin_unlock_irqrestore(&era->lock, flags);
goto again;
}
}
raw_spin_unlock_irqrestore(&era->lock, flags);
return c;
}
static void
__intel_shared_reg_put_constraints(struct cpu_hw_events *cpuc,
struct hw_perf_event_extra *reg)
{
struct er_account *era;
/*
* Only put constraint if extra reg was actually allocated. Also takes
* care of event which do not use an extra shared reg.
*
* Also, if this is a fake cpuc we shouldn't touch any event state
* (reg->alloc) and we don't care about leaving inconsistent cpuc state
* either since it'll be thrown out.
*/
if (!reg->alloc || cpuc->is_fake)
return;
era = &cpuc->shared_regs->regs[reg->idx];
/* one fewer user */
atomic_dec(&era->ref);
/* allocate again next time */
reg->alloc = 0;
}
static struct event_constraint *
intel_shared_regs_constraints(struct cpu_hw_events *cpuc,
struct perf_event *event)
{
struct event_constraint *c = NULL, *d;
struct hw_perf_event_extra *xreg, *breg;
xreg = &event->hw.extra_reg;
if (xreg->idx != EXTRA_REG_NONE) {
c = __intel_shared_reg_get_constraints(cpuc, event, xreg);
if (c == &emptyconstraint)
return c;
}
breg = &event->hw.branch_reg;
if (breg->idx != EXTRA_REG_NONE) {
d = __intel_shared_reg_get_constraints(cpuc, event, breg);
if (d == &emptyconstraint) {
__intel_shared_reg_put_constraints(cpuc, xreg);
c = d;
}
}
return c;
}
struct event_constraint *
x86_get_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event)
{
struct event_constraint *c;
if (x86_pmu.event_constraints) {
for_each_event_constraint(c, x86_pmu.event_constraints) {
if ((event->hw.config & c->cmask) == c->code)
return c;
}
}
return &unconstrained;
}
static struct event_constraint *
intel_get_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event)
{
struct event_constraint *c;
c = intel_bts_constraints(event);
if (c)
return c;
c = intel_pebs_constraints(event);
if (c)
return c;
c = intel_shared_regs_constraints(cpuc, event);
if (c)
return c;
return x86_get_event_constraints(cpuc, event);
}
static void
intel_put_shared_regs_event_constraints(struct cpu_hw_events *cpuc,
struct perf_event *event)
{
struct hw_perf_event_extra *reg;
reg = &event->hw.extra_reg;
if (reg->idx != EXTRA_REG_NONE)
__intel_shared_reg_put_constraints(cpuc, reg);
reg = &event->hw.branch_reg;
if (reg->idx != EXTRA_REG_NONE)
__intel_shared_reg_put_constraints(cpuc, reg);
}
static void intel_put_event_constraints(struct cpu_hw_events *cpuc,
struct perf_event *event)
{
intel_put_shared_regs_event_constraints(cpuc, event);
}
static void intel_pebs_aliases_core2(struct perf_event *event)
{
if ((event->hw.config & X86_RAW_EVENT_MASK) == 0x003c) {
/*
* Use an alternative encoding for CPU_CLK_UNHALTED.THREAD_P
* (0x003c) so that we can use it with PEBS.
*
* The regular CPU_CLK_UNHALTED.THREAD_P event (0x003c) isn't
* PEBS capable. However we can use INST_RETIRED.ANY_P
* (0x00c0), which is a PEBS capable event, to get the same
* count.
*
* INST_RETIRED.ANY_P counts the number of cycles that retires
* CNTMASK instructions. By setting CNTMASK to a value (16)
* larger than the maximum number of instructions that can be
* retired per cycle (4) and then inverting the condition, we
* count all cycles that retire 16 or less instructions, which
* is every cycle.
*
* Thereby we gain a PEBS capable cycle counter.
*/
u64 alt_config = X86_CONFIG(.event=0xc0, .inv=1, .cmask=16);
alt_config |= (event->hw.config & ~X86_RAW_EVENT_MASK);
event->hw.config = alt_config;
}
}
static void intel_pebs_aliases_snb(struct perf_event *event)
{
if ((event->hw.config & X86_RAW_EVENT_MASK) == 0x003c) {
/*
* Use an alternative encoding for CPU_CLK_UNHALTED.THREAD_P
* (0x003c) so that we can use it with PEBS.
*
* The regular CPU_CLK_UNHALTED.THREAD_P event (0x003c) isn't
* PEBS capable. However we can use UOPS_RETIRED.ALL
* (0x01c2), which is a PEBS capable event, to get the same
* count.
*
* UOPS_RETIRED.ALL counts the number of cycles that retires
* CNTMASK micro-ops. By setting CNTMASK to a value (16)
* larger than the maximum number of micro-ops that can be
* retired per cycle (4) and then inverting the condition, we
* count all cycles that retire 16 or less micro-ops, which
* is every cycle.
*
* Thereby we gain a PEBS capable cycle counter.
*/
u64 alt_config = X86_CONFIG(.event=0xc2, .umask=0x01, .inv=1, .cmask=16);
alt_config |= (event->hw.config & ~X86_RAW_EVENT_MASK);
event->hw.config = alt_config;
}
}
static int intel_pmu_hw_config(struct perf_event *event)
{
int ret = x86_pmu_hw_config(event);
if (ret)
return ret;
if (event->attr.precise_ip && x86_pmu.pebs_aliases)
x86_pmu.pebs_aliases(event);
if (intel_pmu_needs_lbr_smpl(event)) {
ret = intel_pmu_setup_lbr_filter(event);
if (ret)
return ret;
}
if (event->attr.type != PERF_TYPE_RAW)
return 0;
if (!(event->attr.config & ARCH_PERFMON_EVENTSEL_ANY))
return 0;
if (x86_pmu.version < 3)
return -EINVAL;
if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
return -EACCES;
event->hw.config |= ARCH_PERFMON_EVENTSEL_ANY;
return 0;
}
struct perf_guest_switch_msr *perf_guest_get_msrs(int *nr)
{
if (x86_pmu.guest_get_msrs)
return x86_pmu.guest_get_msrs(nr);
*nr = 0;
return NULL;
}
EXPORT_SYMBOL_GPL(perf_guest_get_msrs);
static struct perf_guest_switch_msr *intel_guest_get_msrs(int *nr)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct perf_guest_switch_msr *arr = cpuc->guest_switch_msrs;
arr[0].msr = MSR_CORE_PERF_GLOBAL_CTRL;
arr[0].host = x86_pmu.intel_ctrl & ~cpuc->intel_ctrl_guest_mask;
arr[0].guest = x86_pmu.intel_ctrl & ~cpuc->intel_ctrl_host_mask;
/*
* If PMU counter has PEBS enabled it is not enough to disable counter
* on a guest entry since PEBS memory write can overshoot guest entry
* and corrupt guest memory. Disabling PEBS solves the problem.
*/
arr[1].msr = MSR_IA32_PEBS_ENABLE;
arr[1].host = cpuc->pebs_enabled;
arr[1].guest = 0;
*nr = 2;
return arr;
}
static struct perf_guest_switch_msr *core_guest_get_msrs(int *nr)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct perf_guest_switch_msr *arr = cpuc->guest_switch_msrs;
int idx;
for (idx = 0; idx < x86_pmu.num_counters; idx++) {
struct perf_event *event = cpuc->events[idx];
arr[idx].msr = x86_pmu_config_addr(idx);
arr[idx].host = arr[idx].guest = 0;
if (!test_bit(idx, cpuc->active_mask))
continue;
arr[idx].host = arr[idx].guest =
event->hw.config | ARCH_PERFMON_EVENTSEL_ENABLE;
if (event->attr.exclude_host)
arr[idx].host &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
else if (event->attr.exclude_guest)
arr[idx].guest &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
}
*nr = x86_pmu.num_counters;
return arr;
}
static void core_pmu_enable_event(struct perf_event *event)
{
if (!event->attr.exclude_host)
x86_pmu_enable_event(event);
}
static void core_pmu_enable_all(int added)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
int idx;
for (idx = 0; idx < x86_pmu.num_counters; idx++) {
struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
if (!test_bit(idx, cpuc->active_mask) ||
cpuc->events[idx]->attr.exclude_host)
continue;
__x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
}
}
PMU_FORMAT_ATTR(event, "config:0-7" );
PMU_FORMAT_ATTR(umask, "config:8-15" );
PMU_FORMAT_ATTR(edge, "config:18" );
PMU_FORMAT_ATTR(pc, "config:19" );
PMU_FORMAT_ATTR(any, "config:21" ); /* v3 + */
PMU_FORMAT_ATTR(inv, "config:23" );
PMU_FORMAT_ATTR(cmask, "config:24-31" );
static struct attribute *intel_arch_formats_attr[] = {
&format_attr_event.attr,
&format_attr_umask.attr,
&format_attr_edge.attr,
&format_attr_pc.attr,
&format_attr_inv.attr,
&format_attr_cmask.attr,
NULL,
};
ssize_t intel_event_sysfs_show(char *page, u64 config)
{
u64 event = (config & ARCH_PERFMON_EVENTSEL_EVENT);
return x86_event_sysfs_show(page, config, event);
}
static __initconst const struct x86_pmu core_pmu = {
.name = "core",
.handle_irq = x86_pmu_handle_irq,
.disable_all = x86_pmu_disable_all,
.enable_all = core_pmu_enable_all,
.enable = core_pmu_enable_event,
.disable = x86_pmu_disable_event,
.hw_config = x86_pmu_hw_config,
.schedule_events = x86_schedule_events,
.eventsel = MSR_ARCH_PERFMON_EVENTSEL0,
.perfctr = MSR_ARCH_PERFMON_PERFCTR0,
.event_map = intel_pmu_event_map,
.max_events = ARRAY_SIZE(intel_perfmon_event_map),
.apic = 1,
/*
* Intel PMCs cannot be accessed sanely above 32 bit width,
* so we install an artificial 1<<31 period regardless of
* the generic event period:
*/
.max_period = (1ULL << 31) - 1,
.get_event_constraints = intel_get_event_constraints,
.put_event_constraints = intel_put_event_constraints,
.event_constraints = intel_core_event_constraints,
.guest_get_msrs = core_guest_get_msrs,
.format_attrs = intel_arch_formats_attr,
.events_sysfs_show = intel_event_sysfs_show,
};
struct intel_shared_regs *allocate_shared_regs(int cpu)
{
struct intel_shared_regs *regs;
int i;
regs = kzalloc_node(sizeof(struct intel_shared_regs),
GFP_KERNEL, cpu_to_node(cpu));
if (regs) {
/*
* initialize the locks to keep lockdep happy
*/
for (i = 0; i < EXTRA_REG_MAX; i++)
raw_spin_lock_init(®s->regs[i].lock);
regs->core_id = -1;
}
return regs;
}
static int intel_pmu_cpu_prepare(int cpu)
{
struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
if (!(x86_pmu.extra_regs || x86_pmu.lbr_sel_map))
return NOTIFY_OK;
cpuc->shared_regs = allocate_shared_regs(cpu);
if (!cpuc->shared_regs)
return NOTIFY_BAD;
return NOTIFY_OK;
}
static void intel_pmu_cpu_starting(int cpu)
{
struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
int core_id = topology_core_id(cpu);
int i;
init_debug_store_on_cpu(cpu);
/*
* Deal with CPUs that don't clear their LBRs on power-up.
*/
intel_pmu_lbr_reset();
cpuc->lbr_sel = NULL;
if (!cpuc->shared_regs)
return;
if (!(x86_pmu.er_flags & ERF_NO_HT_SHARING)) {
for_each_cpu(i, topology_thread_cpumask(cpu)) {
struct intel_shared_regs *pc;
pc = per_cpu(cpu_hw_events, i).shared_regs;
if (pc && pc->core_id == core_id) {
cpuc->kfree_on_online = cpuc->shared_regs;
cpuc->shared_regs = pc;
break;
}
}
cpuc->shared_regs->core_id = core_id;
cpuc->shared_regs->refcnt++;
}
if (x86_pmu.lbr_sel_map)
cpuc->lbr_sel = &cpuc->shared_regs->regs[EXTRA_REG_LBR];
}
static void intel_pmu_cpu_dying(int cpu)
{
struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
struct intel_shared_regs *pc;
pc = cpuc->shared_regs;
if (pc) {
if (pc->core_id == -1 || --pc->refcnt == 0)
kfree(pc);
cpuc->shared_regs = NULL;
}
fini_debug_store_on_cpu(cpu);
}
static void intel_pmu_flush_branch_stack(void)
{
/*
* Intel LBR does not tag entries with the
* PID of the current task, then we need to
* flush it on ctxsw
* For now, we simply reset it
*/
if (x86_pmu.lbr_nr)
intel_pmu_lbr_reset();
}
PMU_FORMAT_ATTR(offcore_rsp, "config1:0-63");
static struct attribute *intel_arch3_formats_attr[] = {
&format_attr_event.attr,
&format_attr_umask.attr,
&format_attr_edge.attr,
&format_attr_pc.attr,
&format_attr_any.attr,
&format_attr_inv.attr,
&format_attr_cmask.attr,
&format_attr_offcore_rsp.attr, /* XXX do NHM/WSM + SNB breakout */
NULL,
};
static __initconst const struct x86_pmu intel_pmu = {
.name = "Intel",
.handle_irq = intel_pmu_handle_irq,
.disable_all = intel_pmu_disable_all,
.enable_all = intel_pmu_enable_all,
.enable = intel_pmu_enable_event,
.disable = intel_pmu_disable_event,
.hw_config = intel_pmu_hw_config,
.schedule_events = x86_schedule_events,
.eventsel = MSR_ARCH_PERFMON_EVENTSEL0,
.perfctr = MSR_ARCH_PERFMON_PERFCTR0,
.event_map = intel_pmu_event_map,
.max_events = ARRAY_SIZE(intel_perfmon_event_map),
.apic = 1,
/*
* Intel PMCs cannot be accessed sanely above 32 bit width,
* so we install an artificial 1<<31 period regardless of
* the generic event period:
*/
.max_period = (1ULL << 31) - 1,
.get_event_constraints = intel_get_event_constraints,
.put_event_constraints = intel_put_event_constraints,
.pebs_aliases = intel_pebs_aliases_core2,
.format_attrs = intel_arch3_formats_attr,
.events_sysfs_show = intel_event_sysfs_show,
.cpu_prepare = intel_pmu_cpu_prepare,
.cpu_starting = intel_pmu_cpu_starting,
.cpu_dying = intel_pmu_cpu_dying,
.guest_get_msrs = intel_guest_get_msrs,
.flush_branch_stack = intel_pmu_flush_branch_stack,
};
static __init void intel_clovertown_quirk(void)
{
/*
* PEBS is unreliable due to:
*
* AJ67 - PEBS may experience CPL leaks
* AJ68 - PEBS PMI may be delayed by one event
* AJ69 - GLOBAL_STATUS[62] will only be set when DEBUGCTL[12]
* AJ106 - FREEZE_LBRS_ON_PMI doesn't work in combination with PEBS
*
* AJ67 could be worked around by restricting the OS/USR flags.
* AJ69 could be worked around by setting PMU_FREEZE_ON_PMI.
*
* AJ106 could possibly be worked around by not allowing LBR
* usage from PEBS, including the fixup.
* AJ68 could possibly be worked around by always programming
* a pebs_event_reset[0] value and coping with the lost events.
*
* But taken together it might just make sense to not enable PEBS on
* these chips.
*/
pr_warn("PEBS disabled due to CPU errata\n");
x86_pmu.pebs = 0;
x86_pmu.pebs_constraints = NULL;
}
static int intel_snb_pebs_broken(int cpu)
{
u32 rev = UINT_MAX; /* default to broken for unknown models */
switch (cpu_data(cpu).x86_model) {
case 42: /* SNB */
rev = 0x28;
break;
case 45: /* SNB-EP */
switch (cpu_data(cpu).x86_mask) {
case 6: rev = 0x618; break;
case 7: rev = 0x70c; break;
}
}
return (cpu_data(cpu).microcode < rev);
}
static void intel_snb_check_microcode(void)
{
int pebs_broken = 0;
int cpu;
get_online_cpus();
for_each_online_cpu(cpu) {
if ((pebs_broken = intel_snb_pebs_broken(cpu)))
break;
}
put_online_cpus();
if (pebs_broken == x86_pmu.pebs_broken)
return;
/*
* Serialized by the microcode lock..
*/
if (x86_pmu.pebs_broken) {
pr_info("PEBS enabled due to microcode update\n");
x86_pmu.pebs_broken = 0;
} else {
pr_info("PEBS disabled due to CPU errata, please upgrade microcode\n");
x86_pmu.pebs_broken = 1;
}
}
static __init void intel_sandybridge_quirk(void)
{
x86_pmu.check_microcode = intel_snb_check_microcode;
intel_snb_check_microcode();
}
static const struct { int id; char *name; } intel_arch_events_map[] __initconst = {
{ PERF_COUNT_HW_CPU_CYCLES, "cpu cycles" },
{ PERF_COUNT_HW_INSTRUCTIONS, "instructions" },
{ PERF_COUNT_HW_BUS_CYCLES, "bus cycles" },
{ PERF_COUNT_HW_CACHE_REFERENCES, "cache references" },
{ PERF_COUNT_HW_CACHE_MISSES, "cache misses" },
{ PERF_COUNT_HW_BRANCH_INSTRUCTIONS, "branch instructions" },
{ PERF_COUNT_HW_BRANCH_MISSES, "branch misses" },
};
static __init void intel_arch_events_quirk(void)
{
int bit;
/* disable event that reported as not presend by cpuid */
for_each_set_bit(bit, x86_pmu.events_mask, ARRAY_SIZE(intel_arch_events_map)) {
intel_perfmon_event_map[intel_arch_events_map[bit].id] = 0;
pr_warn("CPUID marked event: \'%s\' unavailable\n",
intel_arch_events_map[bit].name);
}
}
static __init void intel_nehalem_quirk(void)
{
union cpuid10_ebx ebx;
ebx.full = x86_pmu.events_maskl;
if (ebx.split.no_branch_misses_retired) {
/*
* Erratum AAJ80 detected, we work it around by using
* the BR_MISP_EXEC.ANY event. This will over-count
* branch-misses, but it's still much better than the
* architectural event which is often completely bogus:
*/
intel_perfmon_event_map[PERF_COUNT_HW_BRANCH_MISSES] = 0x7f89;
ebx.split.no_branch_misses_retired = 0;
x86_pmu.events_maskl = ebx.full;
pr_info("CPU erratum AAJ80 worked around\n");
}
}
__init int intel_pmu_init(void)
{
union cpuid10_edx edx;
union cpuid10_eax eax;
union cpuid10_ebx ebx;
struct event_constraint *c;
unsigned int unused;
int version;
if (!cpu_has(&boot_cpu_data, X86_FEATURE_ARCH_PERFMON)) {
switch (boot_cpu_data.x86) {
case 0x6:
return p6_pmu_init();
case 0xb:
return knc_pmu_init();
case 0xf:
return p4_pmu_init();
}
return -ENODEV;
}
/*
* Check whether the Architectural PerfMon supports
* Branch Misses Retired hw_event or not.
*/
cpuid(10, &eax.full, &ebx.full, &unused, &edx.full);
if (eax.split.mask_length < ARCH_PERFMON_EVENTS_COUNT)
return -ENODEV;
version = eax.split.version_id;
if (version < 2)
x86_pmu = core_pmu;
else
x86_pmu = intel_pmu;
x86_pmu.version = version;
x86_pmu.num_counters = eax.split.num_counters;
x86_pmu.cntval_bits = eax.split.bit_width;
x86_pmu.cntval_mask = (1ULL << eax.split.bit_width) - 1;
x86_pmu.events_maskl = ebx.full;
x86_pmu.events_mask_len = eax.split.mask_length;
x86_pmu.max_pebs_events = min_t(unsigned, MAX_PEBS_EVENTS, x86_pmu.num_counters);
/*
* Quirk: v2 perfmon does not report fixed-purpose events, so
* assume at least 3 events:
*/
if (version > 1)
x86_pmu.num_counters_fixed = max((int)edx.split.num_counters_fixed, 3);
/*
* v2 and above have a perf capabilities MSR
*/
if (version > 1) {
u64 capabilities;
rdmsrl(MSR_IA32_PERF_CAPABILITIES, capabilities);
x86_pmu.intel_cap.capabilities = capabilities;
}
intel_ds_init();
x86_add_quirk(intel_arch_events_quirk); /* Install first, so it runs last */
/*
* Install the hw-cache-events table:
*/
switch (boot_cpu_data.x86_model) {
case 14: /* 65 nm core solo/duo, "Yonah" */
pr_cont("Core events, ");
break;
case 15: /* original 65 nm celeron/pentium/core2/xeon, "Merom"/"Conroe" */
x86_add_quirk(intel_clovertown_quirk);
case 22: /* single-core 65 nm celeron/core2solo "Merom-L"/"Conroe-L" */
case 23: /* current 45 nm celeron/core2/xeon "Penryn"/"Wolfdale" */
case 29: /* six-core 45 nm xeon "Dunnington" */
memcpy(hw_cache_event_ids, core2_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
intel_pmu_lbr_init_core();
x86_pmu.event_constraints = intel_core2_event_constraints;
x86_pmu.pebs_constraints = intel_core2_pebs_event_constraints;
pr_cont("Core2 events, ");
break;
case 26: /* 45 nm nehalem, "Bloomfield" */
case 30: /* 45 nm nehalem, "Lynnfield" */
case 46: /* 45 nm nehalem-ex, "Beckton" */
memcpy(hw_cache_event_ids, nehalem_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, nehalem_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_nhm();
x86_pmu.event_constraints = intel_nehalem_event_constraints;
x86_pmu.pebs_constraints = intel_nehalem_pebs_event_constraints;
x86_pmu.enable_all = intel_pmu_nhm_enable_all;
x86_pmu.extra_regs = intel_nehalem_extra_regs;
/* UOPS_ISSUED.STALLED_CYCLES */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
/* UOPS_EXECUTED.CORE_ACTIVE_CYCLES,c=1,i=1 */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =
X86_CONFIG(.event=0xb1, .umask=0x3f, .inv=1, .cmask=1);
x86_add_quirk(intel_nehalem_quirk);
pr_cont("Nehalem events, ");
break;
case 28: /* Atom */
case 38: /* Lincroft */
case 39: /* Penwell */
case 53: /* Cloverview */
case 54: /* Cedarview */
memcpy(hw_cache_event_ids, atom_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
intel_pmu_lbr_init_atom();
x86_pmu.event_constraints = intel_gen_event_constraints;
x86_pmu.pebs_constraints = intel_atom_pebs_event_constraints;
pr_cont("Atom events, ");
break;
case 37: /* 32 nm nehalem, "Clarkdale" */
case 44: /* 32 nm nehalem, "Gulftown" */
case 47: /* 32 nm Xeon E7 */
memcpy(hw_cache_event_ids, westmere_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, nehalem_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_nhm();
x86_pmu.event_constraints = intel_westmere_event_constraints;
x86_pmu.enable_all = intel_pmu_nhm_enable_all;
x86_pmu.pebs_constraints = intel_westmere_pebs_event_constraints;
x86_pmu.extra_regs = intel_westmere_extra_regs;
x86_pmu.er_flags |= ERF_HAS_RSP_1;
/* UOPS_ISSUED.STALLED_CYCLES */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
/* UOPS_EXECUTED.CORE_ACTIVE_CYCLES,c=1,i=1 */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =
X86_CONFIG(.event=0xb1, .umask=0x3f, .inv=1, .cmask=1);
pr_cont("Westmere events, ");
break;
case 42: /* SandyBridge */
case 45: /* SandyBridge, "Romely-EP" */
x86_add_quirk(intel_sandybridge_quirk);
memcpy(hw_cache_event_ids, snb_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, snb_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_snb();
x86_pmu.event_constraints = intel_snb_event_constraints;
x86_pmu.pebs_constraints = intel_snb_pebs_event_constraints;
x86_pmu.pebs_aliases = intel_pebs_aliases_snb;
x86_pmu.extra_regs = intel_snb_extra_regs;
/* all extra regs are per-cpu when HT is on */
x86_pmu.er_flags |= ERF_HAS_RSP_1;
x86_pmu.er_flags |= ERF_NO_HT_SHARING;
/* UOPS_ISSUED.ANY,c=1,i=1 to count stall cycles */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
/* UOPS_DISPATCHED.THREAD,c=1,i=1 to count stall cycles*/
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =
X86_CONFIG(.event=0xb1, .umask=0x01, .inv=1, .cmask=1);
pr_cont("SandyBridge events, ");
break;
case 58: /* IvyBridge */
case 62: /* IvyBridge EP */
memcpy(hw_cache_event_ids, snb_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, snb_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_snb();
x86_pmu.event_constraints = intel_ivb_event_constraints;
x86_pmu.pebs_constraints = intel_ivb_pebs_event_constraints;
x86_pmu.pebs_aliases = intel_pebs_aliases_snb;
x86_pmu.extra_regs = intel_snb_extra_regs;
/* all extra regs are per-cpu when HT is on */
x86_pmu.er_flags |= ERF_HAS_RSP_1;
x86_pmu.er_flags |= ERF_NO_HT_SHARING;
/* UOPS_ISSUED.ANY,c=1,i=1 to count stall cycles */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
pr_cont("IvyBridge events, ");
break;
default:
switch (x86_pmu.version) {
case 1:
x86_pmu.event_constraints = intel_v1_event_constraints;
pr_cont("generic architected perfmon v1, ");
break;
default:
/*
* default constraints for v2 and up
*/
x86_pmu.event_constraints = intel_gen_event_constraints;
pr_cont("generic architected perfmon, ");
break;
}
}
if (x86_pmu.num_counters > INTEL_PMC_MAX_GENERIC) {
WARN(1, KERN_ERR "hw perf events %d > max(%d), clipping!",
x86_pmu.num_counters, INTEL_PMC_MAX_GENERIC);
x86_pmu.num_counters = INTEL_PMC_MAX_GENERIC;
}
x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
if (x86_pmu.num_counters_fixed > INTEL_PMC_MAX_FIXED) {
WARN(1, KERN_ERR "hw perf events fixed %d > max(%d), clipping!",
x86_pmu.num_counters_fixed, INTEL_PMC_MAX_FIXED);
x86_pmu.num_counters_fixed = INTEL_PMC_MAX_FIXED;
}
x86_pmu.intel_ctrl |=
((1LL << x86_pmu.num_counters_fixed)-1) << INTEL_PMC_IDX_FIXED;
if (x86_pmu.event_constraints) {
/*
* event on fixed counter2 (REF_CYCLES) only works on this
* counter, so do not extend mask to generic counters
*/
for_each_event_constraint(c, x86_pmu.event_constraints) {
if (c->cmask != X86_RAW_EVENT_MASK
|| c->idxmsk64 == INTEL_PMC_MSK_FIXED_REF_CYCLES) {
continue;
}
c->idxmsk64 |= (1ULL << x86_pmu.num_counters) - 1;
c->weight += x86_pmu.num_counters;
}
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5653_0 |
crossvul-cpp_data_bad_5110_0 | /* toshiba.c
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include "wtap-int.h"
#include "toshiba.h"
#include "file_wrappers.h"
#include <stdlib.h>
#include <string.h>
/* This module reads the output of the 'snoop' command in the Toshiba
* TR-600 and TR-650 "Compact" ISDN Routers. You can telnet to the
* router and run 'snoop' on the different channels, and at different
* detail levels. Be sure to choose the 'dump' level to get the hex dump.
* The 'snoop' command has nothing to do with the Solaris 'snoop'
* command, except that they both capture packets.
*/
/*
Example 'snoop' output data:
Script started on Thu Sep 9 21:48:49 1999
]0;gram@nirvana:/tmp$ telnet 10.0.0.254
Trying 10.0.0.254...
Connected to 10.0.0.254.
Escape character is '^]'.
TR-600(tr600) System Console
Login:admin
Password:*******
*--------------------------------------------------------*
| T O S H I B A T R - 6 0 0 |
| < Compact Router > |
| V1.02.02 |
| |
| (C) Copyright TOSHIBA Corp. 1997 All rights reserved. |
*--------------------------------------------------------*
tr600>snoop dump b1
Trace start?(on/off/dump/dtl)->dump
IP Address?->b1
B1 Port Filetering
Trace start(Dump Mode)...
tr600>[No.1] 00:00:09.14 B1:1 Tx 207.193.26.136->151.164.1.8 DNS SPORT=1028 LEN=38 CHKSUM=4FD4 ID=2390 Query RD QCNT=1 pow.zing.org?
OFFSET 0001-0203-0405-0607-0809-0A0B-0C0D-0E0F 0123456789ABCDEF LEN=67
0000 : FF03 003D C000 0008 2145 0000 3A12 6500 ...=....!E..:.e.
0010 : 003F 11E6 58CF C11A 8897 A401 0804 0400 .?..X...........
0020 : 3500 264F D409 5601 0000 0100 0000 0000 5.&O..V.........
0030 : 0003 706F 7704 7A69 6E67 036F 7267 0000 ..pow.zing.org..
0040 : 0100 01 ...
[No.2] 00:00:09.25 B1:1 Rx 151.164.1.8->207.193.26.136 DNS DPORT=1028 LEN=193 CHKSUM=3E06 ID=2390 Answer RD RA QCNT=1 pow.zing.org? ANCNT=1 pow.zing.org=206.57.36.90 TTL=2652
OFFSET 0001-0203-0405-0607-0809-0A0B-0C0D-0E0F 0123456789ABCDEF LEN=222
0000 : FF03 003D C000 0013 2145 0000 D590 9340 ...=....!E.....@
0010 : 00F7 116F 8E97 A401 08CF C11A 8800 3504 ...o..........5.
0020 : 0400 C13E 0609 5681 8000 0100 0100 0300 ...>..V.........
0030 : 0303 706F 7704 7A69 6E67 036F 7267 0000 ..pow.zing.org..
0040 : 0100 01C0 0C00 0100 0100 000A 5C00 04CE ............\...
0050 : 3924 5A04 5A49 4E47 036F 7267 0000 0200 9$Z.ZING.org....
0060 : 0100 016F 5B00 0D03 4841 4E03 5449 5703 ...o[...HAN.TIW.
0070 : 4E45 5400 C02E 0002 0001 0001 6F5B 0006 NET.........o[..
0080 : 034E 5331 C02E C02E 0002 0001 0001 6F5B .NS1..........o[
0090 : 001C 0854 414C 4945 5349 4E0D 434F 4E46 ...TALIESIN.CONF
00A0 : 4142 554C 4154 494F 4E03 434F 4D00 C042 ABULATION.COM..B
00B0 : 0001 0001 0001 51EC 0004 CE39 2406 C05B ......Q....9$..[
00C0 : 0001 0001 0001 6F5B 0004 CE39 245A C06D ......o[...9$Z.m
00D0 : 0001 0001 0001 4521 0004 187C 1F01 ......E!...|..
*/
/* Magic text to check for toshiba-ness of file */
static const char toshiba_hdr_magic[] =
{ 'T', ' ', 'O', ' ', 'S', ' ', 'H', ' ', 'I', ' ', 'B', ' ', 'A' };
#define TOSHIBA_HDR_MAGIC_SIZE (sizeof toshiba_hdr_magic / sizeof toshiba_hdr_magic[0])
/* Magic text for start of packet */
static const char toshiba_rec_magic[] = { '[', 'N', 'o', '.' };
#define TOSHIBA_REC_MAGIC_SIZE (sizeof toshiba_rec_magic / sizeof toshiba_rec_magic[0])
/*
* XXX - is this the biggest packet we can get?
*/
#define TOSHIBA_MAX_PACKET_LEN 16384
static gboolean toshiba_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset);
static gboolean toshiba_seek_read(wtap *wth, gint64 seek_off,
struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info);
static gboolean parse_single_hex_dump_line(char* rec, guint8 *buf,
guint byte_offset);
static gboolean parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr,
Buffer *buf, int *err, gchar **err_info);
/* Seeks to the beginning of the next packet, and returns the
byte offset. Returns -1 on failure, and sets "*err" to the error
and "*err_info" to null or an additional error string. */
static gint64 toshiba_seek_next_packet(wtap *wth, int *err, gchar **err_info)
{
int byte;
guint level = 0;
gint64 cur_off;
while ((byte = file_getc(wth->fh)) != EOF) {
if (byte == toshiba_rec_magic[level]) {
level++;
if (level >= TOSHIBA_REC_MAGIC_SIZE) {
/* note: we're leaving file pointer right after the magic characters */
cur_off = file_tell(wth->fh);
if (cur_off == -1) {
/* Error. */
*err = file_error(wth->fh, err_info);
return -1;
}
return cur_off + 1;
}
} else {
level = 0;
}
}
/* EOF or error. */
*err = file_error(wth->fh, err_info);
return -1;
}
#define TOSHIBA_HEADER_LINES_TO_CHECK 200
#define TOSHIBA_LINE_LENGTH 240
/* Look through the first part of a file to see if this is
* a Toshiba trace file.
*
* Returns TRUE if it is, FALSE if it isn't or if we get an I/O error;
* if we get an I/O error, "*err" will be set to a non-zero value and
* "*err_info" will be set to null or an additional error string.
*/
static gboolean toshiba_check_file_type(wtap *wth, int *err, gchar **err_info)
{
char buf[TOSHIBA_LINE_LENGTH];
guint i, reclen, level, line;
char byte;
buf[TOSHIBA_LINE_LENGTH-1] = 0;
for (line = 0; line < TOSHIBA_HEADER_LINES_TO_CHECK; line++) {
if (file_gets(buf, TOSHIBA_LINE_LENGTH, wth->fh) == NULL) {
/* EOF or error. */
*err = file_error(wth->fh, err_info);
return FALSE;
}
reclen = (guint) strlen(buf);
if (reclen < TOSHIBA_HDR_MAGIC_SIZE) {
continue;
}
level = 0;
for (i = 0; i < reclen; i++) {
byte = buf[i];
if (byte == toshiba_hdr_magic[level]) {
level++;
if (level >= TOSHIBA_HDR_MAGIC_SIZE) {
return TRUE;
}
}
else {
level = 0;
}
}
}
*err = 0;
return FALSE;
}
wtap_open_return_val toshiba_open(wtap *wth, int *err, gchar **err_info)
{
/* Look for Toshiba header */
if (!toshiba_check_file_type(wth, err, err_info)) {
if (*err != 0 && *err != WTAP_ERR_SHORT_READ)
return WTAP_OPEN_ERROR;
return WTAP_OPEN_NOT_MINE;
}
wth->file_encap = WTAP_ENCAP_PER_PACKET;
wth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_TOSHIBA;
wth->snapshot_length = 0; /* not known */
wth->subtype_read = toshiba_read;
wth->subtype_seek_read = toshiba_seek_read;
wth->file_tsprec = WTAP_TSPREC_CSEC;
return WTAP_OPEN_MINE;
}
/* Find the next packet and parse it; called from wtap_read(). */
static gboolean toshiba_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset)
{
gint64 offset;
/* Find the next packet */
offset = toshiba_seek_next_packet(wth, err, err_info);
if (offset < 1)
return FALSE;
*data_offset = offset;
/* Parse the packet */
return parse_toshiba_packet(wth->fh, &wth->phdr, wth->frame_buffer,
err, err_info);
}
/* Used to read packets in random-access fashion */
static gboolean
toshiba_seek_read(wtap *wth, gint64 seek_off,
struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
if (file_seek(wth->random_fh, seek_off - 1, SEEK_SET, err) == -1)
return FALSE;
if (!parse_toshiba_packet(wth->random_fh, phdr, buf, err, err_info)) {
if (*err == 0)
*err = WTAP_ERR_SHORT_READ;
return FALSE;
}
return TRUE;
}
/* Parses a packet. */
static gboolean
parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
char line[TOSHIBA_LINE_LENGTH];
int num_items_scanned;
int pkt_len, pktnum, hr, min, sec, csec;
char channel[10], direction[10];
int i, hex_lines;
guint8 *pd;
/* Our file pointer should be on the line containing the
* summary information for a packet. Read in that line and
* extract the useful information
*/
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Find text in line after "[No.". Limit the length of the
* two strings since we have fixed buffers for channel[] and
* direction[] */
num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s",
&pktnum, &hr, &min, &sec, &csec, channel, direction);
if (num_items_scanned != 7) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: record header isn't valid");
return FALSE;
}
/* Scan lines until we find the OFFSET line. In a "telnet" trace,
* this will be the next line. But if you save your telnet session
* to a file from within a Windows-based telnet client, it may
* put in line breaks at 80 columns (or however big your "telnet" box
* is). CRT (a Windows telnet app from VanDyke) does this.
* Here we assume that 80 columns will be the minimum size, and that
* the OFFSET line is not broken in the middle. It's the previous
* line that is normally long and can thus be broken at column 80.
*/
do {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Check for "OFFSET 0001-0203" at beginning of line */
line[16] = '\0';
} while (strcmp(line, "OFFSET 0001-0203") != 0);
num_items_scanned = sscanf(line+64, "LEN=%9d", &pkt_len);
if (num_items_scanned != 1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item");
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
phdr->ts.secs = hr * 3600 + min * 60 + sec;
phdr->ts.nsecs = csec * 10000000;
phdr->caplen = pkt_len;
phdr->len = pkt_len;
switch (channel[0]) {
case 'B':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = (guint8)
strtol(&channel[1], NULL, 10);
break;
case 'D':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = 0;
break;
default:
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
/* XXX - is there an FCS in the frame? */
pseudo_header->eth.fcs_len = -1;
break;
}
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, TOSHIBA_MAX_PACKET_LEN);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (!parse_single_hex_dump_line(line, pd, i * 16)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: hex dump not valid");
return FALSE;
}
}
return TRUE;
}
/*
1 2 3 4
0123456789012345678901234567890123456789012345
0000 : FF03 003D C000 0008 2145 0000 3A12 6500 ...=....!E..:.e.
0010 : 003F 11E6 58CF C11A 8897 A401 0804 0400 .?..X...........
0020 : 0100 01 ...
*/
#define START_POS 7
#define HEX_LENGTH ((8 * 4) + 7) /* eight clumps of 4 bytes with 7 inner spaces */
/* Take a string representing one line from a hex dump and converts the
* text to binary data. We check the printed offset with the offset
* we are passed to validate the record. We place the bytes in the buffer
* at the specified offset.
*
* In the process, we're going to write all over the string.
*
* Returns TRUE if good hex dump, FALSE if bad.
*/
static gboolean
parse_single_hex_dump_line(char* rec, guint8 *buf, guint byte_offset) {
int pos, i;
char *s;
unsigned long value;
guint16 word_value;
/* Get the byte_offset directly from the record */
rec[4] = '\0';
s = rec;
value = strtoul(s, NULL, 16);
if (value != byte_offset) {
return FALSE;
}
/* Go through the substring representing the values and:
* 1. Replace any spaces with '0's
* 2. Place \0's every 5 bytes (to terminate the string)
*
* Then read the eight sets of hex bytes
*/
for (pos = START_POS; pos < START_POS + HEX_LENGTH; pos++) {
if (rec[pos] == ' ') {
rec[pos] = '0';
}
}
pos = START_POS;
for (i = 0; i < 8; i++) {
rec[pos+4] = '\0';
word_value = (guint16) strtoul(&rec[pos], NULL, 16);
buf[byte_offset + i * 2 + 0] = (guint8) (word_value >> 8);
buf[byte_offset + i * 2 + 1] = (guint8) (word_value & 0x00ff);
pos += 5;
}
return TRUE;
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5110_0 |
crossvul-cpp_data_bad_5109_0 | /* toshiba.c
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include "wtap-int.h"
#include "toshiba.h"
#include "file_wrappers.h"
#include <stdlib.h>
#include <string.h>
/* This module reads the output of the 'snoop' command in the Toshiba
* TR-600 and TR-650 "Compact" ISDN Routers. You can telnet to the
* router and run 'snoop' on the different channels, and at different
* detail levels. Be sure to choose the 'dump' level to get the hex dump.
* The 'snoop' command has nothing to do with the Solaris 'snoop'
* command, except that they both capture packets.
*/
/*
Example 'snoop' output data:
Script started on Thu Sep 9 21:48:49 1999
]0;gram@nirvana:/tmp$ telnet 10.0.0.254
Trying 10.0.0.254...
Connected to 10.0.0.254.
Escape character is '^]'.
TR-600(tr600) System Console
Login:admin
Password:*******
*--------------------------------------------------------*
| T O S H I B A T R - 6 0 0 |
| < Compact Router > |
| V1.02.02 |
| |
| (C) Copyright TOSHIBA Corp. 1997 All rights reserved. |
*--------------------------------------------------------*
tr600>snoop dump b1
Trace start?(on/off/dump/dtl)->dump
IP Address?->b1
B1 Port Filetering
Trace start(Dump Mode)...
tr600>[No.1] 00:00:09.14 B1:1 Tx 207.193.26.136->151.164.1.8 DNS SPORT=1028 LEN=38 CHKSUM=4FD4 ID=2390 Query RD QCNT=1 pow.zing.org?
OFFSET 0001-0203-0405-0607-0809-0A0B-0C0D-0E0F 0123456789ABCDEF LEN=67
0000 : FF03 003D C000 0008 2145 0000 3A12 6500 ...=....!E..:.e.
0010 : 003F 11E6 58CF C11A 8897 A401 0804 0400 .?..X...........
0020 : 3500 264F D409 5601 0000 0100 0000 0000 5.&O..V.........
0030 : 0003 706F 7704 7A69 6E67 036F 7267 0000 ..pow.zing.org..
0040 : 0100 01 ...
[No.2] 00:00:09.25 B1:1 Rx 151.164.1.8->207.193.26.136 DNS DPORT=1028 LEN=193 CHKSUM=3E06 ID=2390 Answer RD RA QCNT=1 pow.zing.org? ANCNT=1 pow.zing.org=206.57.36.90 TTL=2652
OFFSET 0001-0203-0405-0607-0809-0A0B-0C0D-0E0F 0123456789ABCDEF LEN=222
0000 : FF03 003D C000 0013 2145 0000 D590 9340 ...=....!E.....@
0010 : 00F7 116F 8E97 A401 08CF C11A 8800 3504 ...o..........5.
0020 : 0400 C13E 0609 5681 8000 0100 0100 0300 ...>..V.........
0030 : 0303 706F 7704 7A69 6E67 036F 7267 0000 ..pow.zing.org..
0040 : 0100 01C0 0C00 0100 0100 000A 5C00 04CE ............\...
0050 : 3924 5A04 5A49 4E47 036F 7267 0000 0200 9$Z.ZING.org....
0060 : 0100 016F 5B00 0D03 4841 4E03 5449 5703 ...o[...HAN.TIW.
0070 : 4E45 5400 C02E 0002 0001 0001 6F5B 0006 NET.........o[..
0080 : 034E 5331 C02E C02E 0002 0001 0001 6F5B .NS1..........o[
0090 : 001C 0854 414C 4945 5349 4E0D 434F 4E46 ...TALIESIN.CONF
00A0 : 4142 554C 4154 494F 4E03 434F 4D00 C042 ABULATION.COM..B
00B0 : 0001 0001 0001 51EC 0004 CE39 2406 C05B ......Q....9$..[
00C0 : 0001 0001 0001 6F5B 0004 CE39 245A C06D ......o[...9$Z.m
00D0 : 0001 0001 0001 4521 0004 187C 1F01 ......E!...|..
*/
/* Magic text to check for toshiba-ness of file */
static const char toshiba_hdr_magic[] =
{ 'T', ' ', 'O', ' ', 'S', ' ', 'H', ' ', 'I', ' ', 'B', ' ', 'A' };
#define TOSHIBA_HDR_MAGIC_SIZE (sizeof toshiba_hdr_magic / sizeof toshiba_hdr_magic[0])
/* Magic text for start of packet */
static const char toshiba_rec_magic[] = { '[', 'N', 'o', '.' };
#define TOSHIBA_REC_MAGIC_SIZE (sizeof toshiba_rec_magic / sizeof toshiba_rec_magic[0])
static gboolean toshiba_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset);
static gboolean toshiba_seek_read(wtap *wth, gint64 seek_off,
struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info);
static gboolean parse_single_hex_dump_line(char* rec, guint8 *buf,
guint byte_offset);
static gboolean parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr,
Buffer *buf, int *err, gchar **err_info);
/* Seeks to the beginning of the next packet, and returns the
byte offset. Returns -1 on failure, and sets "*err" to the error
and "*err_info" to null or an additional error string. */
static gint64 toshiba_seek_next_packet(wtap *wth, int *err, gchar **err_info)
{
int byte;
guint level = 0;
gint64 cur_off;
while ((byte = file_getc(wth->fh)) != EOF) {
if (byte == toshiba_rec_magic[level]) {
level++;
if (level >= TOSHIBA_REC_MAGIC_SIZE) {
/* note: we're leaving file pointer right after the magic characters */
cur_off = file_tell(wth->fh);
if (cur_off == -1) {
/* Error. */
*err = file_error(wth->fh, err_info);
return -1;
}
return cur_off + 1;
}
} else {
level = 0;
}
}
/* EOF or error. */
*err = file_error(wth->fh, err_info);
return -1;
}
#define TOSHIBA_HEADER_LINES_TO_CHECK 200
#define TOSHIBA_LINE_LENGTH 240
/* Look through the first part of a file to see if this is
* a Toshiba trace file.
*
* Returns TRUE if it is, FALSE if it isn't or if we get an I/O error;
* if we get an I/O error, "*err" will be set to a non-zero value and
* "*err_info" will be set to null or an additional error string.
*/
static gboolean toshiba_check_file_type(wtap *wth, int *err, gchar **err_info)
{
char buf[TOSHIBA_LINE_LENGTH];
guint i, reclen, level, line;
char byte;
buf[TOSHIBA_LINE_LENGTH-1] = 0;
for (line = 0; line < TOSHIBA_HEADER_LINES_TO_CHECK; line++) {
if (file_gets(buf, TOSHIBA_LINE_LENGTH, wth->fh) == NULL) {
/* EOF or error. */
*err = file_error(wth->fh, err_info);
return FALSE;
}
reclen = (guint) strlen(buf);
if (reclen < TOSHIBA_HDR_MAGIC_SIZE) {
continue;
}
level = 0;
for (i = 0; i < reclen; i++) {
byte = buf[i];
if (byte == toshiba_hdr_magic[level]) {
level++;
if (level >= TOSHIBA_HDR_MAGIC_SIZE) {
return TRUE;
}
}
else {
level = 0;
}
}
}
*err = 0;
return FALSE;
}
wtap_open_return_val toshiba_open(wtap *wth, int *err, gchar **err_info)
{
/* Look for Toshiba header */
if (!toshiba_check_file_type(wth, err, err_info)) {
if (*err != 0 && *err != WTAP_ERR_SHORT_READ)
return WTAP_OPEN_ERROR;
return WTAP_OPEN_NOT_MINE;
}
wth->file_encap = WTAP_ENCAP_PER_PACKET;
wth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_TOSHIBA;
wth->snapshot_length = 0; /* not known */
wth->subtype_read = toshiba_read;
wth->subtype_seek_read = toshiba_seek_read;
wth->file_tsprec = WTAP_TSPREC_CSEC;
return WTAP_OPEN_MINE;
}
/* Find the next packet and parse it; called from wtap_read(). */
static gboolean toshiba_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset)
{
gint64 offset;
/* Find the next packet */
offset = toshiba_seek_next_packet(wth, err, err_info);
if (offset < 1)
return FALSE;
*data_offset = offset;
/* Parse the packet */
return parse_toshiba_packet(wth->fh, &wth->phdr, wth->frame_buffer,
err, err_info);
}
/* Used to read packets in random-access fashion */
static gboolean
toshiba_seek_read(wtap *wth, gint64 seek_off,
struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
if (file_seek(wth->random_fh, seek_off - 1, SEEK_SET, err) == -1)
return FALSE;
if (!parse_toshiba_packet(wth->random_fh, phdr, buf, err, err_info)) {
if (*err == 0)
*err = WTAP_ERR_SHORT_READ;
return FALSE;
}
return TRUE;
}
/* Parses a packet. */
static gboolean
parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
char line[TOSHIBA_LINE_LENGTH];
int num_items_scanned;
guint pkt_len;
int pktnum, hr, min, sec, csec;
char channel[10], direction[10];
int i, hex_lines;
guint8 *pd;
/* Our file pointer should be on the line containing the
* summary information for a packet. Read in that line and
* extract the useful information
*/
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Find text in line after "[No.". Limit the length of the
* two strings since we have fixed buffers for channel[] and
* direction[] */
num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s",
&pktnum, &hr, &min, &sec, &csec, channel, direction);
if (num_items_scanned != 7) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: record header isn't valid");
return FALSE;
}
/* Scan lines until we find the OFFSET line. In a "telnet" trace,
* this will be the next line. But if you save your telnet session
* to a file from within a Windows-based telnet client, it may
* put in line breaks at 80 columns (or however big your "telnet" box
* is). CRT (a Windows telnet app from VanDyke) does this.
* Here we assume that 80 columns will be the minimum size, and that
* the OFFSET line is not broken in the middle. It's the previous
* line that is normally long and can thus be broken at column 80.
*/
do {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Check for "OFFSET 0001-0203" at beginning of line */
line[16] = '\0';
} while (strcmp(line, "OFFSET 0001-0203") != 0);
num_items_scanned = sscanf(line+64, "LEN=%9u", &pkt_len);
if (num_items_scanned != 1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item");
return FALSE;
}
if (pkt_len > WTAP_MAX_PACKET_SIZE) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup_printf("toshiba: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
phdr->ts.secs = hr * 3600 + min * 60 + sec;
phdr->ts.nsecs = csec * 10000000;
phdr->caplen = pkt_len;
phdr->len = pkt_len;
switch (channel[0]) {
case 'B':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = (guint8)
strtol(&channel[1], NULL, 10);
break;
case 'D':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = 0;
break;
default:
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
/* XXX - is there an FCS in the frame? */
pseudo_header->eth.fcs_len = -1;
break;
}
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (!parse_single_hex_dump_line(line, pd, i * 16)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: hex dump not valid");
return FALSE;
}
}
return TRUE;
}
/*
1 2 3 4
0123456789012345678901234567890123456789012345
0000 : FF03 003D C000 0008 2145 0000 3A12 6500 ...=....!E..:.e.
0010 : 003F 11E6 58CF C11A 8897 A401 0804 0400 .?..X...........
0020 : 0100 01 ...
*/
#define START_POS 7
#define HEX_LENGTH ((8 * 4) + 7) /* eight clumps of 4 bytes with 7 inner spaces */
/* Take a string representing one line from a hex dump and converts the
* text to binary data. We check the printed offset with the offset
* we are passed to validate the record. We place the bytes in the buffer
* at the specified offset.
*
* In the process, we're going to write all over the string.
*
* Returns TRUE if good hex dump, FALSE if bad.
*/
static gboolean
parse_single_hex_dump_line(char* rec, guint8 *buf, guint byte_offset) {
int pos, i;
char *s;
unsigned long value;
guint16 word_value;
/* Get the byte_offset directly from the record */
rec[4] = '\0';
s = rec;
value = strtoul(s, NULL, 16);
if (value != byte_offset) {
return FALSE;
}
/* Go through the substring representing the values and:
* 1. Replace any spaces with '0's
* 2. Place \0's every 5 bytes (to terminate the string)
*
* Then read the eight sets of hex bytes
*/
for (pos = START_POS; pos < START_POS + HEX_LENGTH; pos++) {
if (rec[pos] == ' ') {
rec[pos] = '0';
}
}
pos = START_POS;
for (i = 0; i < 8; i++) {
rec[pos+4] = '\0';
word_value = (guint16) strtoul(&rec[pos], NULL, 16);
buf[byte_offset + i * 2 + 0] = (guint8) (word_value >> 8);
buf[byte_offset + i * 2 + 1] = (guint8) (word_value & 0x00ff);
pos += 5;
}
return TRUE;
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5109_0 |
crossvul-cpp_data_good_5285_0 | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Marcus Boerger <helly@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "ext/standard/php_var.h"
#include "ext/standard/php_smart_str.h"
#include "zend_interfaces.h"
#include "zend_exceptions.h"
#include "php_spl.h"
#include "spl_functions.h"
#include "spl_engine.h"
#include "spl_iterators.h"
#include "spl_array.h"
#include "spl_exceptions.h"
zend_object_handlers spl_handler_ArrayObject;
PHPAPI zend_class_entry *spl_ce_ArrayObject;
zend_object_handlers spl_handler_ArrayIterator;
PHPAPI zend_class_entry *spl_ce_ArrayIterator;
PHPAPI zend_class_entry *spl_ce_RecursiveArrayIterator;
#define SPL_ARRAY_STD_PROP_LIST 0x00000001
#define SPL_ARRAY_ARRAY_AS_PROPS 0x00000002
#define SPL_ARRAY_CHILD_ARRAYS_ONLY 0x00000004
#define SPL_ARRAY_OVERLOADED_REWIND 0x00010000
#define SPL_ARRAY_OVERLOADED_VALID 0x00020000
#define SPL_ARRAY_OVERLOADED_KEY 0x00040000
#define SPL_ARRAY_OVERLOADED_CURRENT 0x00080000
#define SPL_ARRAY_OVERLOADED_NEXT 0x00100000
#define SPL_ARRAY_IS_REF 0x01000000
#define SPL_ARRAY_IS_SELF 0x02000000
#define SPL_ARRAY_USE_OTHER 0x04000000
#define SPL_ARRAY_INT_MASK 0xFFFF0000
#define SPL_ARRAY_CLONE_MASK 0x0300FFFF
#define SPL_ARRAY_METHOD_NO_ARG 0
#define SPL_ARRAY_METHOD_USE_ARG 1
#define SPL_ARRAY_METHOD_MAY_USER_ARG 2
typedef struct _spl_array_object {
zend_object std;
zval *array;
zval *retval;
HashPosition pos;
ulong pos_h;
int ar_flags;
int is_self;
zend_function *fptr_offset_get;
zend_function *fptr_offset_set;
zend_function *fptr_offset_has;
zend_function *fptr_offset_del;
zend_function *fptr_count;
zend_class_entry* ce_get_iterator;
HashTable *debug_info;
unsigned char nApplyCount;
} spl_array_object;
static inline HashTable *spl_array_get_hash_table(spl_array_object* intern, int check_std_props TSRMLS_DC) { /* {{{ */
if ((intern->ar_flags & SPL_ARRAY_IS_SELF) != 0) {
if (!intern->std.properties) {
rebuild_object_properties(&intern->std);
}
return intern->std.properties;
} else if ((intern->ar_flags & SPL_ARRAY_USE_OTHER) && (check_std_props == 0 || (intern->ar_flags & SPL_ARRAY_STD_PROP_LIST) == 0) && Z_TYPE_P(intern->array) == IS_OBJECT) {
spl_array_object *other = (spl_array_object*)zend_object_store_get_object(intern->array TSRMLS_CC);
return spl_array_get_hash_table(other, check_std_props TSRMLS_CC);
} else if ((intern->ar_flags & ((check_std_props ? SPL_ARRAY_STD_PROP_LIST : 0) | SPL_ARRAY_IS_SELF)) != 0) {
if (!intern->std.properties) {
rebuild_object_properties(&intern->std);
}
return intern->std.properties;
} else {
return HASH_OF(intern->array);
}
} /* }}} */
static void spl_array_rewind(spl_array_object *intern TSRMLS_DC);
static void spl_array_update_pos(spl_array_object* intern) /* {{{ */
{
Bucket *pos = intern->pos;
if (pos != NULL) {
intern->pos_h = pos->h;
}
} /* }}} */
static void spl_array_set_pos(spl_array_object* intern, HashPosition pos) /* {{{ */
{
intern->pos = pos;
spl_array_update_pos(intern);
} /* }}} */
SPL_API int spl_hash_verify_pos_ex(spl_array_object * intern, HashTable * ht TSRMLS_DC) /* {{{ */
{
Bucket *p;
/* IS_CONSISTENT(ht);*/
/* HASH_PROTECT_RECURSION(ht);*/
p = ht->arBuckets[intern->pos_h & ht->nTableMask];
while (p != NULL) {
if (p == intern->pos) {
return SUCCESS;
}
p = p->pNext;
}
/* HASH_UNPROTECT_RECURSION(ht); */
spl_array_rewind(intern TSRMLS_CC);
return FAILURE;
} /* }}} */
SPL_API int spl_hash_verify_pos(spl_array_object * intern TSRMLS_DC) /* {{{ */
{
HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
return spl_hash_verify_pos_ex(intern, ht TSRMLS_CC);
}
/* }}} */
/* {{{ spl_array_object_free_storage */
static void spl_array_object_free_storage(void *object TSRMLS_DC)
{
spl_array_object *intern = (spl_array_object *)object;
zend_object_std_dtor(&intern->std TSRMLS_CC);
zval_ptr_dtor(&intern->array);
zval_ptr_dtor(&intern->retval);
if (intern->debug_info != NULL) {
zend_hash_destroy(intern->debug_info);
efree(intern->debug_info);
}
efree(object);
}
/* }}} */
zend_object_iterator *spl_array_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC);
/* {{{ spl_array_object_new_ex */
static zend_object_value spl_array_object_new_ex(zend_class_entry *class_type, spl_array_object **obj, zval *orig, int clone_orig TSRMLS_DC)
{
zend_object_value retval = {0};
spl_array_object *intern;
zval *tmp;
zend_class_entry * parent = class_type;
int inherited = 0;
intern = emalloc(sizeof(spl_array_object));
memset(intern, 0, sizeof(spl_array_object));
*obj = intern;
ALLOC_INIT_ZVAL(intern->retval);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
intern->ar_flags = 0;
intern->debug_info = NULL;
intern->ce_get_iterator = spl_ce_ArrayIterator;
if (orig) {
spl_array_object *other = (spl_array_object*)zend_object_store_get_object(orig TSRMLS_CC);
intern->ar_flags &= ~ SPL_ARRAY_CLONE_MASK;
intern->ar_flags |= (other->ar_flags & SPL_ARRAY_CLONE_MASK);
intern->ce_get_iterator = other->ce_get_iterator;
if (clone_orig) {
intern->array = other->array;
if (Z_OBJ_HT_P(orig) == &spl_handler_ArrayObject) {
MAKE_STD_ZVAL(intern->array);
array_init(intern->array);
zend_hash_copy(HASH_OF(intern->array), HASH_OF(other->array), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*));
}
if (Z_OBJ_HT_P(orig) == &spl_handler_ArrayIterator) {
Z_ADDREF_P(other->array);
}
} else {
intern->array = orig;
Z_ADDREF_P(intern->array);
intern->ar_flags |= SPL_ARRAY_IS_REF | SPL_ARRAY_USE_OTHER;
}
} else {
MAKE_STD_ZVAL(intern->array);
array_init(intern->array);
intern->ar_flags &= ~SPL_ARRAY_IS_REF;
}
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) spl_array_object_free_storage, NULL TSRMLS_CC);
while (parent) {
if (parent == spl_ce_ArrayIterator || parent == spl_ce_RecursiveArrayIterator) {
retval.handlers = &spl_handler_ArrayIterator;
class_type->get_iterator = spl_array_get_iterator;
break;
} else if (parent == spl_ce_ArrayObject) {
retval.handlers = &spl_handler_ArrayObject;
break;
}
parent = parent->parent;
inherited = 1;
}
if (!parent) { /* this must never happen */
php_error_docref(NULL TSRMLS_CC, E_COMPILE_ERROR, "Internal compiler error, Class is not child of ArrayObject or ArrayIterator");
}
if (inherited) {
zend_hash_find(&class_type->function_table, "offsetget", sizeof("offsetget"), (void **) &intern->fptr_offset_get);
if (intern->fptr_offset_get->common.scope == parent) {
intern->fptr_offset_get = NULL;
}
zend_hash_find(&class_type->function_table, "offsetset", sizeof("offsetset"), (void **) &intern->fptr_offset_set);
if (intern->fptr_offset_set->common.scope == parent) {
intern->fptr_offset_set = NULL;
}
zend_hash_find(&class_type->function_table, "offsetexists", sizeof("offsetexists"), (void **) &intern->fptr_offset_has);
if (intern->fptr_offset_has->common.scope == parent) {
intern->fptr_offset_has = NULL;
}
zend_hash_find(&class_type->function_table, "offsetunset", sizeof("offsetunset"), (void **) &intern->fptr_offset_del);
if (intern->fptr_offset_del->common.scope == parent) {
intern->fptr_offset_del = NULL;
}
zend_hash_find(&class_type->function_table, "count", sizeof("count"), (void **) &intern->fptr_count);
if (intern->fptr_count->common.scope == parent) {
intern->fptr_count = NULL;
}
}
/* Cache iterator functions if ArrayIterator or derived. Check current's */
/* cache since only current is always required */
if (retval.handlers == &spl_handler_ArrayIterator) {
if (!class_type->iterator_funcs.zf_current) {
zend_hash_find(&class_type->function_table, "rewind", sizeof("rewind"), (void **) &class_type->iterator_funcs.zf_rewind);
zend_hash_find(&class_type->function_table, "valid", sizeof("valid"), (void **) &class_type->iterator_funcs.zf_valid);
zend_hash_find(&class_type->function_table, "key", sizeof("key"), (void **) &class_type->iterator_funcs.zf_key);
zend_hash_find(&class_type->function_table, "current", sizeof("current"), (void **) &class_type->iterator_funcs.zf_current);
zend_hash_find(&class_type->function_table, "next", sizeof("next"), (void **) &class_type->iterator_funcs.zf_next);
}
if (inherited) {
if (class_type->iterator_funcs.zf_rewind->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_REWIND;
if (class_type->iterator_funcs.zf_valid->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_VALID;
if (class_type->iterator_funcs.zf_key->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_KEY;
if (class_type->iterator_funcs.zf_current->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_CURRENT;
if (class_type->iterator_funcs.zf_next->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_NEXT;
}
}
spl_array_rewind(intern TSRMLS_CC);
return retval;
}
/* }}} */
/* {{{ spl_array_object_new */
static zend_object_value spl_array_object_new(zend_class_entry *class_type TSRMLS_DC)
{
spl_array_object *tmp;
return spl_array_object_new_ex(class_type, &tmp, NULL, 0 TSRMLS_CC);
}
/* }}} */
/* {{{ spl_array_object_clone */
static zend_object_value spl_array_object_clone(zval *zobject TSRMLS_DC)
{
zend_object_value new_obj_val;
zend_object *old_object;
zend_object *new_object;
zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);
spl_array_object *intern;
old_object = zend_objects_get_address(zobject TSRMLS_CC);
new_obj_val = spl_array_object_new_ex(old_object->ce, &intern, zobject, 1 TSRMLS_CC);
new_object = &intern->std;
zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC);
return new_obj_val;
}
/* }}} */
static zval **spl_array_get_dimension_ptr_ptr(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
zval **retval;
char *key;
uint len;
long index;
HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (!offset || !ht) {
return &EG(uninitialized_zval_ptr);
}
if ((type == BP_VAR_W || type == BP_VAR_RW) && (ht->nApplyCount > 0)) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return &EG(error_zval_ptr);;
}
switch (Z_TYPE_P(offset)) {
case IS_STRING:
key = Z_STRVAL_P(offset);
len = Z_STRLEN_P(offset) + 1;
string_offest:
if (zend_symtable_find(ht, key, len, (void **) &retval) == FAILURE) {
switch (type) {
case BP_VAR_R:
zend_error(E_NOTICE, "Undefined index: %s", key);
case BP_VAR_UNSET:
case BP_VAR_IS:
retval = &EG(uninitialized_zval_ptr);
break;
case BP_VAR_RW:
zend_error(E_NOTICE,"Undefined index: %s", key);
case BP_VAR_W: {
zval *value;
ALLOC_INIT_ZVAL(value);
zend_symtable_update(ht, key, len, (void**)&value, sizeof(void*), (void **)&retval);
}
}
}
return retval;
case IS_NULL:
key = "";
len = 1;
goto string_offest;
case IS_RESOURCE:
zend_error(E_STRICT, "Resource ID#%ld used as offset, casting to integer (%ld)", Z_LVAL_P(offset), Z_LVAL_P(offset));
case IS_DOUBLE:
case IS_BOOL:
case IS_LONG:
if (offset->type == IS_DOUBLE) {
index = (long)Z_DVAL_P(offset);
} else {
index = Z_LVAL_P(offset);
}
if (zend_hash_index_find(ht, index, (void **) &retval) == FAILURE) {
switch (type) {
case BP_VAR_R:
zend_error(E_NOTICE, "Undefined offset: %ld", index);
case BP_VAR_UNSET:
case BP_VAR_IS:
retval = &EG(uninitialized_zval_ptr);
break;
case BP_VAR_RW:
zend_error(E_NOTICE, "Undefined offset: %ld", index);
case BP_VAR_W: {
zval *value;
ALLOC_INIT_ZVAL(value);
zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), (void **)&retval);
}
}
}
return retval;
default:
zend_error(E_WARNING, "Illegal offset type");
return (type == BP_VAR_W || type == BP_VAR_RW) ?
&EG(error_zval_ptr) : &EG(uninitialized_zval_ptr);
}
} /* }}} */
static zval *spl_array_read_dimension_ex(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */
{
zval **ret;
if (check_inherited) {
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if (intern->fptr_offset_get) {
zval *rv;
if (!offset) {
ALLOC_INIT_ZVAL(offset);
} else {
SEPARATE_ARG_IF_REF(offset);
}
zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_get, "offsetGet", &rv, offset);
zval_ptr_dtor(&offset);
if (rv) {
zval_ptr_dtor(&intern->retval);
MAKE_STD_ZVAL(intern->retval);
ZVAL_ZVAL(intern->retval, rv, 1, 1);
return intern->retval;
}
return EG(uninitialized_zval_ptr);
}
}
ret = spl_array_get_dimension_ptr_ptr(check_inherited, object, offset, type TSRMLS_CC);
/* When in a write context,
* ZE has to be fooled into thinking this is in a reference set
* by separating (if necessary) and returning as an is_ref=1 zval (even if refcount == 1) */
if ((type == BP_VAR_W || type == BP_VAR_RW || type == BP_VAR_UNSET) && !Z_ISREF_PP(ret) && ret != &EG(uninitialized_zval_ptr)) {
if (Z_REFCOUNT_PP(ret) > 1) {
zval *newval;
/* Separate */
MAKE_STD_ZVAL(newval);
*newval = **ret;
zval_copy_ctor(newval);
Z_SET_REFCOUNT_P(newval, 1);
/* Replace */
Z_DELREF_PP(ret);
*ret = newval;
}
Z_SET_ISREF_PP(ret);
}
return *ret;
} /* }}} */
static zval *spl_array_read_dimension(zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */
{
return spl_array_read_dimension_ex(1, object, offset, type TSRMLS_CC);
} /* }}} */
static void spl_array_write_dimension_ex(int check_inherited, zval *object, zval *offset, zval *value TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
long index;
HashTable *ht;
if (check_inherited && intern->fptr_offset_set) {
if (!offset) {
ALLOC_INIT_ZVAL(offset);
} else {
SEPARATE_ARG_IF_REF(offset);
}
zend_call_method_with_2_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_set, "offsetSet", NULL, offset, value);
zval_ptr_dtor(&offset);
return;
}
if (!offset) {
ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (ht->nApplyCount > 0) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return;
}
Z_ADDREF_P(value);
zend_hash_next_index_insert(ht, (void**)&value, sizeof(void*), NULL);
return;
}
switch(Z_TYPE_P(offset)) {
case IS_STRING:
ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (ht->nApplyCount > 0) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return;
}
Z_ADDREF_P(value);
zend_symtable_update(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void**)&value, sizeof(void*), NULL);
return;
case IS_DOUBLE:
case IS_RESOURCE:
case IS_BOOL:
case IS_LONG:
ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (ht->nApplyCount > 0) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return;
}
if (offset->type == IS_DOUBLE) {
index = (long)Z_DVAL_P(offset);
} else {
index = Z_LVAL_P(offset);
}
Z_ADDREF_P(value);
zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), NULL);
return;
case IS_NULL:
ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (ht->nApplyCount > 0) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return;
}
Z_ADDREF_P(value);
zend_hash_next_index_insert(ht, (void**)&value, sizeof(void*), NULL);
return;
default:
zend_error(E_WARNING, "Illegal offset type");
return;
}
} /* }}} */
static void spl_array_write_dimension(zval *object, zval *offset, zval *value TSRMLS_DC) /* {{{ */
{
spl_array_write_dimension_ex(1, object, offset, value TSRMLS_CC);
} /* }}} */
static void spl_array_unset_dimension_ex(int check_inherited, zval *object, zval *offset TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
long index;
HashTable *ht;
if (check_inherited && intern->fptr_offset_del) {
SEPARATE_ARG_IF_REF(offset);
zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_del, "offsetUnset", NULL, offset);
zval_ptr_dtor(&offset);
return;
}
switch(Z_TYPE_P(offset)) {
case IS_STRING:
ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (ht->nApplyCount > 0) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return;
}
if (ht == &EG(symbol_table)) {
if (zend_delete_global_variable(Z_STRVAL_P(offset), Z_STRLEN_P(offset) TSRMLS_CC)) {
zend_error(E_NOTICE,"Undefined index: %s", Z_STRVAL_P(offset));
}
} else {
if (zend_symtable_del(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1) == FAILURE) {
zend_error(E_NOTICE,"Undefined index: %s", Z_STRVAL_P(offset));
} else {
spl_array_object *obj = intern;
while (1) {
if ((obj->ar_flags & SPL_ARRAY_IS_SELF) != 0) {
break;
} else if (Z_TYPE_P(obj->array) == IS_OBJECT) {
if ((obj->ar_flags & SPL_ARRAY_USE_OTHER) == 0) {
obj = (spl_array_object*)zend_object_store_get_object(obj->array TSRMLS_CC);
break;
} else {
obj = (spl_array_object*)zend_object_store_get_object(obj->array TSRMLS_CC);
}
} else {
obj = NULL;
break;
}
}
if (obj) {
zend_property_info *property_info = zend_get_property_info(obj->std.ce, offset, 1 TSRMLS_CC);
if (property_info &&
(property_info->flags & ZEND_ACC_STATIC) == 0 &&
property_info->offset >= 0) {
obj->std.properties_table[property_info->offset] = NULL;
}
}
}
}
break;
case IS_DOUBLE:
case IS_RESOURCE:
case IS_BOOL:
case IS_LONG:
if (offset->type == IS_DOUBLE) {
index = (long)Z_DVAL_P(offset);
} else {
index = Z_LVAL_P(offset);
}
ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (ht->nApplyCount > 0) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return;
}
if (zend_hash_index_del(ht, index) == FAILURE) {
zend_error(E_NOTICE,"Undefined offset: %ld", Z_LVAL_P(offset));
}
break;
default:
zend_error(E_WARNING, "Illegal offset type");
return;
}
spl_hash_verify_pos(intern TSRMLS_CC); /* call rewind on FAILURE */
} /* }}} */
static void spl_array_unset_dimension(zval *object, zval *offset TSRMLS_DC) /* {{{ */
{
spl_array_unset_dimension_ex(1, object, offset TSRMLS_CC);
} /* }}} */
static int spl_array_has_dimension_ex(int check_inherited, zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
long index;
zval *rv, *value = NULL, **tmp;
if (check_inherited && intern->fptr_offset_has) {
zval *offset_tmp = offset;
SEPARATE_ARG_IF_REF(offset_tmp);
zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_has, "offsetExists", &rv, offset_tmp);
zval_ptr_dtor(&offset_tmp);
if (rv && zend_is_true(rv)) {
zval_ptr_dtor(&rv);
if (check_empty != 1) {
return 1;
} else if (intern->fptr_offset_get) {
value = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC);
}
} else {
if (rv) {
zval_ptr_dtor(&rv);
}
return 0;
}
}
if (!value) {
HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
switch(Z_TYPE_P(offset)) {
case IS_STRING:
if (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &tmp) != FAILURE) {
if (check_empty == 2) {
return 1;
}
} else {
return 0;
}
break;
case IS_DOUBLE:
case IS_RESOURCE:
case IS_BOOL:
case IS_LONG:
if (offset->type == IS_DOUBLE) {
index = (long)Z_DVAL_P(offset);
} else {
index = Z_LVAL_P(offset);
}
if (zend_hash_index_find(ht, index, (void **)&tmp) != FAILURE) {
if (check_empty == 2) {
return 1;
}
} else {
return 0;
}
break;
default:
zend_error(E_WARNING, "Illegal offset type");
return 0;
}
if (check_empty && check_inherited && intern->fptr_offset_get) {
value = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC);
} else {
value = *tmp;
}
}
return check_empty ? zend_is_true(value) : Z_TYPE_P(value) != IS_NULL;
} /* }}} */
static int spl_array_has_dimension(zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */
{
return spl_array_has_dimension_ex(1, object, offset, check_empty TSRMLS_CC);
} /* }}} */
/* {{{ spl_array_object_verify_pos_ex */
static inline int spl_array_object_verify_pos_ex(spl_array_object *object, HashTable *ht, const char *msg_prefix TSRMLS_DC)
{
if (!ht) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%sArray was modified outside object and is no longer an array", msg_prefix);
return FAILURE;
}
if (object->pos && (object->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(object, ht TSRMLS_CC) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%sArray was modified outside object and internal position is no longer valid", msg_prefix);
return FAILURE;
}
return SUCCESS;
} /* }}} */
/* {{{ spl_array_object_verify_pos */
static inline int spl_array_object_verify_pos(spl_array_object *object, HashTable *ht TSRMLS_DC)
{
return spl_array_object_verify_pos_ex(object, ht, "" TSRMLS_CC);
} /* }}} */
/* {{{ proto bool ArrayObject::offsetExists(mixed $index)
proto bool ArrayIterator::offsetExists(mixed $index)
Returns whether the requested $index exists. */
SPL_METHOD(Array, offsetExists)
{
zval *index;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) {
return;
}
RETURN_BOOL(spl_array_has_dimension_ex(0, getThis(), index, 2 TSRMLS_CC));
} /* }}} */
/* {{{ proto mixed ArrayObject::offsetGet(mixed $index)
proto mixed ArrayIterator::offsetGet(mixed $index)
Returns the value at the specified $index. */
SPL_METHOD(Array, offsetGet)
{
zval *index, *value;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) {
return;
}
value = spl_array_read_dimension_ex(0, getThis(), index, BP_VAR_R TSRMLS_CC);
RETURN_ZVAL(value, 1, 0);
} /* }}} */
/* {{{ proto void ArrayObject::offsetSet(mixed $index, mixed $newval)
proto void ArrayIterator::offsetSet(mixed $index, mixed $newval)
Sets the value at the specified $index to $newval. */
SPL_METHOD(Array, offsetSet)
{
zval *index, *value;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &index, &value) == FAILURE) {
return;
}
spl_array_write_dimension_ex(0, getThis(), index, value TSRMLS_CC);
} /* }}} */
void spl_array_iterator_append(zval *object, zval *append_value TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (!aht) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array");
return;
}
if (Z_TYPE_P(intern->array) == IS_OBJECT) {
php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Cannot append properties to objects, use %s::offsetSet() instead", Z_OBJCE_P(object)->name);
return;
}
spl_array_write_dimension(object, NULL, append_value TSRMLS_CC);
if (!intern->pos) {
spl_array_set_pos(intern, aht->pListTail);
}
} /* }}} */
/* {{{ proto void ArrayObject::append(mixed $newval)
proto void ArrayIterator::append(mixed $newval)
Appends the value (cannot be called for objects). */
SPL_METHOD(Array, append)
{
zval *value;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &value) == FAILURE) {
return;
}
spl_array_iterator_append(getThis(), value TSRMLS_CC);
} /* }}} */
/* {{{ proto void ArrayObject::offsetUnset(mixed $index)
proto void ArrayIterator::offsetUnset(mixed $index)
Unsets the value at the specified $index. */
SPL_METHOD(Array, offsetUnset)
{
zval *index;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) {
return;
}
spl_array_unset_dimension_ex(0, getThis(), index TSRMLS_CC);
} /* }}} */
/* {{{ proto array ArrayObject::getArrayCopy()
proto array ArrayIterator::getArrayCopy()
Return a copy of the contained array */
SPL_METHOD(Array, getArrayCopy)
{
zval *object = getThis(), *tmp;
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
array_init(return_value);
zend_hash_copy(HASH_OF(return_value), spl_array_get_hash_table(intern, 0 TSRMLS_CC), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*));
} /* }}} */
static HashTable *spl_array_get_properties(zval *object TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *result;
if (intern->nApplyCount > 1) {
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Nesting level too deep - recursive dependency?");
}
intern->nApplyCount++;
result = spl_array_get_hash_table(intern, 1 TSRMLS_CC);
intern->nApplyCount--;
return result;
} /* }}} */
static HashTable* spl_array_get_debug_info(zval *obj, int *is_temp TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(obj TSRMLS_CC);
zval *tmp, *storage;
int name_len;
char *zname;
zend_class_entry *base;
*is_temp = 0;
if (!intern->std.properties) {
rebuild_object_properties(&intern->std);
}
if (HASH_OF(intern->array) == intern->std.properties) {
return intern->std.properties;
} else {
if (intern->debug_info == NULL) {
ALLOC_HASHTABLE(intern->debug_info);
ZEND_INIT_SYMTABLE_EX(intern->debug_info, zend_hash_num_elements(intern->std.properties) + 1, 0);
}
if (intern->debug_info->nApplyCount == 0) {
zend_hash_clean(intern->debug_info);
zend_hash_copy(intern->debug_info, intern->std.properties, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *));
storage = intern->array;
zval_add_ref(&storage);
base = (Z_OBJ_HT_P(obj) == &spl_handler_ArrayIterator) ? spl_ce_ArrayIterator : spl_ce_ArrayObject;
zname = spl_gen_private_prop_name(base, "storage", sizeof("storage")-1, &name_len TSRMLS_CC);
zend_symtable_update(intern->debug_info, zname, name_len+1, &storage, sizeof(zval *), NULL);
efree(zname);
}
return intern->debug_info;
}
}
/* }}} */
static HashTable *spl_array_get_gc(zval *object, zval ***gc_data, int *gc_data_count TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
*gc_data = &intern->array;
*gc_data_count = 1;
return zend_std_get_properties(object TSRMLS_CC);
}
/* }}} */
static zval *spl_array_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0
&& !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) {
return spl_array_read_dimension(object, member, type TSRMLS_CC);
}
return std_object_handlers.read_property(object, member, type, key TSRMLS_CC);
} /* }}} */
static void spl_array_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0
&& !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) {
spl_array_write_dimension(object, member, value TSRMLS_CC);
return;
}
std_object_handlers.write_property(object, member, value, key TSRMLS_CC);
} /* }}} */
static zval **spl_array_get_property_ptr_ptr(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0
&& !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) {
return spl_array_get_dimension_ptr_ptr(1, object, member, type TSRMLS_CC);
}
return std_object_handlers.get_property_ptr_ptr(object, member, type, key TSRMLS_CC);
} /* }}} */
static int spl_array_has_property(zval *object, zval *member, int has_set_exists, const zend_literal *key TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0
&& !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) {
return spl_array_has_dimension(object, member, has_set_exists TSRMLS_CC);
}
return std_object_handlers.has_property(object, member, has_set_exists, key TSRMLS_CC);
} /* }}} */
static void spl_array_unset_property(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0
&& !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) {
spl_array_unset_dimension(object, member TSRMLS_CC);
spl_array_rewind(intern TSRMLS_CC); /* because deletion might invalidate position */
return;
}
std_object_handlers.unset_property(object, member, key TSRMLS_CC);
} /* }}} */
static int spl_array_compare_objects(zval *o1, zval *o2 TSRMLS_DC) /* {{{ */
{
HashTable *ht1,
*ht2;
spl_array_object *intern1,
*intern2;
int result = 0;
zval temp_zv;
intern1 = (spl_array_object*)zend_object_store_get_object(o1 TSRMLS_CC);
intern2 = (spl_array_object*)zend_object_store_get_object(o2 TSRMLS_CC);
ht1 = spl_array_get_hash_table(intern1, 0 TSRMLS_CC);
ht2 = spl_array_get_hash_table(intern2, 0 TSRMLS_CC);
zend_compare_symbol_tables(&temp_zv, ht1, ht2 TSRMLS_CC);
result = (int)Z_LVAL(temp_zv);
/* if we just compared std.properties, don't do it again */
if (result == 0 &&
!(ht1 == intern1->std.properties && ht2 == intern2->std.properties)) {
result = std_object_handlers.compare_objects(o1, o2 TSRMLS_CC);
}
return result;
} /* }}} */
static int spl_array_skip_protected(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */
{
char *string_key;
uint string_length;
ulong num_key;
if (Z_TYPE_P(intern->array) == IS_OBJECT) {
do {
if (zend_hash_get_current_key_ex(aht, &string_key, &string_length, &num_key, 0, &intern->pos) == HASH_KEY_IS_STRING) {
/* zend_hash_get_current_key_ex() should never set
* string_length to 0 when returning HASH_KEY_IS_STRING, but we
* may as well be defensive and consider that successful.
* Beyond that, we're looking for protected keys (which will
* have a null byte at string_key[0]), but want to avoid
* skipping completely empty keys (which will also have the
* null byte, but a string_length of 1). */
if (!string_length || string_key[0] || string_length == 1) {
return SUCCESS;
}
} else {
return SUCCESS;
}
if (zend_hash_has_more_elements_ex(aht, &intern->pos) != SUCCESS) {
return FAILURE;
}
zend_hash_move_forward_ex(aht, &intern->pos);
spl_array_update_pos(intern);
} while (1);
}
return FAILURE;
} /* }}} */
static int spl_array_next_no_verify(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */
{
zend_hash_move_forward_ex(aht, &intern->pos);
spl_array_update_pos(intern);
if (Z_TYPE_P(intern->array) == IS_OBJECT) {
return spl_array_skip_protected(intern, aht TSRMLS_CC);
} else {
return zend_hash_has_more_elements_ex(aht, &intern->pos);
}
} /* }}} */
static int spl_array_next_ex(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */
{
if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid");
return FAILURE;
}
return spl_array_next_no_verify(intern, aht TSRMLS_CC);
} /* }}} */
static int spl_array_next(spl_array_object *intern TSRMLS_DC) /* {{{ */
{
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
return spl_array_next_ex(intern, aht TSRMLS_CC);
} /* }}} */
/* define an overloaded iterator structure */
typedef struct {
zend_user_iterator intern;
spl_array_object *object;
} spl_array_it;
static void spl_array_it_dtor(zend_object_iterator *iter TSRMLS_DC) /* {{{ */
{
spl_array_it *iterator = (spl_array_it *)iter;
zend_user_it_invalidate_current(iter TSRMLS_CC);
zval_ptr_dtor((zval**)&iterator->intern.it.data);
efree(iterator);
}
/* }}} */
static int spl_array_it_valid(zend_object_iterator *iter TSRMLS_DC) /* {{{ */
{
spl_array_it *iterator = (spl_array_it *)iter;
spl_array_object *object = iterator->object;
HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC);
if (object->ar_flags & SPL_ARRAY_OVERLOADED_VALID) {
return zend_user_it_valid(iter TSRMLS_CC);
} else {
if (spl_array_object_verify_pos_ex(object, aht, "ArrayIterator::valid(): " TSRMLS_CC) == FAILURE) {
return FAILURE;
}
return zend_hash_has_more_elements_ex(aht, &object->pos);
}
}
/* }}} */
static void spl_array_it_get_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) /* {{{ */
{
spl_array_it *iterator = (spl_array_it *)iter;
spl_array_object *object = iterator->object;
HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC);
if (object->ar_flags & SPL_ARRAY_OVERLOADED_CURRENT) {
zend_user_it_get_current_data(iter, data TSRMLS_CC);
} else {
if (zend_hash_get_current_data_ex(aht, (void**)data, &object->pos) == FAILURE) {
*data = NULL;
}
}
}
/* }}} */
static void spl_array_it_get_current_key(zend_object_iterator *iter, zval *key TSRMLS_DC) /* {{{ */
{
spl_array_it *iterator = (spl_array_it *)iter;
spl_array_object *object = iterator->object;
HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC);
if (object->ar_flags & SPL_ARRAY_OVERLOADED_KEY) {
zend_user_it_get_current_key(iter, key TSRMLS_CC);
} else {
if (spl_array_object_verify_pos_ex(object, aht, "ArrayIterator::current(): " TSRMLS_CC) == FAILURE) {
ZVAL_NULL(key);
} else {
zend_hash_get_current_key_zval_ex(aht, key, &object->pos);
}
}
}
/* }}} */
static void spl_array_it_move_forward(zend_object_iterator *iter TSRMLS_DC) /* {{{ */
{
spl_array_it *iterator = (spl_array_it *)iter;
spl_array_object *object = iterator->object;
HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC);
if (object->ar_flags & SPL_ARRAY_OVERLOADED_NEXT) {
zend_user_it_move_forward(iter TSRMLS_CC);
} else {
zend_user_it_invalidate_current(iter TSRMLS_CC);
if (!aht) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::current(): Array was modified outside object and is no longer an array");
return;
}
if ((object->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(object, aht TSRMLS_CC) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::next(): Array was modified outside object and internal position is no longer valid");
} else {
spl_array_next_no_verify(object, aht TSRMLS_CC);
}
}
}
/* }}} */
static void spl_array_rewind_ex(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */
{
zend_hash_internal_pointer_reset_ex(aht, &intern->pos);
spl_array_update_pos(intern);
spl_array_skip_protected(intern, aht TSRMLS_CC);
} /* }}} */
static void spl_array_rewind(spl_array_object *intern TSRMLS_DC) /* {{{ */
{
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (!aht) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::rewind(): Array was modified outside object and is no longer an array");
return;
}
spl_array_rewind_ex(intern, aht TSRMLS_CC);
}
/* }}} */
static void spl_array_it_rewind(zend_object_iterator *iter TSRMLS_DC) /* {{{ */
{
spl_array_it *iterator = (spl_array_it *)iter;
spl_array_object *object = iterator->object;
if (object->ar_flags & SPL_ARRAY_OVERLOADED_REWIND) {
zend_user_it_rewind(iter TSRMLS_CC);
} else {
zend_user_it_invalidate_current(iter TSRMLS_CC);
spl_array_rewind(object TSRMLS_CC);
}
}
/* }}} */
/* {{{ spl_array_set_array */
static void spl_array_set_array(zval *object, spl_array_object *intern, zval **array, long ar_flags, int just_array TSRMLS_DC) {
if (Z_TYPE_PP(array) == IS_ARRAY) {
SEPARATE_ZVAL_IF_NOT_REF(array);
}
if (Z_TYPE_PP(array) == IS_OBJECT && (Z_OBJ_HT_PP(array) == &spl_handler_ArrayObject || Z_OBJ_HT_PP(array) == &spl_handler_ArrayIterator)) {
zval_ptr_dtor(&intern->array);
if (just_array) {
spl_array_object *other = (spl_array_object*)zend_object_store_get_object(*array TSRMLS_CC);
ar_flags = other->ar_flags & ~SPL_ARRAY_INT_MASK;
}
ar_flags |= SPL_ARRAY_USE_OTHER;
intern->array = *array;
} else {
if (Z_TYPE_PP(array) != IS_OBJECT && Z_TYPE_PP(array) != IS_ARRAY) {
zend_throw_exception(spl_ce_InvalidArgumentException, "Passed variable is not an array or object, using empty array instead", 0 TSRMLS_CC);
return;
}
zval_ptr_dtor(&intern->array);
intern->array = *array;
}
if (object == *array) {
intern->ar_flags |= SPL_ARRAY_IS_SELF;
intern->ar_flags &= ~SPL_ARRAY_USE_OTHER;
} else {
intern->ar_flags &= ~SPL_ARRAY_IS_SELF;
}
intern->ar_flags |= ar_flags;
Z_ADDREF_P(intern->array);
if (Z_TYPE_PP(array) == IS_OBJECT) {
zend_object_get_properties_t handler = Z_OBJ_HANDLER_PP(array, get_properties);
if ((handler != std_object_handlers.get_properties && handler != spl_array_get_properties)
|| !spl_array_get_hash_table(intern, 0 TSRMLS_CC)) {
zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Overloaded object of type %s is not compatible with %s", Z_OBJCE_PP(array)->name, intern->std.ce->name);
}
}
spl_array_rewind(intern TSRMLS_CC);
}
/* }}} */
/* iterator handler table */
zend_object_iterator_funcs spl_array_it_funcs = {
spl_array_it_dtor,
spl_array_it_valid,
spl_array_it_get_current_data,
spl_array_it_get_current_key,
spl_array_it_move_forward,
spl_array_it_rewind
};
zend_object_iterator *spl_array_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) /* {{{ */
{
spl_array_it *iterator;
spl_array_object *array_object = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if (by_ref && (array_object->ar_flags & SPL_ARRAY_OVERLOADED_CURRENT)) {
zend_error(E_ERROR, "An iterator cannot be used with foreach by reference");
}
iterator = emalloc(sizeof(spl_array_it));
Z_ADDREF_P(object);
iterator->intern.it.data = (void*)object;
iterator->intern.it.funcs = &spl_array_it_funcs;
iterator->intern.ce = ce;
iterator->intern.value = NULL;
iterator->object = array_object;
return (zend_object_iterator*)iterator;
}
/* }}} */
/* {{{ proto void ArrayObject::__construct(array|object ar = array() [, int flags = 0 [, string iterator_class = "ArrayIterator"]])
proto void ArrayIterator::__construct(array|object ar = array() [, int flags = 0])
Constructs a new array iterator from a path. */
SPL_METHOD(Array, __construct)
{
zval *object = getThis();
spl_array_object *intern;
zval **array;
long ar_flags = 0;
zend_class_entry *ce_get_iterator = spl_ce_Iterator;
zend_error_handling error_handling;
if (ZEND_NUM_ARGS() == 0) {
return; /* nothing to do */
}
zend_replace_error_handling(EH_THROW, spl_ce_InvalidArgumentException, &error_handling TSRMLS_CC);
intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z|lC", &array, &ar_flags, &ce_get_iterator) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
if (ZEND_NUM_ARGS() > 2) {
intern->ce_get_iterator = ce_get_iterator;
}
ar_flags &= ~SPL_ARRAY_INT_MASK;
spl_array_set_array(object, intern, array, ar_flags, ZEND_NUM_ARGS() == 1 TSRMLS_CC);
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
/* }}} */
/* {{{ proto void ArrayObject::setIteratorClass(string iterator_class)
Set the class used in getIterator. */
SPL_METHOD(Array, setIteratorClass)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
zend_class_entry * ce_get_iterator = spl_ce_Iterator;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "C", &ce_get_iterator) == FAILURE) {
return;
}
intern->ce_get_iterator = ce_get_iterator;
}
/* }}} */
/* {{{ proto string ArrayObject::getIteratorClass()
Get the class used in getIterator. */
SPL_METHOD(Array, getIteratorClass)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_STRING(intern->ce_get_iterator->name, 1);
}
/* }}} */
/* {{{ proto int ArrayObject::getFlags()
Get flags */
SPL_METHOD(Array, getFlags)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->ar_flags & ~SPL_ARRAY_INT_MASK);
}
/* }}} */
/* {{{ proto void ArrayObject::setFlags(int flags)
Set flags */
SPL_METHOD(Array, setFlags)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
long ar_flags = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &ar_flags) == FAILURE) {
return;
}
intern->ar_flags = (intern->ar_flags & SPL_ARRAY_INT_MASK) | (ar_flags & ~SPL_ARRAY_INT_MASK);
}
/* }}} */
/* {{{ proto Array|Object ArrayObject::exchangeArray(Array|Object ar = array())
Replace the referenced array or object with a new one and return the old one (right now copy - to be changed) */
SPL_METHOD(Array, exchangeArray)
{
zval *object = getThis(), *tmp, **array;
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
array_init(return_value);
zend_hash_copy(HASH_OF(return_value), spl_array_get_hash_table(intern, 0 TSRMLS_CC), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*));
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z", &array) == FAILURE) {
return;
}
spl_array_set_array(object, intern, array, 0L, 1 TSRMLS_CC);
}
/* }}} */
/* {{{ proto ArrayIterator ArrayObject::getIterator()
Create a new iterator from a ArrayObject instance */
SPL_METHOD(Array, getIterator)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
spl_array_object *iterator;
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (!aht) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array");
return;
}
return_value->type = IS_OBJECT;
return_value->value.obj = spl_array_object_new_ex(intern->ce_get_iterator, &iterator, object, 0 TSRMLS_CC);
Z_SET_REFCOUNT_P(return_value, 1);
Z_SET_ISREF_P(return_value);
}
/* }}} */
/* {{{ proto void ArrayIterator::rewind()
Rewind array back to the start */
SPL_METHOD(Array, rewind)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_array_rewind(intern TSRMLS_CC);
}
/* }}} */
/* {{{ proto void ArrayIterator::seek(int $position)
Seek to position. */
SPL_METHOD(Array, seek)
{
long opos, position;
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
int result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &position) == FAILURE) {
return;
}
if (!aht) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array");
return;
}
opos = position;
if (position >= 0) { /* negative values are not supported */
spl_array_rewind(intern TSRMLS_CC);
result = SUCCESS;
while (position-- > 0 && (result = spl_array_next(intern TSRMLS_CC)) == SUCCESS);
if (result == SUCCESS && zend_hash_has_more_elements_ex(aht, &intern->pos) == SUCCESS) {
return; /* ok */
}
}
zend_throw_exception_ex(spl_ce_OutOfBoundsException, 0 TSRMLS_CC, "Seek position %ld is out of range", opos);
} /* }}} */
int static spl_array_object_count_elements_helper(spl_array_object *intern, long *count TSRMLS_DC) /* {{{ */
{
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
HashPosition pos;
if (!aht) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array");
*count = 0;
return FAILURE;
}
if (Z_TYPE_P(intern->array) == IS_OBJECT) {
/* We need to store the 'pos' since we'll modify it in the functions
* we're going to call and which do not support 'pos' as parameter. */
pos = intern->pos;
*count = 0;
spl_array_rewind(intern TSRMLS_CC);
while(intern->pos && spl_array_next(intern TSRMLS_CC) == SUCCESS) {
(*count)++;
}
spl_array_set_pos(intern, pos);
return SUCCESS;
} else {
*count = zend_hash_num_elements(aht);
return SUCCESS;
}
} /* }}} */
int spl_array_object_count_elements(zval *object, long *count TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if (intern->fptr_count) {
zval *rv;
zend_call_method_with_0_params(&object, intern->std.ce, &intern->fptr_count, "count", &rv);
if (rv) {
zval_ptr_dtor(&intern->retval);
MAKE_STD_ZVAL(intern->retval);
ZVAL_ZVAL(intern->retval, rv, 1, 1);
convert_to_long(intern->retval);
*count = (long) Z_LVAL_P(intern->retval);
return SUCCESS;
}
*count = 0;
return FAILURE;
}
return spl_array_object_count_elements_helper(intern, count TSRMLS_CC);
} /* }}} */
/* {{{ proto int ArrayObject::count()
proto int ArrayIterator::count()
Return the number of elements in the Iterator. */
SPL_METHOD(Array, count)
{
long count;
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_array_object_count_elements_helper(intern, &count TSRMLS_CC);
RETURN_LONG(count);
} /* }}} */
static void spl_array_method(INTERNAL_FUNCTION_PARAMETERS, char *fname, int fname_len, int use_arg) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
zval *tmp, *arg = NULL;
zval *retval_ptr = NULL;
MAKE_STD_ZVAL(tmp);
Z_TYPE_P(tmp) = IS_ARRAY;
Z_ARRVAL_P(tmp) = aht;
if (!use_arg) {
aht->nApplyCount++;
zend_call_method(NULL, NULL, NULL, fname, fname_len, &retval_ptr, 1, tmp, NULL TSRMLS_CC);
aht->nApplyCount--;
} else if (use_arg == SPL_ARRAY_METHOD_MAY_USER_ARG) {
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "|z", &arg) == FAILURE) {
Z_TYPE_P(tmp) = IS_NULL;
zval_ptr_dtor(&tmp);
zend_throw_exception(spl_ce_BadMethodCallException, "Function expects one argument at most", 0 TSRMLS_CC);
return;
}
aht->nApplyCount++;
zend_call_method(NULL, NULL, NULL, fname, fname_len, &retval_ptr, arg? 2 : 1, tmp, arg TSRMLS_CC);
aht->nApplyCount--;
} else {
if (ZEND_NUM_ARGS() != 1 || zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "z", &arg) == FAILURE) {
Z_TYPE_P(tmp) = IS_NULL;
zval_ptr_dtor(&tmp);
zend_throw_exception(spl_ce_BadMethodCallException, "Function expects exactly one argument", 0 TSRMLS_CC);
return;
}
aht->nApplyCount++;
zend_call_method(NULL, NULL, NULL, fname, fname_len, &retval_ptr, 2, tmp, arg TSRMLS_CC);
aht->nApplyCount--;
}
Z_TYPE_P(tmp) = IS_NULL; /* we want to destroy the zval, not the hashtable */
zval_ptr_dtor(&tmp);
if (retval_ptr) {
COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr);
}
} /* }}} */
#define SPL_ARRAY_METHOD(cname, fname, use_arg) \
SPL_METHOD(cname, fname) \
{ \
spl_array_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, #fname, sizeof(#fname)-1, use_arg); \
}
/* {{{ proto int ArrayObject::asort([int $sort_flags = SORT_REGULAR ])
proto int ArrayIterator::asort([int $sort_flags = SORT_REGULAR ])
Sort the entries by values. */
SPL_ARRAY_METHOD(Array, asort, SPL_ARRAY_METHOD_MAY_USER_ARG) /* }}} */
/* {{{ proto int ArrayObject::ksort([int $sort_flags = SORT_REGULAR ])
proto int ArrayIterator::ksort([int $sort_flags = SORT_REGULAR ])
Sort the entries by key. */
SPL_ARRAY_METHOD(Array, ksort, SPL_ARRAY_METHOD_MAY_USER_ARG) /* }}} */
/* {{{ proto int ArrayObject::uasort(callback cmp_function)
proto int ArrayIterator::uasort(callback cmp_function)
Sort the entries by values user defined function. */
SPL_ARRAY_METHOD(Array, uasort, SPL_ARRAY_METHOD_USE_ARG) /* }}} */
/* {{{ proto int ArrayObject::uksort(callback cmp_function)
proto int ArrayIterator::uksort(callback cmp_function)
Sort the entries by key using user defined function. */
SPL_ARRAY_METHOD(Array, uksort, SPL_ARRAY_METHOD_USE_ARG) /* }}} */
/* {{{ proto int ArrayObject::natsort()
proto int ArrayIterator::natsort()
Sort the entries by values using "natural order" algorithm. */
SPL_ARRAY_METHOD(Array, natsort, SPL_ARRAY_METHOD_NO_ARG) /* }}} */
/* {{{ proto int ArrayObject::natcasesort()
proto int ArrayIterator::natcasesort()
Sort the entries by key using case insensitive "natural order" algorithm. */
SPL_ARRAY_METHOD(Array, natcasesort, SPL_ARRAY_METHOD_NO_ARG) /* }}} */
/* {{{ proto mixed|NULL ArrayIterator::current()
Return current array entry */
SPL_METHOD(Array, current)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
zval **entry;
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (spl_array_object_verify_pos(intern, aht TSRMLS_CC) == FAILURE) {
return;
}
if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) {
return;
}
RETVAL_ZVAL(*entry, 1, 0);
}
/* }}} */
/* {{{ proto mixed|NULL ArrayIterator::key()
Return current array key */
SPL_METHOD(Array, key)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_array_iterator_key(getThis(), return_value TSRMLS_CC);
} /* }}} */
void spl_array_iterator_key(zval *object, zval *return_value TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (spl_array_object_verify_pos(intern, aht TSRMLS_CC) == FAILURE) {
return;
}
zend_hash_get_current_key_zval_ex(aht, return_value, &intern->pos);
}
/* }}} */
/* {{{ proto void ArrayIterator::next()
Move to next entry */
SPL_METHOD(Array, next)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (spl_array_object_verify_pos(intern, aht TSRMLS_CC) == FAILURE) {
return;
}
spl_array_next_no_verify(intern, aht TSRMLS_CC);
}
/* }}} */
/* {{{ proto bool ArrayIterator::valid()
Check whether array contains more entries */
SPL_METHOD(Array, valid)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (spl_array_object_verify_pos(intern, aht TSRMLS_CC) == FAILURE) {
RETURN_FALSE;
} else {
RETURN_BOOL(zend_hash_has_more_elements_ex(aht, &intern->pos) == SUCCESS);
}
}
/* }}} */
/* {{{ proto bool RecursiveArrayIterator::hasChildren()
Check whether current element has children (e.g. is an array) */
SPL_METHOD(Array, hasChildren)
{
zval *object = getThis(), **entry;
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (spl_array_object_verify_pos(intern, aht TSRMLS_CC) == FAILURE) {
RETURN_FALSE;
}
if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) {
RETURN_FALSE;
}
RETURN_BOOL(Z_TYPE_PP(entry) == IS_ARRAY || (Z_TYPE_PP(entry) == IS_OBJECT && (intern->ar_flags & SPL_ARRAY_CHILD_ARRAYS_ONLY) == 0));
}
/* }}} */
/* {{{ proto object RecursiveArrayIterator::getChildren()
Create a sub iterator for the current element (same class as $this) */
SPL_METHOD(Array, getChildren)
{
zval *object = getThis(), **entry, *flags;
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (spl_array_object_verify_pos(intern, aht TSRMLS_CC) == FAILURE) {
return;
}
if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) {
return;
}
if (Z_TYPE_PP(entry) == IS_OBJECT) {
if ((intern->ar_flags & SPL_ARRAY_CHILD_ARRAYS_ONLY) != 0) {
return;
}
if (instanceof_function(Z_OBJCE_PP(entry), Z_OBJCE_P(getThis()) TSRMLS_CC)) {
RETURN_ZVAL(*entry, 1, 0);
}
}
MAKE_STD_ZVAL(flags);
ZVAL_LONG(flags, SPL_ARRAY_USE_OTHER | intern->ar_flags);
spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, *entry, flags TSRMLS_CC);
zval_ptr_dtor(&flags);
}
/* }}} */
/* {{{ proto string ArrayObject::serialize()
Serialize the object */
SPL_METHOD(Array, serialize)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
zval members, *pmembers;
php_serialize_data_t var_hash;
smart_str buf = {0};
zval *flags;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (!aht) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array");
return;
}
PHP_VAR_SERIALIZE_INIT(var_hash);
MAKE_STD_ZVAL(flags);
ZVAL_LONG(flags, (intern->ar_flags & SPL_ARRAY_CLONE_MASK));
/* storage */
smart_str_appendl(&buf, "x:", 2);
php_var_serialize(&buf, &flags, &var_hash TSRMLS_CC);
zval_ptr_dtor(&flags);
if (!(intern->ar_flags & SPL_ARRAY_IS_SELF)) {
php_var_serialize(&buf, &intern->array, &var_hash TSRMLS_CC);
smart_str_appendc(&buf, ';');
}
/* members */
smart_str_appendl(&buf, "m:", 2);
INIT_PZVAL(&members);
if (!intern->std.properties) {
rebuild_object_properties(&intern->std);
}
Z_ARRVAL(members) = intern->std.properties;
Z_TYPE(members) = IS_ARRAY;
pmembers = &members;
php_var_serialize(&buf, &pmembers, &var_hash TSRMLS_CC); /* finishes the string */
/* done */
PHP_VAR_SERIALIZE_DESTROY(var_hash);
if (buf.c) {
RETURN_STRINGL(buf.c, buf.len, 0);
}
RETURN_NULL();
} /* }}} */
/* {{{ proto void ArrayObject::unserialize(string serialized)
* unserialize the object
*/
SPL_METHOD(Array, unserialize)
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *buf;
int buf_len;
const unsigned char *p, *s;
php_unserialize_data_t var_hash;
zval *pmembers, *pflags = NULL;
HashTable *aht;
long flags;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) {
return;
}
if (buf_len == 0) {
return;
}
aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (aht->nApplyCount > 0) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return;
}
/* storage */
s = p = (const unsigned char*)buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (*p!= 'x' || *++p != ':') {
goto outexcept;
}
++p;
ALLOC_INIT_ZVAL(pflags);
if (!php_var_unserialize(&pflags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pflags) != IS_LONG) {
goto outexcept;
}
var_push_dtor(&var_hash, &pflags);
--p; /* for ';' */
flags = Z_LVAL_P(pflags);
/* flags needs to be verified and we also need to verify whether the next
* thing we get is ';'. After that we require an 'm' or somethign else
* where 'm' stands for members and anything else should be an array. If
* neither 'a' or 'm' follows we have an error. */
if (*p != ';') {
goto outexcept;
}
++p;
if (*p!='m') {
if (*p!='a' && *p!='O' && *p!='C' && *p!='r') {
goto outexcept;
}
intern->ar_flags &= ~SPL_ARRAY_CLONE_MASK;
intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK;
zval_ptr_dtor(&intern->array);
ALLOC_INIT_ZVAL(intern->array);
if (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC)
|| (Z_TYPE_P(intern->array) != IS_ARRAY && Z_TYPE_P(intern->array) != IS_OBJECT)) {
zval_ptr_dtor(&intern->array);
goto outexcept;
}
var_push_dtor(&var_hash, &intern->array);
}
if (*p != ';') {
goto outexcept;
}
++p;
/* members */
if (*p!= 'm' || *++p != ':') {
goto outexcept;
}
++p;
ALLOC_INIT_ZVAL(pmembers);
if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pmembers) != IS_ARRAY) {
zval_ptr_dtor(&pmembers);
goto outexcept;
}
var_push_dtor(&var_hash, &pmembers);
/* copy members */
if (!intern->std.properties) {
rebuild_object_properties(&intern->std);
}
zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *));
zval_ptr_dtor(&pmembers);
/* done reading $serialized */
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (pflags) {
zval_ptr_dtor(&pflags);
}
return;
outexcept:
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (pflags) {
zval_ptr_dtor(&pflags);
}
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len);
return;
} /* }}} */
/* {{{ arginfo and function table */
ZEND_BEGIN_ARG_INFO_EX(arginfo_array___construct, 0, 0, 0)
ZEND_ARG_INFO(0, array)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_array_offsetGet, 0, 0, 1)
ZEND_ARG_INFO(0, index)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_array_offsetSet, 0, 0, 2)
ZEND_ARG_INFO(0, index)
ZEND_ARG_INFO(0, newval)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_array_append, 0)
ZEND_ARG_INFO(0, value)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_array_seek, 0)
ZEND_ARG_INFO(0, position)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_array_exchangeArray, 0)
ZEND_ARG_INFO(0, array)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_array_setFlags, 0)
ZEND_ARG_INFO(0, flags)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_array_setIteratorClass, 0)
ZEND_ARG_INFO(0, iteratorClass)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_array_uXsort, 0)
ZEND_ARG_INFO(0, cmp_function)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_array_unserialize, 0)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_array_void, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry spl_funcs_ArrayObject[] = {
SPL_ME(Array, __construct, arginfo_array___construct, ZEND_ACC_PUBLIC)
SPL_ME(Array, offsetExists, arginfo_array_offsetGet, ZEND_ACC_PUBLIC)
SPL_ME(Array, offsetGet, arginfo_array_offsetGet, ZEND_ACC_PUBLIC)
SPL_ME(Array, offsetSet, arginfo_array_offsetSet, ZEND_ACC_PUBLIC)
SPL_ME(Array, offsetUnset, arginfo_array_offsetGet, ZEND_ACC_PUBLIC)
SPL_ME(Array, append, arginfo_array_append, ZEND_ACC_PUBLIC)
SPL_ME(Array, getArrayCopy, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, count, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, getFlags, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, setFlags, arginfo_array_setFlags, ZEND_ACC_PUBLIC)
SPL_ME(Array, asort, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, ksort, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, uasort, arginfo_array_uXsort, ZEND_ACC_PUBLIC)
SPL_ME(Array, uksort, arginfo_array_uXsort, ZEND_ACC_PUBLIC)
SPL_ME(Array, natsort, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, natcasesort, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, unserialize, arginfo_array_unserialize, ZEND_ACC_PUBLIC)
SPL_ME(Array, serialize, arginfo_array_void, ZEND_ACC_PUBLIC)
/* ArrayObject specific */
SPL_ME(Array, getIterator, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, exchangeArray, arginfo_array_exchangeArray, ZEND_ACC_PUBLIC)
SPL_ME(Array, setIteratorClass, arginfo_array_setIteratorClass, ZEND_ACC_PUBLIC)
SPL_ME(Array, getIteratorClass, arginfo_array_void, ZEND_ACC_PUBLIC)
PHP_FE_END
};
static const zend_function_entry spl_funcs_ArrayIterator[] = {
SPL_ME(Array, __construct, arginfo_array___construct, ZEND_ACC_PUBLIC)
SPL_ME(Array, offsetExists, arginfo_array_offsetGet, ZEND_ACC_PUBLIC)
SPL_ME(Array, offsetGet, arginfo_array_offsetGet, ZEND_ACC_PUBLIC)
SPL_ME(Array, offsetSet, arginfo_array_offsetSet, ZEND_ACC_PUBLIC)
SPL_ME(Array, offsetUnset, arginfo_array_offsetGet, ZEND_ACC_PUBLIC)
SPL_ME(Array, append, arginfo_array_append, ZEND_ACC_PUBLIC)
SPL_ME(Array, getArrayCopy, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, count, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, getFlags, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, setFlags, arginfo_array_setFlags, ZEND_ACC_PUBLIC)
SPL_ME(Array, asort, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, ksort, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, uasort, arginfo_array_uXsort, ZEND_ACC_PUBLIC)
SPL_ME(Array, uksort, arginfo_array_uXsort, ZEND_ACC_PUBLIC)
SPL_ME(Array, natsort, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, natcasesort, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, unserialize, arginfo_array_unserialize, ZEND_ACC_PUBLIC)
SPL_ME(Array, serialize, arginfo_array_void, ZEND_ACC_PUBLIC)
/* ArrayIterator specific */
SPL_ME(Array, rewind, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, current, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, key, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, next, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, valid, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, seek, arginfo_array_seek, ZEND_ACC_PUBLIC)
PHP_FE_END
};
static const zend_function_entry spl_funcs_RecursiveArrayIterator[] = {
SPL_ME(Array, hasChildren, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, getChildren, arginfo_array_void, ZEND_ACC_PUBLIC)
PHP_FE_END
};
/* }}} */
/* {{{ PHP_MINIT_FUNCTION(spl_array) */
PHP_MINIT_FUNCTION(spl_array)
{
REGISTER_SPL_STD_CLASS_EX(ArrayObject, spl_array_object_new, spl_funcs_ArrayObject);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Aggregate);
REGISTER_SPL_IMPLEMENTS(ArrayObject, ArrayAccess);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Serializable);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Countable);
memcpy(&spl_handler_ArrayObject, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
spl_handler_ArrayObject.clone_obj = spl_array_object_clone;
spl_handler_ArrayObject.read_dimension = spl_array_read_dimension;
spl_handler_ArrayObject.write_dimension = spl_array_write_dimension;
spl_handler_ArrayObject.unset_dimension = spl_array_unset_dimension;
spl_handler_ArrayObject.has_dimension = spl_array_has_dimension;
spl_handler_ArrayObject.count_elements = spl_array_object_count_elements;
spl_handler_ArrayObject.get_properties = spl_array_get_properties;
spl_handler_ArrayObject.get_debug_info = spl_array_get_debug_info;
spl_handler_ArrayObject.get_gc = spl_array_get_gc;
spl_handler_ArrayObject.read_property = spl_array_read_property;
spl_handler_ArrayObject.write_property = spl_array_write_property;
spl_handler_ArrayObject.get_property_ptr_ptr = spl_array_get_property_ptr_ptr;
spl_handler_ArrayObject.has_property = spl_array_has_property;
spl_handler_ArrayObject.unset_property = spl_array_unset_property;
spl_handler_ArrayObject.compare_objects = spl_array_compare_objects;
REGISTER_SPL_STD_CLASS_EX(ArrayIterator, spl_array_object_new, spl_funcs_ArrayIterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Iterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, ArrayAccess);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, SeekableIterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Serializable);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Countable);
memcpy(&spl_handler_ArrayIterator, &spl_handler_ArrayObject, sizeof(zend_object_handlers));
spl_ce_ArrayIterator->get_iterator = spl_array_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(RecursiveArrayIterator, ArrayIterator, spl_array_object_new, spl_funcs_RecursiveArrayIterator);
REGISTER_SPL_IMPLEMENTS(RecursiveArrayIterator, RecursiveIterator);
spl_ce_RecursiveArrayIterator->get_iterator = spl_array_get_iterator;
REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST);
REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS);
REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST);
REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS);
REGISTER_SPL_CLASS_CONST_LONG(RecursiveArrayIterator, "CHILD_ARRAYS_ONLY", SPL_ARRAY_CHILD_ARRAYS_ONLY);
return SUCCESS;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: fdm=marker
* vim: noet sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5285_0 |
crossvul-cpp_data_good_2627_0 | /*
* Copyright (c) 1994-2008 Carnegie Mellon University. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The name "Carnegie Mellon University" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For permission or any legal
* details, please contact
* Carnegie Mellon University
* Center for Technology Transfer and Enterprise Creation
* 4615 Forbes Avenue
* Suite 302
* Pittsburgh, PA 15213
* (412) 268-7393, fax: (412) 268-7395
* innovation@andrew.cmu.edu
*
* 4. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Computing Services
* at Carnegie Mellon University (http://www.cmu.edu/computing/)."
*
* CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <config.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <syslog.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <stdbool.h>
#include <errno.h>
#include <sasl/sasl.h>
#ifdef HAVE_SSL
#include <openssl/hmac.h>
#include <openssl/rand.h>
#endif /* HAVE_SSL */
#include "acl.h"
#include "annotate.h"
#include "append.h"
#include "auth.h"
#ifdef USE_AUTOCREATE
#include "autocreate.h"
#endif // USE_AUTOCREATE
#include "assert.h"
#include "backend.h"
#include "bsearch.h"
#include "bufarray.h"
#include "charset.h"
#include "dlist.h"
#include "exitcodes.h"
#include "idle.h"
#include "global.h"
#include "times.h"
#include "proxy.h"
#include "imap_proxy.h"
#include "imapd.h"
#include "imapurl.h"
#include "imparse.h"
#include "index.h"
#include "mailbox.h"
#include "message.h"
#include "mboxevent.h"
#include "mboxkey.h"
#include "mboxlist.h"
#include "mboxname.h"
#include "mbdump.h"
#include "mupdate-client.h"
#include "partlist.h"
#include "proc.h"
#include "quota.h"
#include "seen.h"
#include "statuscache.h"
#include "sync_log.h"
#include "sync_support.h"
#include "telemetry.h"
#include "tls.h"
#include "user.h"
#include "userdeny.h"
#include "util.h"
#include "version.h"
#include "xmalloc.h"
#include "xstrlcat.h"
#include "xstrlcpy.h"
#include "ptrarray.h"
#include "xstats.h"
/* generated headers are not necessarily in current directory */
#include "imap/imap_err.h"
#include "imap/pushstats.h" /* SNMP interface */
#include "iostat.h"
extern int optind;
extern char *optarg;
/* global state */
const int config_need_data = CONFIG_NEED_PARTITION_DATA;
static int imaps = 0;
static sasl_ssf_t extprops_ssf = 0;
static int nosaslpasswdcheck = 0;
static int apns_enabled = 0;
/* PROXY STUFF */
/* we want a list of our outgoing connections here and which one we're
currently piping */
static const int ultraparanoid = 1; /* should we kick after every operation? */
unsigned int proxy_cmdcnt;
static int referral_kick = 0; /* kick after next command recieved, for
referrals that are likely to change the
mailbox list */
/* global conversations database holder to avoid re-opening during
* status command or list responses */
struct conversations_state *global_conversations = NULL;
/* all subscription commands go to the backend server containing the
user's inbox */
struct backend *backend_inbox = NULL;
/* the current server most commands go to */
struct backend *backend_current = NULL;
/* our cached connections */
struct backend **backend_cached = NULL;
/* cached connection to mupdate master (for multiple XFER and MUPDATEPUSH) */
static mupdate_handle *mupdate_h = NULL;
/* are we doing virtdomains with multiple IPs? */
static int disable_referrals;
/* has the client issued an RLIST, RLSUB, or LIST (REMOTE)? */
static int supports_referrals;
/* end PROXY STUFF */
/* per-user/session state */
static int imapd_timeout;
struct protstream *imapd_out = NULL;
struct protstream *imapd_in = NULL;
static struct protgroup *protin = NULL;
static const char *imapd_clienthost = "[local]";
static int imapd_logfd = -1;
char *imapd_userid = NULL, *proxy_userid = NULL;
static char *imapd_magicplus = NULL;
struct auth_state *imapd_authstate = 0;
static int imapd_userisadmin = 0;
static int imapd_userisproxyadmin = 0;
static sasl_conn_t *imapd_saslconn; /* the sasl connection context */
static int imapd_starttls_done = 0; /* have we done a successful starttls? */
static int imapd_tls_required = 0; /* is tls required? */
static void *imapd_tls_comp = NULL; /* TLS compression method, if any */
static int imapd_compress_done = 0; /* have we done a successful compress? */
static const char *plaintextloginalert = NULL;
static int ignorequota = 0;
#define QUIRK_SEARCHFUZZY (1<<0)
static struct id_data {
struct attvaluelist *params;
int did_id;
int quirks;
} imapd_id;
#ifdef HAVE_SSL
/* our tls connection, if any */
static SSL *tls_conn = NULL;
#endif /* HAVE_SSL */
/* stage(s) for APPEND */
struct appendstage {
struct stagemsg *stage;
FILE *f;
strarray_t flags;
time_t internaldate;
int binary;
struct entryattlist *annotations;
};
static ptrarray_t stages = PTRARRAY_INITIALIZER;
/* the sasl proxy policy context */
static struct proxy_context imapd_proxyctx = {
1, 1, &imapd_authstate, &imapd_userisadmin, &imapd_userisproxyadmin
};
/* current sub-user state */
static struct index_state *imapd_index;
/* current namespace */
struct namespace imapd_namespace;
/* track if we're idling */
static int idling = 0;
const struct mbox_name_attribute mbox_name_attributes[] = {
/* from RFC 3501 */
{ MBOX_ATTRIBUTE_NOINFERIORS, "\\Noinferiors" },
{ MBOX_ATTRIBUTE_NOSELECT, "\\Noselect" },
{ MBOX_ATTRIBUTE_MARKED, "\\Marked" },
{ MBOX_ATTRIBUTE_UNMARKED, "\\Unmarked" },
/* from RFC 5258 */
{ MBOX_ATTRIBUTE_NONEXISTENT, "\\NonExistent" },
{ MBOX_ATTRIBUTE_SUBSCRIBED, "\\Subscribed" },
{ MBOX_ATTRIBUTE_REMOTE, "\\Remote" },
{ MBOX_ATTRIBUTE_HASCHILDREN, "\\HasChildren" },
{ MBOX_ATTRIBUTE_HASNOCHILDREN, "\\HasNoChildren" },
{ 0, NULL }
};
/*
* These bitmasks define how List selection options can be combined:
* list_select_mod_opts may only be used if at least one list_select_base_opt
* is also present.
* For example, (RECURSIVEMATCH) and (RECURSIVEMATCH REMOTE) are invalid, but
* (RECURSIVEMATCH SUBSCRIBED) is ok.
*/
static const int list_select_base_opts = LIST_SEL_SUBSCRIBED;
static const int list_select_mod_opts = LIST_SEL_RECURSIVEMATCH;
/* structure that list_data passes its callbacks */
struct list_rock {
struct listargs *listargs;
strarray_t *subs;
char *last_name;
mbentry_t *last_mbentry;
uint32_t last_attributes;
int last_category;
hash_table server_table; /* for proxying */
};
/* Information about one mailbox name that LIST returns */
struct list_entry {
const char *name;
uint32_t attributes; /* bitmap of MBOX_ATTRIBUTE_* */
};
/* structure that list_data_recursivematch passes its callbacks */
struct list_rock_recursivematch {
struct listargs *listargs;
struct hash_table table; /* maps mailbox names to attributes (uint32_t *) */
int count; /* # of entries in table */
struct list_entry *array;
};
/* CAPABILITIES are defined here, not including TLS/SASL ones,
and those that are configurable */
enum {
CAPA_PREAUTH = 0x1,
CAPA_POSTAUTH = 0x2
};
struct capa_struct {
const char *str;
int mask;
};
static struct capa_struct base_capabilities[] = {
/* pre-auth capabilities */
{ "IMAP4rev1", 3 },
{ "LITERAL+", 3 },
{ "ID", 3 },
{ "ENABLE", 3 },
/* post-auth capabilities */
{ "ACL", 2 },
{ "RIGHTS=kxten", 2 },
{ "QUOTA", 2 },
{ "MAILBOX-REFERRALS", 2 },
{ "NAMESPACE", 2 },
{ "UIDPLUS", 2 },
{ "NO_ATOMIC_RENAME", 2 },
{ "UNSELECT", 2 },
{ "CHILDREN", 2 },
{ "MULTIAPPEND", 2 },
{ "BINARY", 2 },
{ "CATENATE", 2 },
{ "CONDSTORE", 2 },
{ "ESEARCH", 2 },
{ "SEARCH=FUZZY", 2 }, /* RFC 6203 */
{ "SORT", 2 },
{ "SORT=MODSEQ", 2 },
{ "SORT=DISPLAY", 2 },
{ "SORT=UID", 2 }, /* not standard */
{ "THREAD=ORDEREDSUBJECT", 2 },
{ "THREAD=REFERENCES", 2 },
{ "THREAD=REFS", 2 }, /* draft-ietf-morg-inthread */
{ "ANNOTATEMORE", 2 },
{ "ANNOTATE-EXPERIMENT-1", 2 },
{ "METADATA", 2 },
{ "LIST-EXTENDED", 2 },
{ "LIST-STATUS", 2 },
{ "LIST-MYRIGHTS", 2 }, /* not standard */
{ "LIST-METADATA", 2 }, /* not standard */
{ "WITHIN", 2 },
{ "QRESYNC", 2 },
{ "SCAN", 2 },
{ "XLIST", 2 }, /* not standard */
{ "XMOVE", 2 }, /* not standard */
{ "MOVE", 2 },
{ "SPECIAL-USE", 2 },
{ "CREATE-SPECIAL-USE", 2 },
{ "DIGEST=SHA1", 2 }, /* not standard */
{ "X-REPLICATION", 2 }, /* not standard */
#ifdef HAVE_SSL
{ "URLAUTH", 2 },
{ "URLAUTH=BINARY", 2 },
#endif
/* keep this to mark the end of the list */
{ 0, 0 }
};
static void motd_file(void);
void shut_down(int code);
void fatal(const char *s, int code);
static void cmdloop(void);
static void cmd_login(char *tag, char *user);
static void cmd_authenticate(char *tag, char *authtype, char *resp);
static void cmd_noop(char *tag, char *cmd);
static void capa_response(int flags);
static void cmd_capability(char *tag);
static void cmd_append(char *tag, char *name, const char *cur_name);
static void cmd_select(char *tag, char *cmd, char *name);
static void cmd_close(char *tag, char *cmd);
static int parse_fetch_args(const char *tag, const char *cmd,
int allow_vanished,
struct fetchargs *fa);
static void cmd_fetch(char *tag, char *sequence, int usinguid);
static void cmd_store(char *tag, char *sequence, int usinguid);
static void cmd_search(char *tag, int usinguid);
static void cmd_sort(char *tag, int usinguid);
static void cmd_thread(char *tag, int usinguid);
static void cmd_copy(char *tag, char *sequence, char *name, int usinguid, int ismove);
static void cmd_expunge(char *tag, char *sequence);
static void cmd_create(char *tag, char *name, struct dlist *extargs, int localonly);
static void cmd_delete(char *tag, char *name, int localonly, int force);
static void cmd_dump(char *tag, char *name, int uid_start);
static void cmd_undump(char *tag, char *name);
static void cmd_xfer(const char *tag, const char *name,
const char *toserver, const char *topart);
static void cmd_rename(char *tag, char *oldname, char *newname, char *partition);
static void cmd_reconstruct(const char *tag, const char *name, int recursive);
static void getlistargs(char *tag, struct listargs *listargs);
static void cmd_list(char *tag, struct listargs *listargs);
static void cmd_changesub(char *tag, char *namespace, char *name, int add);
static void cmd_getacl(const char *tag, const char *name);
static void cmd_listrights(char *tag, char *name, char *identifier);
static void cmd_myrights(const char *tag, const char *name);
static void cmd_setacl(char *tag, const char *name,
const char *identifier, const char *rights);
static void cmd_getquota(const char *tag, const char *name);
static void cmd_getquotaroot(const char *tag, const char *name);
static void cmd_setquota(const char *tag, const char *quotaroot);
static void cmd_status(char *tag, char *name);
static void cmd_namespace(char* tag);
static void cmd_mupdatepush(char *tag, char *name);
static void cmd_id(char* tag);
static void cmd_idle(char* tag);
static void cmd_starttls(char *tag, int imaps);
static void cmd_xconvsort(char *tag, int updates);
static void cmd_xconvmultisort(char *tag);
static void cmd_xconvmeta(const char *tag);
static void cmd_xconvfetch(const char *tag);
static int do_xconvfetch(struct dlist *cidlist,
modseq_t ifchangedsince,
struct fetchargs *fetchargs);
static void cmd_xsnippets(char *tag);
static void cmd_xstats(char *tag, int c);
static void cmd_xapplepushservice(const char *tag,
struct applepushserviceargs *applepushserviceargs);
static void cmd_xbackup(const char *tag, const char *mailbox,
const char *channel);
#ifdef HAVE_SSL
static void cmd_urlfetch(char *tag);
static void cmd_genurlauth(char *tag);
static void cmd_resetkey(char *tag, char *mailbox, char *mechanism);
#endif
#ifdef HAVE_ZLIB
static void cmd_compress(char *tag, char *alg);
#endif
static void cmd_getannotation(const char* tag, char *mboxpat);
static void cmd_getmetadata(const char* tag);
static void cmd_setannotation(const char* tag, char *mboxpat);
static void cmd_setmetadata(const char* tag, char *mboxpat);
static void cmd_xrunannotator(const char *tag, const char *sequence,
int usinguid);
static void cmd_xwarmup(const char *tag);
static void cmd_enable(char* tag);
static void cmd_syncget(const char *tag, struct dlist *kl);
static void cmd_syncapply(const char *tag, struct dlist *kl,
struct sync_reserve_list *reserve_list);
static void cmd_syncrestart(const char *tag, struct sync_reserve_list **reserve_listp,
int realloc);
static void cmd_syncrestore(const char *tag, struct dlist *kin,
struct sync_reserve_list *reserve_list);
static void cmd_xkillmy(const char *tag, const char *cmdname);
static void cmd_xforever(const char *tag);
static void cmd_xmeid(const char *tag, const char *id);
static int parsecreateargs(struct dlist **extargs);
static int parse_annotate_fetch_data(const char *tag,
int permessage_flag,
strarray_t *entries,
strarray_t *attribs);
static int parse_metadata_string_or_list(const char *tag,
strarray_t *sa,
int *is_list);
static int parse_annotate_store_data(const char *tag,
int permessage_flag,
struct entryattlist **entryatts);
static int parse_metadata_store_data(const char *tag,
struct entryattlist **entryatts);
static int getlistselopts(char *tag, struct listargs *args);
static int getlistretopts(char *tag, struct listargs *args);
static int get_snippetargs(struct snippetargs **sap);
static void free_snippetargs(struct snippetargs **sap);
static int getsortcriteria(char *tag, struct sortcrit **sortcrit);
static int getdatetime(time_t *date);
static int parse_windowargs(const char *tag, struct windowargs **, int);
static void free_windowargs(struct windowargs *wa);
static void appendfieldlist(struct fieldlist **l, char *section,
strarray_t *fields, char *trail,
void *d, size_t size);
static void freefieldlist(struct fieldlist *l);
void freestrlist(struct strlist *l);
static int set_haschildren(const mbentry_t *entry, void *rock);
static char *canonical_list_pattern(const char *reference,
const char *pattern);
static void canonical_list_patterns(const char *reference,
strarray_t *patterns);
static int list_cb(struct findall_data *data, void *rock);
static int subscribed_cb(struct findall_data *data, void *rock);
static void list_data(struct listargs *listargs);
static int list_data_remote(struct backend *be, char *tag,
struct listargs *listargs, strarray_t *subs);
static void clear_id();
extern int saslserver(sasl_conn_t *conn, const char *mech,
const char *init_resp, const char *resp_prefix,
const char *continuation, const char *empty_resp,
struct protstream *pin, struct protstream *pout,
int *sasl_result, char **success_data);
/* Enable the resetting of a sasl_conn_t */
static int reset_saslconn(sasl_conn_t **conn);
static struct
{
char *ipremoteport;
char *iplocalport;
sasl_ssf_t ssf;
char *authid;
} saslprops = {NULL,NULL,0,NULL};
static int imapd_canon_user(sasl_conn_t *conn, void *context,
const char *user, unsigned ulen,
unsigned flags, const char *user_realm,
char *out, unsigned out_max, unsigned *out_ulen)
{
char userbuf[MAX_MAILBOX_BUFFER], *p;
size_t n;
int r;
if (!ulen) ulen = strlen(user);
if (config_getswitch(IMAPOPT_IMAPMAGICPLUS)) {
/* make a working copy of the auth[z]id */
if (ulen >= MAX_MAILBOX_BUFFER) {
sasl_seterror(conn, 0, "buffer overflow while canonicalizing");
return SASL_BUFOVER;
}
memcpy(userbuf, user, ulen);
userbuf[ulen] = '\0';
user = userbuf;
/* See if we're using the magic plus */
if ((p = strchr(userbuf, '+'))) {
n = config_virtdomains ? strcspn(p, "@") : strlen(p);
if (flags & SASL_CU_AUTHZID) {
/* make a copy of the magic plus */
if (imapd_magicplus) free(imapd_magicplus);
imapd_magicplus = xstrndup(p, n);
}
/* strip the magic plus from the auth[z]id */
memmove(p, p+n, strlen(p+n)+1);
ulen -= n;
}
}
r = mysasl_canon_user(conn, context, user, ulen, flags, user_realm,
out, out_max, out_ulen);
if (!r && imapd_magicplus && flags == SASL_CU_AUTHZID) {
/* If we're only doing the authzid, put back the magic plus
in case its used in the challenge/response calculation */
n = strlen(imapd_magicplus);
if (*out_ulen + n > out_max) {
sasl_seterror(conn, 0, "buffer overflow while canonicalizing");
r = SASL_BUFOVER;
}
else {
p = (config_virtdomains && (p = strchr(out, '@'))) ?
p : out + *out_ulen;
memmove(p+n, p, strlen(p)+1);
memcpy(p, imapd_magicplus, n);
*out_ulen += n;
}
}
return r;
}
static int imapd_proxy_policy(sasl_conn_t *conn,
void *context,
const char *requested_user, unsigned rlen,
const char *auth_identity, unsigned alen,
const char *def_realm,
unsigned urlen,
struct propctx *propctx)
{
char userbuf[MAX_MAILBOX_BUFFER];
if (config_getswitch(IMAPOPT_IMAPMAGICPLUS)) {
size_t n;
char *p;
/* make a working copy of the authzid */
if (!rlen) rlen = strlen(requested_user);
if (rlen >= MAX_MAILBOX_BUFFER) {
sasl_seterror(conn, 0, "buffer overflow while proxying");
return SASL_BUFOVER;
}
memcpy(userbuf, requested_user, rlen);
userbuf[rlen] = '\0';
requested_user = userbuf;
/* See if we're using the magic plus */
if ((p = strchr(userbuf, '+'))) {
n = config_virtdomains ? strcspn(p, "@") : strlen(p);
/* strip the magic plus from the authzid */
memmove(p, p+n, strlen(p+n)+1);
rlen -= n;
}
}
return mysasl_proxy_policy(conn, context, requested_user, rlen,
auth_identity, alen, def_realm, urlen, propctx);
}
static int imapd_sasl_log(void *context __attribute__((unused)),
int level, const char *message)
{
int syslog_level = LOG_INFO;
switch (level) {
case SASL_LOG_ERR:
case SASL_LOG_FAIL:
syslog_level = LOG_ERR;
break;
case SASL_LOG_WARN:
syslog_level = LOG_WARNING;
break;
case SASL_LOG_DEBUG:
case SASL_LOG_TRACE:
case SASL_LOG_PASS:
syslog_level = LOG_DEBUG;
break;
}
syslog(syslog_level, "SASL %s", message);
return SASL_OK;
}
static const struct sasl_callback mysasl_cb[] = {
{ SASL_CB_GETOPT, (mysasl_cb_ft *) &mysasl_config, NULL },
{ SASL_CB_PROXY_POLICY, (mysasl_cb_ft *) &imapd_proxy_policy, (void*) &imapd_proxyctx },
{ SASL_CB_CANON_USER, (mysasl_cb_ft *) &imapd_canon_user, (void*) &disable_referrals },
{ SASL_CB_LOG, (mysasl_cb_ft *) &imapd_sasl_log, NULL },
{ SASL_CB_LIST_END, NULL, NULL }
};
/* imapd_refer() issues a referral to the client. */
static void imapd_refer(const char *tag,
const char *server,
const char *mailbox)
{
struct imapurl imapurl;
char url[MAX_MAILBOX_PATH+1];
memset(&imapurl, 0, sizeof(struct imapurl));
imapurl.server = server;
imapurl.mailbox = mailbox;
imapurl.auth = !strcmp(imapd_userid, "anonymous") ? "anonymous" : "*";
imapurl_toURL(url, &imapurl);
prot_printf(imapd_out, "%s NO [REFERRAL %s] Remote mailbox.\r\n",
tag, url);
free(imapurl.freeme);
}
/* wrapper for mboxlist_lookup that will force a referral if we are remote
* returns IMAP_SERVER_UNAVAILABLE if we don't have a place to send the client
* (that'd be a bug).
* returns IMAP_MAILBOX_MOVED if we referred the client */
/* ext_name is the external name of the mailbox */
/* you can avoid referring the client by setting tag or ext_name to NULL. */
static int mlookup(const char *tag, const char *ext_name,
const char *name, mbentry_t **mbentryptr)
{
int r;
mbentry_t *mbentry = NULL;
r = mboxlist_lookup(name, &mbentry, NULL);
if ((r == IMAP_MAILBOX_NONEXISTENT || (!r && (mbentry->mbtype & MBTYPE_RESERVE))) &&
config_mupdate_server) {
/* It is not currently active, make sure we have the most recent
* copy of the database */
kick_mupdate();
mboxlist_entry_free(&mbentry);
r = mboxlist_lookup(name, &mbentry, NULL);
}
if (r) goto done;
if (mbentry->mbtype & MBTYPE_RESERVE) {
r = IMAP_MAILBOX_RESERVED;
}
else if (mbentry->mbtype & MBTYPE_DELETED) {
r = IMAP_MAILBOX_NONEXISTENT;
}
else if (mbentry->mbtype & MBTYPE_MOVING) {
/* do we have rights on the mailbox? */
if (!imapd_userisadmin &&
(!mbentry->acl || !(cyrus_acl_myrights(imapd_authstate, mbentry->acl) & ACL_LOOKUP))) {
r = IMAP_MAILBOX_NONEXISTENT;
} else if (tag && ext_name && mbentry->server) {
imapd_refer(tag, mbentry->server, ext_name);
r = IMAP_MAILBOX_MOVED;
} else if (config_mupdate_server) {
r = IMAP_SERVER_UNAVAILABLE;
} else {
r = IMAP_MAILBOX_NOTSUPPORTED;
}
}
done:
if (r) mboxlist_entry_free(&mbentry);
else if (mbentryptr) *mbentryptr = mbentry;
else mboxlist_entry_free(&mbentry); /* we don't actually want it! */
return r;
}
static void imapd_reset(void)
{
int i;
int bytes_in = 0;
int bytes_out = 0;
proc_cleanup();
/* close backend connections */
i = 0;
while (backend_cached && backend_cached[i]) {
proxy_downserver(backend_cached[i]);
if (backend_cached[i]->last_result.s) {
free(backend_cached[i]->last_result.s);
}
free(backend_cached[i]);
i++;
}
if (backend_cached) free(backend_cached);
backend_cached = NULL;
backend_inbox = backend_current = NULL;
if (mupdate_h) mupdate_disconnect(&mupdate_h);
mupdate_h = NULL;
proxy_cmdcnt = 0;
disable_referrals = 0;
supports_referrals = 0;
if (imapd_index) index_close(&imapd_index);
if (imapd_in) {
/* Flush the incoming buffer */
prot_NONBLOCK(imapd_in);
prot_fill(imapd_in);
bytes_in = prot_bytes_in(imapd_in);
prot_free(imapd_in);
}
if (imapd_out) {
/* Flush the outgoing buffer */
prot_flush(imapd_out);
bytes_out = prot_bytes_out(imapd_out);
prot_free(imapd_out);
}
if (config_auditlog)
syslog(LOG_NOTICE, "auditlog: traffic sessionid=<%s> bytes_in=<%d> bytes_out=<%d>",
session_id(), bytes_in, bytes_out);
imapd_in = imapd_out = NULL;
if (protin) protgroup_reset(protin);
#ifdef HAVE_SSL
if (tls_conn) {
if (tls_reset_servertls(&tls_conn) == -1) {
fatal("tls_reset() failed", EC_TEMPFAIL);
}
tls_conn = NULL;
}
#endif
cyrus_reset_stdio();
imapd_clienthost = "[local]";
if (imapd_logfd != -1) {
close(imapd_logfd);
imapd_logfd = -1;
}
if (imapd_userid != NULL) {
free(imapd_userid);
imapd_userid = NULL;
}
if (proxy_userid != NULL) {
free(proxy_userid);
proxy_userid = NULL;
}
if (imapd_magicplus != NULL) {
free(imapd_magicplus);
imapd_magicplus = NULL;
}
if (imapd_authstate) {
auth_freestate(imapd_authstate);
imapd_authstate = NULL;
}
imapd_userisadmin = 0;
imapd_userisproxyadmin = 0;
client_capa = 0;
if (imapd_saslconn) {
sasl_dispose(&imapd_saslconn);
free(imapd_saslconn);
imapd_saslconn = NULL;
}
imapd_compress_done = 0;
imapd_tls_comp = NULL;
imapd_starttls_done = 0;
plaintextloginalert = NULL;
if(saslprops.iplocalport) {
free(saslprops.iplocalport);
saslprops.iplocalport = NULL;
}
if(saslprops.ipremoteport) {
free(saslprops.ipremoteport);
saslprops.ipremoteport = NULL;
}
if(saslprops.authid) {
free(saslprops.authid);
saslprops.authid = NULL;
}
saslprops.ssf = 0;
clear_id();
}
/*
* run once when process is forked;
* MUST NOT exit directly; must return with non-zero error code
*/
int service_init(int argc, char **argv, char **envp)
{
int opt, events;
if (geteuid() == 0) fatal("must run as the Cyrus user", EC_USAGE);
setproctitle_init(argc, argv, envp);
/* set signal handlers */
signals_set_shutdown(&shut_down);
signal(SIGPIPE, SIG_IGN);
/* load the SASL plugins */
global_sasl_init(1, 1, mysasl_cb);
/* open the mboxlist, we'll need it for real work */
mboxlist_init(0);
mboxlist_open(NULL);
/* open the quota db, we'll need it for real work */
quotadb_init(0);
quotadb_open(NULL);
/* open the user deny db */
denydb_init(0);
denydb_open(0);
/* setup for sending IMAP IDLE notifications */
idle_init();
/* setup for mailbox event notifications */
events = mboxevent_init();
apns_enabled =
(events & EVENT_APPLEPUSHSERVICE) && config_getstring(IMAPOPT_APS_TOPIC);
search_attr_init();
/* create connection to the SNMP listener, if available. */
snmp_connect(); /* ignore return code */
snmp_set_str(SERVER_NAME_VERSION,cyrus_version());
while ((opt = getopt(argc, argv, "Np:sq")) != EOF) {
switch (opt) {
case 's': /* imaps (do starttls right away) */
imaps = 1;
if (!tls_enabled()) {
syslog(LOG_ERR, "imaps: required OpenSSL options not present");
fatal("imaps: required OpenSSL options not present",
EC_CONFIG);
}
break;
case 'p': /* external protection */
extprops_ssf = atoi(optarg);
break;
case 'N': /* bypass SASL password check. Not recommended unless
* you know what you're doing! */
nosaslpasswdcheck = 1;
break;
case 'q': /* don't enforce quotas */
ignorequota = 1;
break;
default:
break;
}
}
/* Initialize the annotatemore extention */
if (config_mupdate_server)
annotate_init(annotate_fetch_proxy, annotate_store_proxy);
else
annotate_init(NULL, NULL);
annotatemore_open();
if (config_getswitch(IMAPOPT_STATUSCACHE)) {
statuscache_open();
}
/* Create a protgroup for input from the client and selected backend */
protin = protgroup_new(2);
return 0;
}
/*
* run for each accepted connection
*/
#ifdef ID_SAVE_CMDLINE
int service_main(int argc, char **argv, char **envp __attribute__((unused)))
#else
int service_main(int argc __attribute__((unused)),
char **argv __attribute__((unused)),
char **envp __attribute__((unused)))
#endif
{
sasl_security_properties_t *secprops = NULL;
const char *localip, *remoteip;
struct mboxevent *mboxevent = NULL;
struct io_count *io_count_start = NULL;
struct io_count *io_count_stop = NULL;
if (config_iolog) {
io_count_start = xmalloc (sizeof (struct io_count));
io_count_stop = xmalloc (sizeof (struct io_count));
read_io_count(io_count_start);
}
session_new_id();
signals_poll();
#ifdef ID_SAVE_CMDLINE
/* get command line args for use in ID before getopt mangles them */
id_getcmdline(argc, argv);
#endif
sync_log_init();
imapd_in = prot_new(0, 0);
imapd_out = prot_new(1, 1);
protgroup_insert(protin, imapd_in);
/* Find out name of client host */
imapd_clienthost = get_clienthost(0, &localip, &remoteip);
/* create the SASL connection */
if (sasl_server_new("imap", config_servername,
NULL, NULL, NULL, NULL, 0,
&imapd_saslconn) != SASL_OK) {
fatal("SASL failed initializing: sasl_server_new()", EC_TEMPFAIL);
}
secprops = mysasl_secprops(0);
if (sasl_setprop(imapd_saslconn, SASL_SEC_PROPS, secprops) != SASL_OK)
fatal("Failed to set SASL property", EC_TEMPFAIL);
if (sasl_setprop(imapd_saslconn, SASL_SSF_EXTERNAL, &extprops_ssf) != SASL_OK)
fatal("Failed to set SASL property", EC_TEMPFAIL);
if (localip && remoteip) {
sasl_setprop(imapd_saslconn, SASL_IPREMOTEPORT, remoteip);
saslprops.ipremoteport = xstrdup(remoteip);
sasl_setprop(imapd_saslconn, SASL_IPLOCALPORT, localip);
saslprops.iplocalport = xstrdup(localip);
}
imapd_tls_required = config_getswitch(IMAPOPT_TLS_REQUIRED);
proc_register(config_ident, imapd_clienthost, NULL, NULL, NULL);
/* Set inactivity timer */
imapd_timeout = config_getint(IMAPOPT_TIMEOUT);
if (imapd_timeout < 30) imapd_timeout = 30;
imapd_timeout *= 60;
prot_settimeout(imapd_in, imapd_timeout);
prot_setflushonread(imapd_in, imapd_out);
/* we were connected on imaps port so we should do
TLS negotiation immediately */
if (imaps == 1) cmd_starttls(NULL, 1);
snmp_increment(TOTAL_CONNECTIONS, 1);
snmp_increment(ACTIVE_CONNECTIONS, 1);
/* Setup a default namespace until replaced after authentication. */
mboxname_init_namespace(&imapd_namespace, /*isadmin*/1);
mboxevent_setnamespace(&imapd_namespace);
cmdloop();
/* LOGOUT executed */
prot_flush(imapd_out);
snmp_increment(ACTIVE_CONNECTIONS, -1);
/* send a Logout event notification */
if ((mboxevent = mboxevent_new(EVENT_LOGOUT))) {
mboxevent_set_access(mboxevent, saslprops.iplocalport,
saslprops.ipremoteport, imapd_userid, NULL, 1);
mboxevent_notify(&mboxevent);
mboxevent_free(&mboxevent);
}
/* cleanup */
imapd_reset();
if (config_iolog) {
read_io_count(io_count_stop);
syslog(LOG_INFO,
"IMAP session stats : I/O read : %d bytes : I/O write : %d bytes",
io_count_stop->io_read_count - io_count_start->io_read_count,
io_count_stop->io_write_count - io_count_start->io_write_count);
free (io_count_start);
free (io_count_stop);
}
return 0;
}
/* Called by service API to shut down the service */
void service_abort(int error)
{
shut_down(error);
}
/*
* Try to find a motd file; if found spit out message as an [ALERT]
*/
static void motd_file(void)
{
char *filename = NULL;
int fd = -1;
struct protstream *motd_in = NULL;
char buf[MAX_MAILBOX_PATH+1];
char *p;
filename = strconcat(config_dir, "/msg/motd", (char *)NULL);
fd = open(filename, O_RDONLY, 0);
if (fd < 0)
goto out;
motd_in = prot_new(fd, 0);
prot_fgets(buf, sizeof(buf), motd_in);
if ((p = strchr(buf, '\r'))!=NULL) *p = 0;
if ((p = strchr(buf, '\n'))!=NULL) *p = 0;
for (p = buf; *p == '['; p++); /* can't have [ be first char, sigh */
prot_printf(imapd_out, "* OK [ALERT] %s\r\n", p);
out:
if (motd_in)
prot_free(motd_in);
if (fd >= 0)
close(fd);
free(filename);
}
/*
* Cleanly shut down and exit
*/
void shut_down(int code) __attribute__((noreturn));
void shut_down(int code)
{
int i;
int bytes_in = 0;
int bytes_out = 0;
in_shutdown = 1;
proc_cleanup();
i = 0;
while (backend_cached && backend_cached[i]) {
proxy_downserver(backend_cached[i]);
if (backend_cached[i]->last_result.s) {
free(backend_cached[i]->last_result.s);
}
free(backend_cached[i]);
i++;
}
if (backend_cached) free(backend_cached);
if (mupdate_h) mupdate_disconnect(&mupdate_h);
if (idling)
idle_stop(index_mboxname(imapd_index));
if (imapd_index) index_close(&imapd_index);
sync_log_done();
seen_done();
mboxkey_done();
mboxlist_close();
mboxlist_done();
quotadb_close();
quotadb_done();
denydb_close();
denydb_done();
annotatemore_close();
annotate_done();
idle_done();
if (config_getswitch(IMAPOPT_STATUSCACHE)) {
statuscache_close();
statuscache_done();
}
partlist_local_done();
if (imapd_in) {
/* Flush the incoming buffer */
prot_NONBLOCK(imapd_in);
prot_fill(imapd_in);
bytes_in = prot_bytes_in(imapd_in);
prot_free(imapd_in);
}
if (imapd_out) {
/* Flush the outgoing buffer */
prot_flush(imapd_out);
bytes_out = prot_bytes_out(imapd_out);
prot_free(imapd_out);
/* one less active connection */
snmp_increment(ACTIVE_CONNECTIONS, -1);
}
if (config_auditlog)
syslog(LOG_NOTICE, "auditlog: traffic sessionid=<%s> bytes_in=<%d> bytes_out=<%d>",
session_id(), bytes_in, bytes_out);
if (protin) protgroup_free(protin);
#ifdef HAVE_SSL
tls_shutdown_serverengine();
#endif
cyrus_done();
exit(code);
}
EXPORTED void fatal(const char *s, int code)
{
static int recurse_code = 0;
if (recurse_code) {
/* We were called recursively. Just give up */
proc_cleanup();
snmp_increment(ACTIVE_CONNECTIONS, -1);
exit(recurse_code);
}
recurse_code = code;
if (imapd_out) {
prot_printf(imapd_out, "* BYE Fatal error: %s\r\n", s);
prot_flush(imapd_out);
}
if (stages.count) {
/* Cleanup the stage(s) */
struct appendstage *curstage;
while ((curstage = ptrarray_pop(&stages))) {
if (curstage->f != NULL) fclose(curstage->f);
append_removestage(curstage->stage);
strarray_fini(&curstage->flags);
freeentryatts(curstage->annotations);
free(curstage);
}
ptrarray_fini(&stages);
}
syslog(LOG_ERR, "Fatal error: %s", s);
shut_down(code);
}
/*
* Check the currently selected mailbox for updates.
*
* 'be' is the backend (if any) that we just proxied a command to.
*/
static void imapd_check(struct backend *be, int usinguid)
{
if (backend_current && backend_current != be) {
/* remote mailbox */
char mytag[128];
proxy_gentag(mytag, sizeof(mytag));
prot_printf(backend_current->out, "%s Noop\r\n", mytag);
pipe_until_tag(backend_current, mytag, 0);
}
else {
/* local mailbox */
index_check(imapd_index, usinguid, 0);
}
}
/*
* Top-level command loop parsing
*/
static void cmdloop(void)
{
int c;
int usinguid, havepartition, havenamespace, recursive;
static struct buf tag, cmd, arg1, arg2, arg3;
char *p, shut[MAX_MAILBOX_PATH+1], cmdname[100];
const char *err;
const char * commandmintimer;
double commandmintimerd = 0.0;
struct sync_reserve_list *reserve_list =
sync_reserve_list_create(SYNC_MESSAGE_LIST_HASH_SIZE);
struct applepushserviceargs applepushserviceargs;
prot_printf(imapd_out, "* OK [CAPABILITY ");
capa_response(CAPA_PREAUTH);
prot_printf(imapd_out, "]");
if (config_serverinfo) prot_printf(imapd_out, " %s", config_servername);
if (config_serverinfo == IMAP_ENUM_SERVERINFO_ON) {
prot_printf(imapd_out, " Cyrus IMAP %s", cyrus_version());
}
prot_printf(imapd_out, " server ready\r\n");
/* clear cancelled flag if present before the next command */
cmd_cancelled();
motd_file();
/* Get command timer logging paramater. This string
* is a time in seconds. Any command that takes >=
* this time to execute is logged */
commandmintimer = config_getstring(IMAPOPT_COMMANDMINTIMER);
cmdtime_settimer(commandmintimer ? 1 : 0);
if (commandmintimer) {
commandmintimerd = atof(commandmintimer);
}
for (;;) {
/* Release any held index */
index_release(imapd_index);
/* Flush any buffered output */
prot_flush(imapd_out);
if (backend_current) prot_flush(backend_current->out);
/* command no longer running */
proc_register(config_ident, imapd_clienthost, imapd_userid, index_mboxname(imapd_index), NULL);
/* Check for shutdown file */
if ( !imapd_userisadmin && imapd_userid &&
(shutdown_file(shut, sizeof(shut)) ||
userdeny(imapd_userid, config_ident, shut, sizeof(shut)))) {
for (p = shut; *p == '['; p++); /* can't have [ be first char */
prot_printf(imapd_out, "* BYE [ALERT] %s\r\n", p);
telemetry_rusage(imapd_userid);
shut_down(0);
}
signals_poll();
if (!proxy_check_input(protin, imapd_in, imapd_out,
backend_current ? backend_current->in : NULL,
NULL, 0)) {
/* No input from client */
continue;
}
/* Parse tag */
c = getword(imapd_in, &tag);
if (c == EOF) {
if ((err = prot_error(imapd_in))!=NULL
&& strcmp(err, PROT_EOF_STRING)) {
syslog(LOG_WARNING, "%s, closing connection", err);
prot_printf(imapd_out, "* BYE %s\r\n", err);
}
goto done;
}
if (c != ' ' || !imparse_isatom(tag.s) || (tag.s[0] == '*' && !tag.s[1])) {
prot_printf(imapd_out, "* BAD Invalid tag\r\n");
eatline(imapd_in, c);
continue;
}
/* Parse command name */
c = getword(imapd_in, &cmd);
if (!cmd.s[0]) {
prot_printf(imapd_out, "%s BAD Null command\r\n", tag.s);
eatline(imapd_in, c);
continue;
}
lcase(cmd.s);
xstrncpy(cmdname, cmd.s, 99);
cmd.s[0] = toupper((unsigned char) cmd.s[0]);
if (config_getswitch(IMAPOPT_CHATTY))
syslog(LOG_NOTICE, "command: %s %s", tag.s, cmd.s);
proc_register(config_ident, imapd_clienthost, imapd_userid, index_mboxname(imapd_index), cmd.s);
/* if we need to force a kick, do so */
if (referral_kick) {
kick_mupdate();
referral_kick = 0;
}
if (plaintextloginalert) {
prot_printf(imapd_out, "* OK [ALERT] %s\r\n",
plaintextloginalert);
plaintextloginalert = NULL;
}
/* Only Authenticate/Enable/Login/Logout/Noop/Capability/Id/Starttls
allowed when not logged in */
if (!imapd_userid && !strchr("AELNCIS", cmd.s[0])) goto nologin;
/* Start command timer */
cmdtime_starttimer();
/* note that about half the commands (the common ones that don't
hit the mailboxes file) now close the mailboxes file just in
case it was open. */
switch (cmd.s[0]) {
case 'A':
if (!strcmp(cmd.s, "Authenticate")) {
int haveinitresp = 0;
if (c != ' ') goto missingargs;
c = getword(imapd_in, &arg1);
if (!imparse_isatom(arg1.s)) {
prot_printf(imapd_out, "%s BAD Invalid authenticate mechanism\r\n", tag.s);
eatline(imapd_in, c);
continue;
}
if (c == ' ') {
haveinitresp = 1;
c = getword(imapd_in, &arg2);
if (c == EOF) goto missingargs;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
if (imapd_userid) {
prot_printf(imapd_out, "%s BAD Already authenticated\r\n", tag.s);
continue;
}
cmd_authenticate(tag.s, arg1.s, haveinitresp ? arg2.s : NULL);
snmp_increment(AUTHENTICATE_COUNT, 1);
}
else if (!imapd_userid) goto nologin;
else if (!strcmp(cmd.s, "Append")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_append(tag.s, arg1.s, NULL);
snmp_increment(APPEND_COUNT, 1);
}
else goto badcmd;
break;
case 'C':
if (!strcmp(cmd.s, "Capability")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_capability(tag.s);
snmp_increment(CAPABILITY_COUNT, 1);
}
else if (!imapd_userid) goto nologin;
#ifdef HAVE_ZLIB
else if (!strcmp(cmd.s, "Compress")) {
if (c != ' ') goto missingargs;
c = getword(imapd_in, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_compress(tag.s, arg1.s);
snmp_increment(COMPRESS_COUNT, 1);
}
#endif /* HAVE_ZLIB */
else if (!strcmp(cmd.s, "Check")) {
if (!imapd_index && !backend_current) goto nomailbox;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_noop(tag.s, cmd.s);
snmp_increment(CHECK_COUNT, 1);
}
else if (!strcmp(cmd.s, "Copy")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
copy:
c = getword(imapd_in, &arg1);
if (c == '\r') goto missingargs;
if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_copy(tag.s, arg1.s, arg2.s, usinguid, /*ismove*/0);
snmp_increment(COPY_COUNT, 1);
}
else if (!strcmp(cmd.s, "Create")) {
struct dlist *extargs = NULL;
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == ' ') {
c = parsecreateargs(&extargs);
if (c == EOF) goto badpartition;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_create(tag.s, arg1.s, extargs, 0);
dlist_free(&extargs);
snmp_increment(CREATE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Close")) {
if (!imapd_index && !backend_current) goto nomailbox;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_close(tag.s, cmd.s);
snmp_increment(CLOSE_COUNT, 1);
}
else goto badcmd;
break;
case 'D':
if (!strcmp(cmd.s, "Delete")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_delete(tag.s, arg1.s, 0, 0);
snmp_increment(DELETE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Deleteacl")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_setacl(tag.s, arg1.s, arg2.s, NULL);
snmp_increment(DELETEACL_COUNT, 1);
}
else if (!strcmp(cmd.s, "Dump")) {
int uid_start = 0;
if(c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if(c == ' ') {
c = getastring(imapd_in, imapd_out, &arg2);
if(!imparse_isnumber(arg2.s)) goto extraargs;
uid_start = atoi(arg2.s);
}
if(c == '\r') c = prot_getc(imapd_in);
if(c != '\n') goto extraargs;
cmd_dump(tag.s, arg1.s, uid_start);
/* snmp_increment(DUMP_COUNT, 1);*/
}
else goto badcmd;
break;
case 'E':
if (!imapd_userid) goto nologin;
else if (!strcmp(cmd.s, "Enable")) {
if (c != ' ') goto missingargs;
cmd_enable(tag.s);
}
else if (!strcmp(cmd.s, "Expunge")) {
if (!imapd_index && !backend_current) goto nomailbox;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_expunge(tag.s, 0);
snmp_increment(EXPUNGE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Examine")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
prot_ungetc(c, imapd_in);
cmd_select(tag.s, cmd.s, arg1.s);
snmp_increment(EXAMINE_COUNT, 1);
}
else goto badcmd;
break;
case 'F':
if (!strcmp(cmd.s, "Fetch")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
fetch:
c = getword(imapd_in, &arg1);
if (c == '\r') goto missingargs;
if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence;
cmd_fetch(tag.s, arg1.s, usinguid);
snmp_increment(FETCH_COUNT, 1);
}
else goto badcmd;
break;
case 'G':
if (!strcmp(cmd.s, "Getacl")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_getacl(tag.s, arg1.s);
snmp_increment(GETACL_COUNT, 1);
}
else if (!strcmp(cmd.s, "Getannotation")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_getannotation(tag.s, arg1.s);
snmp_increment(GETANNOTATION_COUNT, 1);
}
else if (!strcmp(cmd.s, "Getmetadata")) {
if (c != ' ') goto missingargs;
cmd_getmetadata(tag.s);
snmp_increment(GETANNOTATION_COUNT, 1);
}
else if (!strcmp(cmd.s, "Getquota")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_getquota(tag.s, arg1.s);
snmp_increment(GETQUOTA_COUNT, 1);
}
else if (!strcmp(cmd.s, "Getquotaroot")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_getquotaroot(tag.s, arg1.s);
snmp_increment(GETQUOTAROOT_COUNT, 1);
}
#ifdef HAVE_SSL
else if (!strcmp(cmd.s, "Genurlauth")) {
if (c != ' ') goto missingargs;
cmd_genurlauth(tag.s);
/* snmp_increment(GENURLAUTH_COUNT, 1);*/
}
#endif
else goto badcmd;
break;
case 'I':
if (!strcmp(cmd.s, "Id")) {
if (c != ' ') goto missingargs;
cmd_id(tag.s);
snmp_increment(ID_COUNT, 1);
}
else if (!imapd_userid) goto nologin;
else if (!strcmp(cmd.s, "Idle") && idle_enabled()) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_idle(tag.s);
snmp_increment(IDLE_COUNT, 1);
}
else goto badcmd;
break;
case 'L':
if (!strcmp(cmd.s, "Login")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if(c != ' ') goto missingargs;
cmd_login(tag.s, arg1.s);
snmp_increment(LOGIN_COUNT, 1);
}
else if (!strcmp(cmd.s, "Logout")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
snmp_increment(LOGOUT_COUNT, 1);
/* force any responses from our selected backend */
if (backend_current) imapd_check(NULL, 0);
prot_printf(imapd_out, "* BYE %s\r\n",
error_message(IMAP_BYE_LOGOUT));
prot_printf(imapd_out, "%s OK %s\r\n", tag.s,
error_message(IMAP_OK_COMPLETED));
if (imapd_userid && *imapd_userid) {
telemetry_rusage(imapd_userid);
}
goto done;
}
else if (!imapd_userid) goto nologin;
else if (!strcmp(cmd.s, "List")) {
struct listargs listargs;
if (c != ' ') goto missingargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.ret = LIST_RET_CHILDREN;
getlistargs(tag.s, &listargs);
if (listargs.pat.count) cmd_list(tag.s, &listargs);
snmp_increment(LIST_COUNT, 1);
}
else if (!strcmp(cmd.s, "Lsub")) {
struct listargs listargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.cmd = LIST_CMD_LSUB;
listargs.sel = LIST_SEL_SUBSCRIBED;
if (!strcasecmpsafe(imapd_magicplus, "+dav"))
listargs.sel |= LIST_SEL_DAV;
listargs.ref = arg1.s;
strarray_append(&listargs.pat, arg2.s);
cmd_list(tag.s, &listargs);
snmp_increment(LSUB_COUNT, 1);
}
else if (!strcmp(cmd.s, "Listrights")) {
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_listrights(tag.s, arg1.s, arg2.s);
snmp_increment(LISTRIGHTS_COUNT, 1);
}
else if (!strcmp(cmd.s, "Localappend")) {
/* create a local-only mailbox */
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c != ' ') goto missingargs;
cmd_append(tag.s, arg1.s, *arg2.s ? arg2.s : NULL);
snmp_increment(APPEND_COUNT, 1);
}
else if (!strcmp(cmd.s, "Localcreate")) {
/* create a local-only mailbox */
struct dlist *extargs = NULL;
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == ' ') {
c = parsecreateargs(&extargs);
if (c == EOF) goto badpartition;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_create(tag.s, arg1.s, extargs, 1);
dlist_free(&extargs);
/* xxxx snmp_increment(CREATE_COUNT, 1); */
}
else if (!strcmp(cmd.s, "Localdelete")) {
/* delete a mailbox locally only */
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_delete(tag.s, arg1.s, 1, 1);
/* xxxx snmp_increment(DELETE_COUNT, 1); */
}
else goto badcmd;
break;
case 'M':
if (!strcmp(cmd.s, "Myrights")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_myrights(tag.s, arg1.s);
/* xxxx snmp_increment(MYRIGHTS_COUNT, 1); */
}
else if (!strcmp(cmd.s, "Mupdatepush")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if(c == EOF) goto missingargs;
if(c == '\r') c = prot_getc(imapd_in);
if(c != '\n') goto extraargs;
cmd_mupdatepush(tag.s, arg1.s);
/* xxxx snmp_increment(MUPDATEPUSH_COUNT, 1); */
}
else if (!strcmp(cmd.s, "Move")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
move:
c = getword(imapd_in, &arg1);
if (c == '\r') goto missingargs;
if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_copy(tag.s, arg1.s, arg2.s, usinguid, /*ismove*/1);
snmp_increment(COPY_COUNT, 1);
} else goto badcmd;
break;
case 'N':
if (!strcmp(cmd.s, "Noop")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_noop(tag.s, cmd.s);
/* xxxx snmp_increment(NOOP_COUNT, 1); */
}
else if (!imapd_userid) goto nologin;
else if (!strcmp(cmd.s, "Namespace")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_namespace(tag.s);
/* xxxx snmp_increment(NAMESPACE_COUNT, 1); */
}
else goto badcmd;
break;
case 'R':
if (!strcmp(cmd.s, "Rename")) {
havepartition = 0;
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == EOF) goto missingargs;
if (c == ' ') {
havepartition = 1;
c = getword(imapd_in, &arg3);
if (!imparse_isatom(arg3.s)) goto badpartition;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_rename(tag.s, arg1.s, arg2.s, havepartition ? arg3.s : 0);
/* xxxx snmp_increment(RENAME_COUNT, 1); */
} else if(!strcmp(cmd.s, "Reconstruct")) {
recursive = 0;
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if(c == ' ') {
/* Optional RECURSEIVE argument */
c = getword(imapd_in, &arg2);
if(!imparse_isatom(arg2.s))
goto extraargs;
else if(!strcasecmp(arg2.s, "RECURSIVE"))
recursive = 1;
else
goto extraargs;
}
if(c == '\r') c = prot_getc(imapd_in);
if(c != '\n') goto extraargs;
cmd_reconstruct(tag.s, arg1.s, recursive);
/* snmp_increment(RECONSTRUCT_COUNT, 1); */
}
else if (!strcmp(cmd.s, "Rlist")) {
struct listargs listargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.sel = LIST_SEL_REMOTE;
listargs.ret = LIST_RET_CHILDREN;
listargs.ref = arg1.s;
strarray_append(&listargs.pat, arg2.s);
cmd_list(tag.s, &listargs);
/* snmp_increment(LIST_COUNT, 1); */
}
else if (!strcmp(cmd.s, "Rlsub")) {
struct listargs listargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.cmd = LIST_CMD_LSUB;
listargs.sel = LIST_SEL_REMOTE | LIST_SEL_SUBSCRIBED;
listargs.ref = arg1.s;
strarray_append(&listargs.pat, arg2.s);
cmd_list(tag.s, &listargs);
/* snmp_increment(LSUB_COUNT, 1); */
}
#ifdef HAVE_SSL
else if (!strcmp(cmd.s, "Resetkey")) {
int have_mbox = 0, have_mech = 0;
if (c == ' ') {
have_mbox = 1;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == ' ') {
have_mech = 1;
c = getword(imapd_in, &arg2);
}
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_resetkey(tag.s, have_mbox ? arg1.s : 0,
have_mech ? arg2.s : 0);
/* snmp_increment(RESETKEY_COUNT, 1);*/
}
#endif
else goto badcmd;
break;
case 'S':
if (!strcmp(cmd.s, "Starttls")) {
if (!tls_enabled()) {
/* we don't support starttls */
goto badcmd;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
/* XXX discard any input pipelined after STARTTLS */
prot_flush(imapd_in);
/* if we've already done SASL fail */
if (imapd_userid != NULL) {
prot_printf(imapd_out,
"%s BAD Can't Starttls after authentication\r\n", tag.s);
continue;
}
/* if we've already done COMPRESS fail */
if (imapd_compress_done == 1) {
prot_printf(imapd_out,
"%s BAD Can't Starttls after Compress\r\n", tag.s);
continue;
}
/* check if already did a successful tls */
if (imapd_starttls_done == 1) {
prot_printf(imapd_out,
"%s BAD Already did a successful Starttls\r\n",
tag.s);
continue;
}
cmd_starttls(tag.s, 0);
snmp_increment(STARTTLS_COUNT, 1);
continue;
}
if (!imapd_userid) {
goto nologin;
} else if (!strcmp(cmd.s, "Store")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
store:
c = getword(imapd_in, &arg1);
if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence;
cmd_store(tag.s, arg1.s, usinguid);
snmp_increment(STORE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Select")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
prot_ungetc(c, imapd_in);
cmd_select(tag.s, cmd.s, arg1.s);
snmp_increment(SELECT_COUNT, 1);
}
else if (!strcmp(cmd.s, "Search")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
search:
cmd_search(tag.s, usinguid);
snmp_increment(SEARCH_COUNT, 1);
}
else if (!strcmp(cmd.s, "Subscribe")) {
if (c != ' ') goto missingargs;
havenamespace = 0;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == ' ') {
havenamespace = 1;
c = getastring(imapd_in, imapd_out, &arg2);
}
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
if (havenamespace) {
cmd_changesub(tag.s, arg1.s, arg2.s, 1);
}
else {
cmd_changesub(tag.s, (char *)0, arg1.s, 1);
}
snmp_increment(SUBSCRIBE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Setacl")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg3);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_setacl(tag.s, arg1.s, arg2.s, arg3.s);
snmp_increment(SETACL_COUNT, 1);
}
else if (!strcmp(cmd.s, "Setannotation")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_setannotation(tag.s, arg1.s);
snmp_increment(SETANNOTATION_COUNT, 1);
}
else if (!strcmp(cmd.s, "Setmetadata")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_setmetadata(tag.s, arg1.s);
snmp_increment(SETANNOTATION_COUNT, 1);
}
else if (!strcmp(cmd.s, "Setquota")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_setquota(tag.s, arg1.s);
snmp_increment(SETQUOTA_COUNT, 1);
}
else if (!strcmp(cmd.s, "Sort")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
sort:
cmd_sort(tag.s, usinguid);
snmp_increment(SORT_COUNT, 1);
}
else if (!strcmp(cmd.s, "Status")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_status(tag.s, arg1.s);
snmp_increment(STATUS_COUNT, 1);
}
else if (!strcmp(cmd.s, "Scan")) {
struct listargs listargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg3);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.ref = arg1.s;
strarray_append(&listargs.pat, arg2.s);
listargs.scan = arg3.s;
cmd_list(tag.s, &listargs);
snmp_increment(SCAN_COUNT, 1);
}
else if (!strcmp(cmd.s, "Syncapply")) {
if (!imapd_userisadmin) goto badcmd;
struct dlist *kl = sync_parseline(imapd_in);
if (kl) {
cmd_syncapply(tag.s, kl, reserve_list);
dlist_free(&kl);
}
else goto extraargs;
}
else if (!strcmp(cmd.s, "Syncget")) {
if (!imapd_userisadmin) goto badcmd;
struct dlist *kl = sync_parseline(imapd_in);
if (kl) {
cmd_syncget(tag.s, kl);
dlist_free(&kl);
}
else goto extraargs;
}
else if (!strcmp(cmd.s, "Syncrestart")) {
if (!imapd_userisadmin) goto badcmd;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
/* just clear the GUID cache */
cmd_syncrestart(tag.s, &reserve_list, 1);
}
else if (!strcmp(cmd.s, "Syncrestore")) {
if (!imapd_userisadmin) goto badcmd;
struct dlist *kl = sync_parseline(imapd_in);
if (kl) {
cmd_syncrestore(tag.s, kl, reserve_list);
dlist_free(&kl);
}
else goto extraargs;
}
else goto badcmd;
break;
case 'T':
if (!strcmp(cmd.s, "Thread")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
thread:
cmd_thread(tag.s, usinguid);
snmp_increment(THREAD_COUNT, 1);
}
else goto badcmd;
break;
case 'U':
if (!strcmp(cmd.s, "Uid")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 1;
if (c != ' ') goto missingargs;
c = getword(imapd_in, &arg1);
if (c != ' ') goto missingargs;
lcase(arg1.s);
xstrncpy(cmdname, arg1.s, 99);
if (!strcmp(arg1.s, "fetch")) {
goto fetch;
}
else if (!strcmp(arg1.s, "store")) {
goto store;
}
else if (!strcmp(arg1.s, "search")) {
goto search;
}
else if (!strcmp(arg1.s, "sort")) {
goto sort;
}
else if (!strcmp(arg1.s, "thread")) {
goto thread;
}
else if (!strcmp(arg1.s, "copy")) {
goto copy;
}
else if (!strcmp(arg1.s, "move")) {
goto move;
}
else if (!strcmp(arg1.s, "xmove")) {
goto move;
}
else if (!strcmp(arg1.s, "expunge")) {
c = getword(imapd_in, &arg1);
if (!imparse_issequence(arg1.s)) goto badsequence;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_expunge(tag.s, arg1.s);
snmp_increment(EXPUNGE_COUNT, 1);
}
else if (!strcmp(arg1.s, "xrunannotator")) {
goto xrunannotator;
}
else {
prot_printf(imapd_out, "%s BAD Unrecognized UID subcommand\r\n", tag.s);
eatline(imapd_in, c);
}
}
else if (!strcmp(cmd.s, "Unsubscribe")) {
if (c != ' ') goto missingargs;
havenamespace = 0;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == ' ') {
havenamespace = 1;
c = getastring(imapd_in, imapd_out, &arg2);
}
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
if (havenamespace) {
cmd_changesub(tag.s, arg1.s, arg2.s, 0);
}
else {
cmd_changesub(tag.s, (char *)0, arg1.s, 0);
}
snmp_increment(UNSUBSCRIBE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Unselect")) {
if (!imapd_index && !backend_current) goto nomailbox;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_close(tag.s, cmd.s);
snmp_increment(UNSELECT_COUNT, 1);
}
else if (!strcmp(cmd.s, "Undump")) {
if(c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
/* we want to get a list at this point */
if(c != ' ') goto missingargs;
cmd_undump(tag.s, arg1.s);
/* snmp_increment(UNDUMP_COUNT, 1);*/
}
#ifdef HAVE_SSL
else if (!strcmp(cmd.s, "Urlfetch")) {
if (c != ' ') goto missingargs;
cmd_urlfetch(tag.s);
/* snmp_increment(URLFETCH_COUNT, 1);*/
}
#endif
else goto badcmd;
break;
case 'X':
if (!strcmp(cmd.s, "Xbackup")) {
int havechannel = 0;
if (!config_getswitch(IMAPOPT_XBACKUP_ENABLED))
goto badcmd;
/* user */
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
/* channel */
if (c == ' ') {
havechannel = 1;
c = getword(imapd_in, &arg2);
if (c == EOF) goto missingargs;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_xbackup(tag.s, arg1.s, havechannel ? arg2.s : NULL);
// snmp_increment(XBACKUP_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xconvfetch")) {
cmd_xconvfetch(tag.s);
// snmp_increment(XCONVFETCH_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xconvmultisort")) {
if (c != ' ') goto missingargs;
if (!imapd_index && !backend_current) goto nomailbox;
cmd_xconvmultisort(tag.s);
// snmp_increment(XCONVMULTISORT_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xconvsort")) {
if (c != ' ') goto missingargs;
if (!imapd_index && !backend_current) goto nomailbox;
cmd_xconvsort(tag.s, 0);
// snmp_increment(XCONVSORT_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xconvupdates")) {
if (c != ' ') goto missingargs;
if (!imapd_index && !backend_current) goto nomailbox;
cmd_xconvsort(tag.s, 1);
// snmp_increment(XCONVUPDATES_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xfer")) {
int havepartition = 0;
/* Mailbox */
if(c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
/* Dest Server */
if(c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if(c == ' ') {
/* Dest Partition */
c = getastring(imapd_in, imapd_out, &arg3);
if (!imparse_isatom(arg3.s)) goto badpartition;
havepartition = 1;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_xfer(tag.s, arg1.s, arg2.s,
(havepartition ? arg3.s : NULL));
/* snmp_increment(XFER_COUNT, 1);*/
}
else if (!strcmp(cmd.s, "Xconvmeta")) {
cmd_xconvmeta(tag.s);
}
else if (!strcmp(cmd.s, "Xlist")) {
struct listargs listargs;
if (c != ' ') goto missingargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.cmd = LIST_CMD_XLIST;
listargs.ret = LIST_RET_CHILDREN | LIST_RET_SPECIALUSE;
getlistargs(tag.s, &listargs);
if (listargs.pat.count) cmd_list(tag.s, &listargs);
snmp_increment(LIST_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xmove")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
goto move;
}
else if (!strcmp(cmd.s, "Xrunannotator")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
xrunannotator:
c = getword(imapd_in, &arg1);
if (!arg1.len || !imparse_issequence(arg1.s)) goto badsequence;
cmd_xrunannotator(tag.s, arg1.s, usinguid);
// snmp_increment(XRUNANNOTATOR_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xsnippets")) {
if (c != ' ') goto missingargs;
if (!imapd_index && !backend_current) goto nomailbox;
cmd_xsnippets(tag.s);
// snmp_increment(XSNIPPETS_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xstats")) {
cmd_xstats(tag.s, c);
}
else if (!strcmp(cmd.s, "Xwarmup")) {
/* XWARMUP doesn't need a mailbox to be selected */
if (c != ' ') goto missingargs;
cmd_xwarmup(tag.s);
// snmp_increment(XWARMUP_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xkillmy")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_xkillmy(tag.s, arg1.s);
}
else if (!strcmp(cmd.s, "Xforever")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_xforever(tag.s);
}
else if (!strcmp(cmd.s, "Xmeid")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_xmeid(tag.s, arg1.s);
}
else if (apns_enabled && !strcmp(cmd.s, "Xapplepushservice")) {
if (c != ' ') goto missingargs;
memset(&applepushserviceargs, 0, sizeof(struct applepushserviceargs));
do {
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto aps_missingargs;
if (!strcmp(arg1.s, "mailboxes")) {
c = prot_getc(imapd_in);
if (c != '(')
goto aps_missingargs;
c = prot_getc(imapd_in);
if (c != ')') {
prot_ungetc(c, imapd_in);
do {
c = getastring(imapd_in, imapd_out, &arg2);
if (c == EOF) break;
strarray_push(&applepushserviceargs.mailboxes, arg2.s);
} while (c == ' ');
}
if (c != ')')
goto aps_missingargs;
c = prot_getc(imapd_in);
}
else {
c = getastring(imapd_in, imapd_out, &arg2);
// regular key/value
if (!strcmp(arg1.s, "aps-version")) {
if (!imparse_isnumber(arg2.s)) goto aps_extraargs;
applepushserviceargs.aps_version = atoi(arg2.s);
}
else if (!strcmp(arg1.s, "aps-account-id"))
buf_copy(&applepushserviceargs.aps_account_id, &arg2);
else if (!strcmp(arg1.s, "aps-device-token"))
buf_copy(&applepushserviceargs.aps_device_token, &arg2);
else if (!strcmp(arg1.s, "aps-subtopic"))
buf_copy(&applepushserviceargs.aps_subtopic, &arg2);
else
goto aps_extraargs;
}
} while (c == ' ');
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto aps_extraargs;
cmd_xapplepushservice(tag.s, &applepushserviceargs);
}
else goto badcmd;
break;
default:
badcmd:
prot_printf(imapd_out, "%s BAD Unrecognized command\r\n", tag.s);
eatline(imapd_in, c);
}
/* End command timer - don't log "idle" commands */
if (commandmintimer && strcmp("idle", cmdname)) {
double cmdtime, nettime;
const char *mboxname = index_mboxname(imapd_index);
if (!mboxname) mboxname = "<none>";
cmdtime_endtimer(&cmdtime, &nettime);
if (cmdtime >= commandmintimerd) {
syslog(LOG_NOTICE, "cmdtimer: '%s' '%s' '%s' '%f' '%f' '%f'",
imapd_userid ? imapd_userid : "<none>", cmdname, mboxname,
cmdtime, nettime, cmdtime + nettime);
}
}
continue;
nologin:
prot_printf(imapd_out, "%s BAD Please login first\r\n", tag.s);
eatline(imapd_in, c);
continue;
nomailbox:
prot_printf(imapd_out,
"%s BAD Please select a mailbox first\r\n", tag.s);
eatline(imapd_in, c);
continue;
aps_missingargs:
buf_free(&applepushserviceargs.aps_account_id);
buf_free(&applepushserviceargs.aps_device_token);
buf_free(&applepushserviceargs.aps_subtopic);
strarray_fini(&applepushserviceargs.mailboxes);
missingargs:
prot_printf(imapd_out,
"%s BAD Missing required argument to %s\r\n", tag.s, cmd.s);
eatline(imapd_in, c);
continue;
aps_extraargs:
buf_free(&applepushserviceargs.aps_account_id);
buf_free(&applepushserviceargs.aps_device_token);
buf_free(&applepushserviceargs.aps_subtopic);
strarray_fini(&applepushserviceargs.mailboxes);
extraargs:
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to %s\r\n", tag.s, cmd.s);
eatline(imapd_in, c);
continue;
badsequence:
prot_printf(imapd_out,
"%s BAD Invalid sequence in %s\r\n", tag.s, cmd.s);
eatline(imapd_in, c);
continue;
badpartition:
prot_printf(imapd_out,
"%s BAD Invalid partition name in %s\r\n", tag.s, cmd.s);
eatline(imapd_in, c);
continue;
}
done:
cmd_syncrestart(NULL, &reserve_list, 0);
}
#ifdef USE_AUTOCREATE
/*
* Autocreate Inbox and subfolders upon login
*/
static void autocreate_inbox(void)
{
if (imapd_userisadmin) return;
if (imapd_userisproxyadmin) return;
if (config_getint(IMAPOPT_AUTOCREATE_QUOTA) >= 0) {
char *inboxname = mboxname_user_mbox(imapd_userid, NULL);
int r = mboxlist_lookup(inboxname, NULL, NULL);
free(inboxname);
if (r != IMAP_MAILBOX_NONEXISTENT) return;
autocreate_user(&imapd_namespace, imapd_userid);
}
}
#endif // USE_AUTOCREATE
static void authentication_success(void)
{
int r;
struct mboxevent *mboxevent;
/* authstate already created by mysasl_proxy_policy() */
imapd_userisadmin = global_authisa(imapd_authstate, IMAPOPT_ADMINS);
/* Create telemetry log */
imapd_logfd = telemetry_log(imapd_userid, imapd_in, imapd_out, 0);
/* Set namespace */
r = mboxname_init_namespace(&imapd_namespace,
imapd_userisadmin || imapd_userisproxyadmin);
mboxevent_setnamespace(&imapd_namespace);
if (r) {
syslog(LOG_ERR, "%s", error_message(r));
fatal(error_message(r), EC_CONFIG);
}
/* Make a copy of the external userid for use in proxying */
proxy_userid = xstrdup(imapd_userid);
/* send a Login event notification */
if ((mboxevent = mboxevent_new(EVENT_LOGIN))) {
mboxevent_set_access(mboxevent, saslprops.iplocalport,
saslprops.ipremoteport, imapd_userid, NULL, 1);
mboxevent_notify(&mboxevent);
mboxevent_free(&mboxevent);
}
#ifdef USE_AUTOCREATE
autocreate_inbox();
#endif // USE_AUTOCREATE
}
static int checklimits(const char *tag)
{
struct proc_limits limits;
limits.procname = "imapd";
limits.clienthost = imapd_clienthost;
limits.userid = imapd_userid;
if (proc_checklimits(&limits)) {
const char *sep = "";
prot_printf(imapd_out, "%s NO Too many open connections (", tag);
if (limits.maxhost) {
prot_printf(imapd_out, "%s%d of %d from %s", sep,
limits.host, limits.maxhost, imapd_clienthost);
sep = ", ";
}
if (limits.maxuser) {
prot_printf(imapd_out, "%s%d of %d for %s", sep,
limits.user, limits.maxuser, imapd_userid);
}
prot_printf(imapd_out, ")\r\n");
free(imapd_userid);
imapd_userid = NULL;
auth_freestate(imapd_authstate);
imapd_authstate = NULL;
return 1;
}
return 0;
}
/*
* Perform a LOGIN command
*/
static void cmd_login(char *tag, char *user)
{
char userbuf[MAX_MAILBOX_BUFFER];
char replybuf[MAX_MAILBOX_BUFFER];
unsigned userlen;
const char *canon_user = userbuf;
const void *val;
int c;
struct buf passwdbuf;
char *passwd;
const char *reply = NULL;
int r;
int failedloginpause;
if (imapd_userid) {
eatline(imapd_in, ' ');
prot_printf(imapd_out, "%s BAD Already logged in\r\n", tag);
return;
}
r = imapd_canon_user(imapd_saslconn, NULL, user, 0,
SASL_CU_AUTHID | SASL_CU_AUTHZID, NULL,
userbuf, sizeof(userbuf), &userlen);
if (r) {
eatline(imapd_in, ' ');
syslog(LOG_NOTICE, "badlogin: %s plaintext %s invalid user",
imapd_clienthost, beautify_string(user));
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(IMAP_INVALID_USER));
return;
}
/* possibly disallow login */
if (imapd_tls_required ||
(!imapd_starttls_done && (extprops_ssf < 2) &&
!config_getswitch(IMAPOPT_ALLOWPLAINTEXT) &&
!is_userid_anonymous(canon_user))) {
eatline(imapd_in, ' ');
prot_printf(imapd_out, "%s NO Login only available under a layer\r\n",
tag);
return;
}
memset(&passwdbuf,0,sizeof(struct buf));
c = getastring(imapd_in, imapd_out, &passwdbuf);
if(c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
buf_free(&passwdbuf);
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to LOGIN\r\n",
tag);
eatline(imapd_in, c);
return;
}
passwd = passwdbuf.s;
if (is_userid_anonymous(canon_user)) {
if (config_getswitch(IMAPOPT_ALLOWANONYMOUSLOGIN)) {
passwd = beautify_string(passwd);
if (strlen(passwd) > 500) passwd[500] = '\0';
syslog(LOG_NOTICE, "login: %s anonymous %s",
imapd_clienthost, passwd);
reply = "Anonymous access granted";
imapd_userid = xstrdup("anonymous");
}
else {
syslog(LOG_NOTICE, "badlogin: %s anonymous login refused",
imapd_clienthost);
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(IMAP_ANONYMOUS_NOT_PERMITTED));
buf_free(&passwdbuf);
return;
}
}
else if ( nosaslpasswdcheck ) {
snprintf(replybuf, sizeof(replybuf),
"User logged in SESSIONID=<%s>", session_id());
reply = replybuf;
imapd_userid = xstrdup(canon_user);
imapd_authstate = auth_newstate(canon_user);
syslog(LOG_NOTICE, "login: %s %s%s nopassword%s %s", imapd_clienthost,
imapd_userid, imapd_magicplus ? imapd_magicplus : "",
imapd_starttls_done ? "+TLS" : "", reply);
}
else if ((r = sasl_checkpass(imapd_saslconn,
canon_user,
strlen(canon_user),
passwd,
strlen(passwd))) != SASL_OK) {
syslog(LOG_NOTICE, "badlogin: %s plaintext %s %s",
imapd_clienthost, canon_user, sasl_errdetail(imapd_saslconn));
failedloginpause = config_getint(IMAPOPT_FAILEDLOGINPAUSE);
if (failedloginpause != 0) {
sleep(failedloginpause);
}
/* Don't allow user probing */
if (r == SASL_NOUSER) r = SASL_BADAUTH;
if ((reply = sasl_errstring(r, NULL, NULL)) != NULL) {
prot_printf(imapd_out, "%s NO Login failed: %s\r\n", tag, reply);
} else {
prot_printf(imapd_out, "%s NO Login failed: %d\r\n", tag, r);
}
snmp_increment_args(AUTHENTICATION_NO, 1,
VARIABLE_AUTH, 0 /* hash_simple("LOGIN") */,
VARIABLE_LISTEND);
buf_free(&passwdbuf);
return;
}
else {
r = sasl_getprop(imapd_saslconn, SASL_USERNAME, &val);
if(r != SASL_OK) {
if ((reply = sasl_errstring(r, NULL, NULL)) != NULL) {
prot_printf(imapd_out, "%s NO Login failed: %s\r\n",
tag, reply);
} else {
prot_printf(imapd_out, "%s NO Login failed: %d\r\n", tag, r);
}
snmp_increment_args(AUTHENTICATION_NO, 1,
VARIABLE_AUTH, 0 /* hash_simple("LOGIN") */,
VARIABLE_LISTEND);
buf_free(&passwdbuf);
return;
}
snprintf(replybuf, sizeof(replybuf),
"User logged in SESSIONID=<%s>", session_id());
reply = replybuf;
imapd_userid = xstrdup((const char *) val);
snmp_increment_args(AUTHENTICATION_YES, 1,
VARIABLE_AUTH, 0 /*hash_simple("LOGIN") */,
VARIABLE_LISTEND);
syslog(LOG_NOTICE, "login: %s %s%s plaintext%s %s", imapd_clienthost,
imapd_userid, imapd_magicplus ? imapd_magicplus : "",
imapd_starttls_done ? "+TLS" : "",
reply ? reply : "");
/* Apply penalty only if not under layer */
if (!imapd_starttls_done) {
int plaintextloginpause = config_getint(IMAPOPT_PLAINTEXTLOGINPAUSE);
if (plaintextloginpause) {
sleep(plaintextloginpause);
}
/* Fetch plaintext login nag message */
plaintextloginalert = config_getstring(IMAPOPT_PLAINTEXTLOGINALERT);
}
}
buf_free(&passwdbuf);
if (checklimits(tag)) return;
prot_printf(imapd_out, "%s OK [CAPABILITY ", tag);
capa_response(CAPA_PREAUTH|CAPA_POSTAUTH);
prot_printf(imapd_out, "] %s\r\n", reply);
authentication_success();
}
/*
* Perform an AUTHENTICATE command
*/
static void cmd_authenticate(char *tag, char *authtype, char *resp)
{
int sasl_result;
const void *val;
const char *ssfmsg = NULL;
char replybuf[MAX_MAILBOX_BUFFER];
const char *reply = NULL;
const char *canon_user;
int r;
int failedloginpause;
if (imapd_tls_required) {
prot_printf(imapd_out,
"%s NO Authenticate only available under a layer\r\n", tag);
return;
}
r = saslserver(imapd_saslconn, authtype, resp, "", "+ ", "",
imapd_in, imapd_out, &sasl_result, NULL);
if (r) {
const char *errorstring = NULL;
switch (r) {
case IMAP_SASL_CANCEL:
prot_printf(imapd_out,
"%s BAD Client canceled authentication\r\n", tag);
break;
case IMAP_SASL_PROTERR:
errorstring = prot_error(imapd_in);
prot_printf(imapd_out,
"%s NO Error reading client response: %s\r\n",
tag, errorstring ? errorstring : "");
break;
default:
/* failed authentication */
syslog(LOG_NOTICE, "badlogin: %s %s [%s]",
imapd_clienthost, authtype, sasl_errdetail(imapd_saslconn));
snmp_increment_args(AUTHENTICATION_NO, 1,
VARIABLE_AUTH, 0, /* hash_simple(authtype) */
VARIABLE_LISTEND);
failedloginpause = config_getint(IMAPOPT_FAILEDLOGINPAUSE);
if (failedloginpause != 0) {
sleep(failedloginpause);
}
/* Don't allow user probing */
if (sasl_result == SASL_NOUSER) sasl_result = SASL_BADAUTH;
errorstring = sasl_errstring(sasl_result, NULL, NULL);
if (errorstring) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, errorstring);
} else {
prot_printf(imapd_out, "%s NO Error authenticating\r\n", tag);
}
}
reset_saslconn(&imapd_saslconn);
return;
}
/* successful authentication */
/* get the userid from SASL --- already canonicalized from
* mysasl_proxy_policy()
*/
sasl_result = sasl_getprop(imapd_saslconn, SASL_USERNAME, &val);
if (sasl_result != SASL_OK) {
prot_printf(imapd_out, "%s NO weird SASL error %d SASL_USERNAME\r\n",
tag, sasl_result);
syslog(LOG_ERR, "weird SASL error %d getting SASL_USERNAME",
sasl_result);
reset_saslconn(&imapd_saslconn);
return;
}
canon_user = (const char *) val;
/* If we're proxying, the authzid may contain a magic plus,
so re-canonify it */
if (config_getswitch(IMAPOPT_IMAPMAGICPLUS) && strchr(canon_user, '+')) {
char userbuf[MAX_MAILBOX_BUFFER];
unsigned userlen;
sasl_result = imapd_canon_user(imapd_saslconn, NULL, canon_user, 0,
SASL_CU_AUTHID | SASL_CU_AUTHZID,
NULL, userbuf, sizeof(userbuf), &userlen);
if (sasl_result != SASL_OK) {
prot_printf(imapd_out,
"%s NO SASL canonification error %d\r\n",
tag, sasl_result);
reset_saslconn(&imapd_saslconn);
return;
}
imapd_userid = xstrdup(userbuf);
} else {
imapd_userid = xstrdup(canon_user);
}
snprintf(replybuf, sizeof(replybuf),
"User logged in SESSIONID=<%s>", session_id());
reply = replybuf;
syslog(LOG_NOTICE, "login: %s %s%s %s%s %s", imapd_clienthost,
imapd_userid, imapd_magicplus ? imapd_magicplus : "",
authtype, imapd_starttls_done ? "+TLS" : "", reply);
sasl_getprop(imapd_saslconn, SASL_SSF, &val);
saslprops.ssf = *((sasl_ssf_t *) val);
/* really, we should be doing a sasl_getprop on SASL_SSF_EXTERNAL,
but the current libsasl doesn't allow that. */
if (imapd_starttls_done) {
switch(saslprops.ssf) {
case 0: ssfmsg = "tls protection"; break;
case 1: ssfmsg = "tls plus integrity protection"; break;
default: ssfmsg = "tls plus privacy protection"; break;
}
} else {
switch(saslprops.ssf) {
case 0: ssfmsg = "no protection"; break;
case 1: ssfmsg = "integrity protection"; break;
default: ssfmsg = "privacy protection"; break;
}
}
snmp_increment_args(AUTHENTICATION_YES, 1,
VARIABLE_AUTH, 0, /* hash_simple(authtype) */
VARIABLE_LISTEND);
if (checklimits(tag)) {
reset_saslconn(&imapd_saslconn);
return;
}
if (!saslprops.ssf) {
prot_printf(imapd_out, "%s OK [CAPABILITY ", tag);
capa_response(CAPA_PREAUTH|CAPA_POSTAUTH);
prot_printf(imapd_out, "] Success (%s) SESSIONID=<%s>\r\n",
ssfmsg, session_id());
} else {
prot_printf(imapd_out, "%s OK Success (%s) SESSIONID=<%s>\r\n",
tag, ssfmsg, session_id());
}
prot_setsasl(imapd_in, imapd_saslconn);
prot_setsasl(imapd_out, imapd_saslconn);
authentication_success();
}
/*
* Perform a NOOP command
*/
static void cmd_noop(char *tag, char *cmd)
{
if (backend_current) {
/* remote mailbox */
prot_printf(backend_current->out, "%s %s\r\n", tag, cmd);
pipe_including_tag(backend_current, tag, 0);
return;
}
index_check(imapd_index, 1, 0);
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
static void clear_id() {
if (imapd_id.params) {
freeattvalues(imapd_id.params);
}
memset(&imapd_id, 0, sizeof(struct id_data));
}
/*
* Parse and perform an ID command.
*
* the command has been parsed up to the parameter list.
*
* we only allow one ID in non-authenticated state from a given client.
* we only allow MAXIDFAILED consecutive failed IDs from a given client.
* we only record MAXIDLOG ID responses from a given client.
*/
static void cmd_id(char *tag)
{
int c = EOF, npair = 0;
static struct buf arg, field;
/* check if we've already had an ID in non-authenticated state */
if (!imapd_userid && imapd_id.did_id) {
prot_printf(imapd_out, "%s OK NIL\r\n", tag);
eatline(imapd_in, c);
return;
}
clear_id();
/* ok, accept parameter list */
c = getword(imapd_in, &arg);
/* check for "NIL" or start of parameter list */
if (strcasecmp(arg.s, "NIL") && c != '(') {
prot_printf(imapd_out, "%s BAD Invalid parameter list in Id\r\n", tag);
eatline(imapd_in, c);
return;
}
/* parse parameter list */
if (c == '(') {
for (;;) {
if (c == ')') {
/* end of string/value pairs */
break;
}
/* get field name */
c = getstring(imapd_in, imapd_out, &field);
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Invalid/missing field name in Id\r\n",
tag);
eatline(imapd_in, c);
return;
}
/* get field value */
c = getnstring(imapd_in, imapd_out, &arg);
if (c != ' ' && c != ')') {
prot_printf(imapd_out,
"%s BAD Invalid/missing value in Id\r\n",
tag);
eatline(imapd_in, c);
return;
}
/* ok, we're anal, but we'll still process the ID command */
if (strlen(field.s) > MAXIDFIELDLEN) {
prot_printf(imapd_out,
"%s BAD field longer than %u octets in Id\r\n",
tag, MAXIDFIELDLEN);
eatline(imapd_in, c);
return;
}
if (arg.len > MAXIDVALUELEN) {
prot_printf(imapd_out,
"%s BAD value longer than %u octets in Id\r\n",
tag, MAXIDVALUELEN);
eatline(imapd_in, c);
return;
}
if (++npair > MAXIDPAIRS) {
prot_printf(imapd_out,
"%s BAD too many (%u) field-value pairs in ID\r\n",
tag, MAXIDPAIRS);
eatline(imapd_in, c);
return;
}
if (!strcmp(field.s, "os") && !strcmp(arg.s, "iOS")) {
imapd_id.quirks |= QUIRK_SEARCHFUZZY;
}
/* ok, we're happy enough */
appendattvalue(&imapd_id.params, field.s, &arg);
}
if (c != ')') {
/* erp! */
prot_printf(imapd_out, "%s BAD trailing junk\r\n", tag);
eatline(imapd_in, c);
return;
}
c = prot_getc(imapd_in);
}
/* check for CRLF */
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out, "%s BAD Unexpected extra arguments to Id\r\n", tag);
eatline(imapd_in, c);
return;
}
/* log the client's ID string.
eventually this should be a callback or something. */
if (npair) {
struct buf logbuf = BUF_INITIALIZER;
struct attvaluelist *pptr;
for (pptr = imapd_id.params; pptr; pptr = pptr->next) {
const char *val = buf_cstring(&pptr->value);
/* should we check for and format literals here ??? */
buf_printf(&logbuf, " \"%s\" ", pptr->attrib);
if (!val || !strcmp(val, "NIL"))
buf_printf(&logbuf, "NIL");
else
buf_printf(&logbuf, "\"%s\"", val);
}
syslog(LOG_INFO, "client id sessionid=<%s>:%s", session_id(), buf_cstring(&logbuf));
buf_free(&logbuf);
}
/* spit out our ID string.
eventually this might be configurable. */
if (config_getswitch(IMAPOPT_IMAPIDRESPONSE) &&
(imapd_authstate || (config_serverinfo == IMAP_ENUM_SERVERINFO_ON))) {
id_response(imapd_out);
prot_printf(imapd_out, ")\r\n");
}
else
prot_printf(imapd_out, "* ID NIL\r\n");
imapd_check(NULL, 0);
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
imapd_id.did_id = 1;
}
static bool deadline_exceeded(const struct timespec *d)
{
struct timespec now;
if (d->tv_sec <= 0) {
/* No deadline configured */
return false;
}
errno = 0;
if (clock_gettime(CLOCK_MONOTONIC, &now) == -1) {
syslog(LOG_ERR, "clock_gettime (%d %m): error reading clock", errno);
return false;
}
return now.tv_sec > d->tv_sec ||
(now.tv_sec == d->tv_sec && now.tv_nsec > d->tv_nsec);
}
/*
* Perform an IDLE command
*/
static void cmd_idle(char *tag)
{
int c = EOF;
int flags;
static struct buf arg;
static int idle_period = -1;
static time_t idle_timeout = -1;
struct timespec deadline = { 0, 0 };
if (idle_timeout == -1) {
idle_timeout = config_getint(IMAPOPT_IMAPIDLETIMEOUT);
if (idle_timeout <= 0) {
idle_timeout = config_getint(IMAPOPT_TIMEOUT);
}
idle_timeout *= 60; /* unit is minutes */
}
if (idle_timeout > 0) {
errno = 0;
if (clock_gettime(CLOCK_MONOTONIC, &deadline) == -1) {
syslog(LOG_ERR, "clock_gettime (%d %m): error reading clock",
errno);
} else {
deadline.tv_sec += idle_timeout;
}
}
if (!backend_current) { /* Local mailbox */
/* Tell client we are idling and waiting for end of command */
prot_printf(imapd_out, "+ idling\r\n");
prot_flush(imapd_out);
/* Start doing mailbox updates */
index_check(imapd_index, 1, 0);
idle_start(index_mboxname(imapd_index));
/* use this flag so if getc causes a shutdown due to
* connection abort we tell idled about it */
idling = 1;
index_release(imapd_index);
while ((flags = idle_wait(imapd_in->fd))) {
if (deadline_exceeded(&deadline)) {
syslog(LOG_DEBUG, "timeout for user '%s' while idling",
imapd_userid);
shut_down(0);
break;
}
if (flags & IDLE_INPUT) {
/* Get continuation data */
c = getword(imapd_in, &arg);
break;
}
/* Send unsolicited untagged responses to the client */
if (flags & IDLE_MAILBOX)
index_check(imapd_index, 1, 0);
if (flags & IDLE_ALERT) {
char shut[MAX_MAILBOX_PATH+1];
if (! imapd_userisadmin &&
(shutdown_file(shut, sizeof(shut)) ||
(imapd_userid &&
userdeny(imapd_userid, config_ident, shut, sizeof(shut))))) {
char *p;
for (p = shut; *p == '['; p++); /* can't have [ be first char */
prot_printf(imapd_out, "* BYE [ALERT] %s\r\n", p);
shut_down(0);
}
}
index_release(imapd_index);
prot_flush(imapd_out);
}
/* Stop updates and do any necessary cleanup */
idling = 0;
idle_stop(index_mboxname(imapd_index));
}
else { /* Remote mailbox */
int done = 0;
enum { shutdown_skip, shutdown_bye, shutdown_silent } shutdown = shutdown_skip;
char buf[2048];
/* get polling period */
if (idle_period == -1) {
idle_period = config_getint(IMAPOPT_IMAPIDLEPOLL);
}
if (CAPA(backend_current, CAPA_IDLE)) {
/* Start IDLE on backend */
prot_printf(backend_current->out, "%s IDLE\r\n", tag);
if (!prot_fgets(buf, sizeof(buf), backend_current->in)) {
/* If we received nothing from the backend, fail */
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(IMAP_SERVER_UNAVAILABLE));
return;
}
if (buf[0] != '+') {
/* If we received anything but a continuation response,
spit out what we received and quit */
prot_write(imapd_out, buf, strlen(buf));
return;
}
}
/* Tell client we are idling and waiting for end of command */
prot_printf(imapd_out, "+ idling\r\n");
prot_flush(imapd_out);
/* Pipe updates to client while waiting for end of command */
while (!done) {
if (deadline_exceeded(&deadline)) {
syslog(LOG_DEBUG,
"timeout for user '%s' while idling on remote mailbox",
imapd_userid);
shutdown = shutdown_silent;
goto done;
}
/* Flush any buffered output */
prot_flush(imapd_out);
/* Check for shutdown file */
if (!imapd_userisadmin &&
(shutdown_file(buf, sizeof(buf)) ||
(imapd_userid &&
userdeny(imapd_userid, config_ident, buf, sizeof(buf))))) {
done = 1;
shutdown = shutdown_bye;
goto done;
}
done = proxy_check_input(protin, imapd_in, imapd_out,
backend_current->in, NULL, idle_period);
/* If not running IDLE on backend, poll the mailbox for updates */
if (!CAPA(backend_current, CAPA_IDLE)) {
imapd_check(NULL, 0);
}
}
/* Get continuation data */
c = getword(imapd_in, &arg);
done:
if (CAPA(backend_current, CAPA_IDLE)) {
/* Either the client timed out, or ended the command.
In either case we're done, so terminate IDLE on backend */
prot_printf(backend_current->out, "Done\r\n");
pipe_until_tag(backend_current, tag, 0);
}
switch (shutdown) {
case shutdown_bye:
;
char *p;
for (p = buf; *p == '['; p++); /* can't have [ be first char */
prot_printf(imapd_out, "* BYE [ALERT] %s\r\n", p);
/* fallthrough */
case shutdown_silent:
shut_down(0);
break;
case shutdown_skip:
default:
break;
}
}
imapd_check(NULL, 1);
if (c != EOF) {
if (!strcasecmp(arg.s, "Done") &&
(c = (c == '\r') ? prot_getc(imapd_in) : c) == '\n') {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
else {
prot_printf(imapd_out,
"%s BAD Invalid Idle continuation\r\n", tag);
eatline(imapd_in, c);
}
}
}
static void capa_response(int flags)
{
const char *sasllist; /* the list of SASL mechanisms */
int mechcount;
int need_space = 0;
int i;
int lminus = config_getswitch(IMAPOPT_LITERALMINUS);
for (i = 0; base_capabilities[i].str; i++) {
const char *capa = base_capabilities[i].str;
/* Filter capabilities if requested */
if (capa_is_disabled(capa))
continue;
/* Don't show "MAILBOX-REFERRALS" if disabled by config */
if (config_getswitch(IMAPOPT_PROXYD_DISABLE_MAILBOX_REFERRALS) &&
!strcmp(capa, "MAILBOX-REFERRALS"))
continue;
/* Don't show if they're not shown at this level of login */
if (!(base_capabilities[i].mask & flags))
continue;
/* cheap and nasty version of LITERAL- support - just say so */
if (lminus && !strcmp(capa, "LITERAL+"))
capa = "LITERAL-";
/* print the capability */
if (need_space) prot_putc(' ', imapd_out);
else need_space = 1;
prot_printf(imapd_out, "%s", base_capabilities[i].str);
}
if (config_mupdate_server) {
prot_printf(imapd_out, " MUPDATE=mupdate://%s/", config_mupdate_server);
}
if (apns_enabled) {
prot_printf(imapd_out, " XAPPLEPUSHSERVICE");
}
if (tls_enabled() && !imapd_starttls_done && !imapd_authstate) {
prot_printf(imapd_out, " STARTTLS");
}
if (imapd_tls_required || imapd_authstate ||
(!imapd_starttls_done && (extprops_ssf < 2) &&
!config_getswitch(IMAPOPT_ALLOWPLAINTEXT))) {
prot_printf(imapd_out, " LOGINDISABLED");
}
/* add the SASL mechs */
if (!imapd_tls_required && (!imapd_authstate || saslprops.ssf) &&
sasl_listmech(imapd_saslconn, NULL,
"AUTH=", " AUTH=",
!imapd_authstate ? " SASL-IR" : "", &sasllist,
NULL, &mechcount) == SASL_OK && mechcount > 0) {
prot_printf(imapd_out, " %s", sasllist);
} else {
/* else don't show anything */
}
if (!(flags & CAPA_POSTAUTH)) return;
if (config_getswitch(IMAPOPT_CONVERSATIONS))
prot_printf(imapd_out, " XCONVERSATIONS");
#ifdef HAVE_ZLIB
if (!imapd_compress_done && !imapd_tls_comp) {
prot_printf(imapd_out, " COMPRESS=DEFLATE");
}
#endif // HAVE_ZLIB
for (i = 0 ; i < QUOTA_NUMRESOURCES ; i++)
prot_printf(imapd_out, " X-QUOTA=%s", quota_names[i]);
if (idle_enabled()) {
prot_printf(imapd_out, " IDLE");
}
}
/*
* Perform a CAPABILITY command
*/
static void cmd_capability(char *tag)
{
imapd_check(NULL, 0);
prot_printf(imapd_out, "* CAPABILITY ");
capa_response(CAPA_PREAUTH|CAPA_POSTAUTH);
prot_printf(imapd_out, "\r\n%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
/*
* Parse and perform an APPEND command.
* The command has been parsed up to and including
* the mailbox name.
*/
static int isokflag(char *s, int *isseen)
{
if (s[0] == '\\') {
lcase(s);
if (!strcmp(s, "\\seen")) {
*isseen = 1;
return 1;
}
if (!strcmp(s, "\\answered")) return 1;
if (!strcmp(s, "\\flagged")) return 1;
if (!strcmp(s, "\\draft")) return 1;
if (!strcmp(s, "\\deleted")) return 1;
/* uh oh, system flag i don't recognize */
return 0;
} else {
/* valid user flag? */
return imparse_isatom(s);
}
}
static int getliteralsize(const char *p, int c,
unsigned *size, int *binary, const char **parseerr)
{
int isnowait = 0;
uint32_t num;
/* Check for literal8 */
if (*p == '~') {
p++;
*binary = 1;
}
/* check for start of literal */
if (*p != '{') {
*parseerr = "Missing required argument to Append command";
return IMAP_PROTOCOL_ERROR;
}
/* Read size from literal */
if (parseuint32(p+1, &p, &num)) {
*parseerr = "Literal size not a number";
return IMAP_PROTOCOL_ERROR;
}
if (*p == '+') {
isnowait++;
p++;
}
if (c == '\r') {
c = prot_getc(imapd_in);
}
if (*p != '}' || p[1] || c != '\n') {
*parseerr = "Invalid literal in Append command";
return IMAP_PROTOCOL_ERROR;
}
if (!isnowait) {
/* Tell client to send the message */
prot_printf(imapd_out, "+ go ahead\r\n");
prot_flush(imapd_out);
}
*size = num;
return 0;
}
static int catenate_text(FILE *f, unsigned *totalsize, int *binary,
const char **parseerr)
{
int c;
static struct buf arg;
unsigned size = 0;
char buf[4096+1];
unsigned n;
int r;
c = getword(imapd_in, &arg);
/* Read size from literal */
r = getliteralsize(arg.s, c, &size, binary, parseerr);
if (r) return r;
if (*totalsize > UINT_MAX - size) r = IMAP_MESSAGE_TOO_LARGE;
/* Catenate message part to stage */
while (size) {
n = prot_read(imapd_in, buf, size > 4096 ? 4096 : size);
if (!n) {
syslog(LOG_ERR,
"DISCONNECT: client disconnected during upload of literal");
return IMAP_IOERROR;
}
buf[n] = '\0';
if (!*binary && (n != strlen(buf))) r = IMAP_MESSAGE_CONTAINSNULL;
size -= n;
if (r) continue;
/* XXX do we want to try and validate the message like
we do in message_copy_strict()? */
if (f) fwrite(buf, n, 1, f);
}
*totalsize += size;
return r;
}
static int catenate_url(const char *s, const char *cur_name, FILE *f,
unsigned *totalsize, const char **parseerr)
{
struct imapurl url;
struct index_state *state;
uint32_t msgno;
int r = 0, doclose = 0;
unsigned long size = 0;
r = imapurl_fromURL(&url, s);
if (r) {
*parseerr = "Improperly specified URL";
r = IMAP_BADURL;
} else if (url.server) {
*parseerr = "Only relative URLs are supported";
r = IMAP_BADURL;
#if 0
} else if (url.server && strcmp(url.server, config_servername)) {
*parseerr = "Cannot catenate messages from another server";
r = IMAP_BADURL;
#endif
} else if (!url.mailbox && !imapd_index && !cur_name) {
*parseerr = "No mailbox is selected or specified";
r = IMAP_BADURL;
} else if (url.mailbox || (url.mailbox = cur_name)) {
mbentry_t *mbentry = NULL;
/* lookup the location of the mailbox */
char *intname = mboxname_from_external(url.mailbox, &imapd_namespace, imapd_userid);
r = mlookup(NULL, NULL, intname, &mbentry);
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
struct backend *be;
be = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (be) {
r = proxy_catenate_url(be, &url, f, &size, parseerr);
if (*totalsize > UINT_MAX - size)
r = IMAP_MESSAGE_TOO_LARGE;
else
*totalsize += size;
}
else
r = IMAP_SERVER_UNAVAILABLE;
free(url.freeme);
mboxlist_entry_free(&mbentry);
free(intname);
return r;
}
mboxlist_entry_free(&mbentry);
/* local mailbox */
if (!r) {
struct index_init init;
memset(&init, 0, sizeof(init));
init.userid = imapd_userid;
init.authstate = imapd_authstate;
init.out = imapd_out;
r = index_open(intname, &init, &state);
if (init.vanishedlist) seqset_free(init.vanishedlist);
}
if (!r) doclose = 1;
if (!r && !(state->myrights & ACL_READ))
r = (imapd_userisadmin || (state->myrights & ACL_LOOKUP)) ?
IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT;
if (r) {
*parseerr = error_message(r);
r = IMAP_BADURL;
}
free(intname);
} else {
state = imapd_index;
}
if (r) {
/* nothing to do, handled up top */
} else if (url.uidvalidity &&
(state->mailbox->i.uidvalidity != url.uidvalidity)) {
*parseerr = "Uidvalidity of mailbox has changed";
r = IMAP_BADURL;
} else if (!url.uid || !(msgno = index_finduid(state, url.uid)) ||
(index_getuid(state, msgno) != url.uid)) {
*parseerr = "No such message in mailbox";
r = IMAP_BADURL;
} else {
/* Catenate message part to stage */
struct protstream *s = prot_new(fileno(f), 1);
r = index_urlfetch(state, msgno, 0, url.section,
url.start_octet, url.octet_count, s, &size);
if (r == IMAP_BADURL)
*parseerr = "No such message part";
else if (!r) {
if (*totalsize > UINT_MAX - size)
r = IMAP_MESSAGE_TOO_LARGE;
else
*totalsize += size;
}
prot_flush(s);
prot_free(s);
/* XXX do we want to try and validate the message like
we do in message_copy_strict()? */
}
free(url.freeme);
if (doclose) index_close(&state);
return r;
}
static int append_catenate(FILE *f, const char *cur_name, unsigned *totalsize,
int *binary, const char **parseerr, const char **url)
{
int c, r = 0;
static struct buf arg;
do {
c = getword(imapd_in, &arg);
if (c != ' ') {
*parseerr = "Missing message part data in Append command";
return IMAP_PROTOCOL_ERROR;
}
if (!strcasecmp(arg.s, "TEXT")) {
int r1 = catenate_text(f, totalsize, binary, parseerr);
if (r1) return r1;
/* if we see a SP, we're trying to catenate more than one part */
/* Parse newline terminating command */
c = prot_getc(imapd_in);
}
else if (!strcasecmp(arg.s, "URL")) {
c = getastring(imapd_in, imapd_out, &arg);
if (c != ' ' && c != ')') {
*parseerr = "Missing URL in Append command";
return IMAP_PROTOCOL_ERROR;
}
if (!r) {
r = catenate_url(arg.s, cur_name, f, totalsize, parseerr);
if (r) {
*url = arg.s;
return r;
}
}
}
else {
*parseerr = "Invalid message part type in Append command";
return IMAP_PROTOCOL_ERROR;
}
fflush(f);
} while (c == ' ');
if (c != ')') {
*parseerr = "Missing space or ) after catenate list in Append command";
return IMAP_PROTOCOL_ERROR;
}
if (ferror(f) || fsync(fileno(f))) {
syslog(LOG_ERR, "IOERROR: writing message: %m");
return IMAP_IOERROR;
}
return r;
}
/* If an APPEND is proxied from another server,
* 'cur_name' is the name of the currently selected mailbox (if any)
* in case we have to resolve relative URLs
*/
static void cmd_append(char *tag, char *name, const char *cur_name)
{
int c;
static struct buf arg;
time_t now = time(NULL);
quota_t qdiffs[QUOTA_NUMRESOURCES] = QUOTA_DIFFS_INITIALIZER;
unsigned size;
int sync_seen = 0;
int r;
int i;
struct appendstate appendstate;
unsigned long uidvalidity = 0;
long doappenduid = 0;
const char *parseerr = NULL, *url = NULL;
struct appendstage *curstage;
mbentry_t *mbentry = NULL;
/* See if we can append */
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(tag, name, intname, &mbentry);
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
struct backend *s = NULL;
if (supports_referrals) {
imapd_refer(tag, mbentry->server, name);
/* Eat the argument */
eatline(imapd_in, prot_getc(imapd_in));
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!s) r = IMAP_SERVER_UNAVAILABLE;
mboxlist_entry_free(&mbentry);
imapd_check(s, 0);
if (!r) {
int is_active = 1;
s->context = (void*) &is_active;
if (imapd_index) {
const char *mboxname = index_mboxname(imapd_index);
prot_printf(s->out, "%s Localappend {" SIZE_T_FMT "+}\r\n%s"
" {" SIZE_T_FMT "+}\r\n%s ",
tag, strlen(name), name,
strlen(mboxname), mboxname);
} else {
prot_printf(s->out, "%s Localappend {" SIZE_T_FMT "+}\r\n%s"
" \"\" ", tag, strlen(name), name);
}
if (!(r = pipe_command(s, 16384))) {
pipe_including_tag(s, tag, 0);
}
s->context = NULL;
} else {
eatline(imapd_in, prot_getc(imapd_in));
}
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag,
prot_error(imapd_in) ? prot_error(imapd_in) :
error_message(r));
}
free(intname);
return;
}
mboxlist_entry_free(&mbentry);
/* local mailbox */
if (!r) {
qdiffs[QUOTA_MESSAGE] = 1;
r = append_check(intname, imapd_authstate, ACL_INSERT, ignorequota ? NULL : qdiffs);
}
if (r) {
eatline(imapd_in, ' ');
prot_printf(imapd_out, "%s NO %s%s\r\n",
tag,
(r == IMAP_MAILBOX_NONEXISTENT &&
mboxlist_createmailboxcheck(intname, 0, 0,
imapd_userisadmin,
imapd_userid, imapd_authstate,
NULL, NULL, 0) == 0)
? "[TRYCREATE] " : "", error_message(r));
free(intname);
return;
}
c = ' '; /* just parsed a space */
/* we loop, to support MULTIAPPEND */
while (!r && c == ' ') {
curstage = xzmalloc(sizeof(*curstage));
ptrarray_push(&stages, curstage);
/* now parsing "append-opts" in the ABNF */
/* Parse flags */
c = getword(imapd_in, &arg);
if (c == '(' && !arg.s[0]) {
strarray_init(&curstage->flags);
do {
c = getword(imapd_in, &arg);
if (!curstage->flags.count && !arg.s[0] && c == ')') break; /* empty list */
if (!isokflag(arg.s, &sync_seen)) {
parseerr = "Invalid flag in Append command";
r = IMAP_PROTOCOL_ERROR;
goto done;
}
strarray_append(&curstage->flags, arg.s);
} while (c == ' ');
if (c != ')') {
parseerr =
"Missing space or ) after flag name in Append command";
r = IMAP_PROTOCOL_ERROR;
goto done;
}
c = prot_getc(imapd_in);
if (c != ' ') {
parseerr = "Missing space after flag list in Append command";
r = IMAP_PROTOCOL_ERROR;
goto done;
}
c = getword(imapd_in, &arg);
}
/* Parse internaldate */
if (c == '\"' && !arg.s[0]) {
prot_ungetc(c, imapd_in);
c = getdatetime(&(curstage->internaldate));
if (c != ' ') {
parseerr = "Invalid date-time in Append command";
r = IMAP_PROTOCOL_ERROR;
goto done;
}
c = getword(imapd_in, &arg);
}
/* try to parse a sequence of "append-ext" */
for (;;) {
if (!strcasecmp(arg.s, "ANNOTATION")) {
/* RFC5257 */
if (c != ' ') {
parseerr = "Missing annotation data in Append command";
r = IMAP_PROTOCOL_ERROR;
goto done;
}
c = parse_annotate_store_data(tag,
/*permessage_flag*/1,
&curstage->annotations);
if (c == EOF) {
eatline(imapd_in, c);
goto cleanup;
}
qdiffs[QUOTA_ANNOTSTORAGE] += sizeentryatts(curstage->annotations);
c = getword(imapd_in, &arg);
}
else
break; /* not a known extension keyword */
}
/* Stage the message */
curstage->f = append_newstage(intname, now, stages.count, &(curstage->stage));
if (!curstage->f) {
r = IMAP_IOERROR;
goto done;
}
/* now parsing "append-data" in the ABNF */
if (!strcasecmp(arg.s, "CATENATE")) {
if (c != ' ' || (c = prot_getc(imapd_in) != '(')) {
parseerr = "Missing message part(s) in Append command";
r = IMAP_PROTOCOL_ERROR;
goto done;
}
/* Catenate the message part(s) to stage */
size = 0;
r = append_catenate(curstage->f, cur_name, &size,
&(curstage->binary), &parseerr, &url);
if (r) goto done;
}
else {
/* Read size from literal */
r = getliteralsize(arg.s, c, &size, &(curstage->binary), &parseerr);
if (!r && size == 0) r = IMAP_ZERO_LENGTH_LITERAL;
if (r) goto done;
/* Copy message to stage */
r = message_copy_strict(imapd_in, curstage->f, size, curstage->binary);
}
qdiffs[QUOTA_STORAGE] += size;
/* If this is a non-BINARY message, close the stage file.
* Otherwise, leave it open so we can encode the binary parts.
*
* XXX For BINARY MULTIAPPEND, we may have to close the stage files
* anyways to avoid too many open files.
*/
if (!curstage->binary) {
fclose(curstage->f);
curstage->f = NULL;
}
/* if we see a SP, we're trying to append more than one message */
/* Parse newline terminating command */
c = prot_getc(imapd_in);
}
done:
if (r) {
eatline(imapd_in, c);
} else {
/* we should be looking at the end of the line */
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
parseerr = "junk after literal";
r = IMAP_PROTOCOL_ERROR;
eatline(imapd_in, c);
}
}
/* Append from the stage(s) */
if (!r) {
qdiffs[QUOTA_MESSAGE] = stages.count;
r = append_setup(&appendstate, intname,
imapd_userid, imapd_authstate, ACL_INSERT,
ignorequota ? NULL : qdiffs, &imapd_namespace,
(imapd_userisadmin || imapd_userisproxyadmin),
EVENT_MESSAGE_APPEND);
}
if (!r) {
struct body *body;
doappenduid = (appendstate.myrights & ACL_READ);
uidvalidity = append_uidvalidity(&appendstate);
for (i = 0; !r && i < stages.count ; i++) {
curstage = stages.data[i];
body = NULL;
if (curstage->binary) {
r = message_parse_binary_file(curstage->f, &body);
fclose(curstage->f);
curstage->f = NULL;
}
if (!r) {
r = append_fromstage(&appendstate, &body, curstage->stage,
curstage->internaldate,
&curstage->flags, 0,
curstage->annotations);
}
if (body) {
/* Note: either the calls to message_parse_binary_file()
* or append_fromstage() above, may create a body. */
message_free_body(body);
free(body);
body = NULL;
}
}
if (!r) {
r = append_commit(&appendstate);
} else {
append_abort(&appendstate);
}
}
imapd_check(NULL, 1);
if (r == IMAP_PROTOCOL_ERROR && parseerr) {
prot_printf(imapd_out, "%s BAD %s\r\n", tag, parseerr);
} else if (r == IMAP_BADURL) {
prot_printf(imapd_out, "%s NO [BADURL \"%s\"] %s\r\n",
tag, url, parseerr);
} else if (r) {
prot_printf(imapd_out, "%s NO %s%s\r\n",
tag,
(r == IMAP_MAILBOX_NONEXISTENT &&
mboxlist_createmailboxcheck(intname, 0, 0,
imapd_userisadmin,
imapd_userid, imapd_authstate,
NULL, NULL, 0) == 0)
? "[TRYCREATE] " : r == IMAP_MESSAGE_TOO_LARGE
? "[TOOBIG]" : "", error_message(r));
} else if (doappenduid) {
/* is this a space seperated list or sequence list? */
prot_printf(imapd_out, "%s OK [APPENDUID %lu ", tag, uidvalidity);
if (appendstate.nummsg == 1) {
prot_printf(imapd_out, "%u", appendstate.baseuid);
} else {
prot_printf(imapd_out, "%u:%u", appendstate.baseuid,
appendstate.baseuid + appendstate.nummsg - 1);
}
prot_printf(imapd_out, "] %s\r\n", error_message(IMAP_OK_COMPLETED));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
cleanup:
/* Cleanup the stage(s) */
while ((curstage = ptrarray_pop(&stages))) {
if (curstage->f != NULL) fclose(curstage->f);
append_removestage(curstage->stage);
strarray_fini(&curstage->flags);
freeentryatts(curstage->annotations);
free(curstage);
}
free(intname);
ptrarray_fini(&stages);
}
/*
* Warn if mailbox is close to or over any quota resource.
*
* Warn if the following possibilities occur:
* - quotawarnkb not set + quotawarn hit
* - quotawarnkb set larger than mailbox + quotawarn hit
* - quotawarnkb set + hit + quotawarn hit
* - quotawarnmsg not set + quotawarn hit
* - quotawarnmsg set larger than mailbox + quotawarn hit
* - quotawarnmsg set + hit + quotawarn hit
*/
static void warn_about_quota(const char *quotaroot)
{
time_t now = time(NULL);
struct quota q;
int res;
int r;
int thresholds[QUOTA_NUMRESOURCES];
int pc_threshold = config_getint(IMAPOPT_QUOTAWARN);
int pc_usage;
struct buf msg = BUF_INITIALIZER;
static char lastqr[MAX_MAILBOX_PATH+1] = "";
static time_t nextalert = 0;
if (!quotaroot || !*quotaroot)
return; /* no quota, nothing to do */
/* rate limit checks and warnings to every 10 min */
if (!strcmp(quotaroot, lastqr) && now < nextalert)
return;
strlcpy(lastqr, quotaroot, sizeof(lastqr));
nextalert = now + 600;
quota_init(&q, quotaroot);
r = quota_read(&q, NULL, 0);
if (r)
goto out; /* failed to read */
memset(thresholds, 0, sizeof(thresholds));
thresholds[QUOTA_STORAGE] = config_getint(IMAPOPT_QUOTAWARNKB);
thresholds[QUOTA_MESSAGE] = config_getint(IMAPOPT_QUOTAWARNMSG);
thresholds[QUOTA_ANNOTSTORAGE] = config_getint(IMAPOPT_QUOTAWARNKB);
for (res = 0 ; res < QUOTA_NUMRESOURCES ; res++) {
if (q.limits[res] < 0)
continue; /* this resource is unlimited */
buf_reset(&msg);
if (thresholds[res] <= 0 ||
thresholds[res] >= q.limits[res] ||
q.useds[res] > ((quota_t) (q.limits[res] - thresholds[res])) * quota_units[res]) {
pc_usage = (int)(((double) q.useds[res] * 100.0) /
(double) ((quota_t) q.limits[res] * quota_units[res]));
if (q.useds[res] > (quota_t) q.limits[res] * quota_units[res])
buf_printf(&msg, error_message(IMAP_NO_OVERQUOTA),
quota_names[res]);
else if (pc_usage > pc_threshold)
buf_printf(&msg, error_message(IMAP_NO_CLOSEQUOTA),
pc_usage, quota_names[res]);
}
if (msg.len)
prot_printf(imapd_out, "* NO [ALERT] %s\r\n", buf_cstring(&msg));
}
buf_reset(&msg);
out:
quota_free(&q);
}
/*
* Perform a SELECT/EXAMINE/BBOARD command
*/
static void cmd_select(char *tag, char *cmd, char *name)
{
int c;
int r = 0;
int doclose = 0;
mbentry_t *mbentry = NULL;
struct backend *backend_next = NULL;
struct index_init init;
int wasopen = 0;
struct vanished_params *v = &init.vanished;
memset(&init, 0, sizeof(struct index_init));
c = prot_getc(imapd_in);
if (c == ' ') {
static struct buf arg, parm1, parm2;
c = prot_getc(imapd_in);
if (c != '(') goto badlist;
c = getword(imapd_in, &arg);
if (arg.s[0] == '\0') goto badlist;
for (;;) {
ucase(arg.s);
if (!strcmp(arg.s, "CONDSTORE")) {
client_capa |= CAPA_CONDSTORE;
}
else if ((client_capa & CAPA_QRESYNC) &&
!strcmp(arg.s, "QRESYNC")) {
char *p;
if (c != ' ') goto badqresync;
c = prot_getc(imapd_in);
if (c != '(') goto badqresync;
c = getastring(imapd_in, imapd_out, &arg);
v->uidvalidity = strtoul(arg.s, &p, 10);
if (*p || !v->uidvalidity || v->uidvalidity == ULONG_MAX) goto badqresync;
if (c != ' ') goto badqresync;
c = getmodseq(imapd_in, &v->modseq);
if (c == EOF) goto badqresync;
if (c == ' ') {
c = prot_getc(imapd_in);
if (c != '(') {
/* optional UID sequence */
prot_ungetc(c, imapd_in);
c = getword(imapd_in, &arg);
if (!imparse_issequence(arg.s)) goto badqresync;
v->sequence = arg.s;
if (c == ' ') {
c = prot_getc(imapd_in);
if (c != '(') goto badqresync;
}
}
if (c == '(') {
/* optional sequence match data */
c = getword(imapd_in, &parm1);
if (!imparse_issequence(parm1.s)) goto badqresync;
v->match_seq = parm1.s;
if (c != ' ') goto badqresync;
c = getword(imapd_in, &parm2);
if (!imparse_issequence(parm2.s)) goto badqresync;
v->match_uid = parm2.s;
if (c != ')') goto badqresync;
c = prot_getc(imapd_in);
}
}
if (c != ')') goto badqresync;
c = prot_getc(imapd_in);
}
else if (!strcmp(arg.s, "ANNOTATE")) {
/*
* RFC5257 requires us to parse this keyword, which
* indicates that the client wants unsolicited
* ANNOTATION responses in this session, but we don't
* actually have to do anything with it, so we won't.
*/
;
}
else {
prot_printf(imapd_out, "%s BAD Invalid %s modifier %s\r\n",
tag, cmd, arg.s);
eatline(imapd_in, c);
return;
}
if (c == ' ') c = getword(imapd_in, &arg);
else break;
}
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close parenthesis in %s\r\n", tag, cmd);
eatline(imapd_in, c);
return;
}
c = prot_getc(imapd_in);
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to %s\r\n", tag, cmd);
eatline(imapd_in, c);
return;
}
if (imapd_index) {
index_close(&imapd_index);
wasopen = 1;
}
if (backend_current) {
/* remove backend_current from the protgroup */
protgroup_delete(protin, backend_current->in);
wasopen = 1;
}
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(tag, name, intname, &mbentry);
if (r == IMAP_MAILBOX_MOVED) {
free(intname);
return;
}
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
char mytag[128];
if (supports_referrals) {
imapd_refer(tag, mbentry->server, name);
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
backend_next = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox,
imapd_in);
if (!backend_next) r = IMAP_SERVER_UNAVAILABLE;
if (backend_current && backend_current != backend_next) {
/* switching servers; flush old server output */
proxy_gentag(mytag, sizeof(mytag));
prot_printf(backend_current->out, "%s Unselect\r\n", mytag);
/* do not fatal() here, because we don't really care about this
* server anymore anyway */
pipe_until_tag(backend_current, mytag, 1);
}
backend_current = backend_next;
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
if (client_capa) {
/* Enable client capabilities on new backend */
proxy_gentag(mytag, sizeof(mytag));
prot_printf(backend_current->out, "%s Enable", mytag);
if (client_capa & CAPA_QRESYNC)
prot_printf(backend_current->out, " Qresync");
else if (client_capa & CAPA_CONDSTORE)
prot_printf(backend_current->out, " Condstore");
prot_printf(backend_current->out, "\r\n");
pipe_until_tag(backend_current, mytag, 0);
}
/* Send SELECT command to backend */
prot_printf(backend_current->out, "%s %s {" SIZE_T_FMT "+}\r\n%s",
tag, cmd, strlen(name), name);
if (v->uidvalidity) {
prot_printf(backend_current->out, " (QRESYNC (%lu " MODSEQ_FMT,
v->uidvalidity, v->modseq);
if (v->sequence) {
prot_printf(backend_current->out, " %s", v->sequence);
}
if (v->match_seq && v->match_uid) {
prot_printf(backend_current->out, " (%s %s)",
v->match_seq, v->match_uid);
}
prot_printf(backend_current->out, "))");
}
prot_printf(backend_current->out, "\r\n");
switch (pipe_including_tag(backend_current, tag, 0)) {
case PROXY_OK:
syslog(LOG_DEBUG, "open: user %s opened %s on %s",
imapd_userid, name, mbentry->server);
/* add backend_current to the protgroup */
protgroup_insert(protin, backend_current->in);
break;
default:
syslog(LOG_DEBUG, "open: user %s failed to open %s", imapd_userid,
name);
/* not successfully selected */
backend_current = NULL;
break;
}
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
mboxlist_entry_free(&mbentry);
/* local mailbox */
if (backend_current) {
char mytag[128];
/* switching servers; flush old server output */
proxy_gentag(mytag, sizeof(mytag));
prot_printf(backend_current->out, "%s Unselect\r\n", mytag);
/* do not fatal() here, because we don't really care about this
* server anymore anyway */
pipe_until_tag(backend_current, mytag, 1);
}
backend_current = NULL;
if (wasopen) prot_printf(imapd_out, "* OK [CLOSED] Ok\r\n");
init.userid = imapd_userid;
init.authstate = imapd_authstate;
init.out = imapd_out;
init.examine_mode = cmd[0] == 'E';
init.select = 1;
if (!strcasecmpsafe(imapd_magicplus, "+dav")) init.want_dav = 1;
r = index_open(intname, &init, &imapd_index);
if (!r) doclose = 1;
if (!r && !index_hasrights(imapd_index, ACL_READ)) {
r = (imapd_userisadmin || index_hasrights(imapd_index, ACL_LOOKUP)) ?
IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT;
}
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
if (init.vanishedlist) seqset_free(init.vanishedlist);
init.vanishedlist = NULL;
if (doclose) index_close(&imapd_index);
free(intname);
return;
}
if (index_hasrights(imapd_index, ACL_EXPUNGE))
warn_about_quota(imapd_index->mailbox->quotaroot);
index_select(imapd_index, &init);
if (init.vanishedlist) seqset_free(init.vanishedlist);
init.vanishedlist = NULL;
prot_printf(imapd_out, "%s OK [READ-%s] %s\r\n", tag,
index_hasrights(imapd_index, ACL_READ_WRITE) ?
"WRITE" : "ONLY", error_message(IMAP_OK_COMPLETED));
syslog(LOG_DEBUG, "open: user %s opened %s", imapd_userid, name);
free(intname);
return;
badlist:
prot_printf(imapd_out, "%s BAD Invalid modifier list in %s\r\n", tag, cmd);
eatline(imapd_in, c);
return;
badqresync:
prot_printf(imapd_out, "%s BAD Invalid QRESYNC parameter list in %s\r\n",
tag, cmd);
eatline(imapd_in, c);
return;
}
/*
* Perform a CLOSE/UNSELECT command
*/
static void cmd_close(char *tag, char *cmd)
{
if (backend_current) {
/* remote mailbox */
prot_printf(backend_current->out, "%s %s\r\n", tag, cmd);
/* xxx do we want this to say OK if the connection is gone?
* saying NO is clearly wrong, hense the fatal request. */
pipe_including_tag(backend_current, tag, 0);
/* remove backend_current from the protgroup */
protgroup_delete(protin, backend_current->in);
backend_current = NULL;
return;
}
/* local mailbox */
if ((cmd[0] == 'C') && index_hasrights(imapd_index, ACL_EXPUNGE)) {
index_expunge(imapd_index, NULL, 1);
/* don't tell changes here */
}
index_close(&imapd_index);
/* http://www.rfc-editor.org/errata_search.php?rfc=5162
* Errata ID: 1808 - don't send HIGHESTMODSEQ to a close
* command, because it can lose synchronisation */
prot_printf(imapd_out, "%s OK %s\r\n",
tag, error_message(IMAP_OK_COMPLETED));
}
/*
* Append to the section list.
*/
static void section_list_append(struct section **l,
const char *name,
const struct octetinfo *oi)
{
struct section **tail = l;
while (*tail) tail = &(*tail)->next;
*tail = xzmalloc(sizeof(struct section));
(*tail)->name = xstrdup(name);
(*tail)->octetinfo = *oi;
(*tail)->next = NULL;
}
static void section_list_free(struct section *l)
{
struct section *n;
while (l) {
n = l->next;
free(l->name);
free(l);
l = n;
}
}
/*
* Parse the syntax for a partial fetch:
* "<" number "." nz-number ">"
*/
#define PARSE_PARTIAL(start_octet, octet_count) \
(start_octet) = (octet_count) = 0; \
if (*p == '<' && Uisdigit(p[1])) { \
(start_octet) = p[1] - '0'; \
p += 2; \
while (Uisdigit((int) *p)) { \
(start_octet) = \
(start_octet) * 10 + *p++ - '0'; \
} \
\
if (*p == '.' && p[1] >= '1' && p[1] <= '9') { \
(octet_count) = p[1] - '0'; \
p[0] = '>'; p[1] = '\0'; /* clip off the octet count \
(its not used in the reply) */ \
p += 2; \
while (Uisdigit(*p)) { \
(octet_count) = \
(octet_count) * 10 + *p++ - '0'; \
} \
} \
else p--; \
\
if (*p != '>') { \
prot_printf(imapd_out, \
"%s BAD Invalid body partial\r\n", tag); \
eatline(imapd_in, c); \
goto freeargs; \
} \
p++; \
}
static int parse_fetch_args(const char *tag, const char *cmd,
int allow_vanished,
struct fetchargs *fa)
{
static struct buf fetchatt, fieldname;
int c;
int inlist = 0;
char *p, *section;
struct octetinfo oi;
strarray_t *newfields = strarray_new();
c = getword(imapd_in, &fetchatt);
if (c == '(' && !fetchatt.s[0]) {
inlist = 1;
c = getword(imapd_in, &fetchatt);
}
for (;;) {
ucase(fetchatt.s);
switch (fetchatt.s[0]) {
case 'A':
if (!inlist && !strcmp(fetchatt.s, "ALL")) {
fa->fetchitems |= FETCH_ALL;
}
else if (!strcmp(fetchatt.s, "ANNOTATION")) {
fa->fetchitems |= FETCH_ANNOTATION;
if (c != ' ')
goto badannotation;
c = prot_getc(imapd_in);
if (c != '(')
goto badannotation;
c = parse_annotate_fetch_data(tag,
/*permessage_flag*/1,
&fa->entries,
&fa->attribs);
if (c == EOF) {
eatline(imapd_in, c);
goto freeargs;
}
if (c != ')') {
badannotation:
prot_printf(imapd_out, "%s BAD invalid Annotation\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
c = prot_getc(imapd_in);
}
else goto badatt;
break;
case 'B':
if (!strncmp(fetchatt.s, "BINARY[", 7) ||
!strncmp(fetchatt.s, "BINARY.PEEK[", 12) ||
!strncmp(fetchatt.s, "BINARY.SIZE[", 12)) {
int binsize = 0;
p = section = fetchatt.s + 7;
if (!strncmp(p, "PEEK[", 5)) {
p = section += 5;
}
else if (!strncmp(p, "SIZE[", 5)) {
p = section += 5;
binsize = 1;
}
else {
fa->fetchitems |= FETCH_SETSEEN;
}
while (Uisdigit(*p) || *p == '.') {
if (*p == '.' && !Uisdigit(p[-1])) break;
/* Part number cannot begin with '0' */
if (*p == '0' && !Uisdigit(p[-1])) break;
p++;
}
if (*p != ']') {
prot_printf(imapd_out, "%s BAD Invalid binary section\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
p++;
if (!binsize) PARSE_PARTIAL(oi.start_octet, oi.octet_count);
if (*p) {
prot_printf(imapd_out, "%s BAD Junk after binary section\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
if (binsize)
section_list_append(&fa->sizesections, section, &oi);
else
section_list_append(&fa->binsections, section, &oi);
}
else if (!strcmp(fetchatt.s, "BODY")) {
fa->fetchitems |= FETCH_BODY;
}
else if (!strcmp(fetchatt.s, "BODYSTRUCTURE")) {
fa->fetchitems |= FETCH_BODYSTRUCTURE;
}
else if (!strncmp(fetchatt.s, "BODY[", 5) ||
!strncmp(fetchatt.s, "BODY.PEEK[", 10)) {
p = section = fetchatt.s + 5;
if (!strncmp(p, "PEEK[", 5)) {
p = section += 5;
}
else {
fa->fetchitems |= FETCH_SETSEEN;
}
while (Uisdigit(*p) || *p == '.') {
if (*p == '.' && !Uisdigit(p[-1])) break;
/* Obsolete section 0 can only occur before close brace */
if (*p == '0' && !Uisdigit(p[-1]) && p[1] != ']') break;
p++;
}
if (*p == 'H' && !strncmp(p, "HEADER.FIELDS", 13) &&
(p == section || p[-1] == '.') &&
(p[13] == '\0' || !strcmp(p+13, ".NOT"))) {
/*
* If not top-level or a HEADER.FIELDS.NOT, can't pull
* the headers out of the cache.
*/
if (p != section || p[13] != '\0') {
fa->cache_atleast = BIT32_MAX;
}
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing required argument to %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
c = prot_getc(imapd_in);
if (c != '(') {
prot_printf(imapd_out, "%s BAD Missing required open parenthesis in %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
do {
c = getastring(imapd_in, imapd_out, &fieldname);
for (p = fieldname.s; *p; p++) {
if (*p <= ' ' || *p & 0x80 || *p == ':') break;
}
if (*p || !*fieldname.s) {
prot_printf(imapd_out, "%s BAD Invalid field-name in %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
strarray_append(newfields, fieldname.s);
if (fa->cache_atleast < BIT32_MAX) {
bit32 this_ver =
mailbox_cached_header(fieldname.s);
if(this_ver > fa->cache_atleast)
fa->cache_atleast = this_ver;
}
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out, "%s BAD Missing required close parenthesis in %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
/* Grab/parse the ]<x.y> part */
c = getword(imapd_in, &fieldname);
p = fieldname.s;
if (*p++ != ']') {
prot_printf(imapd_out, "%s BAD Missing required close bracket after %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
PARSE_PARTIAL(oi.start_octet, oi.octet_count);
if (*p) {
prot_printf(imapd_out, "%s BAD Junk after body section\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
appendfieldlist(&fa->fsections,
section, newfields, fieldname.s,
&oi, sizeof(oi));
/* old 'newfields' is managed by the fieldlist now */
newfields = strarray_new();
break;
}
switch (*p) {
case 'H':
if (p != section && p[-1] != '.') break;
if (!strncmp(p, "HEADER]", 7)) p += 6;
break;
case 'M':
if (!strncmp(p-1, ".MIME]", 6)) p += 4;
break;
case 'T':
if (p != section && p[-1] != '.') break;
if (!strncmp(p, "TEXT]", 5)) p += 4;
break;
}
if (*p != ']') {
prot_printf(imapd_out, "%s BAD Invalid body section\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
p++;
PARSE_PARTIAL(oi.start_octet, oi.octet_count);
if (*p) {
prot_printf(imapd_out, "%s BAD Junk after body section\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
section_list_append(&fa->bodysections, section, &oi);
}
else goto badatt;
break;
case 'C':
if (!strcmp(fetchatt.s, "CID") &&
config_getswitch(IMAPOPT_CONVERSATIONS)) {
fa->fetchitems |= FETCH_CID;
}
else goto badatt;
break;
case 'D':
if (!strcmp(fetchatt.s, "DIGEST.SHA1")) {
fa->fetchitems |= FETCH_GUID;
}
else goto badatt;
break;
case 'E':
if (!strcmp(fetchatt.s, "ENVELOPE")) {
fa->fetchitems |= FETCH_ENVELOPE;
}
else goto badatt;
break;
case 'F':
if (!inlist && !strcmp(fetchatt.s, "FAST")) {
fa->fetchitems |= FETCH_FAST;
}
else if (!inlist && !strcmp(fetchatt.s, "FULL")) {
fa->fetchitems |= FETCH_FULL;
}
else if (!strcmp(fetchatt.s, "FLAGS")) {
fa->fetchitems |= FETCH_FLAGS;
}
else if (!strcmp(fetchatt.s, "FOLDER")) {
fa->fetchitems |= FETCH_FOLDER;
}
else goto badatt;
break;
case 'I':
if (!strcmp(fetchatt.s, "INTERNALDATE")) {
fa->fetchitems |= FETCH_INTERNALDATE;
}
else goto badatt;
break;
case 'M':
if (!strcmp(fetchatt.s, "MODSEQ")) {
fa->fetchitems |= FETCH_MODSEQ;
}
else goto badatt;
break;
case 'R':
if (!strcmp(fetchatt.s, "RFC822")) {
fa->fetchitems |= FETCH_RFC822|FETCH_SETSEEN;
}
else if (!strcmp(fetchatt.s, "RFC822.HEADER")) {
fa->fetchitems |= FETCH_HEADER;
}
else if (!strcmp(fetchatt.s, "RFC822.PEEK")) {
fa->fetchitems |= FETCH_RFC822;
}
else if (!strcmp(fetchatt.s, "RFC822.SIZE")) {
fa->fetchitems |= FETCH_SIZE;
}
else if (!strcmp(fetchatt.s, "RFC822.TEXT")) {
fa->fetchitems |= FETCH_TEXT|FETCH_SETSEEN;
}
else if (!strcmp(fetchatt.s, "RFC822.SHA1")) {
fa->fetchitems |= FETCH_SHA1;
}
else if (!strcmp(fetchatt.s, "RFC822.FILESIZE")) {
fa->fetchitems |= FETCH_FILESIZE;
}
else if (!strcmp(fetchatt.s, "RFC822.TEXT.PEEK")) {
fa->fetchitems |= FETCH_TEXT;
}
else if (!strcmp(fetchatt.s, "RFC822.HEADER.LINES") ||
!strcmp(fetchatt.s, "RFC822.HEADER.LINES.NOT")) {
if (c != ' ') {
prot_printf(imapd_out, "%s BAD Missing required argument to %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
c = prot_getc(imapd_in);
if (c != '(') {
prot_printf(imapd_out, "%s BAD Missing required open parenthesis in %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
do {
c = getastring(imapd_in, imapd_out, &fieldname);
for (p = fieldname.s; *p; p++) {
if (*p <= ' ' || *p & 0x80 || *p == ':') break;
}
if (*p || !*fieldname.s) {
prot_printf(imapd_out, "%s BAD Invalid field-name in %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
lcase(fieldname.s);;
/* 19 is magic number -- length of
* "RFC822.HEADERS.NOT" */
strarray_append(strlen(fetchatt.s) == 19 ?
&fa->headers : &fa->headers_not,
fieldname.s);
if (strlen(fetchatt.s) != 19) {
fa->cache_atleast = BIT32_MAX;
}
if (fa->cache_atleast < BIT32_MAX) {
bit32 this_ver =
mailbox_cached_header(fieldname.s);
if(this_ver > fa->cache_atleast)
fa->cache_atleast = this_ver;
}
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out, "%s BAD Missing required close parenthesis in %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
c = prot_getc(imapd_in);
}
else goto badatt;
break;
case 'U':
if (!strcmp(fetchatt.s, "UID")) {
fa->fetchitems |= FETCH_UID;
}
else if (!strcmp(fetchatt.s, "UIDVALIDITY")) {
fa->fetchitems |= FETCH_UIDVALIDITY;
}
else goto badatt;
break;
default:
badatt:
prot_printf(imapd_out, "%s BAD Invalid %s attribute %s\r\n", tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
if (inlist && c == ' ') c = getword(imapd_in, &fetchatt);
else break;
}
if (inlist && c == ')') {
inlist = 0;
c = prot_getc(imapd_in);
}
if (inlist) {
prot_printf(imapd_out, "%s BAD Missing close parenthesis in %s\r\n",
tag, cmd);
eatline(imapd_in, c);
goto freeargs;
}
if (c == ' ') {
/* Grab/parse the modifier(s) */
c = prot_getc(imapd_in);
if (c != '(') {
prot_printf(imapd_out,
"%s BAD Missing required open parenthesis in %s modifiers\r\n",
tag, cmd);
eatline(imapd_in, c);
goto freeargs;
}
do {
c = getword(imapd_in, &fetchatt);
ucase(fetchatt.s);
if (!strcmp(fetchatt.s, "CHANGEDSINCE")) {
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing required argument to %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
c = getmodseq(imapd_in, &fa->changedsince);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Invalid argument to %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
fa->fetchitems |= FETCH_MODSEQ;
}
else if (allow_vanished &&
!strcmp(fetchatt.s, "VANISHED")) {
fa->vanished = 1;
}
else {
prot_printf(imapd_out, "%s BAD Invalid %s modifier %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out, "%s BAD Missing close parenthesis in %s\r\n",
tag, cmd);
eatline(imapd_in, c);
goto freeargs;
}
c = prot_getc(imapd_in);
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out, "%s BAD Unexpected extra arguments to %s\r\n", tag, cmd);
eatline(imapd_in, c);
goto freeargs;
}
if (!fa->fetchitems && !fa->bodysections && !fa->fsections &&
!fa->binsections && !fa->sizesections &&
!fa->headers.count && !fa->headers_not.count) {
prot_printf(imapd_out, "%s BAD Missing required argument to %s\r\n", tag, cmd);
goto freeargs;
}
if (fa->vanished && !fa->changedsince) {
prot_printf(imapd_out, "%s BAD Missing required argument to %s\r\n", tag, cmd);
goto freeargs;
}
if (fa->fetchitems & FETCH_MODSEQ) {
if (!(client_capa & CAPA_CONDSTORE)) {
client_capa |= CAPA_CONDSTORE;
if (imapd_index)
prot_printf(imapd_out, "* OK [HIGHESTMODSEQ " MODSEQ_FMT "] \r\n",
index_highestmodseq(imapd_index));
}
}
if (fa->fetchitems & (FETCH_ANNOTATION|FETCH_FOLDER)) {
fa->namespace = &imapd_namespace;
fa->userid = imapd_userid;
}
if (fa->fetchitems & FETCH_ANNOTATION) {
fa->isadmin = imapd_userisadmin || imapd_userisproxyadmin;
fa->authstate = imapd_authstate;
}
strarray_free(newfields);
return 0;
freeargs:
strarray_free(newfields);
return IMAP_PROTOCOL_BAD_PARAMETERS;
}
static void fetchargs_fini (struct fetchargs *fa)
{
section_list_free(fa->binsections);
section_list_free(fa->sizesections);
section_list_free(fa->bodysections);
freefieldlist(fa->fsections);
strarray_fini(&fa->headers);
strarray_fini(&fa->headers_not);
strarray_fini(&fa->entries);
strarray_fini(&fa->attribs);
memset(fa, 0, sizeof(struct fetchargs));
}
/*
* Parse and perform a FETCH/UID FETCH command
* The command has been parsed up to and including
* the sequence
*/
static void cmd_fetch(char *tag, char *sequence, int usinguid)
{
const char *cmd = usinguid ? "UID Fetch" : "Fetch";
struct fetchargs fetchargs;
int fetchedsomething, r;
clock_t start = clock();
char mytime[100];
if (backend_current) {
/* remote mailbox */
prot_printf(backend_current->out, "%s %s %s ", tag, cmd, sequence);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
/* local mailbox */
memset(&fetchargs, 0, sizeof(struct fetchargs));
r = parse_fetch_args(tag, cmd,
(usinguid && (client_capa & CAPA_QRESYNC)),
&fetchargs);
if (r)
goto freeargs;
if (usinguid)
fetchargs.fetchitems |= FETCH_UID;
r = index_fetch(imapd_index, sequence, usinguid, &fetchargs,
&fetchedsomething);
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
if (r) {
prot_printf(imapd_out, "%s NO %s (%s sec)\r\n", tag,
error_message(r), mytime);
} else if (fetchedsomething || usinguid) {
prot_printf(imapd_out, "%s OK %s (%s sec)\r\n", tag,
error_message(IMAP_OK_COMPLETED), mytime);
} else {
/* normal FETCH, nothing came back */
prot_printf(imapd_out, "%s NO %s (%s sec)\r\n", tag,
error_message(IMAP_NO_NOSUCHMSG), mytime);
}
freeargs:
fetchargs_fini(&fetchargs);
}
static void do_one_xconvmeta(struct conversations_state *state,
conversation_id_t cid,
conversation_t *conv,
struct dlist *itemlist)
{
struct dlist *item = dlist_newpklist(NULL, "");
struct dlist *fl;
assert(conv);
assert(itemlist);
for (fl = itemlist->head; fl; fl = fl->next) {
const char *key = dlist_cstring(fl);
/* xxx - parse to a fetchitems? */
if (!strcasecmp(key, "MODSEQ"))
dlist_setnum64(item, "MODSEQ", conv->modseq);
else if (!strcasecmp(key, "EXISTS"))
dlist_setnum32(item, "EXISTS", conv->exists);
else if (!strcasecmp(key, "UNSEEN"))
dlist_setnum32(item, "UNSEEN", conv->unseen);
else if (!strcasecmp(key, "SIZE"))
dlist_setnum32(item, "SIZE", conv->size);
else if (!strcasecmp(key, "COUNT")) {
struct dlist *flist = dlist_newlist(item, "COUNT");
fl = fl->next;
if (dlist_isatomlist(fl)) {
struct dlist *tmp;
for (tmp = fl->head; tmp; tmp = tmp->next) {
const char *lookup = dlist_cstring(tmp);
int i = strarray_find_case(state->counted_flags, lookup, 0);
if (i >= 0) {
dlist_setflag(flist, "FLAG", lookup);
dlist_setnum32(flist, "COUNT", conv->counts[i]);
}
}
}
}
else if (!strcasecmp(key, "SENDERS")) {
conv_sender_t *sender;
struct dlist *slist = dlist_newlist(item, "SENDERS");
for (sender = conv->senders; sender; sender = sender->next) {
struct dlist *sli = dlist_newlist(slist, "");
dlist_setatom(sli, "NAME", sender->name);
dlist_setatom(sli, "ROUTE", sender->route);
dlist_setatom(sli, "MAILBOX", sender->mailbox);
dlist_setatom(sli, "DOMAIN", sender->domain);
}
}
/* XXX - maybe rename FOLDERCOUNTS or something? */
else if (!strcasecmp(key, "FOLDEREXISTS")) {
struct dlist *flist = dlist_newlist(item, "FOLDEREXISTS");
conv_folder_t *folder;
fl = fl->next;
if (dlist_isatomlist(fl)) {
struct dlist *tmp;
for (tmp = fl->head; tmp; tmp = tmp->next) {
const char *extname = dlist_cstring(tmp);
char *intname = mboxname_from_external(extname, &imapd_namespace, imapd_userid);
folder = conversation_find_folder(state, conv, intname);
free(intname);
dlist_setatom(flist, "MBOXNAME", extname);
/* ok if it's not there */
dlist_setnum32(flist, "EXISTS", folder ? folder->exists : 0);
}
}
}
else if (!strcasecmp(key, "FOLDERUNSEEN")) {
struct dlist *flist = dlist_newlist(item, "FOLDERUNSEEN");
conv_folder_t *folder;
fl = fl->next;
if (dlist_isatomlist(fl)) {
struct dlist *tmp;
for (tmp = fl->head; tmp; tmp = tmp->next) {
const char *extname = dlist_cstring(tmp);
char *intname = mboxname_from_external(extname, &imapd_namespace, imapd_userid);
folder = conversation_find_folder(state, conv, intname);
free(intname);
dlist_setatom(flist, "MBOXNAME", extname);
/* ok if it's not there */
dlist_setnum32(flist, "UNSEEN", folder ? folder->unseen : 0);
}
}
}
else {
dlist_setatom(item, key, NULL); /* add a NIL response */
}
}
prot_printf(imapd_out, "* XCONVMETA %s ", conversation_id_encode(cid));
dlist_print(item, 0, imapd_out);
prot_printf(imapd_out, "\r\n");
dlist_free(&item);
}
static void do_xconvmeta(const char *tag,
struct conversations_state *state,
struct dlist *cidlist,
struct dlist *itemlist)
{
conversation_id_t cid;
struct dlist *dl;
int r;
for (dl = cidlist->head; dl; dl = dl->next) {
const char *cidstr = dlist_cstring(dl);
conversation_t *conv = NULL;
if (!conversation_id_decode(&cid, cidstr) || !cid) {
prot_printf(imapd_out, "%s BAD Invalid CID %s\r\n", tag, cidstr);
return;
}
r = conversation_load(state, cid, &conv);
if (r) {
prot_printf(imapd_out, "%s BAD Failed to read %s\r\n", tag, cidstr);
conversation_free(conv);
return;
}
if (conv && conv->exists)
do_one_xconvmeta(state, cid, conv, itemlist);
conversation_free(conv);
}
prot_printf(imapd_out, "%s OK Completed\r\n", tag);
}
static int do_xbackup(const char *channel,
const ptrarray_t *list)
{
sasl_callback_t *cb = NULL;
struct backend *backend = NULL;
const char *hostname;
const char *port;
unsigned sync_flags = 0; // FIXME ??
int partial_success = 0;
int mbox_count = 0;
int i, r;
hostname = sync_get_config(channel, "sync_host");
if (!hostname) {
syslog(LOG_ERR, "XBACKUP: couldn't find hostname for channel '%s'", channel);
return IMAP_BAD_SERVER;
}
port = sync_get_config(channel, "sync_port");
if (port) csync_protocol.service = port;
cb = mysasl_callbacks(NULL,
sync_get_config(channel, "sync_authname"),
sync_get_config(channel, "sync_realm"),
sync_get_config(channel, "sync_password"));
syslog(LOG_INFO, "XBACKUP: connecting to server '%s' for channel '%s'",
hostname, channel);
backend = backend_connect(NULL, hostname, &csync_protocol, NULL, cb, NULL, -1);
if (!backend) {
syslog(LOG_ERR, "XBACKUP: failed to connect to server '%s' for channel '%s'",
hostname, channel);
return IMAP_SERVER_UNAVAILABLE;
}
free_callbacks(cb);
cb = NULL;
for (i = 0; i < list->count; i++) {
const mbname_t *mbname = ptrarray_nth(list, i);
if (!mbname) continue;
const char *userid = mbname_userid(mbname);
const char *intname = mbname_intname(mbname);
if (userid) {
syslog(LOG_INFO, "XBACKUP: replicating user %s", userid);
r = sync_do_user(userid, NULL, backend, /*channelp*/ NULL, sync_flags);
}
else {
struct sync_name_list *mboxname_list = sync_name_list_create();
syslog(LOG_INFO, "XBACKUP: replicating mailbox %s", intname);
sync_name_list_add(mboxname_list, intname);
r = sync_do_mailboxes(mboxname_list, NULL, backend,
/*channelp*/ NULL, sync_flags);
mbox_count++;
sync_name_list_free(&mboxname_list);
}
if (r) {
prot_printf(imapd_out, "* NO %s %s (%s)\r\n",
userid ? "USER" : "MAILBOX",
userid ? userid : intname,
error_message(r));
}
else {
partial_success++;
prot_printf(imapd_out, "* OK %s %s\r\n",
userid ? "USER" : "MAILBOX",
userid ? userid : intname);
}
prot_flush(imapd_out);
/* send RESTART after each user, or 1000 mailboxes */
if (!r && i < list->count - 1 && (userid || mbox_count >= 1000)) {
mbox_count = 0;
sync_send_restart(backend->out);
r = sync_parse_response("RESTART", backend->in, NULL);
if (r) goto done;
}
}
/* send a final RESTART */
sync_send_restart(backend->out);
sync_parse_response("RESTART", backend->in, NULL);
if (partial_success) r = 0;
done:
backend_disconnect(backend);
free(backend);
return r;
}
static int xbackup_addmbox(struct findall_data *data, void *rock)
{
if (!data) return 0;
ptrarray_t *list = (ptrarray_t *) rock;
if (!data->mbname) {
/* No partial matches */ /* FIXME ??? */
return 0;
}
/* Only add shared mailboxes or user INBOXes */
if (!mbname_localpart(data->mbname) ||
(!mbname_isdeleted(data->mbname) &&
!strarray_size(mbname_boxes(data->mbname)))) {
ptrarray_append(list, mbname_dup(data->mbname));
}
return 0;
}
/* Parse and perform an XBACKUP command. */
void cmd_xbackup(const char *tag,
const char *mailbox,
const char *channel)
{
ptrarray_t list = PTRARRAY_INITIALIZER;
int i, r;
/* admins only please */
if (!imapd_userisadmin && !imapd_userisproxyadmin) {
r = IMAP_PERMISSION_DENIED;
goto done;
}
if (!config_getswitch(IMAPOPT_XBACKUP_ENABLED)) {
/* shouldn't get here, but just in case */
r = IMAP_PERMISSION_DENIED;
goto done;
}
mboxlist_findall(NULL, mailbox, 1, NULL, NULL, xbackup_addmbox, &list);
if (list.count) {
r = do_xbackup(channel, &list);
for (i = 0; i < list.count; i++) {
mbname_t *mbname = ptrarray_nth(&list, i);
if (mbname)
mbname_free(&mbname);
}
ptrarray_fini(&list);
}
else {
r = IMAP_MAILBOX_NONEXISTENT;
}
done:
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
}
/*
* Parse and perform a XCONVMETA command.
*/
void cmd_xconvmeta(const char *tag)
{
int r;
int c = ' ';
struct conversations_state *state = NULL;
struct dlist *cidlist = NULL;
struct dlist *itemlist = NULL;
if (backend_current) {
/* remote mailbox */
prot_printf(backend_current->out, "%s XCONVMETA ", tag);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
if (!config_getswitch(IMAPOPT_CONVERSATIONS)) {
prot_printf(imapd_out, "%s BAD Unrecognized command\r\n", tag);
eatline(imapd_in, c);
goto done;
}
c = dlist_parse_asatomlist(&cidlist, 0, imapd_in);
if (c != ' ') {
prot_printf(imapd_out, "%s BAD Failed to parse CID list\r\n", tag);
eatline(imapd_in, c);
goto done;
}
c = dlist_parse_asatomlist(&itemlist, 0, imapd_in);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out, "%s BAD Failed to parse item list\r\n", tag);
eatline(imapd_in, c);
goto done;
}
r = conversations_open_user(imapd_userid, &state);
if (r) {
prot_printf(imapd_out, "%s BAD failed to open db: %s\r\n",
tag, error_message(r));
goto done;
}
do_xconvmeta(tag, state, cidlist, itemlist);
done:
dlist_free(&itemlist);
dlist_free(&cidlist);
conversations_commit(&state);
}
/*
* Parse and perform a XCONVFETCH command.
*/
void cmd_xconvfetch(const char *tag)
{
int c = ' ';
struct fetchargs fetchargs;
int r;
clock_t start = clock();
modseq_t ifchangedsince = 0;
char mytime[100];
struct dlist *cidlist = NULL;
struct dlist *item;
if (backend_current) {
/* remote mailbox */
prot_printf(backend_current->out, "%s XCONVFETCH ", tag);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
if (!config_getswitch(IMAPOPT_CONVERSATIONS)) {
prot_printf(imapd_out, "%s BAD Unrecognized command\r\n", tag);
eatline(imapd_in, c);
return;
}
/* local mailbox */
memset(&fetchargs, 0, sizeof(struct fetchargs));
c = dlist_parse_asatomlist(&cidlist, 0, imapd_in);
if (c != ' ')
goto syntax_error;
/* check CIDs */
for (item = cidlist->head; item; item = item->next) {
if (!dlist_ishex64(item)) {
prot_printf(imapd_out, "%s BAD Invalid CID\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
}
c = getmodseq(imapd_in, &ifchangedsince);
if (c != ' ')
goto syntax_error;
r = parse_fetch_args(tag, "Xconvfetch", 0, &fetchargs);
if (r)
goto freeargs;
fetchargs.fetchitems |= (FETCH_UIDVALIDITY|FETCH_FOLDER);
fetchargs.namespace = &imapd_namespace;
fetchargs.userid = imapd_userid;
r = do_xconvfetch(cidlist, ifchangedsince, &fetchargs);
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
if (r) {
prot_printf(imapd_out, "%s NO %s (%s sec)\r\n", tag,
error_message(r), mytime);
} else {
prot_printf(imapd_out, "%s OK Completed (%s sec)\r\n",
tag, mytime);
}
freeargs:
dlist_free(&cidlist);
fetchargs_fini(&fetchargs);
return;
syntax_error:
prot_printf(imapd_out, "%s BAD Syntax error\r\n", tag);
eatline(imapd_in, c);
dlist_free(&cidlist);
fetchargs_fini(&fetchargs);
}
static int xconvfetch_lookup(struct conversations_state *statep,
conversation_id_t cid,
modseq_t ifchangedsince,
hash_table *wanted_cids,
strarray_t *folder_list)
{
const char *key = conversation_id_encode(cid);
conversation_t *conv = NULL;
conv_folder_t *folder;
int r;
r = conversation_load(statep, cid, &conv);
if (r) return r;
if (!conv)
goto out;
if (!conv->exists)
goto out;
/* output the metadata for this conversation */
{
struct dlist *dl = dlist_newlist(NULL, "");
dlist_setatom(dl, "", "MODSEQ");
do_one_xconvmeta(statep, cid, conv, dl);
dlist_free(&dl);
}
if (ifchangedsince >= conv->modseq)
goto out;
hash_insert(key, (void *)1, wanted_cids);
for (folder = conv->folders; folder; folder = folder->next) {
/* no contents */
if (!folder->exists)
continue;
/* finally, something worth looking at */
strarray_add(folder_list, strarray_nth(statep->folder_names, folder->number));
}
out:
conversation_free(conv);
return 0;
}
static int do_xconvfetch(struct dlist *cidlist,
modseq_t ifchangedsince,
struct fetchargs *fetchargs)
{
struct conversations_state *state = NULL;
int r = 0;
struct index_state *index_state = NULL;
struct dlist *dl;
hash_table wanted_cids = HASH_TABLE_INITIALIZER;
strarray_t folder_list = STRARRAY_INITIALIZER;
struct index_init init;
int i;
r = conversations_open_user(imapd_userid, &state);
if (r) goto out;
construct_hash_table(&wanted_cids, 1024, 0);
for (dl = cidlist->head; dl; dl = dl->next) {
r = xconvfetch_lookup(state, dlist_num(dl), ifchangedsince,
&wanted_cids, &folder_list);
if (r) goto out;
}
/* unchanged, woot */
if (!folder_list.count)
goto out;
fetchargs->cidhash = &wanted_cids;
memset(&init, 0, sizeof(struct index_init));
init.userid = imapd_userid;
init.authstate = imapd_authstate;
init.out = imapd_out;
for (i = 0; i < folder_list.count; i++) {
const char *mboxname = folder_list.data[i];
r = index_open(mboxname, &init, &index_state);
if (r == IMAP_MAILBOX_NONEXISTENT)
continue;
if (r)
goto out;
index_checkflags(index_state, 0, 0);
/* make sure \Deleted messages are expunged. Will also lock the
* mailbox state and read any new information */
r = index_expunge(index_state, NULL, 1);
if (!r)
index_fetchresponses(index_state, NULL, /*usinguid*/1,
fetchargs, NULL);
index_close(&index_state);
if (r) goto out;
}
r = 0;
out:
index_close(&index_state);
conversations_commit(&state);
free_hash_table(&wanted_cids, NULL);
strarray_fini(&folder_list);
return r;
}
#undef PARSE_PARTIAL /* cleanup */
/*
* Parse and perform a STORE/UID STORE command
* The command has been parsed up to and including
* the sequence
*/
static void cmd_store(char *tag, char *sequence, int usinguid)
{
const char *cmd = usinguid ? "UID Store" : "Store";
struct storeargs storeargs;
static struct buf operation, flagname;
int len, c;
int flagsparsed = 0, inlist = 0;
char *modified = NULL;
int r;
if (backend_current) {
/* remote mailbox */
prot_printf(backend_current->out, "%s %s %s ",
tag, cmd, sequence);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
/* local mailbox */
memset(&storeargs, 0, sizeof storeargs);
storeargs.unchangedsince = ~0ULL;
storeargs.usinguid = usinguid;
strarray_init(&storeargs.flags);
c = prot_getc(imapd_in);
if (c == '(') {
/* Grab/parse the modifier(s) */
static struct buf storemod;
do {
c = getword(imapd_in, &storemod);
ucase(storemod.s);
if (!strcmp(storemod.s, "UNCHANGEDSINCE")) {
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing required argument to %s %s\r\n",
tag, cmd, storemod.s);
eatline(imapd_in, c);
return;
}
c = getmodseq(imapd_in, &storeargs.unchangedsince);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Invalid argument to %s UNCHANGEDSINCE\r\n",
tag, cmd);
eatline(imapd_in, c);
return;
}
}
else {
prot_printf(imapd_out, "%s BAD Invalid %s modifier %s\r\n",
tag, cmd, storemod.s);
eatline(imapd_in, c);
return;
}
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close paren in store modifier entry \r\n",
tag);
eatline(imapd_in, c);
return;
}
c = prot_getc(imapd_in);
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing required argument to %s\r\n",
tag, cmd);
eatline(imapd_in, c);
return;
}
}
else
prot_ungetc(c, imapd_in);
c = getword(imapd_in, &operation);
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing required argument to %s\r\n", tag, cmd);
eatline(imapd_in, c);
return;
}
lcase(operation.s);
len = strlen(operation.s);
if (len > 7 && !strcmp(operation.s+len-7, ".silent")) {
storeargs.silent = 1;
operation.s[len-7] = '\0';
}
if (!strcmp(operation.s, "+flags")) {
storeargs.operation = STORE_ADD_FLAGS;
}
else if (!strcmp(operation.s, "-flags")) {
storeargs.operation = STORE_REMOVE_FLAGS;
}
else if (!strcmp(operation.s, "flags")) {
storeargs.operation = STORE_REPLACE_FLAGS;
}
else if (!strcmp(operation.s, "annotation")) {
storeargs.operation = STORE_ANNOTATION;
/* ANNOTATION has implicit .SILENT behaviour */
storeargs.silent = 1;
c = parse_annotate_store_data(tag, /*permessage_flag*/1,
&storeargs.entryatts);
if (c == EOF) {
eatline(imapd_in, c);
goto freeflags;
}
storeargs.namespace = &imapd_namespace;
storeargs.isadmin = imapd_userisadmin;
storeargs.userid = imapd_userid;
storeargs.authstate = imapd_authstate;
goto notflagsdammit;
}
else {
prot_printf(imapd_out, "%s BAD Invalid %s attribute\r\n", tag, cmd);
eatline(imapd_in, ' ');
return;
}
for (;;) {
c = getword(imapd_in, &flagname);
if (c == '(' && !flagname.s[0] && !flagsparsed && !inlist) {
inlist = 1;
continue;
}
if (!flagname.s[0]) break;
if (flagname.s[0] == '\\') {
lcase(flagname.s);
if (!strcmp(flagname.s, "\\seen")) {
storeargs.seen = 1;
}
else if (!strcmp(flagname.s, "\\answered")) {
storeargs.system_flags |= FLAG_ANSWERED;
}
else if (!strcmp(flagname.s, "\\flagged")) {
storeargs.system_flags |= FLAG_FLAGGED;
}
else if (!strcmp(flagname.s, "\\deleted")) {
storeargs.system_flags |= FLAG_DELETED;
}
else if (!strcmp(flagname.s, "\\draft")) {
storeargs.system_flags |= FLAG_DRAFT;
}
else {
prot_printf(imapd_out, "%s BAD Invalid system flag in %s command\r\n",
tag, cmd);
eatline(imapd_in, c);
goto freeflags;
}
}
else if (!imparse_isatom(flagname.s)) {
prot_printf(imapd_out, "%s BAD Invalid flag name %s in %s command\r\n",
tag, flagname.s, cmd);
eatline(imapd_in, c);
goto freeflags;
}
else
strarray_append(&storeargs.flags, flagname.s);
flagsparsed++;
if (c != ' ') break;
}
if (!inlist && !flagsparsed) {
prot_printf(imapd_out, "%s BAD Missing required argument to %s\r\n", tag, cmd);
eatline(imapd_in, c);
return;
}
if (inlist && c == ')') {
inlist = 0;
c = prot_getc(imapd_in);
}
if (inlist) {
prot_printf(imapd_out, "%s BAD Missing close parenthesis in %s\r\n", tag, cmd);
eatline(imapd_in, c);
goto freeflags;
}
notflagsdammit:
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out, "%s BAD Unexpected extra arguments to %s\r\n", tag, cmd);
eatline(imapd_in, c);
goto freeflags;
}
if ((storeargs.unchangedsince != ULONG_MAX) &&
!(client_capa & CAPA_CONDSTORE)) {
client_capa |= CAPA_CONDSTORE;
prot_printf(imapd_out, "* OK [HIGHESTMODSEQ " MODSEQ_FMT "] \r\n",
index_highestmodseq(imapd_index));
}
r = index_store(imapd_index, sequence, &storeargs);
/* format the MODIFIED response code */
if (storeargs.modified) {
char *seqstr = seqset_cstring(storeargs.modified);
assert(seqstr);
modified = strconcat("[MODIFIED ", seqstr, "] ", (char *)NULL);
free(seqstr);
}
else {
modified = xstrdup("");
}
if (r) {
prot_printf(imapd_out, "%s NO %s%s\r\n",
tag, modified, error_message(r));
}
else {
prot_printf(imapd_out, "%s OK %s%s\r\n",
tag, modified, error_message(IMAP_OK_COMPLETED));
}
freeflags:
strarray_fini(&storeargs.flags);
freeentryatts(storeargs.entryatts);
seqset_free(storeargs.modified);
free(modified);
}
static void cmd_search(char *tag, int usinguid)
{
int c;
struct searchargs *searchargs;
clock_t start = clock();
char mytime[100];
int n;
if (backend_current) {
/* remote mailbox */
const char *cmd = usinguid ? "UID Search" : "Search";
prot_printf(backend_current->out, "%s %s ", tag, cmd);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
/* local mailbox */
searchargs = new_searchargs(tag, GETSEARCH_CHARSET_KEYWORD|GETSEARCH_RETURN,
&imapd_namespace, imapd_userid, imapd_authstate,
imapd_userisadmin || imapd_userisproxyadmin);
/* special case quirk for iPhones */
if (imapd_id.quirks & QUIRK_SEARCHFUZZY)
searchargs->fuzzy_depth++;
c = get_search_program(imapd_in, imapd_out, searchargs);
if (c == EOF) {
eatline(imapd_in, ' ');
freesearchargs(searchargs);
return;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out, "%s BAD Unexpected extra arguments to Search\r\n", tag);
eatline(imapd_in, c);
freesearchargs(searchargs);
return;
}
if (searchargs->charset == CHARSET_UNKNOWN_CHARSET) {
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(IMAP_UNRECOGNIZED_CHARSET));
}
else {
n = index_search(imapd_index, searchargs, usinguid);
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
prot_printf(imapd_out, "%s OK %s (%d msgs in %s secs)\r\n", tag,
error_message(IMAP_OK_COMPLETED), n, mytime);
}
freesearchargs(searchargs);
}
/*
* Perform a SORT/UID SORT command
*/
static void cmd_sort(char *tag, int usinguid)
{
int c;
struct sortcrit *sortcrit = NULL;
struct searchargs *searchargs = NULL;
clock_t start = clock();
char mytime[100];
int n;
if (backend_current) {
/* remote mailbox */
const char *cmd = usinguid ? "UID Sort" : "Sort";
prot_printf(backend_current->out, "%s %s ", tag, cmd);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
/* local mailbox */
c = getsortcriteria(tag, &sortcrit);
if (c == EOF) goto error;
searchargs = new_searchargs(tag, GETSEARCH_CHARSET_FIRST,
&imapd_namespace, imapd_userid, imapd_authstate,
imapd_userisadmin || imapd_userisproxyadmin);
if (imapd_id.quirks & QUIRK_SEARCHFUZZY)
searchargs->fuzzy_depth++;
c = get_search_program(imapd_in, imapd_out, searchargs);
if (c == EOF) goto error;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Sort\r\n", tag);
goto error;
}
n = index_sort(imapd_index, sortcrit, searchargs, usinguid);
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
if (CONFIG_TIMING_VERBOSE) {
char *s = sortcrit_as_string(sortcrit);
syslog(LOG_DEBUG, "SORT (%s) processing time: %d msg in %s sec",
s, n, mytime);
free(s);
}
prot_printf(imapd_out, "%s OK %s (%d msgs in %s secs)\r\n", tag,
error_message(IMAP_OK_COMPLETED), n, mytime);
freesortcrit(sortcrit);
freesearchargs(searchargs);
return;
error:
eatline(imapd_in, (c == EOF ? ' ' : c));
freesortcrit(sortcrit);
freesearchargs(searchargs);
}
/*
* Perform a XCONVSORT or XCONVUPDATES command
*/
void cmd_xconvsort(char *tag, int updates)
{
int c;
struct sortcrit *sortcrit = NULL;
struct searchargs *searchargs = NULL;
struct windowargs *windowargs = NULL;
struct index_init init;
struct index_state *oldstate = NULL;
struct conversations_state *cstate = NULL;
clock_t start = clock();
char mytime[100];
int r;
if (backend_current) {
/* remote mailbox */
const char *cmd = "Xconvsort";
prot_printf(backend_current->out, "%s %s ", tag, cmd);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
assert(imapd_index);
if (!config_getswitch(IMAPOPT_CONVERSATIONS)) {
prot_printf(imapd_out, "%s BAD Unrecognized command\r\n", tag);
eatline(imapd_in, ' ');
return;
}
c = getsortcriteria(tag, &sortcrit);
if (c == EOF) goto error;
if (c != ' ') {
prot_printf(imapd_out, "%s BAD Missing window args in XConvSort\r\n",
tag);
goto error;
}
c = parse_windowargs(tag, &windowargs, updates);
if (c != ' ')
goto error;
/* open the conversations state first - we don't care if it fails,
* because that probably just means it's already open */
conversations_open_mbox(index_mboxname(imapd_index), &cstate);
if (updates) {
/* in XCONVUPDATES, need to force a re-read from scratch into
* a new index, because we ask for deleted messages */
oldstate = imapd_index;
imapd_index = NULL;
memset(&init, 0, sizeof(struct index_init));
init.userid = imapd_userid;
init.authstate = imapd_authstate;
init.out = imapd_out;
init.want_expunged = 1;
r = index_open(index_mboxname(oldstate), &init, &imapd_index);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(r));
goto error;
}
index_checkflags(imapd_index, 0, 0);
}
/* need index loaded to even parse searchargs! */
searchargs = new_searchargs(tag, GETSEARCH_CHARSET_FIRST,
&imapd_namespace, imapd_userid, imapd_authstate,
imapd_userisadmin || imapd_userisproxyadmin);
c = get_search_program(imapd_in, imapd_out, searchargs);
if (c == EOF) goto error;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Xconvsort\r\n", tag);
goto error;
}
if (updates)
r = index_convupdates(imapd_index, sortcrit, searchargs, windowargs);
else
r = index_convsort(imapd_index, sortcrit, searchargs, windowargs);
if (oldstate) {
index_close(&imapd_index);
imapd_index = oldstate;
}
if (r < 0) {
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(r));
goto error;
}
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
if (CONFIG_TIMING_VERBOSE) {
char *s = sortcrit_as_string(sortcrit);
syslog(LOG_DEBUG, "XCONVSORT (%s) processing time %s sec",
s, mytime);
free(s);
}
prot_printf(imapd_out, "%s OK %s (in %s secs)\r\n", tag,
error_message(IMAP_OK_COMPLETED), mytime);
out:
if (cstate) conversations_commit(&cstate);
freesortcrit(sortcrit);
freesearchargs(searchargs);
free_windowargs(windowargs);
return;
error:
if (cstate) conversations_commit(&cstate);
if (oldstate) {
if (imapd_index) index_close(&imapd_index);
imapd_index = oldstate;
}
eatline(imapd_in, (c == EOF ? ' ' : c));
goto out;
}
/*
* Perform a XCONVMULTISORT command. This is like XCONVSORT but returns
* search results from multiple folders. It still requires a selected
* mailbox, for two reasons:
*
* a) it's a useful shorthand for choosing what the current
* conversations scope is, and
*
* b) the code to parse a search program currently relies on a selected
* mailbox.
*
* Unlike ESEARCH it doesn't take folder names for scope, instead the
* search scope is implicitly the current conversation scope. This is
* implemented more or less by accident because both the Sphinx index
* and the conversations database are hardcoded to be per-user.
*/
static void cmd_xconvmultisort(char *tag)
{
int c;
struct sortcrit *sortcrit = NULL;
struct searchargs *searchargs = NULL;
struct windowargs *windowargs = NULL;
struct conversations_state *cstate = NULL;
clock_t start = clock();
char mytime[100];
int r;
if (backend_current) {
/* remote mailbox */
const char *cmd = "Xconvmultisort";
prot_printf(backend_current->out, "%s %s ", tag, cmd);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
assert(imapd_index);
if (!config_getswitch(IMAPOPT_CONVERSATIONS)) {
prot_printf(imapd_out, "%s BAD Unrecognized command\r\n", tag);
eatline(imapd_in, ' ');
return;
}
c = getsortcriteria(tag, &sortcrit);
if (c == EOF) goto error;
if (c != ' ') {
prot_printf(imapd_out, "%s BAD Missing window args in XConvMultiSort\r\n",
tag);
goto error;
}
c = parse_windowargs(tag, &windowargs, /*updates*/0);
if (c != ' ')
goto error;
/* open the conversations state first - we don't care if it fails,
* because that probably just means it's already open */
conversations_open_mbox(index_mboxname(imapd_index), &cstate);
/* need index loaded to even parse searchargs! */
searchargs = new_searchargs(tag, GETSEARCH_CHARSET_FIRST,
&imapd_namespace, imapd_userid, imapd_authstate,
imapd_userisadmin || imapd_userisproxyadmin);
c = get_search_program(imapd_in, imapd_out, searchargs);
if (c == EOF) goto error;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to XconvMultiSort\r\n", tag);
goto error;
}
r = index_convmultisort(imapd_index, sortcrit, searchargs, windowargs);
if (r < 0) {
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(r));
goto error;
}
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
if (CONFIG_TIMING_VERBOSE) {
char *s = sortcrit_as_string(sortcrit);
syslog(LOG_DEBUG, "XCONVMULTISORT (%s) processing time %s sec",
s, mytime);
free(s);
}
prot_printf(imapd_out, "%s OK %s (in %s secs)\r\n", tag,
error_message(IMAP_OK_COMPLETED), mytime);
out:
if (cstate) conversations_commit(&cstate);
freesortcrit(sortcrit);
freesearchargs(searchargs);
free_windowargs(windowargs);
return;
error:
if (cstate) conversations_commit(&cstate);
eatline(imapd_in, (c == EOF ? ' ' : c));
goto out;
}
static void cmd_xsnippets(char *tag)
{
int c;
struct searchargs *searchargs = NULL;
struct snippetargs *snippetargs = NULL;
clock_t start = clock();
char mytime[100];
int r;
if (backend_current) {
/* remote mailbox */
const char *cmd = "Xsnippets";
prot_printf(backend_current->out, "%s %s ", tag, cmd);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
assert(imapd_index);
c = get_snippetargs(&snippetargs);
if (c == EOF) {
prot_printf(imapd_out, "%s BAD Syntax error in snippet arguments\r\n", tag);
goto error;
}
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Unexpected arguments in Xsnippets\r\n", tag);
goto error;
}
/* need index loaded to even parse searchargs! */
searchargs = new_searchargs(tag, GETSEARCH_CHARSET_FIRST,
&imapd_namespace, imapd_userid, imapd_authstate,
imapd_userisadmin || imapd_userisproxyadmin);
c = get_search_program(imapd_in, imapd_out, searchargs);
if (c == EOF) goto error;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Xsnippets\r\n", tag);
goto error;
}
r = index_snippets(imapd_index, snippetargs, searchargs);
if (r < 0) {
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(r));
goto error;
}
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
prot_printf(imapd_out, "%s OK %s (in %s secs)\r\n", tag,
error_message(IMAP_OK_COMPLETED), mytime);
out:
freesearchargs(searchargs);
free_snippetargs(&snippetargs);
return;
error:
eatline(imapd_in, (c == EOF ? ' ' : c));
goto out;
}
static void cmd_xstats(char *tag, int c)
{
int metric;
if (backend_current) {
/* remote mailbox */
const char *cmd = "Xstats";
prot_printf(backend_current->out, "%s %s ", tag, cmd);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
if (c == EOF) {
prot_printf(imapd_out, "%s BAD Syntax error in Xstats arguments\r\n", tag);
goto error;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Xstats\r\n", tag);
goto error;
}
prot_printf(imapd_out, "* XSTATS");
for (metric = 0 ; metric < XSTATS_NUM_METRICS ; metric++)
prot_printf(imapd_out, " %s %u", xstats_names[metric], xstats[metric]);
prot_printf(imapd_out, "\r\n");
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
return;
error:
eatline(imapd_in, (c == EOF ? ' ' : c));
}
/*
* Perform a THREAD/UID THREAD command
*/
static void cmd_thread(char *tag, int usinguid)
{
static struct buf arg;
int c;
int alg;
struct searchargs *searchargs;
clock_t start = clock();
char mytime[100];
int n;
if (backend_current) {
/* remote mailbox */
const char *cmd = usinguid ? "UID Thread" : "Thread";
prot_printf(backend_current->out, "%s %s ", tag, cmd);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
/* local mailbox */
/* get algorithm */
c = getword(imapd_in, &arg);
if (c != ' ') {
prot_printf(imapd_out, "%s BAD Missing algorithm in Thread\r\n", tag);
eatline(imapd_in, c);
return;
}
if ((alg = find_thread_algorithm(arg.s)) == -1) {
prot_printf(imapd_out, "%s BAD Invalid Thread algorithm %s\r\n",
tag, arg.s);
eatline(imapd_in, c);
return;
}
searchargs = new_searchargs(tag, GETSEARCH_CHARSET_FIRST,
&imapd_namespace, imapd_userid, imapd_authstate,
imapd_userisadmin || imapd_userisproxyadmin);
c = get_search_program(imapd_in, imapd_out, searchargs);
if (c == EOF) {
eatline(imapd_in, ' ');
freesearchargs(searchargs);
return;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Thread\r\n", tag);
eatline(imapd_in, c);
freesearchargs(searchargs);
return;
}
n = index_thread(imapd_index, alg, searchargs, usinguid);
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
prot_printf(imapd_out, "%s OK %s (%d msgs in %s secs)\r\n", tag,
error_message(IMAP_OK_COMPLETED), n, mytime);
freesearchargs(searchargs);
return;
}
/*
* Perform a COPY/UID COPY command
*/
static void cmd_copy(char *tag, char *sequence, char *name, int usinguid, int ismove)
{
int r, myrights;
char *copyuid = NULL;
mbentry_t *mbentry = NULL;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(NULL, NULL, intname, &mbentry);
if (!r) myrights = cyrus_acl_myrights(imapd_authstate, mbentry->acl);
if (!r && backend_current) {
/* remote mailbox -> local or remote mailbox */
/* xxx start of separate proxy-only code
(remove when we move to a unified environment) */
struct backend *s = NULL;
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
mboxlist_entry_free(&mbentry);
if (!s) {
r = IMAP_SERVER_UNAVAILABLE;
goto done;
}
if (s != backend_current) {
/* this is the hard case; we have to fetch the messages and append
them to the other mailbox */
proxy_copy(tag, sequence, name, myrights, usinguid, s);
goto cleanup;
}
/* xxx end of separate proxy-only code */
/* simply send the COPY to the backend */
prot_printf(
backend_current->out,
"%s %s %s {" SIZE_T_FMT "+}\r\n%s\r\n",
tag,
usinguid ? (ismove ? "UID Move" : "UID Copy") : (ismove ? "Move" : "Copy"),
sequence,
strlen(name),
name
);
pipe_including_tag(backend_current, tag, 0);
goto cleanup;
}
else if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* local mailbox -> remote mailbox
*
* fetch the messages and APPEND them to the backend
*
* xxx completely untested
*/
struct backend *s = NULL;
int res;
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
mboxlist_entry_free(&mbentry);
if (!s) r = IMAP_SERVER_UNAVAILABLE;
else if (!CAPA(s, CAPA_MULTIAPPEND)) {
/* we need MULTIAPPEND for atomicity */
r = IMAP_REMOTE_NO_MULTIAPPEND;
}
if (r) goto done;
assert(!ismove); /* XXX - support proxying moves */
/* start the append */
prot_printf(s->out, "%s Append {" SIZE_T_FMT "+}\r\n%s",
tag, strlen(name), name);
/* append the messages */
r = index_copy_remote(imapd_index, sequence, usinguid, s->out);
if (!r) {
/* ok, finish the append; we need the UIDVALIDITY and UIDs
to return as part of our COPYUID response code */
char *appenduid, *b;
prot_printf(s->out, "\r\n");
res = pipe_until_tag(s, tag, 0);
if (res == PROXY_OK) {
if (myrights & ACL_READ) {
appenduid = strchr(s->last_result.s, '[');
/* skip over APPENDUID */
if (appenduid) {
appenduid += strlen("[appenduid ");
b = strchr(appenduid, ']');
if (b) *b = '\0';
prot_printf(imapd_out, "%s OK [COPYUID %s] %s\r\n", tag,
appenduid, error_message(IMAP_OK_COMPLETED));
} else
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
} else {
prot_printf(imapd_out, "%s %s", tag, s->last_result.s);
}
} else {
/* abort the append */
prot_printf(s->out, " {0}\r\n");
pipe_until_tag(s, tag, 0);
/* report failure */
prot_printf(imapd_out, "%s NO inter-server COPY failed\r\n", tag);
}
goto cleanup;
}
/* need permission to delete from source if it's a move */
if (!r && ismove && !(imapd_index->myrights & ACL_EXPUNGE))
r = IMAP_PERMISSION_DENIED;
/* local mailbox -> local mailbox */
if (!r) {
r = index_copy(imapd_index, sequence, usinguid, intname,
©uid, !config_getswitch(IMAPOPT_SINGLEINSTANCESTORE),
&imapd_namespace,
(imapd_userisadmin || imapd_userisproxyadmin), ismove,
ignorequota);
}
if (ismove && copyuid && !r) {
prot_printf(imapd_out, "* OK [COPYUID %s] %s\r\n",
copyuid, error_message(IMAP_OK_COMPLETED));
free(copyuid);
copyuid = NULL;
}
imapd_check(NULL, ismove || usinguid);
done:
if (r && !(usinguid && r == IMAP_NO_NOSUCHMSG)) {
prot_printf(imapd_out, "%s NO %s%s\r\n", tag,
(r == IMAP_MAILBOX_NONEXISTENT &&
mboxlist_createmailboxcheck(intname, 0, 0,
imapd_userisadmin,
imapd_userid, imapd_authstate,
NULL, NULL, 0) == 0)
? "[TRYCREATE] " : "", error_message(r));
}
else if (copyuid) {
prot_printf(imapd_out, "%s OK [COPYUID %s] %s\r\n", tag,
copyuid, error_message(IMAP_OK_COMPLETED));
free(copyuid);
}
else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
cleanup:
mboxlist_entry_free(&mbentry);
free(intname);
}
/*
* Perform an EXPUNGE command
* sequence == NULL if this isn't a UID EXPUNGE
*/
static void cmd_expunge(char *tag, char *sequence)
{
modseq_t old;
modseq_t new;
int r = 0;
if (backend_current) {
/* remote mailbox */
if (sequence) {
prot_printf(backend_current->out, "%s UID Expunge %s\r\n", tag,
sequence);
} else {
prot_printf(backend_current->out, "%s Expunge\r\n", tag);
}
pipe_including_tag(backend_current, tag, 0);
return;
}
/* local mailbox */
if (!index_hasrights(imapd_index, ACL_EXPUNGE))
r = IMAP_PERMISSION_DENIED;
old = index_highestmodseq(imapd_index);
if (!r) r = index_expunge(imapd_index, sequence, 1);
/* tell expunges */
if (!r) index_tellchanges(imapd_index, 1, sequence ? 1 : 0, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
return;
}
new = index_highestmodseq(imapd_index);
prot_printf(imapd_out, "%s OK ", tag);
if (new > old)
prot_printf(imapd_out, "[HIGHESTMODSEQ " MODSEQ_FMT "] ", new);
prot_printf(imapd_out, "%s\r\n", error_message(IMAP_OK_COMPLETED));
}
/*
* Perform a CREATE command
*/
static void cmd_create(char *tag, char *name, struct dlist *extargs, int localonly)
{
int r = 0;
int mbtype = 0;
const char *partition = NULL;
const char *server = NULL;
struct buf specialuse = BUF_INITIALIZER;
struct dlist *use;
/* We don't care about trailing hierarchy delimiters. */
if (name[0] && name[strlen(name)-1] == imapd_namespace.hier_sep) {
name[strlen(name)-1] = '\0';
}
mbname_t *mbname = mbname_from_extname(name, &imapd_namespace, imapd_userid);
dlist_getatom(extargs, "PARTITION", &partition);
dlist_getatom(extargs, "SERVER", &server);
const char *type = NULL;
dlist_getatom(extargs, "PARTITION", &partition);
dlist_getatom(extargs, "SERVER", &server);
if (dlist_getatom(extargs, "TYPE", &type)) {
if (!strcasecmp(type, "CALENDAR")) mbtype |= MBTYPE_CALENDAR;
else if (!strcasecmp(type, "COLLECTION")) mbtype |= MBTYPE_COLLECTION;
else if (!strcasecmp(type, "ADDRESSBOOK")) mbtype |= MBTYPE_ADDRESSBOOK;
else {
r = IMAP_MAILBOX_BADTYPE;
goto err;
}
}
use = dlist_getchild(extargs, "USE");
if (use) {
/* only user mailboxes can have specialuse, and they must be user toplevel folders */
if (!mbname_userid(mbname) || strarray_size(mbname_boxes(mbname)) != 1) {
r = IMAP_MAILBOX_SPECIALUSE;
goto err;
}
/* I would much prefer to create the specialuse annotation FIRST
* and do the sanity check on the values, so we can return the
* correct error. Sadly, that's a pain - so we compromise by
* "normalising" first */
struct dlist *item;
char *raw;
strarray_t *su = strarray_new();
for (item = use->head; item; item = item->next) {
strarray_append(su, dlist_cstring(item));
}
raw = strarray_join(su, " ");
strarray_free(su);
r = specialuse_validate(imapd_userid, raw, &specialuse);
free(raw);
if (r) {
prot_printf(imapd_out, "%s NO [USEATTR] %s\r\n", tag, error_message(r));
goto done;
}
}
// A non-admin is not allowed to specify the server nor partition on which
// to create the mailbox.
//
// However, this only applies to frontends. If we're a backend, a frontend will
// proxy the partition it wishes to create the mailbox on.
if ((server || partition) && !imapd_userisadmin) {
if (config_mupdate_config == IMAP_ENUM_MUPDATE_CONFIG_STANDARD ||
config_mupdate_config == IMAP_ENUM_MUPDATE_CONFIG_UNIFIED) {
if (!config_getstring(IMAPOPT_PROXYSERVERS)) {
r = IMAP_PERMISSION_DENIED;
goto err;
}
}
}
/* check for INBOX.INBOX creation by broken Apple clients */
const strarray_t *boxes = mbname_boxes(mbname);
if (strarray_size(boxes) > 1
&& !strcasecmp(strarray_nth(boxes, 0), "INBOX")
&& !strcasecmp(strarray_nth(boxes, 1), "INBOX"))
r = IMAP_MAILBOX_BADNAME;
if (r) {
err:
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
goto done;
}
// If the create command does not mandate the mailbox must be created
// locally, let's go and find the most appropriate location.
if (!localonly) {
// If we're running in a Murder, things get more complicated.
if (config_mupdate_server) {
// Consider your actions on a per type of topology basis.
//
// First up: Standard / discrete murder topology, with dedicated
// imap frontends, or unified -- both allow the IMAP server to either
// need to proxy through, or create locally.
if (
config_mupdate_config == IMAP_ENUM_MUPDATE_CONFIG_STANDARD ||
config_mupdate_config == IMAP_ENUM_MUPDATE_CONFIG_UNIFIED
) {
// The way that we detect whether we're a frontend is by testing
// for the proxy servers setting ... :/
if (!config_getstring(IMAPOPT_PROXYSERVERS)) {
// Find the parent mailbox, if any.
mbentry_t *parent = NULL;
// mboxlist_findparent either supplies the parent
// or has a return code of IMAP_MAILBOX_NONEXISTENT.
r = mboxlist_findparent(mbname_intname(mbname), &parent);
if (r) {
if (r != IMAP_MAILBOX_NONEXISTENT) {
prot_printf(imapd_out, "%s NO %s (%s:%d)\r\n", tag, error_message(r), __FILE__, __LINE__);
goto done;
}
}
if (!server && !partition) {
if (!parent) {
server = find_free_server();
if (!server) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(IMAP_SERVER_UNAVAILABLE));
goto done;
}
} else {
server = parent->server;
/* DO NOT set the partition:
only admins are allowed to do this
and the backend will use the partition
of the parent by default anyways.
partition = parent->partition;
*/
}
}
struct backend *s_conn = NULL;
s_conn = proxy_findserver(
server,
&imap_protocol,
proxy_userid,
&backend_cached,
&backend_current,
&backend_inbox,
imapd_in
);
if (!s_conn) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(IMAP_SERVER_UNAVAILABLE));
goto done;
}
// Huh?
if (imapd_userisadmin && supports_referrals) {
// "They are not an admin remotely, so let's refer them" --
// - Who is they?
// - How did imapd_userisadmin get set all of a sudden?
imapd_refer(tag, server, name);
referral_kick = 1;
return;
}
if (!CAPA(s_conn, CAPA_MUPDATE)) {
// Huh?
// "reserve mailbox on MUPDATE"
syslog(LOG_WARNING, "backend %s is not advertising any MUPDATE capability (%s:%d)", server, __FILE__, __LINE__);
}
// why not send a LOCALCREATE to the backend?
prot_printf(s_conn->out, "%s CREATE ", tag);
prot_printastring(s_conn->out, name);
// special use needs extended support, so pass through extargs
if (specialuse.len) {
prot_printf(s_conn->out, "(USE (%s)", buf_cstring(&specialuse));
if (partition) {
prot_printf(s_conn->out, " PARTITION ");
prot_printastring(s_conn->out, partition);
}
prot_putc(')', s_conn->out);
}
// Send partition as an atom, since its supported by older servers
else if (partition) {
prot_putc(' ', s_conn->out);
prot_printastring(s_conn->out, partition);
}
prot_printf(s_conn->out, "\r\n");
int res = pipe_until_tag(s_conn, tag, 0);
if (!CAPA(s_conn, CAPA_MUPDATE)) {
// Huh?
// "do MUPDATE create operations"
syslog(LOG_WARNING, "backend %s is not advertising any MUPDATE capability (%s:%d)", server, __FILE__, __LINE__);
}
/* make sure we've seen the update */
if (ultraparanoid && res == PROXY_OK) kick_mupdate();
imapd_check(s_conn, 0);
prot_printf(imapd_out, "%s %s", tag, s_conn->last_result.s);
goto done;
} else { // (!config_getstring(IMAPOPT_PROXYSERVERS))
// I have a standard murder config but also proxy servers configured; I'm a backend!
goto localcreate;
} // (!config_getstring(IMAPOPT_PROXYSERVERS))
} // (config_mupdate_config == IMAP_ENUM_MUPDATE_CONFIG_STANDARD)
else if (config_mupdate_config == IMAP_ENUM_MUPDATE_CONFIG_REPLICATED) {
// Everything is local
goto localcreate;
} // (config_mupdate_config == IMAP_ENUM_MUPDATE_CONFIG_REPLICATED)
else {
syslog(LOG_ERR, "murder configuration I cannot deal with");
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(IMAP_SERVER_UNAVAILABLE));
goto done;
}
} else { // (config_mupdate_server)
// I'm no part of a Murder, *everything* is localcreate
goto localcreate;
} // (config_mupdate_server)
} else { // (!localonly)
goto localcreate;
}
localcreate:
r = mboxlist_createmailbox(
mbname_intname(mbname), // const char name
mbtype, // int mbtype
partition, // const char partition
imapd_userisadmin || imapd_userisproxyadmin, // int isadmin
imapd_userid, // const char userid
imapd_authstate, // struct auth_state auth_state
localonly, // int localonly
localonly, // int forceuser
0, // int dbonly
1, // int notify
NULL // struct mailbox mailboxptr
);
#ifdef USE_AUTOCREATE
// Clausing autocreate for the INBOX
if (r == IMAP_PERMISSION_DENIED) {
if (!strcasecmp(name, "INBOX")) {
int autocreatequotastorage = config_getint(IMAPOPT_AUTOCREATE_QUOTA);
if (autocreatequotastorage > 0) {
r = mboxlist_createmailbox(
mbname_intname(mbname),
0,
partition,
1,
imapd_userid,
imapd_authstate,
0,
0,
0,
1,
NULL
);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
goto done;
}
int autocreatequotamessage = config_getint(IMAPOPT_AUTOCREATE_QUOTA_MESSAGES);
if ((autocreatequotastorage > 0) || (autocreatequotamessage > 0)) {
quota_t newquotas[QUOTA_NUMRESOURCES];
int res;
for (res = 0; res < QUOTA_NUMRESOURCES; res++) {
newquotas[res] = QUOTA_UNLIMITED;
}
newquotas[QUOTA_STORAGE] = autocreatequotastorage;
newquotas[QUOTA_MESSAGE] = autocreatequotamessage;
(void) mboxlist_setquotas(mbname_intname(mbname), newquotas, 0);
} // (autocreatequotastorage > 0) || (autocreatequotamessage > 0)
} else { // (autocreatequotastorage = config_getint(IMAPOPT_AUTOCREATEQUOTA))
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(IMAP_PERMISSION_DENIED));
goto done;
} // (autocreatequotastorage = config_getint(IMAPOPT_AUTOCREATEQUOTA))
} else { // (!strcasecmp(name, "INBOX"))
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(IMAP_PERMISSION_DENIED));
goto done;
} // (!strcasecmp(name, "INBOX"))
} else if (r) { // (r == IMAP_PERMISSION_DENIED)
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
goto done;
} else { // (r == IMAP_PERMISSION_DENIED)
/* no error: carry on */
} // (r == IMAP_PERMISSION_DENIED)
#else // USE_AUTOCREATE
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
goto done;
} // (r)
#endif // USE_AUTOCREATE
if (specialuse.len) {
r = annotatemore_write(mbname_intname(mbname), "/specialuse", mbname_userid(mbname), &specialuse);
if (r) {
/* XXX - failure here SHOULD cause a cleanup of the created mailbox */
syslog(
LOG_ERR,
"IOERROR: failed to write specialuse for %s on %s (%s) (%s:%d)",
imapd_userid,
mbname_intname(mbname),
buf_cstring(&specialuse),
__FILE__,
__LINE__
);
prot_printf(imapd_out, "%s NO %s (%s:%d)\r\n", tag, error_message(r), __FILE__, __LINE__);
goto done;
}
}
prot_printf(imapd_out, "%s OK Completed\r\n", tag);
imapd_check(NULL, 0);
done:
buf_free(&specialuse);
mbname_free(&mbname);
}
/* Callback for use by cmd_delete */
static int delmbox(const mbentry_t *mbentry, void *rock __attribute__((unused)))
{
int r;
if (!mboxlist_delayed_delete_isenabled()) {
r = mboxlist_deletemailbox(mbentry->name,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate, NULL,
0, 0, 0);
} else if ((imapd_userisadmin || imapd_userisproxyadmin) &&
mboxname_isdeletedmailbox(mbentry->name, NULL)) {
r = mboxlist_deletemailbox(mbentry->name,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate, NULL,
0, 0, 0);
} else {
r = mboxlist_delayed_deletemailbox(mbentry->name,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate, NULL,
0, 0, 0);
}
if (r) {
prot_printf(imapd_out, "* NO delete %s: %s\r\n",
mbentry->name, error_message(r));
}
return 0;
}
/*
* Perform a DELETE command
*/
static void cmd_delete(char *tag, char *name, int localonly, int force)
{
int r;
mbentry_t *mbentry = NULL;
struct mboxevent *mboxevent = NULL;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(NULL, NULL, intname, &mbentry);
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
struct backend *s = NULL;
int res;
if (supports_referrals) {
imapd_refer(tag, mbentry->server, name);
referral_kick = 1;
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
mboxlist_entry_free(&mbentry);
if (!s) r = IMAP_SERVER_UNAVAILABLE;
if (!r) {
prot_printf(s->out, "%s DELETE {" SIZE_T_FMT "+}\r\n%s\r\n",
tag, strlen(name), name);
res = pipe_until_tag(s, tag, 0);
if (!CAPA(s, CAPA_MUPDATE) && res == PROXY_OK) {
/* do MUPDATE delete operations */
}
/* make sure we've seen the update */
if (ultraparanoid && res == PROXY_OK) kick_mupdate();
}
imapd_check(s, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
/* we're allowed to reference last_result since the noop, if
sent, went to a different server */
prot_printf(imapd_out, "%s %s", tag, s->last_result.s);
}
free(intname);
return;
}
mboxlist_entry_free(&mbentry);
mboxevent = mboxevent_new(EVENT_MAILBOX_DELETE);
/* local mailbox */
if (!r) {
if (localonly || !mboxlist_delayed_delete_isenabled()) {
r = mboxlist_deletemailbox(intname,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate, mboxevent,
1-force, localonly, 0);
} else if ((imapd_userisadmin || imapd_userisproxyadmin) &&
mboxname_isdeletedmailbox(intname, NULL)) {
r = mboxlist_deletemailbox(intname,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate, mboxevent,
0 /* checkacl */, localonly, 0);
} else {
r = mboxlist_delayed_deletemailbox(intname,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate, mboxevent,
1-force, 0, 0);
}
}
/* send a MailboxDelete event notification */
if (!r)
mboxevent_notify(&mboxevent);
mboxevent_free(&mboxevent);
/* was it a top-level user mailbox? */
/* localonly deletes are only per-mailbox */
if (!r && !localonly && mboxname_isusermailbox(intname, 1)) {
char *userid = mboxname_to_userid(intname);
if (userid) {
r = mboxlist_usermboxtree(userid, delmbox, NULL, 0);
if (!r) r = user_deletedata(userid, 1);
free(userid);
}
}
if (!r && config_getswitch(IMAPOPT_DELETE_UNSUBSCRIBE)) {
mboxlist_changesub(intname, imapd_userid, imapd_authstate,
/* add */ 0, /* force */ 0, /* notify? */ 1);
}
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
}
else {
if (config_mupdate_server)
kick_mupdate();
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
free(intname);
}
struct renrock
{
const struct namespace *namespace;
int ol;
int nl;
int rename_user;
const char *olduser, *newuser;
char *newmailboxname;
const char *partition;
int found;
};
/* Callback for use by cmd_rename */
static int checkmboxname(const mbentry_t *mbentry, void *rock)
{
struct renrock *text = (struct renrock *)rock;
int r;
text->found++;
if((text->nl + strlen(mbentry->name + text->ol)) >= MAX_MAILBOX_BUFFER)
return IMAP_MAILBOX_BADNAME;
strcpy(text->newmailboxname + text->nl, mbentry->name + text->ol);
/* force create, but don't ignore policy. This is a filthy hack that
will go away when we refactor this code */
r = mboxlist_createmailboxcheck(text->newmailboxname, 0, text->partition, 1,
imapd_userid, imapd_authstate, NULL, NULL, 2);
return r;
}
/* Callback for use by cmd_rename */
static int renmbox(const mbentry_t *mbentry, void *rock)
{
struct renrock *text = (struct renrock *)rock;
char *oldextname = NULL, *newextname = NULL;
int r = 0;
uint32_t uidvalidity = mbentry->uidvalidity;
if((text->nl + strlen(mbentry->name + text->ol)) >= MAX_MAILBOX_BUFFER)
goto done;
strcpy(text->newmailboxname + text->nl, mbentry->name + text->ol);
/* check if a previous deleted mailbox existed */
mbentry_t *newmbentry = NULL;
r = mboxlist_lookup_allow_all(text->newmailboxname, &newmbentry, NULL);
/* XXX - otherwise we should probably reject now, but meh, save it for
* a real cleanup */
if (!r && newmbentry->mbtype == MBTYPE_DELETED) {
/* changing the unique id since last time? */
if (strcmpsafe(mbentry->uniqueid, newmbentry->uniqueid)) {
/* then the UIDVALIDITY must be higher than before */
if (uidvalidity <= newmbentry->uidvalidity)
uidvalidity = newmbentry->uidvalidity+1;
}
}
mboxlist_entry_free(&newmbentry);
/* don't notify implied rename in mailbox hierarchy */
r = mboxlist_renamemailbox(mbentry->name, text->newmailboxname,
text->partition, uidvalidity,
1, imapd_userid, imapd_authstate, NULL, 0, 0,
text->rename_user);
oldextname =
mboxname_to_external(mbentry->name, &imapd_namespace, imapd_userid);
newextname =
mboxname_to_external(text->newmailboxname, &imapd_namespace, imapd_userid);
if(r) {
prot_printf(imapd_out, "* NO rename %s %s: %s\r\n",
oldextname, newextname, error_message(r));
if (!RENAME_STOP_ON_ERROR) r = 0;
} else {
/* If we're renaming a user, change quotaroot and ACL */
if (text->rename_user) {
user_copyquotaroot(mbentry->name, text->newmailboxname);
user_renameacl(text->namespace, text->newmailboxname,
text->olduser, text->newuser);
}
prot_printf(imapd_out, "* OK rename %s %s\r\n",
oldextname, newextname);
}
done:
prot_flush(imapd_out);
free(oldextname);
free(newextname);
return r;
}
/*
* Perform a RENAME command
*/
static void cmd_rename(char *tag, char *oldname, char *newname, char *location)
{
int r = 0;
char *c;
char oldmailboxname[MAX_MAILBOX_BUFFER];
char newmailboxname[MAX_MAILBOX_BUFFER];
char oldmailboxname2[MAX_MAILBOX_BUFFER];
char newmailboxname2[MAX_MAILBOX_BUFFER];
char *oldextname = NULL;
char *newextname = NULL;
char *oldintname = NULL;
char *newintname = NULL;
char *olduser = NULL;
char *newuser = NULL;
int omlen, nmlen;
int subcount = 0; /* number of sub-folders found */
int recursive_rename = 1;
int rename_user = 0;
mbentry_t *mbentry = NULL;
struct renrock rock;
if (location && !imapd_userisadmin) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(IMAP_PERMISSION_DENIED));
return;
}
if (location && strcmp(oldname, newname)) {
prot_printf(imapd_out,
"%s NO Cross-server or cross-partition move w/rename not supported\r\n",
tag);
return;
}
oldintname = mboxname_from_external(oldname, &imapd_namespace, imapd_userid);
strncpy(oldmailboxname, oldintname, MAX_MAILBOX_NAME);
free(oldintname);
newintname = mboxname_from_external(newname, &imapd_namespace, imapd_userid);
strncpy(newmailboxname, newintname, MAX_MAILBOX_NAME);
free(newintname);
olduser = mboxname_to_userid(oldmailboxname);
newuser = mboxname_to_userid(newmailboxname);
/* Keep temporary copy: master is trashed */
strcpy(oldmailboxname2, oldmailboxname);
strcpy(newmailboxname2, newmailboxname);
r = mlookup(NULL, NULL, oldmailboxname, &mbentry);
if (!r && mbentry->mbtype & MBTYPE_REMOTE) {
/* remote mailbox */
struct backend *s = NULL;
int res;
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!s) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(IMAP_SERVER_UNAVAILABLE));
goto done;
}
// Server or partition is going to change
if (location) {
char *destserver = NULL;
char *destpart = NULL;
c = strchr(location, '!');
if (c) {
destserver = xstrndup(location, c - location);
destpart = xstrdup(c + 1);
} else {
destpart = xstrdup(location);
}
if (*destpart == '\0') {
free(destpart);
destpart = NULL;
}
if (!destserver || !strcmp(destserver, mbentry->server)) {
/* same server: proxy a rename */
prot_printf(s->out,
"%s RENAME \"%s\" \"%s\" %s\r\n",
tag,
oldname,
newname,
location);
} else {
/* different server: proxy an xfer */
prot_printf(s->out,
"%s XFER \"%s\" %s%s%s\r\n",
tag,
oldname,
destserver,
destpart ? " " : "",
destpart ? destpart : "");
}
if (destserver) free(destserver);
if (destpart) free(destpart);
res = pipe_until_tag(s, tag, 0);
/* make sure we've seen the update */
if (ultraparanoid && res == PROXY_OK) kick_mupdate();
} else { // (location)
// a simple rename, old name and new name must not be the same
if (!strcmp(oldname, newname)) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(IMAP_SERVER_UNAVAILABLE));
goto done;
}
prot_printf(s->out,
"%s RENAME \"%s\" \"%s\"\r\n",
tag,
oldname,
newname
);
res = pipe_until_tag(s, tag, 0);
/* make sure we've seen the update */
if (ultraparanoid && res == PROXY_OK) kick_mupdate();
}
imapd_check(s, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
/* we're allowed to reference last_result since the noop, if
sent, went to a different server */
prot_printf(imapd_out, "%s %s", tag, s->last_result.s);
}
goto done;
}
/* local mailbox */
if (location && !config_partitiondir(location)) {
/* invalid partition, assume its a server (remote destination) */
char *server;
char *partition;
/* dest partition? */
server = location;
partition = strchr(location, '!');
if (partition) *partition++ = '\0';
cmd_xfer(tag, oldname, server, partition);
goto done;
}
/* local rename: it's OK if the mailbox doesn't exist, we'll check
* if sub mailboxes can be renamed */
if (r == IMAP_MAILBOX_NONEXISTENT)
r = 0;
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
goto done;
}
/* local destination */
/* if this is my inbox, don't do recursive renames */
if (!strcasecmp(oldname, "inbox")) {
recursive_rename = 0;
}
/* check if we're an admin renaming a user */
else if (config_getswitch(IMAPOPT_ALLOWUSERMOVES) &&
mboxname_isusermailbox(oldmailboxname, 1) &&
mboxname_isusermailbox(newmailboxname, 1) &&
strcmp(oldmailboxname, newmailboxname) && /* different user */
imapd_userisadmin) {
rename_user = 1;
}
/* if we're renaming something inside of something else,
don't recursively rename stuff */
omlen = strlen(oldmailboxname);
nmlen = strlen(newmailboxname);
if (omlen < nmlen) {
if (!strncmp(oldmailboxname, newmailboxname, omlen) &&
newmailboxname[omlen] == '.') {
recursive_rename = 0;
}
} else {
if (!strncmp(oldmailboxname, newmailboxname, nmlen) &&
oldmailboxname[nmlen] == '.') {
recursive_rename = 0;
}
}
oldextname = mboxname_to_external(oldmailboxname, &imapd_namespace, imapd_userid);
newextname = mboxname_to_external(newmailboxname, &imapd_namespace, imapd_userid);
/* rename all mailboxes matching this */
if (recursive_rename && strcmp(oldmailboxname, newmailboxname)) {
int ol = omlen + 1;
int nl = nmlen + 1;
char ombn[MAX_MAILBOX_BUFFER];
char nmbn[MAX_MAILBOX_BUFFER];
strcpy(ombn, oldmailboxname);
strcpy(nmbn, newmailboxname);
strcat(ombn, ".");
strcat(nmbn, ".");
/* setup the rock */
rock.namespace = &imapd_namespace;
rock.found = 0;
rock.newmailboxname = nmbn;
rock.ol = ol;
rock.nl = nl;
rock.olduser = olduser;
rock.newuser = newuser;
rock.partition = location;
rock.rename_user = rename_user;
/* Check mboxnames to ensure we can write them all BEFORE we start */
r = mboxlist_allmbox(ombn, checkmboxname, &rock, 0);
subcount = rock.found;
}
/* attempt to rename the base mailbox */
if (!r) {
struct mboxevent *mboxevent = NULL;
uint32_t uidvalidity = mbentry ? mbentry->uidvalidity : 0;
/* don't send rename notification if we only change the partition */
if (strcmp(oldmailboxname, newmailboxname))
mboxevent = mboxevent_new(EVENT_MAILBOX_RENAME);
/* check if a previous deleted mailbox existed */
mbentry_t *newmbentry = NULL;
r = mboxlist_lookup_allow_all(newmailboxname, &newmbentry, NULL);
/* XXX - otherwise we should probably reject now, but meh, save it for
* a real cleanup */
if (!r && newmbentry->mbtype == MBTYPE_DELETED) {
/* changing the unique id since last time? */
if (!mbentry || strcmpsafe(mbentry->uniqueid, newmbentry->uniqueid)) {
/* then the UIDVALIDITY must be higher than before */
if (uidvalidity <= newmbentry->uidvalidity)
uidvalidity = newmbentry->uidvalidity+1;
}
}
mboxlist_entry_free(&newmbentry);
r = mboxlist_renamemailbox(oldmailboxname, newmailboxname, location,
0 /* uidvalidity */, imapd_userisadmin,
imapd_userid, imapd_authstate, mboxevent,
0, 0, rename_user);
/* it's OK to not exist if there are subfolders */
if (r == IMAP_MAILBOX_NONEXISTENT && subcount && !rename_user &&
mboxname_userownsmailbox(imapd_userid, oldmailboxname) &&
mboxname_userownsmailbox(imapd_userid, newmailboxname)) {
mboxevent_free(&mboxevent);
goto submboxes;
}
/* send a MailboxRename event notification if enabled */
if (!r)
mboxevent_notify(&mboxevent);
mboxevent_free(&mboxevent);
}
/* If we're renaming a user, take care of changing quotaroot, ACL,
seen state, subscriptions and sieve scripts */
if (!r && rename_user) {
user_copyquotaroot(oldmailboxname, newmailboxname);
user_renameacl(&imapd_namespace, newmailboxname, olduser, newuser);
user_renamedata(olduser, newuser);
/* XXX report status/progress of meta-data */
}
/* rename all mailboxes matching this */
if (!r && recursive_rename) {
prot_printf(imapd_out, "* OK rename %s %s\r\n",
oldextname, newextname);
prot_flush(imapd_out);
submboxes:
strcat(oldmailboxname, ".");
strcat(newmailboxname, ".");
/* setup the rock */
rock.namespace = &imapd_namespace;
rock.newmailboxname = newmailboxname;
rock.ol = omlen + 1;
rock.nl = nmlen + 1;
rock.olduser = olduser;
rock.newuser = newuser;
rock.partition = location;
rock.rename_user = rename_user;
/* add submailboxes; we pretend we're an admin since we successfully
renamed the parent - we're using internal names here */
r = mboxlist_allmbox(oldmailboxname, renmbox, &rock, 0);
}
/* take care of deleting old ACLs, subscriptions, seen state and quotas */
if (!r && rename_user) {
user_deletedata(olduser, 1);
/* allow the replica to get the correct new quotaroot
* and acls copied across */
sync_log_user(newuser);
/* allow the replica to clean up the old meta files */
sync_log_unuser(olduser);
}
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
if (config_mupdate_server)
kick_mupdate();
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
if (rename_user) sync_log_user(newuser);
}
done:
mboxlist_entry_free(&mbentry);
free(oldextname);
free(newextname);
free(olduser);
free(newuser);
}
/*
* Perform a RECONSTRUCT command
*/
static void cmd_reconstruct(const char *tag, const char *name, int recursive)
{
int r = 0;
char quotaroot[MAX_MAILBOX_BUFFER];
mbentry_t *mbentry = NULL;
struct mailbox *mailbox = NULL;
/* administrators only please */
if (!imapd_userisadmin)
r = IMAP_PERMISSION_DENIED;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
if (!r && !strcmpsafe(intname, index_mboxname(imapd_index)))
r = IMAP_MAILBOX_LOCKED;
if (!r) {
r = mlookup(tag, name, intname, &mbentry);
}
if (r == IMAP_MAILBOX_MOVED) {
free(intname);
return;
}
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
imapd_refer(tag, mbentry->server, name);
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
mboxlist_entry_free(&mbentry);
/* local mailbox */
if (!r) {
int pid;
/* Reconstruct it */
pid = fork();
if (pid == -1) {
r = IMAP_SYS_ERROR;
} else if (pid == 0) {
char buf[4096];
int ret;
/* Child - exec reconstruct*/
syslog(LOG_NOTICE, "Reconstructing '%s' (%s) for user '%s'",
intname, recursive ? "recursive" : "not recursive",
imapd_userid);
fclose(stdin);
fclose(stdout);
fclose(stderr);
ret = snprintf(buf, sizeof(buf), "%s/reconstruct", SBIN_DIR);
if(ret < 0 || ret >= (int) sizeof(buf)) {
/* in child, so fatailing won't disconnect our user */
fatal("reconstruct buffer not sufficiently big", EC_CONFIG);
}
if(recursive) {
execl(buf, buf, "-C", config_filename, "-r", "-f",
intname, NULL);
} else {
execl(buf, buf, "-C", config_filename, intname, NULL);
}
/* if we are here, we have a problem */
exit(-1);
} else {
int status;
/* Parent, wait on child */
if(waitpid(pid, &status, 0) < 0) r = IMAP_SYS_ERROR;
/* Did we fail? */
if(WEXITSTATUS(status) != 0) r = IMAP_SYS_ERROR;
}
}
/* Still in parent, need to re-quota the mailbox*/
/* Find its quota root */
if (!r)
r = mailbox_open_irl(intname, &mailbox);
if(!r) {
if(mailbox->quotaroot) {
strcpy(quotaroot, mailbox->quotaroot);
} else {
strcpy(quotaroot, intname);
}
mailbox_close(&mailbox);
}
/* Run quota -f */
if (!r) {
int pid;
pid = fork();
if(pid == -1) {
r = IMAP_SYS_ERROR;
} else if(pid == 0) {
char buf[4096];
int ret;
/* Child - exec reconstruct*/
syslog(LOG_NOTICE,
"Regenerating quota roots starting with '%s' for user '%s'",
intname, imapd_userid);
fclose(stdin);
fclose(stdout);
fclose(stderr);
ret = snprintf(buf, sizeof(buf), "%s/quota", SBIN_DIR);
if(ret < 0 || ret >= (int) sizeof(buf)) {
/* in child, so fatailing won't disconnect our user */
fatal("quota buffer not sufficiently big", EC_CONFIG);
}
execl(buf, buf, "-C", config_filename, "-f", quotaroot, NULL);
/* if we are here, we have a problem */
exit(-1);
} else {
int status;
/* Parent, wait on child */
if(waitpid(pid, &status, 0) < 0) r = IMAP_SYS_ERROR;
/* Did we fail? */
if(WEXITSTATUS(status) != 0) r = IMAP_SYS_ERROR;
}
}
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
free(intname);
}
/* number of times the callbacks for findall/findsub have been called */
static int list_callback_calls;
/*
* Parse LIST command arguments.
*/
static void getlistargs(char *tag, struct listargs *listargs)
{
static struct buf reference, buf;
int c;
/* Check for and parse LIST-EXTENDED selection options */
c = prot_getc(imapd_in);
if (c == '(') {
listargs->cmd = LIST_CMD_EXTENDED;
c = getlistselopts(tag, listargs);
if (c == EOF) {
eatline(imapd_in, c);
return;
}
}
else
prot_ungetc(c, imapd_in);
if (!strcmpsafe(imapd_magicplus, "+")) listargs->sel |= LIST_SEL_SUBSCRIBED;
else if (!strcasecmpsafe(imapd_magicplus, "+dav")) listargs->sel |= LIST_SEL_DAV;
/* Read in reference name */
c = getastring(imapd_in, imapd_out, &reference);
if (c == EOF && !*reference.s) {
prot_printf(imapd_out,
"%s BAD Missing required argument to List: reference name\r\n",
tag);
eatline(imapd_in, c);
return;
}
listargs->ref = reference.s;
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing required argument to List: mailbox pattern\r\n", tag);
eatline(imapd_in, c);
return;
}
/* Read in mailbox pattern(s) */
c = prot_getc(imapd_in);
if (c == '(') {
listargs->cmd = LIST_CMD_EXTENDED;
for (;;) {
c = getastring(imapd_in, imapd_out, &buf);
if (*buf.s)
strarray_append(&listargs->pat, buf.s);
if (c != ' ') break;
}
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Invalid syntax in List command\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
c = prot_getc(imapd_in);
}
else {
prot_ungetc(c, imapd_in);
c = getastring(imapd_in, imapd_out, &buf);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing required argument to List: mailbox pattern\r\n",
tag);
eatline(imapd_in, c);
goto freeargs;
}
strarray_append(&listargs->pat, buf.s);
}
/* Check for and parse LIST-EXTENDED return options */
if (c == ' ') {
listargs->cmd = LIST_CMD_EXTENDED;
c = getlistretopts(tag, listargs);
if (c == EOF) {
eatline(imapd_in, c);
goto freeargs;
}
}
/* check for CRLF */
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to List\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
#ifdef USE_AUTOCREATE
autocreate_inbox();
#endif // USE_AUTOCREATE
return;
freeargs:
strarray_fini(&listargs->pat);
strarray_fini(&listargs->metaitems);
return;
}
/*
* Perform a LIST, LSUB, RLIST or RLSUB command
*/
static void cmd_list(char *tag, struct listargs *listargs)
{
clock_t start = clock();
char mytime[100];
if (listargs->sel & LIST_SEL_REMOTE) {
if (!config_getswitch(IMAPOPT_PROXYD_DISABLE_MAILBOX_REFERRALS)) {
supports_referrals = !disable_referrals;
}
}
list_callback_calls = 0;
if (listargs->pat.count && !*(listargs->pat.data[0]) && (listargs->cmd == LIST_CMD_LIST)) {
/* special case: query top-level hierarchy separator */
prot_printf(imapd_out, "* LIST (\\Noselect) \"%c\" \"\"\r\n",
imapd_namespace.hier_sep);
} else if (listargs->pat.count && !*(listargs->pat.data[0]) && (listargs->cmd == LIST_CMD_XLIST)) {
/* special case: query top-level hierarchy separator */
prot_printf(imapd_out, "* XLIST (\\Noselect) \"%c\" \"\"\r\n",
imapd_namespace.hier_sep);
} else if ((listargs->cmd == LIST_CMD_LSUB) &&
(backend_inbox || (backend_inbox = proxy_findinboxserver(imapd_userid)))) {
/* remote inbox */
if (list_data_remote(backend_inbox, tag, listargs, NULL))
return;
} else {
list_data(listargs);
}
strarray_fini(&listargs->pat);
strarray_fini(&listargs->metaitems);
imapd_check((listargs->sel & LIST_SEL_SUBSCRIBED) ? NULL : backend_inbox, 0);
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
if ((listargs->sel & LIST_SEL_METADATA) && listargs->metaopts.maxsize &&
listargs->metaopts.biggest > listargs->metaopts.maxsize) {
prot_printf(imapd_out, "%s OK [METADATA LONGENTRIES %u] %s\r\n", tag,
(unsigned)listargs->metaopts.biggest, error_message(IMAP_OK_COMPLETED));
}
else {
prot_printf(imapd_out, "%s OK %s (%s secs", tag,
error_message(IMAP_OK_COMPLETED), mytime);
if (list_callback_calls)
prot_printf(imapd_out, " %u calls", list_callback_calls);
prot_printf(imapd_out, ")\r\n");
}
if (global_conversations) {
conversations_abort(&global_conversations);
global_conversations = NULL;
}
}
/*
* Perform a SUBSCRIBE (add is nonzero) or
* UNSUBSCRIBE (add is zero) command
*/
static void cmd_changesub(char *tag, char *namespace, char *name, int add)
{
const char *cmd = add ? "Subscribe" : "Unsubscribe";
int r = 0;
int force = config_getswitch(IMAPOPT_ALLOWALLSUBSCRIBE);
if (backend_inbox || (backend_inbox = proxy_findinboxserver(imapd_userid))) {
/* remote INBOX */
if (add) {
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(NULL, NULL, intname, NULL);
free(intname);
/* Doesn't exist on murder */
}
imapd_check(backend_inbox, 0);
if (!r) {
if (namespace) {
prot_printf(backend_inbox->out,
"%s %s {" SIZE_T_FMT "+}\r\n%s"
" {" SIZE_T_FMT "+}\r\n%s\r\n",
tag, cmd,
strlen(namespace), namespace,
strlen(name), name);
} else {
prot_printf(backend_inbox->out, "%s %s {" SIZE_T_FMT "+}\r\n%s\r\n",
tag, cmd,
strlen(name), name);
}
pipe_including_tag(backend_inbox, tag, 0);
}
else {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
}
return;
}
/* local INBOX */
if (namespace) lcase(namespace);
if (!namespace || !strcmp(namespace, "mailbox")) {
size_t len = strlen(name);
if (force && imapd_namespace.isalt &&
(((len == strlen(imapd_namespace.prefix[NAMESPACE_USER]) - 1) &&
!strncmp(name, imapd_namespace.prefix[NAMESPACE_USER], len)) ||
((len == strlen(imapd_namespace.prefix[NAMESPACE_SHARED]) - 1) &&
!strncmp(name, imapd_namespace.prefix[NAMESPACE_SHARED], len)))) {
r = 0;
}
else {
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mboxlist_changesub(intname, imapd_userid, imapd_authstate, add, force, 1);
free(intname);
}
}
else if (!strcmp(namespace, "bboard")) {
r = add ? IMAP_MAILBOX_NONEXISTENT : 0;
}
else {
prot_printf(imapd_out, "%s BAD Invalid %s subcommand\r\n", tag, cmd);
return;
}
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s: %s\r\n", tag, cmd, error_message(r));
}
else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
}
/*
* Perform a GETACL command
*/
static void cmd_getacl(const char *tag, const char *name)
{
int r, access;
char *acl;
char *rights, *nextid;
char *freeme = NULL;
mbentry_t *mbentry = NULL;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(tag, name, intname, &mbentry);
if (r == IMAP_MAILBOX_MOVED) return;
if (!r) {
access = cyrus_acl_myrights(imapd_authstate, mbentry->acl);
if (!(access & ACL_ADMIN) &&
!imapd_userisadmin &&
!mboxname_userownsmailbox(imapd_userid, intname)) {
r = (access & ACL_LOOKUP) ?
IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT;
}
}
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
prot_printf(imapd_out, "* ACL ");
prot_printastring(imapd_out, name);
freeme = acl = xstrdupnull(mbentry->acl);
while (acl) {
rights = strchr(acl, '\t');
if (!rights) break;
*rights++ = '\0';
nextid = strchr(rights, '\t');
if (!nextid) break;
*nextid++ = '\0';
prot_printf(imapd_out, " ");
prot_printastring(imapd_out, acl);
prot_printf(imapd_out, " ");
prot_printastring(imapd_out, rights);
acl = nextid;
}
prot_printf(imapd_out, "\r\n");
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
free(freeme);
mboxlist_entry_free(&mbentry);
free(intname);
}
/*
* Perform a LISTRIGHTS command
*/
static void cmd_listrights(char *tag, char *name, char *identifier)
{
int r, rights;
mbentry_t *mbentry = NULL;
struct auth_state *authstate;
const char *canon_identifier;
int implicit;
char rightsdesc[100], optional[33];
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(tag, name, intname, &mbentry);
if (r == IMAP_MAILBOX_MOVED) return;
if (!r) {
rights = cyrus_acl_myrights(imapd_authstate, mbentry->acl);
if (!rights && !imapd_userisadmin &&
!mboxname_userownsmailbox(imapd_userid, intname)) {
r = IMAP_MAILBOX_NONEXISTENT;
}
}
mboxlist_entry_free(&mbentry);
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
return;
}
authstate = auth_newstate(identifier);
if (global_authisa(authstate, IMAPOPT_ADMINS))
canon_identifier = identifier; /* don't canonify global admins */
else
canon_identifier = canonify_userid(identifier, imapd_userid, NULL);
auth_freestate(authstate);
if (!canon_identifier) {
implicit = 0;
}
else if (mboxname_userownsmailbox(canon_identifier, intname)) {
/* identifier's personal mailbox */
implicit = config_implicitrights;
}
else if (mboxname_isusermailbox(intname, 1)) {
/* anyone can post to an INBOX */
implicit = ACL_POST;
}
else {
implicit = 0;
}
/* calculate optional rights */
cyrus_acl_masktostr(implicit ^ (canon_identifier ? ACL_FULL : 0),
optional);
/* build the rights string */
if (implicit) {
cyrus_acl_masktostr(implicit, rightsdesc);
}
else {
strcpy(rightsdesc, "\"\"");
}
if (*optional) {
int i, n = strlen(optional);
char *p = rightsdesc + strlen(rightsdesc);
for (i = 0; i < n; i++) {
*p++ = ' ';
*p++ = optional[i];
}
*p = '\0';
}
prot_printf(imapd_out, "* LISTRIGHTS ");
prot_printastring(imapd_out, name);
(void)prot_putc(' ', imapd_out);
prot_printastring(imapd_out, identifier);
prot_printf(imapd_out, " %s", rightsdesc);
prot_printf(imapd_out, "\r\n%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
free(intname);
}
static int printmyrights(const char *extname, const mbentry_t *mbentry)
{
int rights = 0;
char str[ACL_MAXSTR];
rights = cyrus_acl_myrights(imapd_authstate, mbentry->acl);
/* Add in implicit rights */
if (imapd_userisadmin) {
rights |= ACL_LOOKUP|ACL_ADMIN;
}
else if (mboxname_userownsmailbox(imapd_userid, mbentry->name)) {
rights |= config_implicitrights;
}
if (!(rights & (ACL_LOOKUP|ACL_READ|ACL_INSERT|ACL_CREATE|ACL_DELETEMBOX|ACL_ADMIN))) {
return IMAP_MAILBOX_NONEXISTENT;
}
prot_printf(imapd_out, "* MYRIGHTS ");
prot_printastring(imapd_out, extname);
prot_printf(imapd_out, " ");
prot_printastring(imapd_out, cyrus_acl_masktostr(rights, str));
prot_printf(imapd_out, "\r\n");
return 0;
}
/*
* Perform a MYRIGHTS command
*/
static void cmd_myrights(const char *tag, const char *name)
{
mbentry_t *mbentry = NULL;
int r;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(tag, name, intname, &mbentry);
if (r == IMAP_MAILBOX_MOVED) return;
if (!r) r = printmyrights(name, mbentry);
mboxlist_entry_free(&mbentry);
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
return;
}
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
free(intname);
}
/*
* Perform a SETACL command
*/
static void cmd_setacl(char *tag, const char *name,
const char *identifier, const char *rights)
{
int r;
mbentry_t *mbentry = NULL;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
/* is it remote? */
r = mlookup(tag, name, intname, &mbentry);
if (r == IMAP_MAILBOX_MOVED) return;
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
struct backend *s = NULL;
int res;
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!s) r = IMAP_SERVER_UNAVAILABLE;
if (!r && imapd_userisadmin && supports_referrals) {
/* They aren't an admin remotely, so let's refer them */
imapd_refer(tag, mbentry->server, name);
referral_kick = 1;
mboxlist_entry_free(&mbentry);
return;
}
mboxlist_entry_free(&mbentry);
if (!r) {
if (rights) {
prot_printf(s->out,
"%s Setacl {" SIZE_T_FMT "+}\r\n%s"
" {" SIZE_T_FMT "+}\r\n%s {" SIZE_T_FMT "+}\r\n%s\r\n",
tag, strlen(name), name,
strlen(identifier), identifier,
strlen(rights), rights);
} else {
prot_printf(s->out,
"%s Deleteacl {" SIZE_T_FMT "+}\r\n%s"
" {" SIZE_T_FMT "+}\r\n%s\r\n",
tag, strlen(name), name,
strlen(identifier), identifier);
}
res = pipe_until_tag(s, tag, 0);
if (!CAPA(s, CAPA_MUPDATE) && res == PROXY_OK) {
/* setup new ACL in MUPDATE */
}
/* make sure we've seen the update */
if (ultraparanoid && res == PROXY_OK) kick_mupdate();
}
imapd_check(s, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
/* we're allowed to reference last_result since the noop, if
sent, went to a different server */
prot_printf(imapd_out, "%s %s", tag, s->last_result.s);
}
free(intname);
return;
}
mboxlist_entry_free(&mbentry);
/* local mailbox */
if (!r) {
char *err;
/* send BAD response if rights string contains unrecognised chars */
if (rights && *rights) {
r = cyrus_acl_checkstr(rights, &err);
if (r) {
prot_printf(imapd_out, "%s BAD %s\r\n", tag, err);
free(err);
free(intname);
return;
}
}
r = mboxlist_setacl(&imapd_namespace, intname, identifier, rights,
imapd_userisadmin || imapd_userisproxyadmin,
proxy_userid, imapd_authstate);
}
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
if (config_mupdate_server)
kick_mupdate();
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
free(intname);
}
static void print_quota_used(struct protstream *o, const struct quota *q)
{
int res;
const char *sep = "";
prot_putc('(', o);
for (res = 0 ; res < QUOTA_NUMRESOURCES ; res++) {
if (q->limits[res] >= 0) {
prot_printf(o, "%s%s " QUOTA_T_FMT " " QUOTA_T_FMT,
sep, quota_names[res],
q->useds[res]/quota_units[res],
q->limits[res]);
sep = " ";
}
}
prot_putc(')', o);
}
static void print_quota_limits(struct protstream *o, const struct quota *q)
{
int res;
const char *sep = "";
prot_putc('(', o);
for (res = 0 ; res < QUOTA_NUMRESOURCES ; res++) {
if (q->limits[res] >= 0) {
prot_printf(o, "%s%s " QUOTA_T_FMT,
sep, quota_names[res],
q->limits[res]);
sep = " ";
}
}
prot_putc(')', o);
}
/*
* Callback for (get|set)quota, to ensure that all of the
* submailboxes are on the same server.
*/
static int quota_cb(const mbentry_t *mbentry, void *rock)
{
const char *servername = (const char *)rock;
int r;
if (strcmp(servername, mbentry->server)) {
/* Not on same server as the root */
r = IMAP_NOT_SINGULAR_ROOT;
} else {
r = PROXY_OK;
}
return r;
}
/*
* Perform a GETQUOTA command
*/
static void cmd_getquota(const char *tag, const char *name)
{
int r;
char quotarootbuf[MAX_MAILBOX_BUFFER];
mbentry_t *mbentry = NULL;
struct quota q;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
quota_init(&q, intname);
imapd_check(NULL, 0);
if (!imapd_userisadmin && !imapd_userisproxyadmin) {
r = IMAP_PERMISSION_DENIED;
goto done;
}
r = mlookup(NULL, NULL, intname, &mbentry);
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
snprintf(quotarootbuf, sizeof(quotarootbuf), "%s.", intname);
r = mboxlist_allmbox(quotarootbuf, quota_cb, (void *)mbentry->server, 0);
if (r) goto done;
struct backend *s;
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!s) {
r = IMAP_SERVER_UNAVAILABLE;
goto done;
}
imapd_check(s, 0);
prot_printf(s->out, "%s Getquota {" SIZE_T_FMT "+}\r\n%s\r\n",
tag, strlen(name), name);
pipe_including_tag(s, tag, 0);
goto done;
}
/* local mailbox */
r = quota_read(&q, NULL, 0);
if (r) goto done;
prot_printf(imapd_out, "* QUOTA ");
prot_printastring(imapd_out, name);
prot_printf(imapd_out, " ");
print_quota_used(imapd_out, &q);
prot_printf(imapd_out, "\r\n");
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
done:
if (r) prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
mboxlist_entry_free(&mbentry);
quota_free(&q);
free(intname);
}
/*
* Perform a GETQUOTAROOT command
*/
static void cmd_getquotaroot(const char *tag, const char *name)
{
mbentry_t *mbentry = NULL;
struct mailbox *mailbox = NULL;
int myrights;
int r, doclose = 0;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(tag, name, intname, &mbentry);
if (r == IMAP_MAILBOX_MOVED) {
free(intname);
return;
}
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
struct backend *s;
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!s) r = IMAP_SERVER_UNAVAILABLE;
imapd_check(s, 0);
if (!r) {
prot_printf(s->out, "%s Getquotaroot {" SIZE_T_FMT "+}\r\n%s\r\n",
tag, strlen(name), name);
pipe_including_tag(s, tag, 0);
} else {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
}
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
mboxlist_entry_free(&mbentry);
/* local mailbox */
if (!r) {
r = mailbox_open_irl(intname, &mailbox);
if (!r) {
doclose = 1;
myrights = cyrus_acl_myrights(imapd_authstate, mailbox->acl);
}
}
if (!r) {
if (!imapd_userisadmin && !(myrights & ACL_READ)) {
r = (myrights & ACL_LOOKUP) ?
IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT;
}
}
if (!r) {
prot_printf(imapd_out, "* QUOTAROOT ");
prot_printastring(imapd_out, name);
if (mailbox->quotaroot) {
struct quota q;
char *extname = mboxname_to_external(mailbox->quotaroot, &imapd_namespace, imapd_userid);
prot_printf(imapd_out, " ");
prot_printastring(imapd_out, extname);
quota_init(&q, mailbox->quotaroot);
r = quota_read(&q, NULL, 0);
if (!r) {
prot_printf(imapd_out, "\r\n* QUOTA ");
prot_printastring(imapd_out, extname);
prot_putc(' ', imapd_out);
print_quota_used(imapd_out, &q);
}
quota_free(&q);
free(extname);
}
prot_printf(imapd_out, "\r\n");
}
if (doclose) mailbox_close(&mailbox);
free(intname);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
return;
}
imapd_check(NULL, 0);
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
/*
* Parse and perform a SETQUOTA command
* The command has been parsed up to the resource list
*/
void cmd_setquota(const char *tag, const char *quotaroot)
{
quota_t newquotas[QUOTA_NUMRESOURCES];
int res;
int c;
int force = 0;
static struct buf arg;
int r;
mbentry_t *mbentry = NULL;
char *intname = NULL;
if (!imapd_userisadmin && !imapd_userisproxyadmin) {
/* need to allow proxies so that mailbox moves can set initial quota
* roots */
r = IMAP_PERMISSION_DENIED;
goto out;
}
/* are we forcing the creation of a quotaroot by having a leading +? */
if (quotaroot[0] == '+') {
force = 1;
quotaroot++;
}
intname = mboxname_from_external(quotaroot, &imapd_namespace, imapd_userid);
r = mlookup(NULL, NULL, intname, &mbentry);
if (r == IMAP_MAILBOX_NONEXISTENT)
r = 0; /* will create a quotaroot anyway */
if (r)
goto out;
if (mbentry && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
struct backend *s;
char quotarootbuf[MAX_MAILBOX_BUFFER];
snprintf(quotarootbuf, sizeof(quotarootbuf), "%s.", intname);
r = mboxlist_allmbox(quotarootbuf, quota_cb, (void *)mbentry->server, 0);
if (r)
goto out;
imapd_check(NULL, 0);
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!s) {
r = IMAP_SERVER_UNAVAILABLE;
goto out;
}
imapd_check(s, 0);
prot_printf(s->out, "%s Setquota ", tag);
prot_printstring(s->out, quotaroot);
prot_putc(' ', s->out);
pipe_command(s, 0);
pipe_including_tag(s, tag, 0);
free(intname);
return;
}
mboxlist_entry_free(&mbentry);
/* local mailbox */
/* Now parse the arguments as a setquota_list */
c = prot_getc(imapd_in);
if (c != '(') goto badlist;
for (res = 0 ; res < QUOTA_NUMRESOURCES ; res++)
newquotas[res] = QUOTA_UNLIMITED;
for (;;) {
/* XXX - limit is actually stored in an int value */
int32_t limit = 0;
c = getword(imapd_in, &arg);
if ((c == ')') && !arg.s[0]) break;
if (c != ' ') goto badlist;
res = quota_name_to_resource(arg.s);
if (res < 0) {
r = IMAP_UNSUPPORTED_QUOTA;
goto out;
}
c = getsint32(imapd_in, &limit);
/* note: we accept >= 0 according to rfc2087,
* and also -1 to fix Bug #3559 */
if (limit < -1) goto badlist;
newquotas[res] = limit;
if (c == ')') break;
else if (c != ' ') goto badlist;
}
c = prot_getc(imapd_in);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out, "%s BAD Unexpected extra arguments to SETQUOTA\r\n", tag);
eatline(imapd_in, c);
return;
}
r = mboxlist_setquotas(intname, newquotas, force);
imapd_check(NULL, 0);
out:
mboxlist_entry_free(&mbentry);
free(intname);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
return;
}
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
return;
badlist:
prot_printf(imapd_out, "%s BAD Invalid quota list in Setquota\r\n", tag);
eatline(imapd_in, c);
free(intname);
}
#ifdef HAVE_SSL
/*
* this implements the STARTTLS command, as described in RFC 2595.
* one caveat: it assumes that no external layer is currently present.
* if a client executes this command, information about the external
* layer that was passed on the command line is disgarded. this should
* be fixed.
*/
/* imaps - whether this is an imaps transaction or not */
static void cmd_starttls(char *tag, int imaps)
{
int result;
int *layerp;
char *auth_id;
sasl_ssf_t ssf;
/* SASL and openssl have different ideas about whether ssf is signed */
layerp = (int *) &ssf;
if (imapd_starttls_done == 1)
{
prot_printf(imapd_out, "%s NO TLS already active\r\n", tag);
return;
}
result=tls_init_serverengine("imap",
5, /* depth to verify */
!imaps, /* can client auth? */
NULL);
if (result == -1) {
syslog(LOG_ERR, "error initializing TLS");
if (imaps == 0) {
prot_printf(imapd_out, "%s NO Error initializing TLS\r\n", tag);
} else {
shut_down(0);
}
return;
}
if (imaps == 0)
{
prot_printf(imapd_out, "%s OK Begin TLS negotiation now\r\n", tag);
/* must flush our buffers before starting tls */
prot_flush(imapd_out);
}
result=tls_start_servertls(0, /* read */
1, /* write */
imaps ? 180 : imapd_timeout,
layerp,
&auth_id,
&tls_conn);
/* if error */
if (result==-1) {
if (imaps == 0) {
prot_printf(imapd_out, "%s NO Starttls negotiation failed\r\n", tag);
syslog(LOG_NOTICE, "STARTTLS negotiation failed: %s", imapd_clienthost);
return;
} else {
syslog(LOG_NOTICE, "imaps TLS negotiation failed: %s", imapd_clienthost);
shut_down(0);
}
}
/* tell SASL about the negotiated layer */
result = sasl_setprop(imapd_saslconn, SASL_SSF_EXTERNAL, &ssf);
if (result == SASL_OK) {
saslprops.ssf = ssf;
result = sasl_setprop(imapd_saslconn, SASL_AUTH_EXTERNAL, auth_id);
}
if (result != SASL_OK) {
syslog(LOG_NOTICE, "sasl_setprop() failed: cmd_starttls()");
if (imaps == 0) {
fatal("sasl_setprop() failed: cmd_starttls()", EC_TEMPFAIL);
} else {
shut_down(0);
}
}
if(saslprops.authid) {
free(saslprops.authid);
saslprops.authid = NULL;
}
if(auth_id)
saslprops.authid = xstrdup(auth_id);
/* tell the prot layer about our new layers */
prot_settls(imapd_in, tls_conn);
prot_settls(imapd_out, tls_conn);
imapd_starttls_done = 1;
imapd_tls_required = 0;
#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
imapd_tls_comp = (void *) SSL_get_current_compression(tls_conn);
#endif
}
#else
void cmd_starttls(char *tag __attribute__((unused)),
int imaps __attribute__((unused)))
{
fatal("cmd_starttls() executed, but starttls isn't implemented!",
EC_SOFTWARE);
}
#endif // (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
static int parse_statusitems(unsigned *statusitemsp, const char **errstr)
{
static struct buf arg;
unsigned statusitems = 0;
int c;
int hasconv = config_getswitch(IMAPOPT_CONVERSATIONS);
c = prot_getc(imapd_in);
if (c != '(') return EOF;
c = getword(imapd_in, &arg);
if (arg.s[0] == '\0') return EOF;
for (;;) {
lcase(arg.s);
if (!strcmp(arg.s, "messages")) {
statusitems |= STATUS_MESSAGES;
}
else if (!strcmp(arg.s, "recent")) {
statusitems |= STATUS_RECENT;
}
else if (!strcmp(arg.s, "uidnext")) {
statusitems |= STATUS_UIDNEXT;
}
else if (!strcmp(arg.s, "uidvalidity")) {
statusitems |= STATUS_UIDVALIDITY;
}
else if (!strcmp(arg.s, "unseen")) {
statusitems |= STATUS_UNSEEN;
}
else if (!strcmp(arg.s, "highestmodseq")) {
statusitems |= STATUS_HIGHESTMODSEQ;
}
else if (hasconv && !strcmp(arg.s, "xconvexists")) {
statusitems |= STATUS_XCONVEXISTS;
}
else if (hasconv && !strcmp(arg.s, "xconvunseen")) {
statusitems |= STATUS_XCONVUNSEEN;
}
else if (hasconv && !strcmp(arg.s, "xconvmodseq")) {
statusitems |= STATUS_XCONVMODSEQ;
}
else {
static char buf[200];
snprintf(buf, 200, "Invalid Status attributes %s", arg.s);
*errstr = buf;
return EOF;
}
if (c == ' ') c = getword(imapd_in, &arg);
else break;
}
if (c != ')') {
*errstr = "Missing close parenthesis in Status";
return EOF;
}
c = prot_getc(imapd_in);
/* success */
*statusitemsp = statusitems;
return c;
}
static int print_statusline(const char *extname, unsigned statusitems,
struct statusdata *sd)
{
int sepchar;
prot_printf(imapd_out, "* STATUS ");
prot_printastring(imapd_out, extname);
prot_printf(imapd_out, " ");
sepchar = '(';
if (statusitems & STATUS_MESSAGES) {
prot_printf(imapd_out, "%cMESSAGES %u", sepchar, sd->messages);
sepchar = ' ';
}
if (statusitems & STATUS_RECENT) {
prot_printf(imapd_out, "%cRECENT %u", sepchar, sd->recent);
sepchar = ' ';
}
if (statusitems & STATUS_UIDNEXT) {
prot_printf(imapd_out, "%cUIDNEXT %u", sepchar, sd->uidnext);
sepchar = ' ';
}
if (statusitems & STATUS_UIDVALIDITY) {
prot_printf(imapd_out, "%cUIDVALIDITY %u", sepchar, sd->uidvalidity);
sepchar = ' ';
}
if (statusitems & STATUS_UNSEEN) {
prot_printf(imapd_out, "%cUNSEEN %u", sepchar, sd->unseen);
sepchar = ' ';
}
if (statusitems & STATUS_HIGHESTMODSEQ) {
prot_printf(imapd_out, "%cHIGHESTMODSEQ " MODSEQ_FMT,
sepchar, sd->highestmodseq);
sepchar = ' ';
}
if (statusitems & STATUS_XCONVEXISTS) {
prot_printf(imapd_out, "%cXCONVEXISTS %u", sepchar, sd->xconv.exists);
sepchar = ' ';
}
if (statusitems & STATUS_XCONVUNSEEN) {
prot_printf(imapd_out, "%cXCONVUNSEEN %u", sepchar, sd->xconv.unseen);
sepchar = ' ';
}
if (statusitems & STATUS_XCONVMODSEQ) {
prot_printf(imapd_out, "%cXCONVMODSEQ " MODSEQ_FMT, sepchar, sd->xconv.modseq);
sepchar = ' ';
}
prot_printf(imapd_out, ")\r\n");
return 0;
}
static int imapd_statusdata(const char *mailboxname, unsigned statusitems,
struct statusdata *sd)
{
int r;
struct conversations_state *state = NULL;
if (!(statusitems & STATUS_CONVITEMS)) goto nonconv;
statusitems &= ~STATUS_CONVITEMS; /* strip them for the regular lookup */
/* use the existing state if possible */
state = conversations_get_mbox(mailboxname);
/* otherwise fetch a new one! */
if (!state) {
if (global_conversations) {
conversations_abort(&global_conversations);
global_conversations = NULL;
}
r = conversations_open_mbox(mailboxname, &state);
if (r) {
/* maybe the mailbox doesn't even have conversations - just ignore */
goto nonconv;
}
global_conversations = state;
}
r = conversation_getstatus(state, mailboxname, &sd->xconv);
if (r) return r;
nonconv:
/* use the index status if we can so we get the 'alive' Recent count */
if (!strcmpsafe(mailboxname, index_mboxname(imapd_index)) && imapd_index->mailbox)
return index_status(imapd_index, sd);
/* fall back to generic lookup */
return status_lookup(mailboxname, imapd_userid, statusitems, sd);
}
/*
* Parse and perform a STATUS command
* The command has been parsed up to the attribute list
*/
static void cmd_status(char *tag, char *name)
{
int c;
unsigned statusitems = 0;
const char *errstr = "Bad status string";
mbentry_t *mbentry = NULL;
struct statusdata sdata = STATUSDATA_INIT;
int r = 0;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(tag, name, intname, &mbentry);
if (r == IMAP_MAILBOX_MOVED) {
/* Eat the argument */
eatline(imapd_in, prot_getc(imapd_in));
free(intname);
return;
}
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
if (supports_referrals
&& config_getswitch(IMAPOPT_PROXYD_ALLOW_STATUS_REFERRAL)) {
imapd_refer(tag, mbentry->server, name);
/* Eat the argument */
eatline(imapd_in, prot_getc(imapd_in));
}
else {
struct backend *s;
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!s) r = IMAP_SERVER_UNAVAILABLE;
imapd_check(s, 0);
if (!r) {
prot_printf(s->out, "%s Status {" SIZE_T_FMT "+}\r\n%s ", tag,
strlen(name), name);
if (!pipe_command(s, 65536)) {
pipe_including_tag(s, tag, 0);
}
} else {
eatline(imapd_in, prot_getc(imapd_in));
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
}
}
goto done;
}
/* local mailbox */
imapd_check(NULL, 0);
c = parse_statusitems(&statusitems, &errstr);
if (c == EOF) {
prot_printf(imapd_out, "%s BAD %s\r\n", tag, errstr);
goto done;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Status\r\n", tag);
eatline(imapd_in, c);
goto done;
}
/* check permissions */
if (!r) {
int myrights = cyrus_acl_myrights(imapd_authstate, mbentry->acl);
if (!(myrights & ACL_READ)) {
r = (imapd_userisadmin || (myrights & ACL_LOOKUP)) ?
IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT;
}
}
if (!r) r = imapd_statusdata(intname, statusitems, &sdata);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(r));
}
else {
print_statusline(name, statusitems, &sdata);
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
done:
if (global_conversations) {
conversations_abort(&global_conversations);
global_conversations = NULL;
}
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
/* Callback for cmd_namespace to be passed to mboxlist_findall.
* For each top-level mailbox found, print a bit of the response
* if it is a shared namespace. The rock is used as an integer in
* order to ensure the namespace response is correct on a server with
* no shared namespace.
*/
static int namespacedata(struct findall_data *data, void *rock)
{
if (!data) return 0;
int* sawone = (int*) rock;
switch (data->mb_category) {
case MBNAME_INBOX:
case MBNAME_ALTINBOX:
case MBNAME_ALTPREFIX:
sawone[NAMESPACE_INBOX] = 1;
break;
case MBNAME_OTHERUSER:
sawone[NAMESPACE_USER] = 1;
break;
case MBNAME_SHARED:
sawone[NAMESPACE_SHARED] = 1;
break;
}
return 0;
}
/*
* Print out a response to the NAMESPACE command defined by
* RFC 2342.
*/
static void cmd_namespace(char* tag)
{
int sawone[3] = {0, 0, 0};
char* pattern;
if (SLEEZY_NAMESPACE) {
if (strlen(imapd_userid) + 5 >= MAX_MAILBOX_BUFFER)
sawone[NAMESPACE_INBOX] = 0;
else {
char *inbox = mboxname_user_mbox(imapd_userid, NULL);
sawone[NAMESPACE_INBOX] =
!mboxlist_lookup(inbox, NULL, NULL);
free(inbox);
}
sawone[NAMESPACE_USER] = imapd_userisadmin ? 1 : imapd_namespace.accessible[NAMESPACE_USER];
sawone[NAMESPACE_SHARED] = imapd_userisadmin ? 1 : imapd_namespace.accessible[NAMESPACE_SHARED];
} else {
pattern = xstrdup("%");
/* now find all the exciting toplevel namespaces -
* we're using internal names here
*/
mboxlist_findall(NULL, pattern, imapd_userisadmin, imapd_userid,
imapd_authstate, namespacedata, (void*) sawone);
free(pattern);
}
prot_printf(imapd_out, "* NAMESPACE");
if (sawone[NAMESPACE_INBOX]) {
prot_printf(imapd_out, " ((\"%s\" \"%c\"))",
imapd_namespace.prefix[NAMESPACE_INBOX],
imapd_namespace.hier_sep);
} else {
prot_printf(imapd_out, " NIL");
}
if (sawone[NAMESPACE_USER]) {
prot_printf(imapd_out, " ((\"%s\" \"%c\"))",
imapd_namespace.prefix[NAMESPACE_USER],
imapd_namespace.hier_sep);
} else {
prot_printf(imapd_out, " NIL");
}
if (sawone[NAMESPACE_SHARED]) {
prot_printf(imapd_out, " ((\"%s\" \"%c\"))",
imapd_namespace.prefix[NAMESPACE_SHARED],
imapd_namespace.hier_sep);
} else {
prot_printf(imapd_out, " NIL");
}
prot_printf(imapd_out, "\r\n");
imapd_check(NULL, 0);
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
static int parsecreateargs(struct dlist **extargs)
{
int c;
static struct buf arg, val;
struct dlist *res;
struct dlist *sub;
char *p;
const char *name;
res = dlist_newkvlist(NULL, "CREATE");
c = prot_getc(imapd_in);
if (c == '(') {
/* new style RFC4466 arguments */
do {
c = getword(imapd_in, &arg);
name = ucase(arg.s);
if (c != ' ') goto fail;
c = prot_getc(imapd_in);
if (c == '(') {
/* fun - more lists! */
sub = dlist_newlist(res, name);
do {
c = getword(imapd_in, &val);
dlist_setatom(sub, name, val.s);
} while (c == ' ');
if (c != ')') goto fail;
c = prot_getc(imapd_in);
}
else {
prot_ungetc(c, imapd_in);
c = getword(imapd_in, &val);
dlist_setatom(res, name, val.s);
}
} while (c == ' ');
if (c != ')') goto fail;
c = prot_getc(imapd_in);
}
else {
prot_ungetc(c, imapd_in);
c = getword(imapd_in, &arg);
if (c == EOF) goto fail;
p = strchr(arg.s, '!');
if (p) {
/* with a server */
*p = '\0';
dlist_setatom(res, "SERVER", arg.s);
dlist_setatom(res, "PARTITION", p+1);
}
else {
dlist_setatom(res, "PARTITION", arg.s);
}
}
*extargs = res;
return c;
fail:
dlist_free(&res);
return EOF;
}
/*
* Parse annotate fetch data.
*
* This is a generic routine which parses just the annotation data.
* Any surrounding command text must be parsed elsewhere, ie,
* GETANNOTATION, FETCH.
*/
static int parse_annotate_fetch_data(const char *tag,
int permessage_flag,
strarray_t *entries,
strarray_t *attribs)
{
int c;
static struct buf arg;
c = prot_getc(imapd_in);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation entry\r\n", tag);
goto baddata;
}
else if (c == '(') {
/* entry list */
do {
if (permessage_flag)
c = getastring(imapd_in, imapd_out, &arg);
else
c = getqstring(imapd_in, imapd_out, &arg);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation entry\r\n", tag);
goto baddata;
}
/* add the entry to the list */
strarray_append(entries, arg.s);
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close paren in annotation entry list \r\n",
tag);
goto baddata;
}
c = prot_getc(imapd_in);
}
else {
/* single entry -- add it to the list */
prot_ungetc(c, imapd_in);
if (permessage_flag)
c = getastring(imapd_in, imapd_out, &arg);
else
c = getqstring(imapd_in, imapd_out, &arg);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation entry\r\n", tag);
goto baddata;
}
strarray_append(entries, arg.s);
}
if (c != ' ' || (c = prot_getc(imapd_in)) == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation attribute(s)\r\n", tag);
goto baddata;
}
if (c == '(') {
/* attrib list */
do {
if (permessage_flag)
c = getastring(imapd_in, imapd_out, &arg);
else
c = getqstring(imapd_in, imapd_out, &arg);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation attribute(s)\r\n", tag);
goto baddata;
}
/* add the attrib to the list */
strarray_append(attribs, arg.s);
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close paren in "
"annotation attribute list\r\n", tag);
goto baddata;
}
c = prot_getc(imapd_in);
}
else {
/* single attrib */
prot_ungetc(c, imapd_in);
if (permessage_flag)
c = getastring(imapd_in, imapd_out, &arg);
else
c = getqstring(imapd_in, imapd_out, &arg);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation attribute\r\n", tag);
goto baddata;
}
strarray_append(attribs, arg.s);
}
return c;
baddata:
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
}
/*
* Parse either a single string or a (bracketed) list of strings.
* This is used up to three times in the GETMETADATA command.
*/
static int parse_metadata_string_or_list(const char *tag,
strarray_t *entries,
int *is_list)
{
int c;
static struct buf arg;
// Assume by default the arguments are a list of entries,
// until proven otherwise.
if (is_list) *is_list = 1;
c = prot_getc(imapd_in);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing metadata entry\r\n", tag);
goto baddata;
}
else if (c == '\r') {
return c;
}
else if (c == '(') {
/* entry list */
do {
c = getastring(imapd_in, imapd_out, &arg);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing metadata entry\r\n", tag);
goto baddata;
}
/* add the entry to the list */
strarray_append(entries, arg.s);
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close paren in metadata entry list \r\n",
tag);
goto baddata;
}
if (is_list) *is_list = 0;
c = prot_getc(imapd_in);
}
else {
/* single entry -- add it to the list */
prot_ungetc(c, imapd_in);
c = getastring(imapd_in, imapd_out, &arg);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing metadata entry\r\n", tag);
goto baddata;
}
strarray_append(entries, arg.s);
// It is only not a list if there are no wildcards
if (!strchr(arg.s, '*') && !strchr(arg.s, '%')) {
// Not a list
if (is_list) *is_list = 0;
}
}
if (c == ' ' || c == '\r' || c == ')') return c;
baddata:
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
}
/*
* Parse annotate store data.
*
* This is a generic routine which parses just the annotation data.
* Any surrounding command text must be parsed elsewhere, ie,
* SETANNOTATION, STORE, APPEND.
*
* Also parse RFC5257 per-message annotation store data, which
* is almost identical but differs in that entry names and attrib
* names are astrings rather than strings, and that the whole set
* of data *must* be enclosed in parentheses.
*/
static int parse_annotate_store_data(const char *tag,
int permessage_flag,
struct entryattlist **entryatts)
{
int c, islist = 0;
static struct buf entry, attrib, value;
struct attvaluelist *attvalues = NULL;
*entryatts = NULL;
c = prot_getc(imapd_in);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation entry\r\n", tag);
goto baddata;
}
else if (c == '(') {
/* entry list */
islist = 1;
}
else if (permessage_flag) {
prot_printf(imapd_out,
"%s BAD Missing paren for annotation entry\r\n", tag);
goto baddata;
}
else {
/* single entry -- put the char back */
prot_ungetc(c, imapd_in);
}
do {
/* get entry */
if (permessage_flag)
c = getastring(imapd_in, imapd_out, &entry);
else
c = getqstring(imapd_in, imapd_out, &entry);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation entry\r\n", tag);
goto baddata;
}
/* parse att-value list */
if (c != ' ' || (c = prot_getc(imapd_in)) != '(') {
prot_printf(imapd_out,
"%s BAD Missing annotation attribute-values list\r\n",
tag);
goto baddata;
}
do {
/* get attrib */
if (permessage_flag)
c = getastring(imapd_in, imapd_out, &attrib);
else
c = getqstring(imapd_in, imapd_out, &attrib);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation attribute\r\n", tag);
goto baddata;
}
/* get value */
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing annotation value\r\n", tag);
goto baddata;
}
c = getbnstring(imapd_in, imapd_out, &value);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation value\r\n", tag);
goto baddata;
}
/* add the attrib-value pair to the list */
appendattvalue(&attvalues, attrib.s, &value);
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close paren in annotation "
"attribute-values list\r\n", tag);
goto baddata;
}
/* add the entry to the list */
appendentryatt(entryatts, entry.s, attvalues);
attvalues = NULL;
c = prot_getc(imapd_in);
} while (c == ' ');
if (islist) {
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close paren in annotation entry list \r\n",
tag);
goto baddata;
}
c = prot_getc(imapd_in);
}
return c;
baddata:
if (attvalues) freeattvalues(attvalues);
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
}
/*
* Parse metadata store data.
*
* This is a generic routine which parses just the annotation data.
* Any surrounding command text must be parsed elsewhere, ie,
* SETANNOTATION, STORE, APPEND.
*/
static int parse_metadata_store_data(const char *tag,
struct entryattlist **entryatts)
{
int c;
const char *name;
const char *att;
static struct buf entry, value;
struct attvaluelist *attvalues = NULL;
struct entryattlist *entryp;
int need_add;
*entryatts = NULL;
c = prot_getc(imapd_in);
if (c != '(') {
prot_printf(imapd_out,
"%s BAD Missing metadata entry list\r\n", tag);
goto baddata;
}
do {
/* get entry */
c = getastring(imapd_in, imapd_out, &entry);
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing metadata entry\r\n", tag);
goto baddata;
}
lcase(entry.s);
/* get value */
c = getbnstring(imapd_in, imapd_out, &value);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing metadata value\r\n", tag);
goto baddata;
}
if (!strncmp(entry.s, "/private", 8) &&
(entry.s[8] == '\0' || entry.s[8] == '/')) {
att = "value.priv";
name = entry.s + 8;
}
else if (!strncmp(entry.s, "/shared", 7) &&
(entry.s[7] == '\0' || entry.s[7] == '/')) {
att = "value.shared";
name = entry.s + 7;
}
else {
prot_printf(imapd_out,
"%s BAD entry must begin with /shared or /private\r\n",
tag);
goto baddata;
}
need_add = 1;
for (entryp = *entryatts; entryp; entryp = entryp->next) {
if (strcmp(entryp->entry, name)) continue;
/* it's a match, have to append! */
appendattvalue(&entryp->attvalues, att, &value);
need_add = 0;
break;
}
if (need_add) {
appendattvalue(&attvalues, att, &value);
appendentryatt(entryatts, name, attvalues);
attvalues = NULL;
}
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close paren in annotation entry list \r\n",
tag);
goto baddata;
}
c = prot_getc(imapd_in);
return c;
baddata:
if (attvalues) freeattvalues(attvalues);
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
}
static void getannotation_response(const char *mboxname,
uint32_t uid
__attribute__((unused)),
const char *entry,
struct attvaluelist *attvalues,
void *rock __attribute__((unused)))
{
int sep = '(';
struct attvaluelist *l;
char *extname = *mboxname ?
mboxname_to_external(mboxname, &imapd_namespace, imapd_userid) :
xstrdup(""); /* server annotation */
prot_printf(imapd_out, "* ANNOTATION ");
prot_printastring(imapd_out, extname);
prot_putc(' ', imapd_out);
prot_printstring(imapd_out, entry);
prot_putc(' ', imapd_out);
for (l = attvalues ; l ; l = l->next) {
prot_putc(sep, imapd_out);
sep = ' ';
prot_printstring(imapd_out, l->attrib);
prot_putc(' ', imapd_out);
prot_printmap(imapd_out, l->value.s, l->value.len);
}
prot_printf(imapd_out, ")\r\n");
free(extname);
}
struct annot_fetch_rock
{
strarray_t *entries;
strarray_t *attribs;
annotate_fetch_cb_t callback;
void *cbrock;
};
static int annot_fetch_cb(annotate_state_t *astate, void *rock)
{
struct annot_fetch_rock *arock = rock;
return annotate_state_fetch(astate, arock->entries, arock->attribs,
arock->callback, arock->cbrock);
}
struct annot_store_rock
{
struct entryattlist *entryatts;
};
static int annot_store_cb(annotate_state_t *astate, void *rock)
{
struct annot_store_rock *arock = rock;
return annotate_state_store(astate, arock->entryatts);
}
/*
* Common code used to apply a function to every mailbox which matches
* a mailbox pattern, with an annotate_state_t* set up to point to the
* mailbox.
*/
struct apply_rock {
annotate_state_t *state;
int (*proc)(annotate_state_t *, void *data);
void *data;
char lastname[MAX_MAILBOX_PATH+1];
unsigned int nseen;
};
static int apply_cb(struct findall_data *data, void* rock)
{
if (!data) return 0;
struct apply_rock *arock = (struct apply_rock *)rock;
annotate_state_t *state = arock->state;
int r;
/* Suppress any output of a partial match */
if (!data->mbname)
return 0;
strlcpy(arock->lastname, mbname_intname(data->mbname), sizeof(arock->lastname));
// malloc extra-long to have room for pattern shenanigans later
/* NOTE: this is a fricking horrible abuse of layers. We'll be passing the
* extname less horribly one day */
const char *extname = mbname_extname(data->mbname, &imapd_namespace, imapd_userid);
mbentry_t *backdoor = (mbentry_t *)data->mbentry;
backdoor->ext_name = xmalloc(strlen(extname)+1);
strcpy(backdoor->ext_name, extname);
r = annotate_state_set_mailbox_mbe(state, data->mbentry);
if (r) return r;
r = arock->proc(state, arock->data);
arock->nseen++;
return r;
}
static int apply_mailbox_pattern(annotate_state_t *state,
const char *pattern,
int (*proc)(annotate_state_t *, void *),
void *data)
{
struct apply_rock arock;
int r = 0;
memset(&arock, 0, sizeof(arock));
arock.state = state;
arock.proc = proc;
arock.data = data;
r = mboxlist_findall(&imapd_namespace,
pattern,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid,
imapd_authstate,
apply_cb, &arock);
if (!r && !arock.nseen)
r = IMAP_MAILBOX_NONEXISTENT;
return r;
}
static int apply_mailbox_array(annotate_state_t *state,
const strarray_t *mboxes,
int (*proc)(annotate_state_t *, void *),
void *rock)
{
int i;
mbentry_t *mbentry = NULL;
char *intname = NULL;
int r = 0;
for (i = 0 ; i < mboxes->count ; i++) {
intname = mboxname_from_external(strarray_nth(mboxes, i), &imapd_namespace, imapd_userid);
r = mboxlist_lookup(intname, &mbentry, NULL);
if (r)
break;
r = annotate_state_set_mailbox_mbe(state, mbentry);
if (r)
break;
r = proc(state, rock);
if (r)
break;
mboxlist_entry_free(&mbentry);
free(intname);
intname = NULL;
}
mboxlist_entry_free(&mbentry);
free(intname);
return r;
}
/*
* Perform a GETANNOTATION command
*
* The command has been parsed up to the entries
*/
static void cmd_getannotation(const char *tag, char *mboxpat)
{
int c, r = 0;
strarray_t entries = STRARRAY_INITIALIZER;
strarray_t attribs = STRARRAY_INITIALIZER;
annotate_state_t *astate = NULL;
c = parse_annotate_fetch_data(tag, /*permessage_flag*/0, &entries, &attribs);
if (c == EOF) {
eatline(imapd_in, c);
goto freeargs;
}
/* check for CRLF */
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Getannotation\r\n",
tag);
eatline(imapd_in, c);
goto freeargs;
}
astate = annotate_state_new();
annotate_state_set_auth(astate,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate);
if (!*mboxpat) {
r = annotate_state_set_server(astate);
if (!r)
r = annotate_state_fetch(astate, &entries, &attribs,
getannotation_response, NULL);
}
else {
struct annot_fetch_rock arock;
arock.entries = &entries;
arock.attribs = &attribs;
arock.callback = getannotation_response;
arock.cbrock = NULL;
r = apply_mailbox_pattern(astate, mboxpat, annot_fetch_cb, &arock);
}
/* we didn't write anything */
annotate_state_abort(&astate);
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n",
tag, error_message(IMAP_OK_COMPLETED));
}
freeargs:
strarray_fini(&entries);
strarray_fini(&attribs);
}
static void getmetadata_response(const char *mboxname,
uint32_t uid __attribute__((unused)),
const char *entry,
struct attvaluelist *attvalues,
void *rock)
{
struct getmetadata_options *opts = (struct getmetadata_options *)rock;
if (strcmpsafe(mboxname, opts->lastname) || !entry) {
if (opts->items.count) {
char *extname = NULL;
size_t i;
if (opts->lastname)
extname = mboxname_to_external(opts->lastname, &imapd_namespace, imapd_userid);
else
extname = xstrdup("");
prot_printf(imapd_out, "* METADATA ");
prot_printastring(imapd_out, extname);
prot_putc(' ', imapd_out);
for (i = 0; i + 1 < opts->items.count; i+=2) {
prot_putc(i ? ' ' : '(', imapd_out);
const struct buf *key = bufarray_nth(&opts->items, i);
prot_printmap(imapd_out, key->s, key->len);
prot_putc(' ', imapd_out);
const struct buf *val = bufarray_nth(&opts->items, i+1);
prot_printmap(imapd_out, val->s, val->len);
}
prot_printf(imapd_out, ")\r\n");
free(extname);
}
free(opts->lastname);
opts->lastname = xstrdupnull(mboxname);
bufarray_fini(&opts->items);
}
struct attvaluelist *l;
struct buf buf = BUF_INITIALIZER;
for (l = attvalues ; l ; l = l->next) {
/* size check */
if (opts->maxsize && l->value.len >= opts->maxsize) {
if (l->value.len > opts->biggest) opts->biggest = l->value.len;
continue;
}
/* check if it's a value we print... */
buf_reset(&buf);
if (!strcmp(l->attrib, "value.shared"))
buf_appendcstr(&buf, "/shared");
else if (!strcmp(l->attrib, "value.priv"))
buf_appendcstr(&buf, "/private");
else
continue;
buf_appendcstr(&buf, entry);
bufarray_append(&opts->items, &buf);
bufarray_append(&opts->items, &l->value);
}
buf_free(&buf);
}
static int parse_getmetadata_options(const strarray_t *sa,
struct getmetadata_options *opts)
{
int i;
int n = 0;
struct getmetadata_options dummy = OPTS_INITIALIZER;
if (!opts) opts = &dummy;
for (i = 0 ; i < sa->count ; i+=2) {
const char *option = sa->data[i];
const char *value = sa->data[i+1];
if (!value)
return -1;
if (!strcasecmp(option, "MAXSIZE")) {
char *end = NULL;
/* we add one so that it's "less than" maxsize
* and zero works but is still true */
opts->maxsize = strtoul(value, &end, 10) + 1;
if (!end || *end || end == value)
return -1;
n++;
}
else if (!strcasecmp(option, "DEPTH")) {
if (!strcmp(value, "0"))
opts->depth = 0;
else if (!strcmp(value, "1"))
opts->depth = 1;
else if (!strcasecmp(value, "infinity"))
opts->depth = -1;
else
return -1;
n++;
}
else {
return 0;
}
}
return n;
}
static int _metadata_to_annotate(const strarray_t *entries,
strarray_t *newa, strarray_t *newe,
const char *tag, int depth)
{
int i;
int have_shared = 0;
int have_private = 0;
/* we need to rewrite the entries and attribs to match the way that
* the old annotation system works. */
for (i = 0 ; i < entries->count ; i++) {
char *ent = entries->data[i];
char entry[MAX_MAILBOX_NAME+1];
lcase(ent);
/* there's no way to perfect this - unfortunately - the old style
* syntax doesn't support everything. XXX - will be nice to get
* rid of this... */
if (!strncmp(ent, "/private", 8) &&
(ent[8] == '\0' || ent[8] == '/')) {
xstrncpy(entry, ent + 8, MAX_MAILBOX_NAME);
have_private = 1;
}
else if (!strncmp(ent, "/shared", 7) &&
(ent[7] == '\0' || ent[7] == '/')) {
xstrncpy(entry, ent + 7, MAX_MAILBOX_NAME);
have_shared = 1;
}
else {
if (tag)
prot_printf(imapd_out,
"%s BAD entry must begin with /shared or /private\r\n",
tag);
return IMAP_NO_NOSUCHMSG;
}
strarray_append(newe, entry);
if (depth == 1) {
strncat(entry, "/%", MAX_MAILBOX_NAME);
strarray_append(newe, entry);
}
else if (depth == -1) {
strncat(entry, "/*", MAX_MAILBOX_NAME);
strarray_append(newe, entry);
}
}
if (have_private) strarray_append(newa, "value.priv");
if (have_shared) strarray_append(newa, "value.shared");
return 0;
}
/*
* Perform a GETMETADATA command
*
* The command has been parsed up to the mailbox
*/
static void cmd_getmetadata(const char *tag)
{
int c, r = 0;
strarray_t lists[3] = { STRARRAY_INITIALIZER,
STRARRAY_INITIALIZER,
STRARRAY_INITIALIZER };
int is_list[3] = { 1, 1, 1 };
int nlists = 0;
strarray_t *options = NULL;
strarray_t *mboxes = NULL;
strarray_t *entries = NULL;
strarray_t newe = STRARRAY_INITIALIZER;
strarray_t newa = STRARRAY_INITIALIZER;
struct buf arg1 = BUF_INITIALIZER;
int mbox_is_pattern = 0;
struct getmetadata_options opts = OPTS_INITIALIZER;
annotate_state_t *astate = NULL;
while (nlists < 3)
{
c = parse_metadata_string_or_list(tag, &lists[nlists], &is_list[nlists]);
nlists++;
if (c == '\r' || c == EOF)
break;
}
/* check for CRLF */
if (c == '\r') {
c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Getannotation\r\n",
tag);
eatline(imapd_in, c);
goto freeargs;
}
} else {
// Make sure this line is gone
eatline(imapd_in, c);
}
/*
* We have three strings or lists of strings. Now to figure out
* what's what. We have two complicating factors. First, due to
* a erratum in RFC5464 and our earlier misreading of the document,
* we historically supported specifying the options *after* the
* mailbox name. Second, we have for a few months now supported
* a non-standard extension where a list of mailbox names could
* be supplied instead of just a single one. So we have to apply
* some rules. We support the following syntaxes:
*
* --- no options
* mailbox entry
* mailbox (entries)
* (mailboxes) entry
* (mailboxes) (entries)
*
* --- options in the correct place (per the ABNF in RFC5464)
* (options) mailbox entry
* (options) mailbox (entries)
* (options) (mailboxes) entry
* (options) (mailboxes) (entries)
*
* --- options in the wrong place (per the examples in RFC5464)
* mailbox (options) entry
* mailbox (options) (entries)
* (mailboxes) (options) entry
* (mailboxes) (options) (entries)
*/
if (nlists < 2)
goto missingargs;
entries = &lists[nlists-1]; /* entries always last */
if (nlists == 2) {
/* no options */
mboxes = &lists[0];
mbox_is_pattern = is_list[0];
}
if (nlists == 3) {
/* options, either before or after */
int r0 = (parse_getmetadata_options(&lists[0], NULL) > 0);
int r1 = (parse_getmetadata_options(&lists[1], NULL) > 0);
switch ((r1<<1)|r0) {
case 0:
/* neither are valid options */
goto missingargs;
case 1:
/* (options) (mailboxes) */
options = &lists[0];
mboxes = &lists[1];
mbox_is_pattern = is_list[1];
break;
case 2:
/* (mailboxes) (options) */
mboxes = &lists[0];
mbox_is_pattern = is_list[0];
options = &lists[1];
break;
case 3:
/* both appear like valid options */
prot_printf(imapd_out,
"%s BAD Too many option lists for Getmetadata\r\n",
tag);
eatline(imapd_in, c);
goto freeargs;
}
}
if (options) parse_getmetadata_options(options, &opts);
if (_metadata_to_annotate(entries, &newa, &newe, tag, opts.depth))
goto freeargs;
astate = annotate_state_new();
annotate_state_set_auth(astate,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate);
if (!mboxes->count || !strcmpsafe(mboxes->data[0], NULL)) {
r = annotate_state_set_server(astate);
if (!r)
r = annotate_state_fetch(astate, &newe, &newa,
getmetadata_response, &opts);
}
else {
struct annot_fetch_rock arock;
arock.entries = &newe;
arock.attribs = &newa;
arock.callback = getmetadata_response;
arock.cbrock = &opts;
if (mbox_is_pattern)
r = apply_mailbox_pattern(astate, mboxes->data[0], annot_fetch_cb, &arock);
else
r = apply_mailbox_array(astate, mboxes, annot_fetch_cb, &arock);
}
/* we didn't write anything */
annotate_state_abort(&astate);
getmetadata_response(NULL, 0, NULL, NULL, &opts);
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else if (opts.maxsize && opts.biggest > opts.maxsize) {
prot_printf(imapd_out, "%s OK [METADATA LONGENTRIES %u] %s\r\n",
tag, (unsigned)opts.biggest, error_message(IMAP_OK_COMPLETED));
} else {
prot_printf(imapd_out, "%s OK %s\r\n",
tag, error_message(IMAP_OK_COMPLETED));
}
freeargs:
strarray_fini(&lists[0]);
strarray_fini(&lists[1]);
strarray_fini(&lists[2]);
strarray_fini(&newe);
strarray_fini(&newa);
buf_free(&arg1);
return;
missingargs:
prot_printf(imapd_out, "%s BAD Missing arguments to Getmetadata\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
/*
* Perform a SETANNOTATION command
*
* The command has been parsed up to the entry-att list
*/
static void cmd_setannotation(const char *tag, char *mboxpat)
{
int c, r = 0;
struct entryattlist *entryatts = NULL;
annotate_state_t *astate = NULL;
c = parse_annotate_store_data(tag, 0, &entryatts);
if (c == EOF) {
eatline(imapd_in, c);
goto freeargs;
}
/* check for CRLF */
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Setannotation\r\n",
tag);
eatline(imapd_in, c);
goto freeargs;
}
astate = annotate_state_new();
annotate_state_set_auth(astate, imapd_userisadmin,
imapd_userid, imapd_authstate);
if (!r) {
if (!*mboxpat) {
r = annotate_state_set_server(astate);
if (!r)
r = annotate_state_store(astate, entryatts);
}
else {
struct annot_store_rock arock;
arock.entryatts = entryatts;
r = apply_mailbox_pattern(astate, mboxpat, annot_store_cb, &arock);
}
}
if (!r)
annotate_state_commit(&astate);
else
annotate_state_abort(&astate);
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
freeargs:
if (entryatts) freeentryatts(entryatts);
}
/*
* Perform a SETMETADATA command
*
* The command has been parsed up to the entry-att list
*/
static void cmd_setmetadata(const char *tag, char *mboxpat)
{
int c, r = 0;
struct entryattlist *entryatts = NULL;
annotate_state_t *astate = NULL;
c = parse_metadata_store_data(tag, &entryatts);
if (c == EOF) {
eatline(imapd_in, c);
goto freeargs;
}
/* check for CRLF */
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Setmetadata\r\n",
tag);
eatline(imapd_in, c);
goto freeargs;
}
astate = annotate_state_new();
annotate_state_set_auth(astate, imapd_userisadmin,
imapd_userid, imapd_authstate);
if (!r) {
if (!*mboxpat) {
r = annotate_state_set_server(astate);
if (!r)
r = annotate_state_store(astate, entryatts);
}
else {
struct annot_store_rock arock;
arock.entryatts = entryatts;
r = apply_mailbox_pattern(astate, mboxpat, annot_store_cb, &arock);
}
}
if (!r)
r = annotate_state_commit(&astate);
else
annotate_state_abort(&astate);
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
freeargs:
if (entryatts) freeentryatts(entryatts);
return;
}
static void cmd_xrunannotator(const char *tag, const char *sequence,
int usinguid)
{
const char *cmd = usinguid ? "UID Xrunannotator" : "Xrunannotator";
clock_t start = clock();
char mytime[100];
int c, r = 0;
if (backend_current) {
/* remote mailbox */
prot_printf(backend_current->out, "%s %s %s ", tag, cmd, sequence);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
/* local mailbox */
/* we're expecting no more arguments */
c = prot_getc(imapd_in);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out, "%s BAD Unexpected extra arguments to %s\r\n", tag, cmd);
eatline(imapd_in, c);
return;
}
r = index_run_annotator(imapd_index, sequence, usinguid,
&imapd_namespace, imapd_userisadmin);
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
if (r)
prot_printf(imapd_out, "%s NO %s (%s sec)\r\n", tag,
error_message(r), mytime);
else
prot_printf(imapd_out, "%s OK %s (%s sec)\r\n", tag,
error_message(IMAP_OK_COMPLETED), mytime);
}
static void cmd_xwarmup(const char *tag)
{
const char *cmd = "Xwarmup";
clock_t start = clock();
char mytime[100];
struct buf arg = BUF_INITIALIZER;
int warmup_flags = 0;
struct seqset *uids = NULL;
/* We deal with the mboxlist API instead of the index_state API or
* mailbox API to avoid the overhead of index_open(), which will
* block while reading all the cyrus.index...we want to be
* non-blocking */
struct mboxlist_entry *mbentry = NULL;
int myrights;
int c, r = 0;
char *intname = NULL;
/* parse arguments: expect <mboxname> '('<warmup-items>')' */
c = getastring(imapd_in, imapd_out, &arg);
if (c != ' ') {
syntax_error:
prot_printf(imapd_out, "%s BAD syntax error in %s\r\n", tag, cmd);
eatline(imapd_in, c);
goto out_noprint;
}
intname = mboxname_from_external(arg.s, &imapd_namespace, imapd_userid);
r = mboxlist_lookup(intname, &mbentry, NULL);
if (r) goto out;
/* Do a permissions check to avoid server DoS opportunity. But we
* only need read permission to warmup a mailbox. Also, be careful
* to avoid telling the client about the existance of mailboxes to
* which he doesn't have LOOKUP rights. */
r = IMAP_PERMISSION_DENIED;
myrights = (mbentry->acl ? cyrus_acl_myrights(imapd_authstate, mbentry->acl) : 0);
if (imapd_userisadmin)
r = 0;
else if (!(myrights & ACL_LOOKUP))
r = IMAP_MAILBOX_NONEXISTENT;
else if (myrights & ACL_READ)
r = 0;
if (r) goto out;
if (mbentry->mbtype & MBTYPE_REMOTE) {
/* remote mailbox */
struct backend *be;
be = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!be) {
r = IMAP_SERVER_UNAVAILABLE;
goto out;
}
prot_printf(be->out, "%s %s %s ", tag, cmd, arg.s);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
goto out;
}
/* local mailbox */
/* parse the arguments after the mailbox */
c = prot_getc(imapd_in);
if (c != '(') goto syntax_error;
for (;;) {
c = getword(imapd_in, &arg);
if (arg.len) {
if (!strcasecmp(arg.s, "index"))
warmup_flags |= WARMUP_INDEX;
else if (!strcasecmp(arg.s, "conversations"))
warmup_flags |= WARMUP_CONVERSATIONS;
else if (!strcasecmp(arg.s, "annotations"))
warmup_flags |= WARMUP_ANNOTATIONS;
else if (!strcasecmp(arg.s, "folderstatus"))
warmup_flags |= WARMUP_FOLDERSTATUS;
else if (!strcasecmp(arg.s, "search"))
warmup_flags |= WARMUP_SEARCH;
else if (!strcasecmp(arg.s, "uids")) {
if (c != ' ') goto syntax_error;
c = getword(imapd_in, &arg);
if (c == EOF) goto syntax_error;
if (!imparse_issequence(arg.s)) goto syntax_error;
uids = seqset_parse(arg.s, NULL, /*maxval*/0);
if (!uids) goto syntax_error;
}
else if (!strcasecmp(arg.s, "all"))
warmup_flags |= WARMUP_ALL;
else
goto syntax_error;
}
if (c == ')')
break;
if (c != ' ') goto syntax_error;
}
/* we're expecting no more arguments */
c = prot_getc(imapd_in);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto syntax_error;
r = index_warmup(mbentry, warmup_flags, uids);
out:
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
if (r)
prot_printf(imapd_out, "%s NO %s (%s sec)\r\n", tag,
error_message(r), mytime);
else
prot_printf(imapd_out, "%s OK %s (%s sec)\r\n", tag,
error_message(IMAP_OK_COMPLETED), mytime);
out_noprint:
mboxlist_entry_free(&mbentry);
free(intname);
buf_free(&arg);
if (uids) seqset_free(uids);
}
static void free_snippetargs(struct snippetargs **sap)
{
while (*sap) {
struct snippetargs *sa = *sap;
*sap = sa->next;
free(sa->mboxname);
free(sa->uids.data);
free(sa);
}
}
static int get_snippetargs(struct snippetargs **sap)
{
int c;
struct snippetargs **prevp = sap;
struct snippetargs *sa = NULL;
struct buf arg = BUF_INITIALIZER;
uint32_t uid;
char *intname = NULL;
c = prot_getc(imapd_in);
if (c != '(') goto syntax_error;
for (;;) {
c = prot_getc(imapd_in);
if (c == ')') break;
if (c != '(') goto syntax_error;
c = getastring(imapd_in, imapd_out, &arg);
if (c != ' ') goto syntax_error;
intname = mboxname_from_external(buf_cstring(&arg), &imapd_namespace, imapd_userid);
/* allocate a new snippetargs */
sa = xzmalloc(sizeof(struct snippetargs));
sa->mboxname = xstrdup(intname);
/* append to the list */
*prevp = sa;
prevp = &sa->next;
c = getuint32(imapd_in, &sa->uidvalidity);
if (c != ' ') goto syntax_error;
c = prot_getc(imapd_in);
if (c != '(') break;
for (;;) {
c = getuint32(imapd_in, &uid);
if (c != ' ' && c != ')') goto syntax_error;
if (sa->uids.count + 1 > sa->uids.alloc) {
sa->uids.alloc += 64;
sa->uids.data = xrealloc(sa->uids.data,
sizeof(uint32_t) * sa->uids.alloc);
}
sa->uids.data[sa->uids.count++] = uid;
if (c == ')') break;
}
c = prot_getc(imapd_in);
if (c != ')') goto syntax_error;
}
c = prot_getc(imapd_in);
if (c != ' ') goto syntax_error;
out:
free(intname);
buf_free(&arg);
return c;
syntax_error:
free_snippetargs(sap);
c = EOF;
goto out;
}
static void cmd_dump(char *tag, char *name, int uid_start)
{
int r = 0;
struct mailbox *mailbox = NULL;
/* administrators only please */
if (!imapd_userisadmin)
r = IMAP_PERMISSION_DENIED;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
if (!r) r = mailbox_open_irl(intname, &mailbox);
if (!r) r = dump_mailbox(tag, mailbox, uid_start, MAILBOX_MINOR_VERSION,
imapd_in, imapd_out, imapd_authstate);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
if (mailbox) mailbox_close(&mailbox);
free(intname);
}
static void cmd_undump(char *tag, char *name)
{
int r = 0;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
/* administrators only please */
if (!imapd_userisadmin)
r = IMAP_PERMISSION_DENIED;
if (!r) r = mlookup(tag, name, intname, NULL);
if (!r) r = undump_mailbox(intname, imapd_in, imapd_out, imapd_authstate);
if (r) {
prot_printf(imapd_out, "%s NO %s%s\r\n",
tag,
(r == IMAP_MAILBOX_NONEXISTENT &&
mboxlist_createmailboxcheck(intname, 0, 0,
imapd_userisadmin,
imapd_userid, imapd_authstate,
NULL, NULL, 0) == 0)
? "[TRYCREATE] " : "", error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
free(intname);
}
static int getresult(struct protstream *p, const char *tag)
{
char buf[4096];
char *str = (char *) buf;
while(1) {
if (!prot_fgets(str, sizeof(buf), p)) {
return IMAP_SERVER_UNAVAILABLE;
}
if (!strncmp(str, tag, strlen(tag))) {
str += strlen(tag);
if(!*str) {
/* We got a tag, but no response */
return IMAP_SERVER_UNAVAILABLE;
}
str++;
if (!strncasecmp(str, "OK ", 3)) { return 0; }
if (!strncasecmp(str, "NO ", 3)) { return IMAP_REMOTE_DENIED; }
return IMAP_SERVER_UNAVAILABLE; /* huh? */
}
/* skip this line, we don't really care */
}
}
/* given 2 protstreams and a mailbox, gets the acl and then wipes it */
static int trashacl(struct protstream *pin, struct protstream *pout,
char *mailbox)
{
int i=0, j=0;
char tagbuf[128];
int c; /* getword() returns an int */
struct buf cmd, tmp, user;
int r = 0;
memset(&cmd, 0, sizeof(struct buf));
memset(&tmp, 0, sizeof(struct buf));
memset(&user, 0, sizeof(struct buf));
prot_printf(pout, "ACL0 GETACL {" SIZE_T_FMT "+}\r\n%s\r\n",
strlen(mailbox), mailbox);
while(1) {
c = prot_getc(pin);
if (c != '*') {
prot_ungetc(c, pin);
r = getresult(pin, "ACL0");
break;
}
c = prot_getc(pin); /* skip SP */
c = getword(pin, &cmd);
if (c == EOF) {
r = IMAP_SERVER_UNAVAILABLE;
break;
}
if (!strncmp(cmd.s, "ACL", 3)) {
while(c != '\n') {
/* An ACL response, we should send a DELETEACL command */
c = getastring(pin, pout, &tmp);
if (c == EOF) {
r = IMAP_SERVER_UNAVAILABLE;
goto cleanup;
}
if(c == '\r') {
c = prot_getc(pin);
if(c != '\n') {
r = IMAP_SERVER_UNAVAILABLE;
goto cleanup;
}
}
if(c == '\n') break; /* end of * ACL */
c = getastring(pin, pout, &user);
if (c == EOF) {
r = IMAP_SERVER_UNAVAILABLE;
goto cleanup;
}
snprintf(tagbuf, sizeof(tagbuf), "ACL%d", ++i);
prot_printf(pout, "%s DELETEACL {" SIZE_T_FMT "+}\r\n%s"
" {" SIZE_T_FMT "+}\r\n%s\r\n",
tagbuf, strlen(mailbox), mailbox,
strlen(user.s), user.s);
if(c == '\r') {
c = prot_getc(pin);
if(c != '\n') {
r = IMAP_SERVER_UNAVAILABLE;
goto cleanup;
}
}
/* if the next character is \n, we'll exit the loop */
}
}
else {
/* skip this line, we don't really care */
eatline(pin, c);
}
}
cleanup:
/* Now cleanup after all the DELETEACL commands */
if(!r) {
while(j < i) {
snprintf(tagbuf, sizeof(tagbuf), "ACL%d", ++j);
r = getresult(pin, tagbuf);
if (r) break;
}
}
if(r) eatline(pin, c);
buf_free(&user);
buf_free(&tmp);
buf_free(&cmd);
return r;
}
static int dumpacl(struct protstream *pin, struct protstream *pout,
const char *mboxname, const char *acl_in)
{
int r = 0;
char tag[128];
int tagnum = 1;
char *rights, *nextid;
char *acl_safe = acl_in ? xstrdup(acl_in) : NULL;
char *acl = acl_safe;
while (acl) {
rights = strchr(acl, '\t');
if (!rights) break;
*rights++ = '\0';
nextid = strchr(rights, '\t');
if (!nextid) break;
*nextid++ = '\0';
snprintf(tag, sizeof(tag), "SACL%d", tagnum++);
prot_printf(pout, "%s SETACL {" SIZE_T_FMT "+}\r\n%s"
" {" SIZE_T_FMT "+}\r\n%s {" SIZE_T_FMT "+}\r\n%s\r\n",
tag,
strlen(mboxname), mboxname,
strlen(acl), acl,
strlen(rights), rights);
r = getresult(pin, tag);
if (r) break;
acl = nextid;
}
if(acl_safe) free(acl_safe);
return r;
}
enum {
XFER_MOVING_USER = -1,
XFER_DEACTIVATED = 1,
XFER_REMOTE_CREATED,
XFER_LOCAL_MOVING,
XFER_UNDUMPED,
};
struct xfer_item {
mbentry_t *mbentry;
char extname[MAX_MAILBOX_NAME];
struct mailbox *mailbox;
int state;
struct xfer_item *next;
};
struct xfer_header {
struct backend *be;
int remoteversion;
unsigned long use_replication;
struct buf tagbuf;
char *userid;
char *toserver;
char *topart;
struct seen *seendb;
struct xfer_item *items;
};
static int xfer_mupdate(int isactivate,
const char *mboxname, const char *part,
const char *servername, const char *acl)
{
char buf[MAX_PARTITION_LEN+HOSTNAME_SIZE+2];
int retry = 0;
int r = 0;
/* no mupdate handle */
if (!mupdate_h) return 0;
snprintf(buf, sizeof(buf), "%s!%s", servername, part);
retry:
/* make the change */
if (isactivate)
r = mupdate_activate(mupdate_h, mboxname, buf, acl);
else
r = mupdate_deactivate(mupdate_h, mboxname, buf);
if (r && !retry) {
syslog(LOG_INFO, "MUPDATE: lost connection, retrying");
mupdate_disconnect(&mupdate_h);
r = mupdate_connect(config_mupdate_server, NULL, &mupdate_h, NULL);
if (r) {
syslog(LOG_INFO, "Failed to connect to mupdate '%s'",
config_mupdate_server);
}
else {
retry = 1;
goto retry;
}
}
return r;
}
/* nothing you can do about failures, just try to clean up */
static void xfer_cleanup(struct xfer_header *xfer)
{
struct xfer_item *item, *next;
/* remove items */
item = xfer->items;
while (item) {
next = item->next;
mboxlist_entry_free(&item->mbentry);
free(item);
item = next;
}
xfer->items = NULL;
free(xfer->topart);
free(xfer->userid);
xfer->topart = xfer->userid = NULL;
seen_close(&xfer->seendb);
xfer->seendb = NULL;
}
static void xfer_done(struct xfer_header **xferptr)
{
struct xfer_header *xfer = *xferptr;
syslog(LOG_INFO, "XFER: disconnecting from servers");
free(xfer->toserver);
buf_free(&xfer->tagbuf);
xfer_cleanup(xfer);
free(xfer);
*xferptr = NULL;
}
static int backend_version(struct backend *be)
{
const char *minor;
/* IMPORTANT:
*
* When adding checks for new versions, you must also backport these
* checks to previous versions (especially 2.4 and 2.5).
*
* Otherwise, old versions will be unable to recognise the new version,
* assume it is ancient, and downgrade the index to the oldest version
* supported (version 6, prior to v2.3).
*/
/* It's like looking in the mirror and not suffering from schizophrenia */
if (strstr(be->banner, cyrus_version())) {
return MAILBOX_MINOR_VERSION;
}
/* master branch? */
if (strstr(be->banner, "Cyrus IMAP 3.0")) {
return 13;
}
/* version 2.5 is 13 */
if (strstr(be->banner, "Cyrus IMAP 2.5.")
|| strstr(be->banner, "Cyrus IMAP Murder 2.5.")
|| strstr(be->banner, "git2.5.")) {
return 13;
}
/* version 2.4 was all 12 */
if (strstr(be->banner, "v2.4.") || strstr(be->banner, "git2.4.")) {
return 12;
}
minor = strstr(be->banner, "v2.3.");
if (!minor) return 6;
/* at least version 2.3.10 */
if (minor[1] != ' ') {
return 10;
}
/* single digit version, figure out which */
switch (minor[0]) {
case '0':
case '1':
case '2':
case '3':
return 7;
break;
case '4':
case '5':
case '6':
return 8;
break;
case '7':
case '8':
case '9':
return 9;
break;
}
/* fallthrough, shouldn't happen */
return 6;
}
static int xfer_init(const char *toserver, struct xfer_header **xferptr)
{
struct xfer_header *xfer = xzmalloc(sizeof(struct xfer_header));
int r;
syslog(LOG_INFO, "XFER: connecting to server '%s'", toserver);
/* Get a connection to the remote backend */
xfer->be = proxy_findserver(toserver, &imap_protocol, "", &backend_cached,
NULL, NULL, imapd_in);
if (!xfer->be) {
syslog(LOG_ERR, "Failed to connect to server '%s'", toserver);
r = IMAP_SERVER_UNAVAILABLE;
goto fail;
}
xfer->remoteversion = backend_version(xfer->be);
if (xfer->be->capability & CAPA_REPLICATION) {
syslog(LOG_INFO, "XFER: destination supports replication");
xfer->use_replication = 1;
/* attach our IMAP tag buffer to our protstreams as userdata */
xfer->be->in->userdata = xfer->be->out->userdata = &xfer->tagbuf;
}
xfer->toserver = xstrdup(toserver);
xfer->topart = NULL;
xfer->seendb = NULL;
/* connect to mupdate server if configured */
if (config_mupdate_server && !mupdate_h) {
syslog(LOG_INFO, "XFER: connecting to mupdate '%s'",
config_mupdate_server);
r = mupdate_connect(config_mupdate_server, NULL, &mupdate_h, NULL);
if (r) {
syslog(LOG_INFO, "Failed to connect to mupdate '%s'",
config_mupdate_server);
goto fail;
}
}
*xferptr = xfer;
return 0;
fail:
xfer_done(&xfer);
return r;
}
static int xfer_localcreate(struct xfer_header *xfer)
{
struct xfer_item *item;
int r;
syslog(LOG_INFO, "XFER: creating mailboxes on destination");
for (item = xfer->items; item; item = item->next) {
if (xfer->topart) {
/* need to send partition as an atom */
prot_printf(xfer->be->out, "LC1 LOCALCREATE {" SIZE_T_FMT "+}\r\n%s %s\r\n",
strlen(item->extname), item->extname, xfer->topart);
} else {
prot_printf(xfer->be->out, "LC1 LOCALCREATE {" SIZE_T_FMT "+}\r\n%s\r\n",
strlen(item->extname), item->extname);
}
r = getresult(xfer->be->in, "LC1");
if (r) {
syslog(LOG_ERR, "Could not move mailbox: %s, LOCALCREATE failed",
item->mbentry->name);
return r;
}
item->state = XFER_REMOTE_CREATED;
}
return 0;
}
static int xfer_backport_seen_item(struct xfer_item *item,
struct seen *seendb)
{
struct mailbox *mailbox = item->mailbox;
struct seqset *outlist = NULL;
struct seendata sd = SEENDATA_INITIALIZER;
int r;
outlist = seqset_init(mailbox->i.last_uid, SEQ_MERGE);
struct mailbox_iter *iter = mailbox_iter_init(mailbox, 0, ITER_SKIP_EXPUNGED);
const message_t *msg;
while ((msg = mailbox_iter_step(iter))) {
const struct index_record *record = msg_record(msg);
if (record->system_flags & FLAG_SEEN)
seqset_add(outlist, record->uid, 1);
else
seqset_add(outlist, record->uid, 0);
}
mailbox_iter_done(&iter);
sd.lastread = mailbox->i.recenttime;
sd.lastuid = mailbox->i.recentuid;
sd.lastchange = mailbox->i.last_appenddate;
sd.seenuids = seqset_cstring(outlist);
if (!sd.seenuids) sd.seenuids = xstrdup("");
r = seen_write(seendb, mailbox->uniqueid, &sd);
seen_freedata(&sd);
seqset_free(outlist);
return r;
}
static int xfer_deactivate(struct xfer_header *xfer)
{
struct xfer_item *item;
int r;
syslog(LOG_INFO, "XFER: deactivating mailboxes");
/* Step 3: mupdate.DEACTIVATE(mailbox, newserver) */
for (item = xfer->items; item; item = item->next) {
r = xfer_mupdate(0, item->mbentry->name, item->mbentry->partition,
config_servername, item->mbentry->acl);
if (r) {
syslog(LOG_ERR,
"Could not move mailbox: %s, MUPDATE DEACTIVATE failed",
item->mbentry->name);
return r;
}
item->state = XFER_DEACTIVATED;
}
return 0;
}
static int xfer_undump(struct xfer_header *xfer)
{
struct xfer_item *item;
int r;
mbentry_t *newentry;
struct mailbox *mailbox = NULL;
syslog(LOG_INFO, "XFER: dumping mailboxes to destination");
for (item = xfer->items; item; item = item->next) {
r = mailbox_open_irl(item->mbentry->name, &mailbox);
if (r) {
syslog(LOG_ERR,
"Failed to open mailbox %s for dump_mailbox() %s",
item->mbentry->name, error_message(r));
return r;
}
/* Step 3.5: Set mailbox as MOVING on local server */
/* XXX - this code is awful... need a sane way to manage mbentries */
newentry = mboxlist_entry_create();
newentry->name = xstrdupnull(item->mbentry->name);
newentry->acl = xstrdupnull(item->mbentry->acl);
newentry->server = xstrdupnull(xfer->toserver);
newentry->partition = xstrdupnull(xfer->topart);
newentry->mbtype = item->mbentry->mbtype|MBTYPE_MOVING;
r = mboxlist_update(newentry, 1);
mboxlist_entry_free(&newentry);
if (r) {
syslog(LOG_ERR,
"Could not move mailbox: %s, mboxlist_update() failed %s",
item->mbentry->name, error_message(r));
}
else item->state = XFER_LOCAL_MOVING;
if (!r && xfer->seendb) {
/* Backport the user's seendb on-the-fly */
item->mailbox = mailbox;
r = xfer_backport_seen_item(item, xfer->seendb);
if (r) syslog(LOG_WARNING,
"Failed to backport seen state for mailbox '%s'",
item->mbentry->name);
/* Need to close seendb before dumping Inbox (last item) */
if (!item->next) seen_close(&xfer->seendb);
}
/* Step 4: Dump local -> remote */
if (!r) {
prot_printf(xfer->be->out, "D01 UNDUMP {" SIZE_T_FMT "+}\r\n%s ",
strlen(item->extname), item->extname);
r = dump_mailbox(NULL, mailbox, 0, xfer->remoteversion,
xfer->be->in, xfer->be->out, imapd_authstate);
if (r) {
syslog(LOG_ERR,
"Could not move mailbox: %s, dump_mailbox() failed %s",
item->mbentry->name, error_message(r));
}
}
mailbox_close(&mailbox);
if (r) return r;
r = getresult(xfer->be->in, "D01");
if (r) {
syslog(LOG_ERR, "Could not move mailbox: %s, UNDUMP failed %s",
item->mbentry->name, error_message(r));
return r;
}
/* Step 5: Set ACL on remote */
r = trashacl(xfer->be->in, xfer->be->out,
item->extname);
if (r) {
syslog(LOG_ERR, "Could not clear remote acl on %s",
item->mbentry->name);
return r;
}
r = dumpacl(xfer->be->in, xfer->be->out,
item->extname, item->mbentry->acl);
if (r) {
syslog(LOG_ERR, "Could not set remote acl on %s",
item->mbentry->name);
return r;
}
item->state = XFER_UNDUMPED;
}
return 0;
}
static int xfer_addusermbox(const mbentry_t *mbentry, void *rock)
{
struct xfer_header *xfer = (struct xfer_header *)rock;
/* Skip remote mailbox */
if (mbentry->mbtype & MBTYPE_REMOTE)
return 0;
struct xfer_item *item = xzmalloc(sizeof(struct xfer_item));
// re-read, because we don't have a handy clone function yet
int r = mboxlist_lookup(mbentry->name, &item->mbentry, 0);
if (r) return r;
char *extname = mboxname_to_external(item->mbentry->name, &imapd_namespace, imapd_userid);
strncpy(item->extname, extname, sizeof(item->extname));
free(extname);
item->mailbox = NULL;
item->state = 0;
/* and link on to the list (reverse order) */
item->next = xfer->items;
xfer->items = item;
return 0;
}
static int xfer_initialsync(struct xfer_header *xfer)
{
unsigned flags = SYNC_FLAG_LOGGING | SYNC_FLAG_LOCALONLY;
int r;
if (xfer->userid) {
struct xfer_item *item, *next;
syslog(LOG_INFO, "XFER: initial sync of user %s", xfer->userid);
r = sync_do_user(xfer->userid, xfer->topart, xfer->be,
/*channelp*/NULL, flags);
if (r) return r;
/* User moves may take a while, do another non-blocking sync */
syslog(LOG_INFO, "XFER: second sync of user %s", xfer->userid);
r = sync_do_user(xfer->userid, xfer->topart, xfer->be,
/*channelp*/NULL, flags);
if (r) return r;
/* User may have renamed/deleted a mailbox while syncing,
recreate the submailboxes list */
for (item = xfer->items; item; item = next) {
next = item->next;
mboxlist_entry_free(&item->mbentry);
free(item);
}
xfer->items = NULL;
r = mboxlist_usermboxtree(xfer->userid, xfer_addusermbox,
xfer, MBOXTREE_DELETED);
}
else {
struct sync_name_list *mboxname_list = sync_name_list_create();
syslog(LOG_INFO, "XFER: initial sync of mailbox %s",
xfer->items->mbentry->name);
sync_name_list_add(mboxname_list, xfer->items->mbentry->name);
r = sync_do_mailboxes(mboxname_list, xfer->topart, xfer->be,
/*channelp*/NULL, flags);
sync_name_list_free(&mboxname_list);
}
return r;
}
/*
* This is similar to do_folders() from sync_support, but for a single mailbox.
* It is needed for xfer_finalsync(), which needs to hold a single exclusive
* lock on the mailbox for the duration of this operation.
*/
static int sync_mailbox(struct mailbox *mailbox,
struct sync_folder_list *replica_folders,
const char *topart,
struct backend *be)
{
int r = 0;
struct sync_folder_list *master_folders = NULL;
struct sync_reserve_list *reserve_guids = NULL;
struct sync_msgid_list *part_list;
struct sync_reserve *reserve;
struct sync_folder *mfolder, *rfolder;
struct sync_annot_list *annots = NULL;
modseq_t xconvmodseq = 0;
unsigned flags = SYNC_FLAG_LOGGING | SYNC_FLAG_LOCALONLY;
if (!topart) topart = mailbox->part;
reserve_guids = sync_reserve_list_create(SYNC_MSGID_LIST_HASH_SIZE);
part_list = sync_reserve_partlist(reserve_guids, topart);
/* always send mailbox annotations */
r = read_annotations(mailbox, NULL, &annots);
if (r) {
syslog(LOG_ERR, "sync_mailbox(): read annotations failed: %s '%s'",
mailbox->name, error_message(r));
goto cleanup;
}
/* xconvmodseq */
if (mailbox_has_conversations(mailbox)) {
r = mailbox_get_xconvmodseq(mailbox, &xconvmodseq);
if (r) {
syslog(LOG_ERR, "sync_mailbox(): mailbox get xconvmodseq failed: %s '%s'",
mailbox->name, error_message(r));
goto cleanup;
}
}
master_folders = sync_folder_list_create();
sync_folder_list_add(master_folders,
mailbox->uniqueid, mailbox->name,
mailbox->mbtype,
mailbox->part,
mailbox->acl,
mailbox->i.options,
mailbox->i.uidvalidity,
mailbox->i.last_uid,
mailbox->i.highestmodseq,
mailbox->i.synccrcs,
mailbox->i.recentuid,
mailbox->i.recenttime,
mailbox->i.pop3_last_login,
mailbox->i.pop3_show_after,
annots,
xconvmodseq,
/* ispartial */0);
annots = NULL; /* list took ownership */
mfolder = master_folders->head;
/* when mfolder->mailbox is set, sync_update_mailbox will use it rather
* than obtaining its own (short-lived) locks */
mfolder->mailbox = mailbox;
uint32_t fromuid = 0;
rfolder = sync_folder_lookup(replica_folders, mfolder->uniqueid);
if (rfolder) {
rfolder->mark = 1;
/* does it need a rename? */
if (strcmp(mfolder->name, rfolder->name) ||
strcmp(topart, rfolder->part)) {
/* bail and retry */
syslog(LOG_NOTICE,
"XFER: rename %s!%s -> %s!%s during final sync"
" - must try XFER again",
mfolder->name, mfolder->part, rfolder->name, rfolder->part);
r = IMAP_AGAIN;
goto cleanup;
}
fromuid = rfolder->last_uid;
}
sync_find_reserve_messages(mailbox, fromuid, mailbox->i.last_uid, part_list);
reserve = reserve_guids->head;
r = sync_reserve_partition(reserve->part, replica_folders,
reserve->list, be);
if (r) {
syslog(LOG_ERR, "sync_mailbox(): reserve partition failed: %s '%s'",
mfolder->name, error_message(r));
goto cleanup;
}
r = sync_update_mailbox(mfolder, rfolder, topart, reserve_guids, be, flags);
if (r) {
syslog(LOG_ERR, "sync_mailbox(): update failed: %s '%s'",
mfolder->name, error_message(r));
}
cleanup:
sync_reserve_list_free(&reserve_guids);
sync_folder_list_free(&master_folders);
sync_annot_list_free(&annots);
return r;
}
static int xfer_finalsync(struct xfer_header *xfer)
{
struct sync_name_list *master_quotaroots = sync_name_list_create();
struct sync_folder_list *replica_folders = sync_folder_list_create();
struct sync_folder *rfolder;
struct sync_name_list *replica_subs = NULL;
struct sync_sieve_list *replica_sieve = NULL;
struct sync_seen_list *replica_seen = NULL;
struct sync_quota_list *replica_quota = sync_quota_list_create();
const char *cmd;
struct dlist *kl = NULL;
struct xfer_item *item;
struct mailbox *mailbox = NULL;
mbentry_t newentry;
unsigned flags = SYNC_FLAG_LOGGING | SYNC_FLAG_LOCALONLY;
int r;
if (xfer->userid) {
syslog(LOG_INFO, "XFER: final sync of user %s", xfer->userid);
replica_subs = sync_name_list_create();
replica_sieve = sync_sieve_list_create();
replica_seen = sync_seen_list_create();
cmd = "USER";
kl = dlist_setatom(NULL, cmd, xfer->userid);
}
else {
syslog(LOG_INFO, "XFER: final sync of mailbox %s",
xfer->items->mbentry->name);
cmd = "MAILBOXES";
kl = dlist_newlist(NULL, cmd);
dlist_setatom(kl, "MBOXNAME", xfer->items->mbentry->name);
}
sync_send_lookup(kl, xfer->be->out);
dlist_free(&kl);
r = sync_response_parse(xfer->be->in, cmd, replica_folders, replica_subs,
replica_sieve, replica_seen, replica_quota);
if (r) goto done;
for (item = xfer->items; item; item = item->next) {
r = mailbox_open_iwl(item->mbentry->name, &mailbox);
if (!r) r = sync_mailbox_version_check(&mailbox);
if (r) {
syslog(LOG_ERR,
"Failed to open mailbox %s for xfer_final_sync() %s",
item->mbentry->name, error_message(r));
goto done;
}
/* Open cyrus.annotations before we set mailbox to MOVING and
change its location to destination server and partition */
r = mailbox_get_annotate_state(mailbox, ANNOTATE_ANY_UID, NULL);
if (r) {
syslog(LOG_ERR,
"Failed to get annotate state for mailbox %s"
" for xfer_final_sync() %s",
mailbox->name, error_message(r));
mailbox_close(&mailbox);
goto done;
}
/* Step 3.5: Set mailbox as MOVING on local server */
/* XXX - this code is awful... need a sane way to manage mbentries */
newentry.name = item->mbentry->name;
newentry.acl = item->mbentry->acl;
newentry.uniqueid = item->mbentry->uniqueid;
newentry.uidvalidity = item->mbentry->uidvalidity;
newentry.mbtype = item->mbentry->mbtype|MBTYPE_MOVING;
newentry.server = xfer->toserver;
newentry.partition = xfer->topart;
r = mboxlist_update(&newentry, 1);
if (r) {
syslog(LOG_ERR,
"Could not move mailbox: %s, mboxlist_update() failed %s",
item->mbentry->name, error_message(r));
}
else item->state = XFER_LOCAL_MOVING;
/* Step 4: Sync local -> remote */
if (!r) {
r = sync_mailbox(mailbox, replica_folders, xfer->topart, xfer->be);
if (r) {
syslog(LOG_ERR,
"Could not move mailbox: %s, sync_mailbox() failed %s",
item->mbentry->name, error_message(r));
}
else {
if (mailbox->quotaroot &&
!sync_name_lookup(master_quotaroots, mailbox->quotaroot)) {
sync_name_list_add(master_quotaroots, mailbox->quotaroot);
}
r = sync_do_annotation(mailbox->name, xfer->be, flags);
if (r) {
syslog(LOG_ERR, "Could not move mailbox: %s,"
" sync_do_annotation() failed %s",
item->mbentry->name, error_message(r));
}
}
}
mailbox_close(&mailbox);
if (r) goto done;
item->state = XFER_UNDUMPED;
}
/* Delete folders on replica which no longer exist on master */
for (rfolder = replica_folders->head; rfolder; rfolder = rfolder->next) {
if (rfolder->mark) continue;
r = sync_folder_delete(rfolder->name, xfer->be, flags);
if (r) {
syslog(LOG_ERR, "sync_folder_delete(): failed: %s '%s'",
rfolder->name, error_message(r));
goto done;
}
}
/* Handle any mailbox/user metadata */
r = sync_do_user_quota(master_quotaroots, replica_quota, xfer->be, flags);
if (!r && xfer->userid) {
r = sync_do_user_seen(xfer->userid, replica_seen, xfer->be, flags);
if (!r) r = sync_do_user_sub(xfer->userid, replica_subs,
xfer->be, flags);
if (!r) r = sync_do_user_sieve(xfer->userid, replica_sieve,
xfer->be, flags);
}
done:
sync_name_list_free(&master_quotaroots);
sync_folder_list_free(&replica_folders);
if (replica_subs) sync_name_list_free(&replica_subs);
if (replica_sieve) sync_sieve_list_free(&replica_sieve);
if (replica_seen) sync_seen_list_free(&replica_seen);
if (replica_quota) sync_quota_list_free(&replica_quota);
return r;
}
static int xfer_reactivate(struct xfer_header *xfer)
{
struct xfer_item *item;
int r;
syslog(LOG_INFO, "XFER: reactivating mailboxes");
if (!mupdate_h) return 0;
/* 6.5) Kick remote server to correct mupdate entry */
for (item = xfer->items; item; item = item->next) {
prot_printf(xfer->be->out, "MP1 MUPDATEPUSH {" SIZE_T_FMT "+}\r\n%s\r\n",
strlen(item->extname), item->extname);
r = getresult(xfer->be->in, "MP1");
if (r) {
syslog(LOG_ERR, "MUPDATE: can't activate mailbox entry '%s': %s",
item->mbentry->name, error_message(r));
}
}
return 0;
}
static int xfer_delete(struct xfer_header *xfer)
{
mbentry_t *newentry = NULL;
struct xfer_item *item;
int r;
syslog(LOG_INFO, "XFER: deleting mailboxes on source");
/* 7) local delete of mailbox
* & remove local "remote" mailboxlist entry */
for (item = xfer->items; item; item = item->next) {
/* Set mailbox as DELETED on local server
(need to also reset to local partition,
otherwise mailbox can not be opened for deletion) */
/* XXX - this code is awful... need a sane way to manage mbentries */
newentry = mboxlist_entry_create();
newentry->name = xstrdupnull(item->mbentry->name);
newentry->acl = xstrdupnull(item->mbentry->acl);
newentry->server = xstrdupnull(item->mbentry->server);
newentry->partition = xstrdupnull(item->mbentry->partition);
newentry->mbtype = item->mbentry->mbtype|MBTYPE_DELETED;
r = mboxlist_update(newentry, 1);
mboxlist_entry_free(&newentry);
if (r) {
syslog(LOG_ERR,
"Could not move mailbox: %s, mboxlist_update failed (%s)",
item->mbentry->name, error_message(r));
}
/* Note that we do not check the ACL, and we don't update MUPDATE */
/* note also that we need to remember to let proxyadmins do this */
/* On a unified system, the subsequent MUPDATE PUSH on the remote
should repopulate the local mboxlist entry */
r = mboxlist_deletemailbox(item->mbentry->name,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate, NULL, 0, 1, 0);
if (r) {
syslog(LOG_ERR,
"Could not delete local mailbox during move of %s",
item->mbentry->name);
/* can't abort now! */
}
}
return 0;
}
static void xfer_recover(struct xfer_header *xfer)
{
struct xfer_item *item;
int r;
syslog(LOG_INFO, "XFER: recovering");
/* Backout any changes - we stop on first untouched mailbox */
for (item = xfer->items; item && item->state; item = item->next) {
switch (item->state) {
case XFER_UNDUMPED:
case XFER_LOCAL_MOVING:
/* Unset mailbox as MOVING on local server */
r = mboxlist_update(item->mbentry, 1);
if (r) {
syslog(LOG_ERR,
"Could not back out MOVING flag during move of %s (%s)",
item->mbentry->name, error_message(r));
}
case XFER_REMOTE_CREATED:
if (!xfer->use_replication) {
/* Delete remote mailbox */
prot_printf(xfer->be->out,
"LD1 LOCALDELETE {" SIZE_T_FMT "+}\r\n%s\r\n",
strlen(item->extname), item->extname);
r = getresult(xfer->be->in, "LD1");
if (r) {
syslog(LOG_ERR,
"Could not back out remote mailbox during move of %s (%s)",
item->mbentry->name, error_message(r));
}
}
case XFER_DEACTIVATED:
/* Tell murder it's back here and active */
r = xfer_mupdate(1, item->mbentry->name, item->mbentry->partition,
config_servername, item->mbentry->acl);
if (r) {
syslog(LOG_ERR,
"Could not back out mupdate during move of %s (%s)",
item->mbentry->name, error_message(r));
}
}
}
}
static int do_xfer(struct xfer_header *xfer)
{
int r = 0;
if (xfer->use_replication) {
/* Initial non-blocking sync */
r = xfer_initialsync(xfer);
if (r) return r;
}
r = xfer_deactivate(xfer);
if (!r) {
if (xfer->use_replication) {
/* Final sync with write locks on mailboxes */
r = xfer_finalsync(xfer);
}
else {
r = xfer_localcreate(xfer);
if (!r) r = xfer_undump(xfer);
}
}
if (r) {
/* Something failed, revert back to local server */
xfer_recover(xfer);
return r;
}
/* Successful dump of all mailboxes to remote server.
* Remove them locally and activate them on remote.
* Note - we don't report errors if this fails! */
xfer_delete(xfer);
xfer_reactivate(xfer);
return 0;
}
static int xfer_setquotaroot(struct xfer_header *xfer, const char *mboxname)
{
struct quota q;
int r;
syslog(LOG_INFO, "XFER: setting quota root %s", mboxname);
quota_init(&q, mboxname);
r = quota_read(&q, NULL, 0);
if (r == IMAP_QUOTAROOT_NONEXISTENT) return 0;
if (r) return r;
/* note use of + to force the setting of a nonexistant
* quotaroot */
char *extname = mboxname_to_external(mboxname, &imapd_namespace, imapd_userid);
prot_printf(xfer->be->out, "Q01 SETQUOTA {" SIZE_T_FMT "+}\r\n+%s ",
strlen(extname)+1, extname);
free(extname);
print_quota_limits(xfer->be->out, &q);
prot_printf(xfer->be->out, "\r\n");
quota_free(&q);
r = getresult(xfer->be->in, "Q01");
if (r) syslog(LOG_ERR,
"Could not move mailbox: %s, " \
"failed setting initial quota root\r\n",
mboxname);
return r;
}
struct xfer_list {
const struct namespace *ns;
const char *userid;
const char *part;
short allow_usersubs;
struct xfer_item *mboxes;
};
static int xfer_addmbox(struct findall_data *data, void *rock)
{
if (!data) return 0;
struct xfer_list *list = (struct xfer_list *) rock;
if (!data->mbentry) {
/* No partial matches */
return 0;
}
if (list->part && strcmp(data->mbentry->partition, list->part)) {
/* Not on specified partition */
return 0;
}
/* Only add shared mailboxes, targeted user submailboxes, or user INBOXes */
if (!mbname_localpart(data->mbname) || list->allow_usersubs ||
(!mbname_isdeleted(data->mbname) && !strarray_size(mbname_boxes(data->mbname)))) {
const char *extname = mbname_extname(data->mbname, list->ns, list->userid);
struct xfer_item *mbox = xzmalloc(sizeof(struct xfer_item));
mbox->mbentry = mboxlist_entry_copy(data->mbentry);
strncpy(mbox->extname, extname, sizeof(mbox->extname));
if (mbname_localpart(data->mbname) && !list->allow_usersubs) {
/* User INBOX */
mbox->state = XFER_MOVING_USER;
}
/* Add link on to the list (reverse order) */
mbox->next = list->mboxes;
list->mboxes = mbox;
}
return 0;
}
static void cmd_xfer(const char *tag, const char *name,
const char *toserver, const char *topart)
{
int r = 0, partial_success = 0, mbox_count = 0;
struct xfer_header *xfer = NULL;
struct xfer_list list = { &imapd_namespace, imapd_userid, NULL, 0, NULL };
struct xfer_item *item, *next;
char *intname = NULL;
/* administrators only please */
/* however, proxys can do this, if their authzid is an admin */
if (!imapd_userisadmin && !imapd_userisproxyadmin) {
r = IMAP_PERMISSION_DENIED;
goto done;
}
if (!strcmp(toserver, config_servername)) {
r = IMAP_BAD_SERVER;
goto done;
}
/* Build list of users/mailboxes to transfer */
if (config_partitiondir(name)) {
/* entire partition */
list.part = name;
mboxlist_findall(NULL, "*", 1, NULL, NULL, xfer_addmbox, &list);
} else {
/* mailbox pattern */
mbname_t *mbname;
intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
mbname = mbname_from_intname(intname);
if (mbname_localpart(mbname) &&
(mbname_isdeleted(mbname) || strarray_size(mbname_boxes(mbname)))) {
/* targeted a user submailbox */
list.allow_usersubs = 1;
}
mbname_free(&mbname);
mboxlist_findall(NULL, intname, 1, NULL, NULL, xfer_addmbox, &list);
free(intname);
}
r = xfer_init(toserver, &xfer);
if (r) goto done;
for (item = list.mboxes; item; item = next) {
mbentry_t *mbentry = item->mbentry;
/* NOTE: Since XFER can only be used by an admin, and we always connect
* to the destination backend as an admin, we take advantage of the fact
* that admins *always* use a consistent mailbox naming scheme.
* So, 'name' should be used in any command we send to a backend, and
* 'intname' is the internal name to be used for mupdate and findall.
*/
r = 0;
intname = mbentry->name;
xfer->topart = xstrdup(topart ? topart : mbentry->partition);
/* if we are not moving a user, just move the one mailbox */
if (item->state != XFER_MOVING_USER) {
syslog(LOG_INFO, "XFER: mailbox '%s' -> %s!%s",
mbentry->name, xfer->toserver, xfer->topart);
/* is the selected mailbox the one we're moving? */
if (!strcmpsafe(intname, index_mboxname(imapd_index))) {
r = IMAP_MAILBOX_LOCKED;
goto next;
}
/* we're moving this mailbox */
xfer_addusermbox(mbentry, xfer);
mbox_count++;
r = do_xfer(xfer);
} else {
xfer->userid = mboxname_to_userid(intname);
syslog(LOG_INFO, "XFER: user '%s' -> %s!%s",
xfer->userid, xfer->toserver, xfer->topart);
if (!config_getswitch(IMAPOPT_ALLOWUSERMOVES)) {
/* not configured to allow user moves */
r = IMAP_MAILBOX_NOTSUPPORTED;
} else if (!strcmp(xfer->userid, imapd_userid)) {
/* don't move your own inbox, that could be troublesome */
r = IMAP_MAILBOX_NOTSUPPORTED;
} else if (!strncmpsafe(intname, index_mboxname(imapd_index),
strlen(intname))) {
/* selected mailbox is in the namespace we're moving */
r = IMAP_MAILBOX_LOCKED;
}
if (r) goto next;
if (!xfer->use_replication) {
/* set the quotaroot if needed */
r = xfer_setquotaroot(xfer, intname);
if (r) goto next;
/* backport the seen file if needed */
if (xfer->remoteversion < 12) {
r = seen_open(xfer->userid, SEEN_CREATE, &xfer->seendb);
if (r) goto next;
}
}
r = mboxlist_usermboxtree(xfer->userid, xfer_addusermbox,
xfer, MBOXTREE_DELETED);
/* NOTE: mailboxes were added in reverse, so the inbox is
* done last */
r = do_xfer(xfer);
if (r) goto next;
/* this was a successful user move, and we need to delete
certain user meta-data (but not seen state!) */
syslog(LOG_INFO, "XFER: deleting user metadata");
user_deletedata(xfer->userid, 0);
}
next:
if (r) {
if (xfer->userid)
prot_printf(imapd_out, "* NO USER %s (%s)\r\n",
xfer->userid, error_message(r));
else
prot_printf(imapd_out, "* NO MAILBOX \"%s\" (%s)\r\n",
item->extname, error_message(r));
} else {
partial_success = 1;
if (xfer->userid)
prot_printf(imapd_out, "* OK USER %s\r\n", xfer->userid);
else
prot_printf(imapd_out, "* OK MAILBOX \"%s\"\r\n", item->extname);
}
prot_flush(imapd_out);
mboxlist_entry_free(&mbentry);
next = item->next;
free(item);
if (xfer->userid || mbox_count > 1000) {
/* RESTART after each user or after every 1000 mailboxes */
mbox_count = 0;
sync_send_restart(xfer->be->out);
r = sync_parse_response("RESTART", xfer->be->in, NULL);
if (r) goto done;
}
xfer_cleanup(xfer);
if (partial_success) r = 0;
}
done:
if (xfer) xfer_done(&xfer);
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
return;
}
#define SORTGROWSIZE 10
/*
* Parse sort criteria
*/
static int getsortcriteria(char *tag, struct sortcrit **sortcrit)
{
int c;
static struct buf criteria;
int nsort, n;
int hasconv = config_getswitch(IMAPOPT_CONVERSATIONS);
*sortcrit = NULL;
c = prot_getc(imapd_in);
if (c != '(') goto missingcrit;
c = getword(imapd_in, &criteria);
if (criteria.s[0] == '\0') goto missingcrit;
nsort = 0;
n = 0;
for (;;) {
if (n >= nsort - 1) { /* leave room for implicit criterion */
/* (Re)allocate an array for sort criteria */
nsort += SORTGROWSIZE;
*sortcrit =
(struct sortcrit *) xrealloc(*sortcrit,
nsort * sizeof(struct sortcrit));
/* Zero out the newly added sortcrit */
memset((*sortcrit)+n, 0, SORTGROWSIZE * sizeof(struct sortcrit));
}
lcase(criteria.s);
if (!strcmp(criteria.s, "reverse")) {
(*sortcrit)[n].flags |= SORT_REVERSE;
goto nextcrit;
}
else if (!strcmp(criteria.s, "arrival"))
(*sortcrit)[n].key = SORT_ARRIVAL;
else if (!strcmp(criteria.s, "cc"))
(*sortcrit)[n].key = SORT_CC;
else if (!strcmp(criteria.s, "date"))
(*sortcrit)[n].key = SORT_DATE;
else if (!strcmp(criteria.s, "displayfrom"))
(*sortcrit)[n].key = SORT_DISPLAYFROM;
else if (!strcmp(criteria.s, "displayto"))
(*sortcrit)[n].key = SORT_DISPLAYTO;
else if (!strcmp(criteria.s, "from"))
(*sortcrit)[n].key = SORT_FROM;
else if (!strcmp(criteria.s, "size"))
(*sortcrit)[n].key = SORT_SIZE;
else if (!strcmp(criteria.s, "subject"))
(*sortcrit)[n].key = SORT_SUBJECT;
else if (!strcmp(criteria.s, "to"))
(*sortcrit)[n].key = SORT_TO;
else if (!strcmp(criteria.s, "annotation")) {
const char *userid = NULL;
(*sortcrit)[n].key = SORT_ANNOTATION;
if (c != ' ') goto missingarg;
c = getastring(imapd_in, imapd_out, &criteria);
if (c != ' ') goto missingarg;
(*sortcrit)[n].args.annot.entry = xstrdup(criteria.s);
c = getastring(imapd_in, imapd_out, &criteria);
if (c == EOF) goto missingarg;
if (!strcmp(criteria.s, "value.shared"))
userid = "";
else if (!strcmp(criteria.s, "value.priv"))
userid = imapd_userid;
else
goto missingarg;
(*sortcrit)[n].args.annot.userid = xstrdup(userid);
}
else if (!strcmp(criteria.s, "modseq"))
(*sortcrit)[n].key = SORT_MODSEQ;
else if (!strcmp(criteria.s, "uid"))
(*sortcrit)[n].key = SORT_UID;
else if (!strcmp(criteria.s, "hasflag")) {
(*sortcrit)[n].key = SORT_HASFLAG;
if (c != ' ') goto missingarg;
c = getastring(imapd_in, imapd_out, &criteria);
if (c == EOF) goto missingarg;
(*sortcrit)[n].args.flag.name = xstrdup(criteria.s);
}
else if (hasconv && !strcmp(criteria.s, "convmodseq"))
(*sortcrit)[n].key = SORT_CONVMODSEQ;
else if (hasconv && !strcmp(criteria.s, "convexists"))
(*sortcrit)[n].key = SORT_CONVEXISTS;
else if (hasconv && !strcmp(criteria.s, "convsize"))
(*sortcrit)[n].key = SORT_CONVSIZE;
else if (hasconv && !strcmp(criteria.s, "hasconvflag")) {
(*sortcrit)[n].key = SORT_HASCONVFLAG;
if (c != ' ') goto missingarg;
c = getastring(imapd_in, imapd_out, &criteria);
if (c == EOF) goto missingarg;
(*sortcrit)[n].args.flag.name = xstrdup(criteria.s);
}
else if (!strcmp(criteria.s, "folder"))
(*sortcrit)[n].key = SORT_FOLDER;
else if (!strcmp(criteria.s, "relevancy"))
(*sortcrit)[n].key = SORT_RELEVANCY;
else if (!strcmp(criteria.s, "spamscore"))
(*sortcrit)[n].key = SORT_SPAMSCORE;
else {
prot_printf(imapd_out, "%s BAD Invalid Sort criterion %s\r\n",
tag, criteria.s);
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
}
n++;
nextcrit:
if (c == ' ') c = getword(imapd_in, &criteria);
else break;
}
if ((*sortcrit)[n].flags & SORT_REVERSE && !(*sortcrit)[n].key) {
prot_printf(imapd_out,
"%s BAD Missing Sort criterion to reverse\r\n", tag);
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
}
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close parenthesis in Sort\r\n", tag);
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
}
/* Terminate the list with the implicit sort criterion */
(*sortcrit)[n++].key = SORT_SEQUENCE;
c = prot_getc(imapd_in);
return c;
missingcrit:
prot_printf(imapd_out, "%s BAD Missing Sort criteria\r\n", tag);
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
missingarg:
prot_printf(imapd_out, "%s BAD Missing argument to Sort criterion %s\r\n",
tag, criteria.s);
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
}
static int parse_windowargs(const char *tag,
struct windowargs **wa,
int updates)
{
struct windowargs windowargs;
struct buf arg = BUF_INITIALIZER;
struct buf ext_folder = BUF_INITIALIZER;
int c;
memset(&windowargs, 0, sizeof(windowargs));
c = prot_getc(imapd_in);
if (c == EOF)
goto out;
if (c != '(') {
/* no window args at all */
prot_ungetc(c, imapd_in);
goto out;
}
for (;;)
{
c = prot_getc(imapd_in);
if (c == EOF)
goto out;
if (c == ')')
break; /* end of window args */
prot_ungetc(c, imapd_in);
c = getword(imapd_in, &arg);
if (!arg.len)
goto syntax_error;
if (!strcasecmp(arg.s, "CONVERSATIONS"))
windowargs.conversations = 1;
else if (!strcasecmp(arg.s, "POSITION")) {
if (updates)
goto syntax_error;
if (c != ' ')
goto syntax_error;
c = prot_getc(imapd_in);
if (c != '(')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.position);
if (c != ' ')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.limit);
if (c != ')')
goto syntax_error;
c = prot_getc(imapd_in);
if (windowargs.position == 0)
goto syntax_error;
}
else if (!strcasecmp(arg.s, "ANCHOR")) {
if (updates)
goto syntax_error;
if (c != ' ')
goto syntax_error;
c = prot_getc(imapd_in);
if (c != '(')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.anchor);
if (c != ' ')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.offset);
if (c != ' ')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.limit);
if (c != ')')
goto syntax_error;
c = prot_getc(imapd_in);
if (windowargs.anchor == 0)
goto syntax_error;
}
else if (!strcasecmp(arg.s, "MULTIANCHOR")) {
if (updates)
goto syntax_error;
if (c != ' ')
goto syntax_error;
c = prot_getc(imapd_in);
if (c != '(')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.anchor);
if (c != ' ')
goto syntax_error;
c = getastring(imapd_in, imapd_out, &ext_folder);
if (c != ' ')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.offset);
if (c != ' ')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.limit);
if (c != ')')
goto syntax_error;
c = prot_getc(imapd_in);
if (windowargs.anchor == 0)
goto syntax_error;
}
else if (!strcasecmp(arg.s, "CHANGEDSINCE")) {
if (!updates)
goto syntax_error;
windowargs.changedsince = 1;
if (c != ' ')
goto syntax_error;
c = prot_getc(imapd_in);
if (c != '(')
goto syntax_error;
c = getmodseq(imapd_in, &windowargs.modseq);
if (c != ' ')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.uidnext);
if (c != ')')
goto syntax_error;
c = prot_getc(imapd_in);
} else if (!strcasecmp(arg.s, "UPTO")) {
if (!updates)
goto syntax_error;
if (c != ' ')
goto syntax_error;
c = prot_getc(imapd_in);
if (c != '(')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.upto);
if (c != ')')
goto syntax_error;
c = prot_getc(imapd_in);
if (windowargs.upto == 0)
goto syntax_error;
}
else
goto syntax_error;
if (c == ')')
break;
if (c != ' ')
goto syntax_error;
}
c = prot_getc(imapd_in);
if (c != ' ')
goto syntax_error;
out:
/* these two are mutually exclusive */
if (windowargs.anchor && windowargs.position)
goto syntax_error;
/* changedsince is mandatory for XCONVUPDATES
* and illegal for XCONVSORT */
if (!!updates != windowargs.changedsince)
goto syntax_error;
if (ext_folder.len) {
windowargs.anchorfolder = mboxname_from_external(buf_cstring(&ext_folder),
&imapd_namespace,
imapd_userid);
}
*wa = xmemdup(&windowargs, sizeof(windowargs));
buf_free(&ext_folder);
buf_free(&arg);
return c;
syntax_error:
free(windowargs.anchorfolder);
buf_free(&ext_folder);
prot_printf(imapd_out, "%s BAD Syntax error in window arguments\r\n", tag);
return EOF;
}
static void free_windowargs(struct windowargs *wa)
{
if (!wa)
return;
free(wa->anchorfolder);
free(wa);
}
/*
* Parse LIST selection options.
* The command has been parsed up to and including the opening '('.
*/
static int getlistselopts(char *tag, struct listargs *args)
{
int c;
static struct buf buf;
if ( (c = prot_getc(imapd_in)) == ')')
return prot_getc(imapd_in);
else
prot_ungetc(c, imapd_in);
for (;;) {
c = getword(imapd_in, &buf);
if (!*buf.s) {
prot_printf(imapd_out,
"%s BAD Invalid syntax in List command\r\n",
tag);
return EOF;
}
lcase(buf.s);
if (!strcmp(buf.s, "subscribed")) {
args->sel |= LIST_SEL_SUBSCRIBED;
args->ret |= LIST_RET_SUBSCRIBED;
} else if (!strcmp(buf.s, "vendor.cmu-dav")) {
args->sel |= LIST_SEL_DAV;
} else if (!strcmp(buf.s, "remote")) {
args->sel |= LIST_SEL_REMOTE;
} else if (!strcmp(buf.s, "recursivematch")) {
args->sel |= LIST_SEL_RECURSIVEMATCH;
} else if (!strcmp(buf.s, "special-use")) {
args->sel |= LIST_SEL_SPECIALUSE;
args->ret |= LIST_RET_SPECIALUSE;
} else if (!strcmp(buf.s, "metadata")) {
struct getmetadata_options opts = OPTS_INITIALIZER;
args->sel |= LIST_SEL_METADATA;
args->ret |= LIST_RET_METADATA;
strarray_t options = STRARRAY_INITIALIZER;
c = parse_metadata_string_or_list(tag, &options, NULL);
parse_getmetadata_options(&options, &opts);
args->metaopts = opts;
strarray_fini(&options);
if (c == EOF) return EOF;
} else {
prot_printf(imapd_out,
"%s BAD Invalid List selection option \"%s\"\r\n",
tag, buf.s);
return EOF;
}
if (c != ' ') break;
}
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close parenthesis for List selection options\r\n", tag);
return EOF;
}
if (args->sel & list_select_mod_opts
&& ! (args->sel & list_select_base_opts)) {
prot_printf(imapd_out,
"%s BAD Invalid combination of selection options\r\n",
tag);
return EOF;
}
return prot_getc(imapd_in);
}
/*
* Parse LIST return options.
* The command has been parsed up to and including the ' ' before RETURN.
*/
static int getlistretopts(char *tag, struct listargs *args)
{
static struct buf buf;
int c;
c = getword(imapd_in, &buf);
if (!*buf.s) {
prot_printf(imapd_out,
"%s BAD Invalid syntax in List command\r\n", tag);
return EOF;
}
lcase(buf.s);
if (strcasecmp(buf.s, "return")) {
prot_printf(imapd_out,
"%s BAD Unexpected extra argument to List: \"%s\"\r\n",
tag, buf.s);
return EOF;
}
if (c != ' ' || (c = prot_getc(imapd_in)) != '(') {
prot_printf(imapd_out,
"%s BAD Missing return argument list\r\n", tag);
return EOF;
}
if ( (c = prot_getc(imapd_in)) == ')')
return prot_getc(imapd_in);
else
prot_ungetc(c, imapd_in);
for (;;) {
c = getword(imapd_in, &buf);
if (!*buf.s) {
prot_printf(imapd_out,
"%s BAD Invalid syntax in List command\r\n", tag);
return EOF;
}
lcase(buf.s);
if (!strcmp(buf.s, "subscribed"))
args->ret |= LIST_RET_SUBSCRIBED;
else if (!strcmp(buf.s, "children"))
args->ret |= LIST_RET_CHILDREN;
else if (!strcmp(buf.s, "myrights"))
args->ret |= LIST_RET_MYRIGHTS;
else if (!strcmp(buf.s, "special-use"))
args->ret |= LIST_RET_SPECIALUSE;
else if (!strcmp(buf.s, "status")) {
const char *errstr = "Bad status string";
args->ret |= LIST_RET_STATUS;
c = parse_statusitems(&args->statusitems, &errstr);
if (c == EOF) {
prot_printf(imapd_out, "%s BAD %s", tag, errstr);
return EOF;
}
}
else if (!strcmp(buf.s, "metadata")) {
args->ret |= LIST_RET_METADATA;
/* outputs the error for us */
c = parse_metadata_string_or_list(tag, &args->metaitems, NULL);
if (c == EOF) return EOF;
}
else {
prot_printf(imapd_out,
"%s BAD Invalid List return option \"%s\"\r\n",
tag, buf.s);
return EOF;
}
if (c != ' ') break;
}
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close parenthesis for List return options\r\n", tag);
return EOF;
}
return prot_getc(imapd_in);
}
/*
* Parse a string in IMAP date-time format (and some more
* obscure legacy formats too) to a time_t. Parses both
* date and time parts. See cyrus_parsetime() for formats.
*
* Returns: the next character read from imapd_in, or
* or EOF on error.
*/
static int getdatetime(time_t *date)
{
int c;
int r;
int i = 0;
char buf[RFC3501_DATETIME_MAX+1];
c = prot_getc(imapd_in);
if (c != '\"')
goto baddate;
while ((c = prot_getc(imapd_in)) != '\"') {
if (i >= RFC3501_DATETIME_MAX)
goto baddate;
buf[i++] = c;
}
buf[i] = '\0';
r = time_from_rfc3501(buf, date);
if (r < 0)
goto baddate;
c = prot_getc(imapd_in);
return c;
baddate:
prot_ungetc(c, imapd_in);
return EOF;
}
/*
* Append 'section', 'fields', 'trail' to the fieldlist 'l'.
*/
static void appendfieldlist(struct fieldlist **l, char *section,
strarray_t *fields, char *trail,
void *d, size_t size)
{
struct fieldlist **tail = l;
while (*tail) tail = &(*tail)->next;
*tail = (struct fieldlist *)xmalloc(sizeof(struct fieldlist));
(*tail)->section = xstrdup(section);
(*tail)->fields = fields;
(*tail)->trail = xstrdup(trail);
if(d && size) {
(*tail)->rock = xmalloc(size);
memcpy((*tail)->rock, d, size);
} else {
(*tail)->rock = NULL;
}
(*tail)->next = 0;
}
/*
* Free the fieldlist 'l'
*/
static void freefieldlist(struct fieldlist *l)
{
struct fieldlist *n;
while (l) {
n = l->next;
free(l->section);
strarray_free(l->fields);
free(l->trail);
if (l->rock) free(l->rock);
free((char *)l);
l = n;
}
}
static int set_haschildren(const mbentry_t *mbentry __attribute__((unused)),
void *rock)
{
uint32_t *attributes = (uint32_t *)rock;
list_callback_calls++;
*attributes |= MBOX_ATTRIBUTE_HASCHILDREN;
return CYRUSDB_DONE;
}
static void specialuse_flags(const mbentry_t *mbentry, struct buf *attrib,
int isxlist)
{
if (!mbentry) return;
char *inbox = mboxname_user_mbox(imapd_userid, NULL);
int inboxlen = strlen(inbox);
/* doesn't match inbox, not xlistable */
if (strncmp(mbentry->name, inbox, inboxlen)) {
free(inbox);
return;
}
/* inbox - only print if command is XLIST */
if (mbentry->name[inboxlen] == '\0') {
if (isxlist) buf_init_ro_cstr(attrib, "\\Inbox");
}
/* subdir */
else if (mbentry->name[inboxlen] == '.') {
/* check if there's a special use flag set */
annotatemore_lookup(mbentry->name, "/specialuse", imapd_userid, attrib);
}
free(inbox);
/* otherwise it's actually another user who matches for
* the substr. Ok to just print nothing */
}
static void printmetadata(const mbentry_t *mbentry,
const strarray_t *entries,
struct getmetadata_options *opts)
{
annotate_state_t *astate = annotate_state_new();
strarray_t newa = STRARRAY_INITIALIZER;
strarray_t newe = STRARRAY_INITIALIZER;
annotate_state_set_auth(astate,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate);
int r = annotate_state_set_mailbox_mbe(astate, mbentry);
if (r) goto done;
r = _metadata_to_annotate(entries, &newa, &newe, NULL, opts->depth);
if (r) goto done;
annotate_state_fetch(astate, &newe, &newa, getmetadata_response, opts);
getmetadata_response(NULL, 0, NULL, NULL, opts);
done:
annotate_state_abort(&astate);
}
/* Print LIST or LSUB untagged response */
static void list_response(const char *extname, const mbentry_t *mbentry,
uint32_t attributes, struct listargs *listargs)
{
int r;
struct statusdata sdata = STATUSDATA_INIT;
struct buf specialuse = BUF_INITIALIZER;
if ((attributes & MBOX_ATTRIBUTE_NONEXISTENT)) {
if (!(listargs->cmd == LIST_CMD_EXTENDED)) {
attributes |= MBOX_ATTRIBUTE_NOSELECT;
attributes &= ~MBOX_ATTRIBUTE_NONEXISTENT;
}
}
else if (listargs->scan) {
/* SCAN mailbox for content */
if (!strcmpsafe(mbentry->name, index_mboxname(imapd_index))) {
/* currently selected mailbox */
if (!index_scan(imapd_index, listargs->scan))
return; /* no matching messages */
}
else {
/* other local mailbox */
struct index_state *state;
struct index_init init;
int doclose = 0;
memset(&init, 0, sizeof(struct index_init));
init.userid = imapd_userid;
init.authstate = imapd_authstate;
init.out = imapd_out;
r = index_open(mbentry->name, &init, &state);
if (!r)
doclose = 1;
if (!r && index_hasrights(state, ACL_READ)) {
r = (imapd_userisadmin || index_hasrights(state, ACL_LOOKUP)) ?
IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT;
}
if (!r) {
if (!index_scan(state, listargs->scan)) {
r = -1; /* no matching messages */
}
}
if (doclose) index_close(&state);
if (r) return;
}
}
/* figure out \Has(No)Children if necessary
This is mainly used for LIST (SUBSCRIBED) RETURN (CHILDREN)
*/
uint32_t have_childinfo =
MBOX_ATTRIBUTE_HASCHILDREN | MBOX_ATTRIBUTE_HASNOCHILDREN;
if ((listargs->ret & LIST_RET_CHILDREN) && !(attributes & have_childinfo)) {
if (imapd_namespace.isalt && !strcmp(extname, "INBOX")) {
/* don't look inside INBOX under altnamespace, its children aren't children */
}
else {
char *intname = NULL, *freeme = NULL;
/* if we got here via subscribed_cb, mbentry isn't set */
if (mbentry)
intname = mbentry->name;
else
intname = freeme = mboxname_from_external(extname, &imapd_namespace, imapd_userid);
mboxlist_mboxtree(intname, set_haschildren, &attributes, MBOXTREE_SKIP_ROOT);
if (freeme) free(freeme);
}
if (!(attributes & MBOX_ATTRIBUTE_HASCHILDREN))
attributes |= MBOX_ATTRIBUTE_HASNOCHILDREN;
}
if (attributes & (MBOX_ATTRIBUTE_NONEXISTENT | MBOX_ATTRIBUTE_NOSELECT)) {
int keep = 0;
/* extended get told everything */
if (listargs->cmd == LIST_CMD_EXTENDED) {
keep = 1;
}
/* we have to mention this, it has children */
if (listargs->cmd == LIST_CMD_LSUB) {
/* subscribed children need a mention */
if (attributes & MBOX_ATTRIBUTE_CHILDINFO_SUBSCRIBED)
keep = 1;
/* if mupdate is configured we can't drop out, we might
* be a backend and need to report folders that don't
* exist on this backend - this is awful and complex
* and brittle and should be changed */
if (config_mupdate_server)
keep = 1;
}
else if (attributes & MBOX_ATTRIBUTE_HASCHILDREN)
keep = 1;
if (!keep) return;
}
if (listargs->cmd == LIST_CMD_LSUB) {
/* \Noselect has a special second meaning with (R)LSUB */
if ( !(attributes & MBOX_ATTRIBUTE_SUBSCRIBED)
&& attributes & MBOX_ATTRIBUTE_CHILDINFO_SUBSCRIBED)
attributes |= MBOX_ATTRIBUTE_NOSELECT | MBOX_ATTRIBUTE_HASCHILDREN;
attributes &= ~MBOX_ATTRIBUTE_SUBSCRIBED;
}
/* As CHILDINFO extended data item is not allowed if the
* RECURSIVEMATCH selection option is not specified */
if (!(listargs->sel & LIST_SEL_RECURSIVEMATCH)) {
attributes &= ~MBOX_ATTRIBUTE_CHILDINFO_SUBSCRIBED;
}
/* no inferiors means no children (this basically means the INBOX
* in alt namespace mode */
if (attributes & MBOX_ATTRIBUTE_NOINFERIORS)
attributes &= ~MBOX_ATTRIBUTE_HASCHILDREN;
/* you can't have both! If it's had children, it has children */
if (attributes & MBOX_ATTRIBUTE_HASCHILDREN)
attributes &= ~MBOX_ATTRIBUTE_HASNOCHILDREN;
/* remove redundant flags */
if (listargs->cmd == LIST_CMD_EXTENDED) {
/* \NoInferiors implies \HasNoChildren */
if (attributes & MBOX_ATTRIBUTE_NOINFERIORS)
attributes &= ~MBOX_ATTRIBUTE_HASNOCHILDREN;
/* \NonExistent implies \Noselect */
if (attributes & MBOX_ATTRIBUTE_NONEXISTENT)
attributes &= ~MBOX_ATTRIBUTE_NOSELECT;
}
if (config_getswitch(IMAPOPT_SPECIALUSEALWAYS) ||
listargs->cmd == LIST_CMD_XLIST ||
listargs->ret & LIST_RET_SPECIALUSE) {
specialuse_flags(mbentry, &specialuse, listargs->cmd == LIST_CMD_XLIST);
}
if (listargs->sel & LIST_SEL_SPECIALUSE) {
/* check that this IS a specialuse folder */
if (!buf_len(&specialuse)) return;
}
/* can we read the status data ? */
if ((listargs->ret & LIST_RET_STATUS) && mbentry) {
r = imapd_statusdata(mbentry->name, listargs->statusitems, &sdata);
if (r) {
/* RFC 5819: the STATUS response MUST NOT be returned and the
* LIST response MUST include the \NoSelect attribute. */
attributes |= MBOX_ATTRIBUTE_NOSELECT;
}
}
print_listresponse(listargs->cmd, extname,
imapd_namespace.hier_sep, attributes, &specialuse);
buf_free(&specialuse);
if ((listargs->ret & LIST_RET_STATUS) &&
!(attributes & MBOX_ATTRIBUTE_NOSELECT)) {
/* output the status line now, per rfc 5819 */
if (mbentry) print_statusline(extname, listargs->statusitems, &sdata);
}
if ((listargs->ret & LIST_RET_MYRIGHTS) &&
!(attributes & MBOX_ATTRIBUTE_NOSELECT)) {
if (mbentry) printmyrights(extname, mbentry);
}
if ((listargs->ret & LIST_RET_METADATA) &&
!(attributes & MBOX_ATTRIBUTE_NOSELECT)) {
if (mbentry)
printmetadata(mbentry, &listargs->metaitems, &listargs->metaopts);
}
}
static void _addsubs(struct list_rock *rock)
{
if (!rock->subs) return;
if (!rock->last_mbentry) return;
int i;
const char *last_name = rock->last_mbentry->name;
int namelen = strlen(last_name);
for (i = 0; i < rock->subs->count; i++) {
const char *name = strarray_nth(rock->subs, i);
if (strncmp(last_name, name, namelen))
continue;
else if (!name[namelen]) {
if ((rock->last_attributes & MBOX_ATTRIBUTE_NONEXISTENT))
rock->last_attributes |= MBOX_ATTRIBUTE_CHILDINFO_SUBSCRIBED;
else
rock->last_attributes |= MBOX_ATTRIBUTE_SUBSCRIBED;
}
else if (name[namelen] == '.')
rock->last_attributes |= MBOX_ATTRIBUTE_CHILDINFO_SUBSCRIBED;
}
}
static int perform_output(const char *extname, const mbentry_t *mbentry, struct list_rock *rock)
{
/* skip non-responsive mailboxes early, so they don't break sub folder detection */
if (mbentry && !imapd_userisadmin) {
if (mbentry->mbtype == MBTYPE_NETNEWS) return 0;
if (!(rock->listargs->sel & LIST_SEL_DAV)) {
if (mboxname_iscalendarmailbox(mbentry->name, mbentry->mbtype)) return 0;
if (mboxname_isaddressbookmailbox(mbentry->name, mbentry->mbtype)) return 0;
if (mboxname_isdavdrivemailbox(mbentry->name, mbentry->mbtype)) return 0;
if (mboxname_isdavnotificationsmailbox(mbentry->name, mbentry->mbtype)) return 0;
}
}
if (mbentry && (mbentry->mbtype & MBTYPE_REMOTE)) {
struct listargs *listargs = rock->listargs;
if (hash_lookup(mbentry->server, &rock->server_table)) {
/* already proxied to this backend server */
return 0;
}
if (listargs->scan ||
(listargs->ret &
(LIST_RET_SPECIALUSE | LIST_RET_STATUS | LIST_RET_METADATA))) {
/* remote mailbox that we need to fetch metadata from */
struct backend *s;
hash_insert(mbentry->server,
(void *)0xDEADBEEF, &rock->server_table);
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (s) {
char mytag[128];
proxy_gentag(mytag, sizeof(mytag));
if (listargs->scan) {
/* Send SCAN command to backend */
prot_printf(s->out, "%s Scan {%tu+}\r\n%s {%tu+}\r\n%s"
" {%tu+}\r\n%s\r\n",
mytag, strlen(listargs->ref), listargs->ref,
strlen(listargs->pat.data[0]),
listargs->pat.data[0],
strlen(listargs->scan), listargs->scan);
pipe_until_tag(s, mytag, 0);
}
else {
/* Send LIST command to backend */
list_data_remote(s, mytag, listargs, rock->subs);
}
}
return 0;
}
}
if (rock->last_name) {
if (extname) {
/* same again */
if (!strcmp(rock->last_name, extname)) return 0;
size_t extlen = strlen(extname);
if (extlen < strlen(rock->last_name)
&& rock->last_name[extlen] == imapd_namespace.hier_sep
&& !strncmp(rock->last_name, extname, extlen))
return 0; /* skip duplicate or reversed calls */
}
_addsubs(rock);
/* check if we need to filter out this mailbox */
if (!(rock->listargs->sel & LIST_SEL_SUBSCRIBED) ||
(rock->last_attributes &
(MBOX_ATTRIBUTE_SUBSCRIBED | MBOX_ATTRIBUTE_CHILDINFO_SUBSCRIBED))) {
list_response(rock->last_name, rock->last_mbentry,
rock->last_attributes, rock->listargs);
}
free(rock->last_name);
rock->last_name = NULL;
mboxlist_entry_free(&rock->last_mbentry);
}
if (extname) {
rock->last_name = xstrdup(extname);
if (mbentry) rock->last_mbentry = mboxlist_entry_copy(mbentry);
}
rock->last_attributes = 0;
rock->last_category = 0;
return 1;
}
/* callback for mboxlist_findall
* used when the SUBSCRIBED selection option is NOT given */
static int list_cb(struct findall_data *data, void *rockp)
{
struct list_rock *rock = (struct list_rock *)rockp;
if (!data) {
if (!(rock->last_attributes & MBOX_ATTRIBUTE_HASCHILDREN))
rock->last_attributes |= MBOX_ATTRIBUTE_HASNOCHILDREN;
perform_output(NULL, NULL, rock);
return 0;
}
size_t last_len = (rock->last_name ? strlen(rock->last_name) : 0);
const char *extname = data->extname;
int last_name_is_ancestor =
rock->last_name
&& strlen(extname) >= last_len
&& extname[last_len] == imapd_namespace.hier_sep
&& !memcmp(rock->last_name, extname, last_len);
list_callback_calls++;
/* list_response will calculate haschildren/hasnochildren flags later
* if they're required but not yet set, but it's a little cheaper to
* precalculate them now while we're iterating the mailboxes anyway.
*/
if (last_name_is_ancestor || (rock->last_name && !data->mbname && !strcmp(rock->last_name, extname)))
rock->last_attributes |= MBOX_ATTRIBUTE_HASCHILDREN;
else if (!(rock->last_attributes & MBOX_ATTRIBUTE_HASCHILDREN))
rock->last_attributes |= MBOX_ATTRIBUTE_HASNOCHILDREN;
if (!perform_output(data->extname, data->mbentry, rock))
return 0;
if (!data->mbname)
rock->last_attributes |= MBOX_ATTRIBUTE_HASCHILDREN | MBOX_ATTRIBUTE_NONEXISTENT;
else if (data->mb_category == MBNAME_ALTINBOX)
rock->last_attributes |= MBOX_ATTRIBUTE_NOINFERIORS;
return 0;
}
/* callback for mboxlist_findsub
* used when SUBSCRIBED but not RECURSIVEMATCH is given */
static int subscribed_cb(struct findall_data *data, void *rockp)
{
struct list_rock *rock = (struct list_rock *)rockp;
if (!data) {
perform_output(NULL, NULL, rock);
return 0;
}
size_t last_len = (rock->last_name ? strlen(rock->last_name) : 0);
const char *extname = data->extname;
int last_name_is_ancestor =
rock->last_name
&& strlen(extname) >= last_len
&& extname[last_len] == imapd_namespace.hier_sep
&& !memcmp(rock->last_name, extname, last_len);
list_callback_calls++;
if (last_name_is_ancestor ||
(rock->last_name && !data->mbname && !strcmp(rock->last_name, extname)))
rock->last_attributes |= MBOX_ATTRIBUTE_HASCHILDREN;
if (data->mbname) { /* exact match */
mbentry_t *mbentry = NULL;
mboxlist_lookup(mbname_intname(data->mbname), &mbentry, NULL);
perform_output(extname, mbentry, rock);
mboxlist_entry_free(&mbentry);
rock->last_attributes |= MBOX_ATTRIBUTE_SUBSCRIBED;
if (mboxlist_lookup(mbname_intname(data->mbname), NULL, NULL))
rock->last_attributes |= MBOX_ATTRIBUTE_NONEXISTENT;
if (data->mb_category == MBNAME_ALTINBOX)
rock->last_attributes |= MBOX_ATTRIBUTE_NOINFERIORS;
}
else if (rock->listargs->cmd == LIST_CMD_LSUB) {
/* special case: for LSUB,
* mailbox names that match the pattern but aren't subscribed
* must also be returned if they have a child mailbox that is
* subscribed */
perform_output(extname, data->mbentry, rock);
rock->last_attributes |= MBOX_ATTRIBUTE_CHILDINFO_SUBSCRIBED;
}
return 0;
}
/*
* Takes the "reference name" and "mailbox name" arguments of the LIST command
* and returns a "canonical LIST pattern". The caller is responsible for
* free()ing the returned string.
*/
static char *canonical_list_pattern(const char *reference, const char *pattern)
{
int patlen = strlen(pattern);
int reflen = strlen(reference);
char *buf = xmalloc(patlen + reflen + 1);
buf[0] = '\0';
if (*reference) {
if (reference[reflen-1] == imapd_namespace.hier_sep &&
pattern[0] == imapd_namespace.hier_sep)
--reflen;
memcpy(buf, reference, reflen);
buf[reflen] = '\0';
}
strcat(buf, pattern);
return buf;
}
/*
* Turns the strings in patterns into "canonical LIST pattern"s. Also
* translates any hierarchy separators.
*/
static void canonical_list_patterns(const char *reference,
strarray_t *patterns)
{
static int ignorereference = 0;
int i;
/* Ignore the reference argument?
(the behavior in 1.5.10 & older) */
if (ignorereference == 0)
ignorereference = config_getswitch(IMAPOPT_IGNOREREFERENCE);
for (i = 0 ; i < patterns->count ; i++) {
char *p = patterns->data[i];
if (!ignorereference || p[0] == imapd_namespace.hier_sep) {
strarray_setm(patterns, i,
canonical_list_pattern(reference, p));
p = patterns->data[i];
}
}
}
static void list_data_remotesubscriptions(struct listargs *listargs)
{
/* Need to fetch subscription list from backend_inbox */
struct list_rock rock;
char mytag[128];
memset(&rock, 0, sizeof(struct list_rock));
rock.listargs = listargs;
rock.subs = strarray_new();
construct_hash_table(&rock.server_table, 10, 1);
proxy_gentag(mytag, sizeof(mytag));
if ((listargs->sel & LIST_SEL_SUBSCRIBED) &&
!(listargs->sel & (LIST_SEL_SPECIALUSE | LIST_SEL_METADATA))) {
/* Subscriptions are the only selection criteria.
Send client request as-is to backend_inbox.
Responses will be piped to the client as we build subs list.
*/
list_data_remote(backend_inbox, mytag, listargs, rock.subs);
/* Don't proxy to backend_inbox again */
hash_insert(backend_inbox->hostname,
(void *)0xDEADBEEF, &rock.server_table);
}
else {
/* Multiple selection criteria or need to return subscription info.
Just fetch subscriptions without piping responses to the client.
If we send entire client request, subscribed mailboxes on
non-Inbox servers might be filtered out due to lack of metadata
to meet the selection criteria.
Note that we end up sending two requests to backend_inbox,
but there doesn't appear to be any way around this.
*/
struct listargs myargs;
memcpy(&myargs, listargs, sizeof(struct listargs));
myargs.sel = LIST_SEL_SUBSCRIBED;
myargs.ret = 0;
list_data_remote(backend_inbox, mytag, &myargs, rock.subs);
}
/* find */
mboxlist_findallmulti(&imapd_namespace, &listargs->pat,
imapd_userisadmin, imapd_userid,
imapd_authstate, list_cb, &rock);
strarray_free(rock.subs);
free_hash_table(&rock.server_table, NULL);
if (rock.last_name) free(rock.last_name);
}
/* callback for mboxlist_findsub
* used by list_data_recursivematch */
static int recursivematch_cb(struct findall_data *data, void *rockp)
{
if (!data) return 0;
struct list_rock_recursivematch *rock = (struct list_rock_recursivematch *)rockp;
list_callback_calls++;
const char *extname = data->extname;
/* skip non-responsive mailboxes early, so they don't break sub folder detection */
if (!(imapd_userisadmin || (rock->listargs->sel & LIST_SEL_DAV))) {
mbname_t *mbname = (mbname_t *) data->mbname;
const char *intname;
int r;
if (!mbname) {
mbname = mbname_from_extname(extname, &imapd_namespace, imapd_userid);
}
intname = mbname_intname(mbname);
r = mboxname_iscalendarmailbox(intname, 0) ||
mboxname_isaddressbookmailbox(intname, 0) ||
mboxname_isdavdrivemailbox(intname, 0) ||
mboxname_isdavnotificationsmailbox(intname, 0);
if (!data->mbname) mbname_free(&mbname);
if (r) return 0;
}
uint32_t *list_info = hash_lookup(extname, &rock->table);
if (!list_info) {
list_info = xzmalloc(sizeof(uint32_t));
hash_insert(extname, list_info, &rock->table);
rock->count++;
}
if (data->mbname) { /* exact match */
*list_info |= MBOX_ATTRIBUTE_SUBSCRIBED;
}
else {
*list_info |= MBOX_ATTRIBUTE_CHILDINFO_SUBSCRIBED | MBOX_ATTRIBUTE_HASCHILDREN;
}
return 0;
}
/* callback for hash_enumerate */
static void copy_to_array(const char *key, void *data, void *void_rock)
{
uint32_t *attributes = (uint32_t *)data;
struct list_rock_recursivematch *rock =
(struct list_rock_recursivematch *)void_rock;
assert(rock->count > 0);
rock->array[--rock->count].name = key;
rock->array[rock->count].attributes = *attributes;
}
/* Comparator for sorting an array of struct list_entry by mboxname. */
static int list_entry_comparator(const void *p1, const void *p2) {
const struct list_entry *e1 = (struct list_entry *)p1;
const struct list_entry *e2 = (struct list_entry *)p2;
return bsearch_compare_mbox(e1->name, e2->name);
}
static void list_data_recursivematch(struct listargs *listargs) {
struct list_rock_recursivematch rock;
rock.count = 0;
rock.listargs = listargs;
construct_hash_table(&rock.table, 100, 1);
/* find */
mboxlist_findsubmulti(&imapd_namespace, &listargs->pat, imapd_userisadmin, imapd_userid,
imapd_authstate, recursivematch_cb, &rock, 1);
if (rock.count) {
int i;
int entries = rock.count;
/* sort */
rock.array = xmalloc(entries * (sizeof(struct list_entry)));
hash_enumerate(&rock.table, copy_to_array, &rock);
qsort(rock.array, entries, sizeof(struct list_entry),
list_entry_comparator);
assert(rock.count == 0);
/* print */
for (i = 0; i < entries; i++) {
if (!rock.array[i].name) continue;
mbentry_t *mbentry = NULL;
mboxlist_lookup(rock.array[i].name, &mbentry, NULL);
list_response(rock.array[i].name,
mbentry,
rock.array[i].attributes,
rock.listargs);
mboxlist_entry_free(&mbentry);
}
free(rock.array);
}
free_hash_table(&rock.table, free);
}
/* Retrieves the data and prints the untagged responses for a LIST command. */
static void list_data(struct listargs *listargs)
{
canonical_list_patterns(listargs->ref, &listargs->pat);
/* Check to see if we should only list the personal namespace */
if (!(listargs->cmd == LIST_CMD_EXTENDED)
&& !strcmp(listargs->pat.data[0], "*")
&& config_getswitch(IMAPOPT_FOOLSTUPIDCLIENTS)) {
strarray_set(&listargs->pat, 0, "INBOX*");
}
if ((listargs->ret & LIST_RET_SUBSCRIBED) &&
(backend_inbox || (backend_inbox = proxy_findinboxserver(imapd_userid)))) {
list_data_remotesubscriptions(listargs);
}
else if (listargs->sel & LIST_SEL_RECURSIVEMATCH) {
list_data_recursivematch(listargs);
}
else {
struct list_rock rock;
memset(&rock, 0, sizeof(struct list_rock));
rock.listargs = listargs;
if (listargs->sel & LIST_SEL_SUBSCRIBED) {
mboxlist_findsubmulti(&imapd_namespace, &listargs->pat,
imapd_userisadmin, imapd_userid,
imapd_authstate, subscribed_cb, &rock, 1);
}
else {
if (config_mupdate_server) {
/* In case we proxy to backends due to select/return criteria */
construct_hash_table(&rock.server_table, 10, 1);
}
/* XXX: is there a cheaper way to figure out \Subscribed? */
if (listargs->ret & LIST_RET_SUBSCRIBED) {
rock.subs = mboxlist_sublist(imapd_userid);
}
mboxlist_findallmulti(&imapd_namespace, &listargs->pat,
imapd_userisadmin, imapd_userid,
imapd_authstate, list_cb, &rock);
if (rock.subs) strarray_free(rock.subs);
if (rock.server_table.size)
free_hash_table(&rock.server_table, NULL);
}
if (rock.last_name) free(rock.last_name);
}
}
/*
* Retrieves the data and prints the untagged responses for a LIST command in
* the case of a remote inbox.
*/
static int list_data_remote(struct backend *be, char *tag,
struct listargs *listargs, strarray_t *subs)
{
if ((listargs->cmd == LIST_CMD_EXTENDED) &&
!CAPA(be, CAPA_LISTEXTENDED)) {
/* client wants to use extended list command but backend doesn't
* support it */
prot_printf(imapd_out,
"%s NO Backend server does not support LIST-EXTENDED\r\n",
tag);
return IMAP_MAILBOX_NOTSUPPORTED;
}
/* print tag, command and list selection options */
if (listargs->cmd == LIST_CMD_LSUB) {
prot_printf(be->out, "%s Lsub ", tag);
} else if (listargs->cmd == LIST_CMD_XLIST) {
prot_printf(be->out, "%s Xlist ", tag);
} else {
prot_printf(be->out, "%s List ", tag);
uint32_t select_mask = listargs->sel;
if (be != backend_inbox) {
/* don't send subscribed selection options to non-Inbox backend */
select_mask &= ~(LIST_SEL_SUBSCRIBED | LIST_SEL_RECURSIVEMATCH);
}
/* print list selection options */
if (select_mask) {
const char *select_opts[] = {
/* XXX MUST be in same order as LIST_SEL_* bitmask */
"subscribed", "remote", "recursivematch",
"special-use", "vendor.cmu-dav", "metadata", NULL
};
char c = '(';
int i;
for (i = 0; select_opts[i]; i++) {
unsigned opt = (1 << i);
if (!(select_mask & opt)) continue;
prot_printf(be->out, "%c%s", c, select_opts[i]);
c = ' ';
if (opt == LIST_SEL_METADATA) {
/* print metadata options */
prot_puts(be->out, " (depth ");
if (listargs->metaopts.depth < 0) {
prot_puts(be->out, "infinity");
}
else {
prot_printf(be->out, "%d",
listargs->metaopts.depth);
}
if (listargs->metaopts.maxsize) {
prot_printf(be->out, " maxsize %zu",
listargs->metaopts.maxsize);
}
(void)prot_putc(')', be->out);
}
}
prot_puts(be->out, ") ");
}
}
/* print reference argument */
prot_printf(be->out,
"{%tu+}\r\n%s ", strlen(listargs->ref), listargs->ref);
/* print mailbox pattern(s) */
if (listargs->pat.count > 1) {
char **p;
char c = '(';
for (p = listargs->pat.data ; *p ; p++) {
prot_printf(be->out,
"%c{%tu+}\r\n%s", c, strlen(*p), *p);
c = ' ';
}
(void)prot_putc(')', be->out);
} else {
prot_printf(be->out, "{%tu+}\r\n%s",
strlen(listargs->pat.data[0]), listargs->pat.data[0]);
}
/* print list return options */
if (listargs->ret && listargs->cmd == LIST_CMD_EXTENDED) {
const char *return_opts[] = {
/* XXX MUST be in same order as LIST_RET_* bitmask */
"subscribed", "children", "special-use",
"status ", "myrights", "metadata ", NULL
};
char c = '(';
int i, j;
prot_puts(be->out, " return ");
for (i = 0; return_opts[i]; i++) {
unsigned opt = (1 << i);
if (!(listargs->ret & opt)) continue;
prot_printf(be->out, "%c%s", c, return_opts[i]);
c = ' ';
if (opt == LIST_RET_STATUS) {
/* print status items */
const char *status_items[] = {
/* XXX MUST be in same order as STATUS_* bitmask */
"messages", "recent", "uidnext", "uidvalidity", "unseen",
"highestmodseq", "xconvexists", "xconvunseen",
"xconvmodseq", NULL
};
c = '(';
for (j = 0; status_items[j]; j++) {
if (!(listargs->statusitems & (1 << j))) continue;
prot_printf(be->out, "%c%s", c, status_items[j]);
c = ' ';
}
(void)prot_putc(')', be->out);
}
else if (opt == LIST_RET_METADATA) {
/* print metadata items */
int n = strarray_size(&listargs->metaitems);
c = '(';
for (j = 0; j < n; j++) {
prot_printf(be->out, "%c\"%s\"", c,
strarray_nth(&listargs->metaitems, j));
c = ' ';
}
(void)prot_putc(')', be->out);
}
}
(void)prot_putc(')', be->out);
}
prot_printf(be->out, "\r\n");
pipe_lsub(be, imapd_userid, tag, 0, listargs, subs);
return 0;
}
/* Reset the given sasl_conn_t to a sane state */
static int reset_saslconn(sasl_conn_t **conn)
{
int ret;
sasl_security_properties_t *secprops = NULL;
sasl_dispose(conn);
/* do initialization typical of service_main */
ret = sasl_server_new("imap", config_servername,
NULL, NULL, NULL,
NULL, 0, conn);
if(ret != SASL_OK) return ret;
if(saslprops.ipremoteport)
ret = sasl_setprop(*conn, SASL_IPREMOTEPORT,
saslprops.ipremoteport);
if(ret != SASL_OK) return ret;
if(saslprops.iplocalport)
ret = sasl_setprop(*conn, SASL_IPLOCALPORT,
saslprops.iplocalport);
if(ret != SASL_OK) return ret;
secprops = mysasl_secprops(0);
ret = sasl_setprop(*conn, SASL_SEC_PROPS, secprops);
if(ret != SASL_OK) return ret;
/* end of service_main initialization excepting SSF */
/* If we have TLS/SSL info, set it */
if(saslprops.ssf) {
ret = sasl_setprop(*conn, SASL_SSF_EXTERNAL, &saslprops.ssf);
} else {
ret = sasl_setprop(*conn, SASL_SSF_EXTERNAL, &extprops_ssf);
}
if(ret != SASL_OK) return ret;
if(saslprops.authid) {
ret = sasl_setprop(*conn, SASL_AUTH_EXTERNAL, saslprops.authid);
if(ret != SASL_OK) return ret;
}
/* End TLS/SSL Info */
return SASL_OK;
}
static void cmd_mupdatepush(char *tag, char *name)
{
int r = 0, retry = 0;
mbentry_t *mbentry = NULL;
char buf[MAX_PARTITION_LEN + HOSTNAME_SIZE + 2];
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
if (!imapd_userisadmin) {
r = IMAP_PERMISSION_DENIED;
goto done;
}
if (!config_mupdate_server) {
r = IMAP_SERVER_UNAVAILABLE;
goto done;
}
r = mlookup(tag, name, intname, &mbentry);
if (r) goto done;
/* Push mailbox to mupdate server */
if (!mupdate_h) {
syslog(LOG_INFO, "XFER: connecting to mupdate '%s'",
config_mupdate_server);
r = mupdate_connect(config_mupdate_server, NULL, &mupdate_h, NULL);
retry = 1;
if (r) {
syslog(LOG_INFO, "Failed to connect to mupdate '%s'",
config_mupdate_server);
goto done;
}
}
snprintf(buf, sizeof(buf), "%s!%s",
config_servername, mbentry->partition);
retry:
r = mupdate_activate(mupdate_h, intname, buf, mbentry->acl);
if (r && !retry) {
syslog(LOG_INFO, "MUPDATE: lost connection, retrying");
mupdate_disconnect(&mupdate_h);
r = mupdate_connect(config_mupdate_server, NULL, &mupdate_h, NULL);
if (r) {
syslog(LOG_INFO, "Failed to connect to mupdate '%s'",
config_mupdate_server);
}
else {
retry = 1;
goto retry;
}
}
done:
mboxlist_entry_free(&mbentry);
free(intname);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
}
else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
}
#ifdef HAVE_SSL
enum {
URLAUTH_ALG_HMAC_SHA1 = 0 /* HMAC-SHA1 */
};
static void cmd_urlfetch(char *tag)
{
struct mboxkey *mboxkey_db;
int c, r, doclose;
static struct buf arg, param;
struct imapurl url;
struct index_state *state;
uint32_t msgno;
mbentry_t *mbentry = NULL;
time_t now = time(NULL);
unsigned extended, params;
prot_printf(imapd_out, "* URLFETCH");
do {
char *intname = NULL;
extended = params = 0;
/* See if its an extended URLFETCH */
c = prot_getc(imapd_in);
if (c == '(') extended = 1;
else prot_ungetc(c, imapd_in);
c = getastring(imapd_in, imapd_out, &arg);
(void)prot_putc(' ', imapd_out);
prot_printstring(imapd_out, arg.s);
if (extended) {
while (c == ' ') {
c = getword(imapd_in, ¶m);
ucase(param.s);
if (!strcmp(param.s, "BODY")) {
if (params & (URLFETCH_BODY | URLFETCH_BINARY)) goto badext;
params |= URLFETCH_BODY;
} else if (!strcmp(param.s, "BINARY")) {
if (params & (URLFETCH_BODY | URLFETCH_BINARY)) goto badext;
params |= URLFETCH_BINARY;
} else if (!strcmp(param.s, "BODYPARTSTRUCTURE")) {
if (params & URLFETCH_BODYPARTSTRUCTURE) goto badext;
params |= URLFETCH_BODYPARTSTRUCTURE;
} else {
goto badext;
}
}
if (c != ')') goto badext;
c = prot_getc(imapd_in);
}
doclose = 0;
r = imapurl_fromURL(&url, arg.s);
/* validate the URL */
if (r || !url.user || !url.server || !url.mailbox || !url.uid ||
(url.section && !*url.section) ||
(url.urlauth.access && !(url.urlauth.mech && url.urlauth.token))) {
/* missing info */
r = IMAP_BADURL;
} else if (strcmp(url.server, config_servername)) {
/* wrong server */
r = IMAP_BADURL;
} else if (url.urlauth.expire &&
url.urlauth.expire < mktime(gmtime(&now))) {
/* expired */
r = IMAP_BADURL;
} else if (url.urlauth.access) {
/* check mechanism & authorization */
int authorized = 0;
if (!strcasecmp(url.urlauth.mech, "INTERNAL")) {
if (!strncasecmp(url.urlauth.access, "submit+", 7) &&
global_authisa(imapd_authstate, IMAPOPT_SUBMITSERVERS)) {
/* authorized submit server */
authorized = 1;
} else if (!strncasecmp(url.urlauth.access, "user+", 5) &&
!strcmp(url.urlauth.access+5, imapd_userid)) {
/* currently authorized user */
authorized = 1;
} else if (!strcasecmp(url.urlauth.access, "authuser") &&
strcmp(imapd_userid, "anonymous")) {
/* any non-anonymous authorized user */
authorized = 1;
} else if (!strcasecmp(url.urlauth.access, "anonymous")) {
/* anyone */
authorized = 1;
}
}
if (!authorized) r = IMAP_BADURL;
}
if (r) goto err;
intname = mboxname_from_external(url.mailbox, &imapd_namespace, url.user);
r = mlookup(NULL, NULL, intname, &mbentry);
if (r) goto err;
if ((mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
struct backend *be;
be = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!be) {
r = IMAP_SERVER_UNAVAILABLE;
} else {
/* XXX proxy command to backend */
}
free(url.freeme);
mboxlist_entry_free(&mbentry);
free(intname);
continue;
}
mboxlist_entry_free(&mbentry);
/* local mailbox */
if (url.urlauth.token) {
/* validate the URLAUTH token */
/* yes, this is evil, in-place conversion from hex
* to binary */
if (hex_to_bin(url.urlauth.token, 0,
(unsigned char *) url.urlauth.token) < 1) {
r = IMAP_BADURL;
break;
}
/* first byte is the algorithm used to create token */
switch (url.urlauth.token[0]) {
case URLAUTH_ALG_HMAC_SHA1: {
const char *key;
size_t keylen;
unsigned char vtoken[EVP_MAX_MD_SIZE];
unsigned int vtoken_len;
r = mboxkey_open(url.user, 0, &mboxkey_db);
if (r) break;
r = mboxkey_read(mboxkey_db, intname, &key, &keylen);
if (r) break;
HMAC(EVP_sha1(), key, keylen, (unsigned char *) arg.s,
url.urlauth.rump_len, vtoken, &vtoken_len);
mboxkey_close(mboxkey_db);
if (memcmp(vtoken, url.urlauth.token+1, vtoken_len)) {
r = IMAP_BADURL;
}
break;
}
default:
r = IMAP_BADURL;
break;
}
}
if (r) goto err;
if (!strcmp(index_mboxname(imapd_index), intname)) {
state = imapd_index;
}
else {
/* not the currently selected mailbox, so try to open it */
r = index_open(intname, NULL, &state);
if (!r)
doclose = 1;
if (!r && !url.urlauth.access &&
!(state->myrights & ACL_READ)) {
r = (imapd_userisadmin ||
(state->myrights & ACL_LOOKUP)) ?
IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT;
}
}
if (r) goto err;
if (url.uidvalidity &&
(state->mailbox->i.uidvalidity != url.uidvalidity)) {
r = IMAP_BADURL;
} else if (!url.uid || !(msgno = index_finduid(state, url.uid)) ||
(index_getuid(state, msgno) != url.uid)) {
r = IMAP_BADURL;
} else {
r = index_urlfetch(state, msgno, params, url.section,
url.start_octet, url.octet_count,
imapd_out, NULL);
}
if (doclose)
index_close(&state);
err:
free(url.freeme);
if (r) prot_printf(imapd_out, " NIL");
free(intname);
} while (c == ' ');
prot_printf(imapd_out, "\r\n");
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to URLFETCH\r\n", tag);
eatline(imapd_in, c);
}
else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
return;
badext:
prot_printf(imapd_out, " NIL\r\n");
prot_printf(imapd_out,
"%s BAD Invalid extended URLFETCH parameters\r\n", tag);
eatline(imapd_in, c);
}
#define MBOX_KEY_LEN 16 /* 128 bits */
static void cmd_genurlauth(char *tag)
{
struct mboxkey *mboxkey_db;
int first = 1;
int c, r;
static struct buf arg1, arg2;
struct imapurl url;
char newkey[MBOX_KEY_LEN];
char *urlauth = NULL;
const char *key;
size_t keylen;
unsigned char token[EVP_MAX_MD_SIZE+1]; /* +1 for algorithm */
unsigned int token_len;
mbentry_t *mbentry = NULL;
time_t now = time(NULL);
r = mboxkey_open(imapd_userid, MBOXKEY_CREATE, &mboxkey_db);
if (r) {
prot_printf(imapd_out,
"%s NO Cannot open mailbox key db for %s: %s\r\n",
tag, imapd_userid, error_message(r));
return;
}
do {
char *intname = NULL;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing required argument to Genurlauth\r\n",
tag);
eatline(imapd_in, c);
return;
}
c = getword(imapd_in, &arg2);
if (strcasecmp(arg2.s, "INTERNAL")) {
prot_printf(imapd_out,
"%s BAD Unknown auth mechanism to Genurlauth %s\r\n",
tag, arg2.s);
eatline(imapd_in, c);
return;
}
r = imapurl_fromURL(&url, arg1.s);
/* validate the URL */
if (r || !url.user || !url.server || !url.mailbox || !url.uid ||
(url.section && !*url.section) || !url.urlauth.access) {
r = IMAP_BADURL;
} else if (strcmp(url.user, imapd_userid)) {
/* not using currently authorized user's namespace */
r = IMAP_BADURL;
} else if (strcmp(url.server, config_servername)) {
/* wrong server */
r = IMAP_BADURL;
} else if (url.urlauth.expire &&
url.urlauth.expire < mktime(gmtime(&now))) {
/* already expired */
r = IMAP_BADURL;
}
if (r) goto err;
intname = mboxname_from_external(url.mailbox, &imapd_namespace, imapd_userid);
r = mlookup(NULL, NULL, intname, &mbentry);
if (r) {
prot_printf(imapd_out,
"%s BAD Poorly specified URL to Genurlauth %s\r\n",
tag, arg1.s);
eatline(imapd_in, c);
free(url.freeme);
free(intname);
return;
}
if (mbentry->mbtype & MBTYPE_REMOTE) {
/* XXX proxy to backend */
mboxlist_entry_free(&mbentry);
free(url.freeme);
free(intname);
continue;
}
mboxlist_entry_free(&mbentry);
/* lookup key */
r = mboxkey_read(mboxkey_db, intname, &key, &keylen);
if (r) {
syslog(LOG_ERR, "DBERROR: error fetching mboxkey: %s",
cyrusdb_strerror(r));
}
else if (!key) {
/* create a new key */
RAND_bytes((unsigned char *) newkey, MBOX_KEY_LEN);
key = newkey;
keylen = MBOX_KEY_LEN;
r = mboxkey_write(mboxkey_db, intname, key, keylen);
if (r) {
syslog(LOG_ERR, "DBERROR: error writing new mboxkey: %s",
cyrusdb_strerror(r));
}
}
if (r) {
err:
eatline(imapd_in, c);
prot_printf(imapd_out,
"%s NO Error authorizing %s: %s\r\n",
tag, arg1.s, cyrusdb_strerror(r));
free(url.freeme);
free(intname);
return;
}
/* first byte is the algorithm used to create token */
token[0] = URLAUTH_ALG_HMAC_SHA1;
HMAC(EVP_sha1(), key, keylen, (unsigned char *) arg1.s, strlen(arg1.s),
token+1, &token_len);
token_len++;
urlauth = xrealloc(urlauth, strlen(arg1.s) + 10 +
2 * (EVP_MAX_MD_SIZE+1) + 1);
strcpy(urlauth, arg1.s);
strcat(urlauth, ":internal:");
bin_to_hex(token, token_len, urlauth+strlen(urlauth), BH_LOWER);
if (first) {
prot_printf(imapd_out, "* GENURLAUTH");
first = 0;
}
(void)prot_putc(' ', imapd_out);
prot_printstring(imapd_out, urlauth);
free(intname);
free(url.freeme);
} while (c == ' ');
if (!first) prot_printf(imapd_out, "\r\n");
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to GENURLAUTH\r\n", tag);
eatline(imapd_in, c);
}
else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
free(urlauth);
mboxkey_close(mboxkey_db);
}
static void cmd_resetkey(char *tag, char *name,
char *mechanism __attribute__((unused)))
/* XXX we don't support any external mechanisms, so we ignore it */
{
int r;
if (name) {
/* delete key for specified mailbox */
struct mboxkey *mboxkey_db;
mbentry_t *mbentry = NULL;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(NULL, NULL, intname, &mbentry);
if (r) {
prot_printf(imapd_out, "%s NO Error removing key: %s\r\n",
tag, error_message(r));
free(intname);
return;
}
if (mbentry->mbtype & MBTYPE_REMOTE) {
/* XXX proxy to backend */
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
mboxlist_entry_free(&mbentry);
r = mboxkey_open(imapd_userid, MBOXKEY_CREATE, &mboxkey_db);
if (!r) {
r = mboxkey_write(mboxkey_db, intname, NULL, 0);
mboxkey_close(mboxkey_db);
}
if (r) {
prot_printf(imapd_out, "%s NO Error removing key: %s\r\n",
tag, cyrusdb_strerror(r));
} else {
prot_printf(imapd_out,
"%s OK [URLMECH INTERNAL] key removed\r\n", tag);
}
free(intname);
}
else {
/* delete ALL keys */
/* XXX what do we do about multiple backends? */
r = mboxkey_delete_user(imapd_userid);
if (r) {
prot_printf(imapd_out, "%s NO Error removing keys: %s\r\n",
tag, cyrusdb_strerror(r));
} else {
prot_printf(imapd_out, "%s OK All keys removed\r\n", tag);
}
}
}
#endif /* HAVE_SSL */
#ifdef HAVE_ZLIB
static void cmd_compress(char *tag, char *alg)
{
if (imapd_compress_done) {
prot_printf(imapd_out,
"%s BAD [COMPRESSIONACTIVE] DEFLATE active via COMPRESS\r\n",
tag);
}
#if defined(HAVE_SSL) && (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
else if (imapd_tls_comp) {
prot_printf(imapd_out,
"%s NO [COMPRESSIONACTIVE] %s active via TLS\r\n",
tag, SSL_COMP_get_name(imapd_tls_comp));
}
#endif // defined(HAVE_SSL) && (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
else if (strcasecmp(alg, "DEFLATE")) {
prot_printf(imapd_out,
"%s NO Unknown COMPRESS algorithm: %s\r\n", tag, alg);
}
else if (ZLIB_VERSION[0] != zlibVersion()[0]) {
prot_printf(imapd_out,
"%s NO Error initializing %s (incompatible zlib version)\r\n",
tag, alg);
}
else {
prot_printf(imapd_out,
"%s OK %s active\r\n", tag, alg);
/* enable (de)compression for the prot layer */
prot_setcompress(imapd_in);
prot_setcompress(imapd_out);
imapd_compress_done = 1;
}
}
#endif /* HAVE_ZLIB */
static void cmd_enable(char *tag)
{
static struct buf arg;
int c;
unsigned new_capa = 0;
/* RFC5161 says that enable while selected is actually bogus,
* but it's no skin off our nose to support it, so don't
* bother checking */
do {
c = getword(imapd_in, &arg);
if (!arg.s[0]) {
prot_printf(imapd_out,
"\r\n%s BAD Missing required argument to Enable\r\n",
tag);
eatline(imapd_in, c);
return;
}
if (!strcasecmp(arg.s, "condstore"))
new_capa |= CAPA_CONDSTORE;
else if (!strcasecmp(arg.s, "qresync"))
new_capa |= CAPA_QRESYNC | CAPA_CONDSTORE;
} while (c == ' ');
/* check for CRLF */
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Enable\r\n", tag);
eatline(imapd_in, c);
return;
}
int started = 0;
if (!(client_capa & CAPA_CONDSTORE) &&
(new_capa & CAPA_CONDSTORE)) {
if (!started) prot_printf(imapd_out, "* ENABLED");
started = 1;
prot_printf(imapd_out, " CONDSTORE");
}
if (!(client_capa & CAPA_QRESYNC) &&
(new_capa & CAPA_QRESYNC)) {
if (!started) prot_printf(imapd_out, "* ENABLED");
started = 1;
prot_printf(imapd_out, " QRESYNC");
}
if (started) prot_printf(imapd_out, "\r\n");
/* track the new capabilities */
client_capa |= new_capa;
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
static void cmd_xkillmy(const char *tag, const char *cmdname)
{
char *cmd = xstrdup(cmdname);
char *p;
/* normalise to imapd conventions */
if (Uislower(cmd[0]))
cmd[0] = toupper((unsigned char) cmd[0]);
for (p = cmd+1; *p; p++) {
if (Uisupper(*p)) *p = tolower((unsigned char) *p);
}
proc_killusercmd(imapd_userid, cmd, SIGUSR2);
free(cmd);
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
static void cmd_xforever(const char *tag)
{
unsigned n = 1;
int r = 0;
while (!r) {
sleep(1);
prot_printf(imapd_out, "* FOREVER %u\r\n", n++);
prot_flush(imapd_out);
r = cmd_cancelled();
}
prot_printf(imapd_out, "%s OK %s\r\n", tag, error_message(r));
}
static void cmd_xmeid(const char *tag, const char *id)
{
mboxevent_set_client_id(id);
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
/***************************** server-side sync *****************************/
static void cmd_syncapply(const char *tag, struct dlist *kin, struct sync_reserve_list *reserve_list)
{
struct sync_state sync_state = {
imapd_userid,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_authstate,
&imapd_namespace,
imapd_out,
0 /* local_only */
};
/* administrators only please */
if (!imapd_userisadmin) {
syslog(LOG_ERR, "SYNCERROR: invalid user %s trying to sync", imapd_userid);
prot_printf(imapd_out, "%s NO only admininstrators may use sync commands\r\n", tag);
return;
}
const char *resp = sync_apply(kin, reserve_list, &sync_state);
prot_printf(imapd_out, "%s %s\r\n", tag, resp);
/* Reset inactivity timer in case we spent a long time processing data */
prot_resettimeout(imapd_in);
}
static void cmd_syncget(const char *tag, struct dlist *kin)
{
struct sync_state sync_state = {
imapd_userid,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_authstate,
&imapd_namespace,
imapd_out,
0 /* local_only */
};
/* administrators only please */
if (!imapd_userisadmin) {
syslog(LOG_ERR, "SYNCERROR: invalid user %s trying to sync", imapd_userid);
prot_printf(imapd_out, "%s NO only admininstrators may use sync commands\r\n", tag);
return;
}
const char *resp = sync_get(kin, &sync_state);
prot_printf(imapd_out, "%s %s\r\n", tag, resp);
/* Reset inactivity timer in case we spent a long time processing data */
prot_resettimeout(imapd_in);
}
/* partition_list is simple linked list of names used by cmd_syncrestart */
struct partition_list {
struct partition_list *next;
char *name;
};
static struct partition_list *
partition_list_add(char *name, struct partition_list *pl)
{
struct partition_list *p;
/* Is name already on list? */
for (p=pl; p; p = p->next) {
if (!strcmp(p->name, name))
return(pl);
}
/* Add entry to start of list and return new list */
p = xzmalloc(sizeof(struct partition_list));
p->next = pl;
p->name = xstrdup(name);
return(p);
}
static void
partition_list_free(struct partition_list *current)
{
while (current) {
struct partition_list *next = current->next;
free(current->name);
free(current);
current = next;
}
}
static void cmd_syncrestart(const char *tag, struct sync_reserve_list **reserve_listp, int re_alloc)
{
struct sync_reserve *res;
struct sync_reserve_list *l = *reserve_listp;
struct sync_msgid *msg;
int hash_size = l->hash_size;
struct partition_list *p, *pl = NULL;
for (res = l->head; res; res = res->next) {
for (msg = res->list->head; msg; msg = msg->next) {
if (!msg->fname) continue;
pl = partition_list_add(res->part, pl);
unlink(msg->fname);
}
}
sync_reserve_list_free(reserve_listp);
/* Remove all <partition>/sync./<pid> directories referred to above */
for (p=pl; p ; p = p->next) {
static char buf[MAX_MAILBOX_PATH];
snprintf(buf, MAX_MAILBOX_PATH, "%s/sync./%lu",
config_partitiondir(p->name), (unsigned long)getpid());
rmdir(buf);
/* and the archive partition too */
snprintf(buf, MAX_MAILBOX_PATH, "%s/sync./%lu",
config_archivepartitiondir(p->name), (unsigned long)getpid());
rmdir(buf);
}
partition_list_free(pl);
if (re_alloc) {
*reserve_listp = sync_reserve_list_create(hash_size);
prot_printf(imapd_out, "%s OK Restarting\r\n", tag);
}
else
*reserve_listp = NULL;
}
static void cmd_syncrestore(const char *tag, struct dlist *kin,
struct sync_reserve_list *reserve_list)
{
struct sync_state sync_state = {
imapd_userid,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_authstate,
&imapd_namespace,
imapd_out,
0 /* local_only */
};
/* administrators only please */
if (!imapd_userisadmin) {
syslog(LOG_ERR, "SYNCERROR: invalid user %s trying to sync", imapd_userid);
prot_printf(imapd_out, "%s NO only admininstrators may use sync commands\r\n", tag);
return;
}
const char *resp = sync_restore(kin, reserve_list, &sync_state);
prot_printf(imapd_out, "%s %s\r\n", tag, resp);
/* Reset inactivity timer in case we spent a long time processing data */
prot_resettimeout(imapd_in);
}
static void cmd_xapplepushservice(const char *tag,
struct applepushserviceargs *applepushserviceargs)
{
int r = 0;
strarray_t notif_mailboxes = STRARRAY_INITIALIZER;
int i;
mbentry_t *mbentry = NULL;
const char *aps_topic = config_getstring(IMAPOPT_APS_TOPIC);
if (!aps_topic) {
syslog(LOG_ERR,
"aps_topic not configured, can't complete XAPPLEPUSHSERVICE response");
prot_printf(imapd_out, "%s NO Server configuration error\r\n", tag);
return;
}
if (!buf_len(&applepushserviceargs->aps_account_id)) {
prot_printf(imapd_out, "%s NO Missing APNS account ID\r\n", tag);
return;
}
if (!buf_len(&applepushserviceargs->aps_device_token)) {
prot_printf(imapd_out, "%s NO Missing APNS device token\r\n", tag);
return;
}
if (!buf_len(&applepushserviceargs->aps_subtopic)) {
prot_printf(imapd_out, "%s NO Missing APNS sub-topic\r\n", tag);
return;
}
// v1 is inbox-only, so override the mailbox list
if (applepushserviceargs->aps_version == 1) {
strarray_truncate(&applepushserviceargs->mailboxes, 0);
strarray_push(&applepushserviceargs->mailboxes, "INBOX");
applepushserviceargs->aps_version = 1;
}
else {
// 2 is the most we support
applepushserviceargs->aps_version = 2;
}
for (i = 0; i < strarray_size(&applepushserviceargs->mailboxes); i++) {
const char *name = strarray_nth(&applepushserviceargs->mailboxes, i);
char *intname =
mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(tag, name, intname, &mbentry);
if (!r && mbentry->mbtype == 0) {
strarray_push(¬if_mailboxes, name);
if (applepushserviceargs->aps_version >= 2) {
prot_puts(imapd_out, "* XAPPLEPUSHSERVICE \"mailbox\" ");
prot_printstring(imapd_out, name);
prot_puts(imapd_out, "\r\n");
}
}
mboxlist_entry_free(&mbentry);
free(intname);
}
prot_printf(imapd_out,
"* XAPPLEPUSHSERVICE \"aps-version\" \"%d\" \"aps-topic\" \"%s\"\r\n",
applepushserviceargs->aps_version, aps_topic);
prot_printf(imapd_out, "%s OK XAPPLEPUSHSERVICE completed.\r\n", tag);
struct mboxevent *mboxevent = mboxevent_new(EVENT_APPLEPUSHSERVICE);
mboxevent_set_applepushservice(mboxevent, applepushserviceargs,
¬if_mailboxes, imapd_userid);
mboxevent_notify(&mboxevent);
mboxevent_free(&mboxevent);
buf_release(&applepushserviceargs->aps_account_id);
buf_release(&applepushserviceargs->aps_device_token);
buf_release(&applepushserviceargs->aps_subtopic);
strarray_fini(&applepushserviceargs->mailboxes);
strarray_fini(¬if_mailboxes);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2627_0 |
crossvul-cpp_data_bad_5845_16 | /*********************************************************************
*
* Filename: af_irda.c
* Version: 0.9
* Description: IrDA sockets implementation
* Status: Stable
* Author: Dag Brattli <dagb@cs.uit.no>
* Created at: Sun May 31 10:12:43 1998
* Modified at: Sat Dec 25 21:10:23 1999
* Modified by: Dag Brattli <dag@brattli.net>
* Sources: af_netroom.c, af_ax25.c, af_rose.c, af_x25.c etc.
*
* Copyright (c) 1999 Dag Brattli <dagb@cs.uit.no>
* Copyright (c) 1999-2003 Jean Tourrilhes <jt@hpl.hp.com>
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Linux-IrDA now supports four different types of IrDA sockets:
*
* o SOCK_STREAM: TinyTP connections with SAR disabled. The
* max SDU size is 0 for conn. of this type
* o SOCK_SEQPACKET: TinyTP connections with SAR enabled. TTP may
* fragment the messages, but will preserve
* the message boundaries
* o SOCK_DGRAM: IRDAPROTO_UNITDATA: TinyTP connections with Unitdata
* (unreliable) transfers
* IRDAPROTO_ULTRA: Connectionless and unreliable data
*
********************************************************************/
#include <linux/capability.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/net.h>
#include <linux/irda.h>
#include <linux/poll.h>
#include <asm/ioctls.h> /* TIOCOUTQ, TIOCINQ */
#include <asm/uaccess.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <net/irda/af_irda.h>
static int irda_create(struct net *net, struct socket *sock, int protocol, int kern);
static const struct proto_ops irda_stream_ops;
static const struct proto_ops irda_seqpacket_ops;
static const struct proto_ops irda_dgram_ops;
#ifdef CONFIG_IRDA_ULTRA
static const struct proto_ops irda_ultra_ops;
#define ULTRA_MAX_DATA 382
#endif /* CONFIG_IRDA_ULTRA */
#define IRDA_MAX_HEADER (TTP_MAX_HEADER)
/*
* Function irda_data_indication (instance, sap, skb)
*
* Received some data from TinyTP. Just queue it on the receive queue
*
*/
static int irda_data_indication(void *instance, void *sap, struct sk_buff *skb)
{
struct irda_sock *self;
struct sock *sk;
int err;
IRDA_DEBUG(3, "%s()\n", __func__);
self = instance;
sk = instance;
err = sock_queue_rcv_skb(sk, skb);
if (err) {
IRDA_DEBUG(1, "%s(), error: no more mem!\n", __func__);
self->rx_flow = FLOW_STOP;
/* When we return error, TTP will need to requeue the skb */
return err;
}
return 0;
}
/*
* Function irda_disconnect_indication (instance, sap, reason, skb)
*
* Connection has been closed. Check reason to find out why
*
*/
static void irda_disconnect_indication(void *instance, void *sap,
LM_REASON reason, struct sk_buff *skb)
{
struct irda_sock *self;
struct sock *sk;
self = instance;
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
/* Don't care about it, but let's not leak it */
if(skb)
dev_kfree_skb(skb);
sk = instance;
if (sk == NULL) {
IRDA_DEBUG(0, "%s(%p) : BUG : sk is NULL\n",
__func__, self);
return;
}
/* Prevent race conditions with irda_release() and irda_shutdown() */
bh_lock_sock(sk);
if (!sock_flag(sk, SOCK_DEAD) && sk->sk_state != TCP_CLOSE) {
sk->sk_state = TCP_CLOSE;
sk->sk_shutdown |= SEND_SHUTDOWN;
sk->sk_state_change(sk);
/* Close our TSAP.
* If we leave it open, IrLMP put it back into the list of
* unconnected LSAPs. The problem is that any incoming request
* can then be matched to this socket (and it will be, because
* it is at the head of the list). This would prevent any
* listening socket waiting on the same TSAP to get those
* requests. Some apps forget to close sockets, or hang to it
* a bit too long, so we may stay in this dead state long
* enough to be noticed...
* Note : all socket function do check sk->sk_state, so we are
* safe...
* Jean II
*/
if (self->tsap) {
irttp_close_tsap(self->tsap);
self->tsap = NULL;
}
}
bh_unlock_sock(sk);
/* Note : once we are there, there is not much you want to do
* with the socket anymore, apart from closing it.
* For example, bind() and connect() won't reset sk->sk_err,
* sk->sk_shutdown and sk->sk_flags to valid values...
* Jean II
*/
}
/*
* Function irda_connect_confirm (instance, sap, qos, max_sdu_size, skb)
*
* Connections has been confirmed by the remote device
*
*/
static void irda_connect_confirm(void *instance, void *sap,
struct qos_info *qos,
__u32 max_sdu_size, __u8 max_header_size,
struct sk_buff *skb)
{
struct irda_sock *self;
struct sock *sk;
self = instance;
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
sk = instance;
if (sk == NULL) {
dev_kfree_skb(skb);
return;
}
dev_kfree_skb(skb);
// Should be ??? skb_queue_tail(&sk->sk_receive_queue, skb);
/* How much header space do we need to reserve */
self->max_header_size = max_header_size;
/* IrTTP max SDU size in transmit direction */
self->max_sdu_size_tx = max_sdu_size;
/* Find out what the largest chunk of data that we can transmit is */
switch (sk->sk_type) {
case SOCK_STREAM:
if (max_sdu_size != 0) {
IRDA_ERROR("%s: max_sdu_size must be 0\n",
__func__);
return;
}
self->max_data_size = irttp_get_max_seg_size(self->tsap);
break;
case SOCK_SEQPACKET:
if (max_sdu_size == 0) {
IRDA_ERROR("%s: max_sdu_size cannot be 0\n",
__func__);
return;
}
self->max_data_size = max_sdu_size;
break;
default:
self->max_data_size = irttp_get_max_seg_size(self->tsap);
}
IRDA_DEBUG(2, "%s(), max_data_size=%d\n", __func__,
self->max_data_size);
memcpy(&self->qos_tx, qos, sizeof(struct qos_info));
/* We are now connected! */
sk->sk_state = TCP_ESTABLISHED;
sk->sk_state_change(sk);
}
/*
* Function irda_connect_indication(instance, sap, qos, max_sdu_size, userdata)
*
* Incoming connection
*
*/
static void irda_connect_indication(void *instance, void *sap,
struct qos_info *qos, __u32 max_sdu_size,
__u8 max_header_size, struct sk_buff *skb)
{
struct irda_sock *self;
struct sock *sk;
self = instance;
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
sk = instance;
if (sk == NULL) {
dev_kfree_skb(skb);
return;
}
/* How much header space do we need to reserve */
self->max_header_size = max_header_size;
/* IrTTP max SDU size in transmit direction */
self->max_sdu_size_tx = max_sdu_size;
/* Find out what the largest chunk of data that we can transmit is */
switch (sk->sk_type) {
case SOCK_STREAM:
if (max_sdu_size != 0) {
IRDA_ERROR("%s: max_sdu_size must be 0\n",
__func__);
kfree_skb(skb);
return;
}
self->max_data_size = irttp_get_max_seg_size(self->tsap);
break;
case SOCK_SEQPACKET:
if (max_sdu_size == 0) {
IRDA_ERROR("%s: max_sdu_size cannot be 0\n",
__func__);
kfree_skb(skb);
return;
}
self->max_data_size = max_sdu_size;
break;
default:
self->max_data_size = irttp_get_max_seg_size(self->tsap);
}
IRDA_DEBUG(2, "%s(), max_data_size=%d\n", __func__,
self->max_data_size);
memcpy(&self->qos_tx, qos, sizeof(struct qos_info));
skb_queue_tail(&sk->sk_receive_queue, skb);
sk->sk_state_change(sk);
}
/*
* Function irda_connect_response (handle)
*
* Accept incoming connection
*
*/
static void irda_connect_response(struct irda_sock *self)
{
struct sk_buff *skb;
IRDA_DEBUG(2, "%s()\n", __func__);
skb = alloc_skb(TTP_MAX_HEADER + TTP_SAR_HEADER, GFP_KERNEL);
if (skb == NULL) {
IRDA_DEBUG(0, "%s() Unable to allocate sk_buff!\n",
__func__);
return;
}
/* Reserve space for MUX_CONTROL and LAP header */
skb_reserve(skb, IRDA_MAX_HEADER);
irttp_connect_response(self->tsap, self->max_sdu_size_rx, skb);
}
/*
* Function irda_flow_indication (instance, sap, flow)
*
* Used by TinyTP to tell us if it can accept more data or not
*
*/
static void irda_flow_indication(void *instance, void *sap, LOCAL_FLOW flow)
{
struct irda_sock *self;
struct sock *sk;
IRDA_DEBUG(2, "%s()\n", __func__);
self = instance;
sk = instance;
BUG_ON(sk == NULL);
switch (flow) {
case FLOW_STOP:
IRDA_DEBUG(1, "%s(), IrTTP wants us to slow down\n",
__func__);
self->tx_flow = flow;
break;
case FLOW_START:
self->tx_flow = flow;
IRDA_DEBUG(1, "%s(), IrTTP wants us to start again\n",
__func__);
wake_up_interruptible(sk_sleep(sk));
break;
default:
IRDA_DEBUG(0, "%s(), Unknown flow command!\n", __func__);
/* Unknown flow command, better stop */
self->tx_flow = flow;
break;
}
}
/*
* Function irda_getvalue_confirm (obj_id, value, priv)
*
* Got answer from remote LM-IAS, just pass object to requester...
*
* Note : duplicate from above, but we need our own version that
* doesn't touch the dtsap_sel and save the full value structure...
*/
static void irda_getvalue_confirm(int result, __u16 obj_id,
struct ias_value *value, void *priv)
{
struct irda_sock *self;
self = priv;
if (!self) {
IRDA_WARNING("%s: lost myself!\n", __func__);
return;
}
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
/* We probably don't need to make any more queries */
iriap_close(self->iriap);
self->iriap = NULL;
/* Check if request succeeded */
if (result != IAS_SUCCESS) {
IRDA_DEBUG(1, "%s(), IAS query failed! (%d)\n", __func__,
result);
self->errno = result; /* We really need it later */
/* Wake up any processes waiting for result */
wake_up_interruptible(&self->query_wait);
return;
}
/* Pass the object to the caller (so the caller must delete it) */
self->ias_result = value;
self->errno = 0;
/* Wake up any processes waiting for result */
wake_up_interruptible(&self->query_wait);
}
/*
* Function irda_selective_discovery_indication (discovery)
*
* Got a selective discovery indication from IrLMP.
*
* IrLMP is telling us that this node is new and matching our hint bit
* filter. Wake up any process waiting for answer...
*/
static void irda_selective_discovery_indication(discinfo_t *discovery,
DISCOVERY_MODE mode,
void *priv)
{
struct irda_sock *self;
IRDA_DEBUG(2, "%s()\n", __func__);
self = priv;
if (!self) {
IRDA_WARNING("%s: lost myself!\n", __func__);
return;
}
/* Pass parameter to the caller */
self->cachedaddr = discovery->daddr;
/* Wake up process if its waiting for device to be discovered */
wake_up_interruptible(&self->query_wait);
}
/*
* Function irda_discovery_timeout (priv)
*
* Timeout in the selective discovery process
*
* We were waiting for a node to be discovered, but nothing has come up
* so far. Wake up the user and tell him that we failed...
*/
static void irda_discovery_timeout(u_long priv)
{
struct irda_sock *self;
IRDA_DEBUG(2, "%s()\n", __func__);
self = (struct irda_sock *) priv;
BUG_ON(self == NULL);
/* Nothing for the caller */
self->cachelog = NULL;
self->cachedaddr = 0;
self->errno = -ETIME;
/* Wake up process if its still waiting... */
wake_up_interruptible(&self->query_wait);
}
/*
* Function irda_open_tsap (self)
*
* Open local Transport Service Access Point (TSAP)
*
*/
static int irda_open_tsap(struct irda_sock *self, __u8 tsap_sel, char *name)
{
notify_t notify;
if (self->tsap) {
IRDA_DEBUG(0, "%s: busy!\n", __func__);
return -EBUSY;
}
/* Initialize callbacks to be used by the IrDA stack */
irda_notify_init(¬ify);
notify.connect_confirm = irda_connect_confirm;
notify.connect_indication = irda_connect_indication;
notify.disconnect_indication = irda_disconnect_indication;
notify.data_indication = irda_data_indication;
notify.udata_indication = irda_data_indication;
notify.flow_indication = irda_flow_indication;
notify.instance = self;
strncpy(notify.name, name, NOTIFY_MAX_NAME);
self->tsap = irttp_open_tsap(tsap_sel, DEFAULT_INITIAL_CREDIT,
¬ify);
if (self->tsap == NULL) {
IRDA_DEBUG(0, "%s(), Unable to allocate TSAP!\n",
__func__);
return -ENOMEM;
}
/* Remember which TSAP selector we actually got */
self->stsap_sel = self->tsap->stsap_sel;
return 0;
}
/*
* Function irda_open_lsap (self)
*
* Open local Link Service Access Point (LSAP). Used for opening Ultra
* sockets
*/
#ifdef CONFIG_IRDA_ULTRA
static int irda_open_lsap(struct irda_sock *self, int pid)
{
notify_t notify;
if (self->lsap) {
IRDA_WARNING("%s(), busy!\n", __func__);
return -EBUSY;
}
/* Initialize callbacks to be used by the IrDA stack */
irda_notify_init(¬ify);
notify.udata_indication = irda_data_indication;
notify.instance = self;
strncpy(notify.name, "Ultra", NOTIFY_MAX_NAME);
self->lsap = irlmp_open_lsap(LSAP_CONNLESS, ¬ify, pid);
if (self->lsap == NULL) {
IRDA_DEBUG( 0, "%s(), Unable to allocate LSAP!\n", __func__);
return -ENOMEM;
}
return 0;
}
#endif /* CONFIG_IRDA_ULTRA */
/*
* Function irda_find_lsap_sel (self, name)
*
* Try to lookup LSAP selector in remote LM-IAS
*
* Basically, we start a IAP query, and then go to sleep. When the query
* return, irda_getvalue_confirm will wake us up, and we can examine the
* result of the query...
* Note that in some case, the query fail even before we go to sleep,
* creating some races...
*/
static int irda_find_lsap_sel(struct irda_sock *self, char *name)
{
IRDA_DEBUG(2, "%s(%p, %s)\n", __func__, self, name);
if (self->iriap) {
IRDA_WARNING("%s(): busy with a previous query\n",
__func__);
return -EBUSY;
}
self->iriap = iriap_open(LSAP_ANY, IAS_CLIENT, self,
irda_getvalue_confirm);
if(self->iriap == NULL)
return -ENOMEM;
/* Treat unexpected wakeup as disconnect */
self->errno = -EHOSTUNREACH;
/* Query remote LM-IAS */
iriap_getvaluebyclass_request(self->iriap, self->saddr, self->daddr,
name, "IrDA:TinyTP:LsapSel");
/* Wait for answer, if not yet finished (or failed) */
if (wait_event_interruptible(self->query_wait, (self->iriap==NULL)))
/* Treat signals as disconnect */
return -EHOSTUNREACH;
/* Check what happened */
if (self->errno)
{
/* Requested object/attribute doesn't exist */
if((self->errno == IAS_CLASS_UNKNOWN) ||
(self->errno == IAS_ATTRIB_UNKNOWN))
return -EADDRNOTAVAIL;
else
return -EHOSTUNREACH;
}
/* Get the remote TSAP selector */
switch (self->ias_result->type) {
case IAS_INTEGER:
IRDA_DEBUG(4, "%s() int=%d\n",
__func__, self->ias_result->t.integer);
if (self->ias_result->t.integer != -1)
self->dtsap_sel = self->ias_result->t.integer;
else
self->dtsap_sel = 0;
break;
default:
self->dtsap_sel = 0;
IRDA_DEBUG(0, "%s(), bad type!\n", __func__);
break;
}
if (self->ias_result)
irias_delete_value(self->ias_result);
if (self->dtsap_sel)
return 0;
return -EADDRNOTAVAIL;
}
/*
* Function irda_discover_daddr_and_lsap_sel (self, name)
*
* This try to find a device with the requested service.
*
* It basically look into the discovery log. For each address in the list,
* it queries the LM-IAS of the device to find if this device offer
* the requested service.
* If there is more than one node supporting the service, we complain
* to the user (it should move devices around).
* The, we set both the destination address and the lsap selector to point
* on the service on the unique device we have found.
*
* Note : this function fails if there is more than one device in range,
* because IrLMP doesn't disconnect the LAP when the last LSAP is closed.
* Moreover, we would need to wait the LAP disconnection...
*/
static int irda_discover_daddr_and_lsap_sel(struct irda_sock *self, char *name)
{
discinfo_t *discoveries; /* Copy of the discovery log */
int number; /* Number of nodes in the log */
int i;
int err = -ENETUNREACH;
__u32 daddr = DEV_ADDR_ANY; /* Address we found the service on */
__u8 dtsap_sel = 0x0; /* TSAP associated with it */
IRDA_DEBUG(2, "%s(), name=%s\n", __func__, name);
/* Ask lmp for the current discovery log
* Note : we have to use irlmp_get_discoveries(), as opposed
* to play with the cachelog directly, because while we are
* making our ias query, le log might change... */
discoveries = irlmp_get_discoveries(&number, self->mask.word,
self->nslots);
/* Check if the we got some results */
if (discoveries == NULL)
return -ENETUNREACH; /* No nodes discovered */
/*
* Now, check all discovered devices (if any), and connect
* client only about the services that the client is
* interested in...
*/
for(i = 0; i < number; i++) {
/* Try the address in the log */
self->daddr = discoveries[i].daddr;
self->saddr = 0x0;
IRDA_DEBUG(1, "%s(), trying daddr = %08x\n",
__func__, self->daddr);
/* Query remote LM-IAS for this service */
err = irda_find_lsap_sel(self, name);
switch (err) {
case 0:
/* We found the requested service */
if(daddr != DEV_ADDR_ANY) {
IRDA_DEBUG(1, "%s(), discovered service ''%s'' in two different devices !!!\n",
__func__, name);
self->daddr = DEV_ADDR_ANY;
kfree(discoveries);
return -ENOTUNIQ;
}
/* First time we found that one, save it ! */
daddr = self->daddr;
dtsap_sel = self->dtsap_sel;
break;
case -EADDRNOTAVAIL:
/* Requested service simply doesn't exist on this node */
break;
default:
/* Something bad did happen :-( */
IRDA_DEBUG(0, "%s(), unexpected IAS query failure\n", __func__);
self->daddr = DEV_ADDR_ANY;
kfree(discoveries);
return -EHOSTUNREACH;
break;
}
}
/* Cleanup our copy of the discovery log */
kfree(discoveries);
/* Check out what we found */
if(daddr == DEV_ADDR_ANY) {
IRDA_DEBUG(1, "%s(), cannot discover service ''%s'' in any device !!!\n",
__func__, name);
self->daddr = DEV_ADDR_ANY;
return -EADDRNOTAVAIL;
}
/* Revert back to discovered device & service */
self->daddr = daddr;
self->saddr = 0x0;
self->dtsap_sel = dtsap_sel;
IRDA_DEBUG(1, "%s(), discovered requested service ''%s'' at address %08x\n",
__func__, name, self->daddr);
return 0;
}
/*
* Function irda_getname (sock, uaddr, uaddr_len, peer)
*
* Return the our own, or peers socket address (sockaddr_irda)
*
*/
static int irda_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct sockaddr_irda saddr;
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
memset(&saddr, 0, sizeof(saddr));
if (peer) {
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
saddr.sir_family = AF_IRDA;
saddr.sir_lsap_sel = self->dtsap_sel;
saddr.sir_addr = self->daddr;
} else {
saddr.sir_family = AF_IRDA;
saddr.sir_lsap_sel = self->stsap_sel;
saddr.sir_addr = self->saddr;
}
IRDA_DEBUG(1, "%s(), tsap_sel = %#x\n", __func__, saddr.sir_lsap_sel);
IRDA_DEBUG(1, "%s(), addr = %08x\n", __func__, saddr.sir_addr);
/* uaddr_len come to us uninitialised */
*uaddr_len = sizeof (struct sockaddr_irda);
memcpy(uaddr, &saddr, *uaddr_len);
return 0;
}
/*
* Function irda_listen (sock, backlog)
*
* Just move to the listen state
*
*/
static int irda_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int err = -EOPNOTSUPP;
IRDA_DEBUG(2, "%s()\n", __func__);
lock_sock(sk);
if ((sk->sk_type != SOCK_STREAM) && (sk->sk_type != SOCK_SEQPACKET) &&
(sk->sk_type != SOCK_DGRAM))
goto out;
if (sk->sk_state != TCP_LISTEN) {
sk->sk_max_ack_backlog = backlog;
sk->sk_state = TCP_LISTEN;
err = 0;
}
out:
release_sock(sk);
return err;
}
/*
* Function irda_bind (sock, uaddr, addr_len)
*
* Used by servers to register their well known TSAP
*
*/
static int irda_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sock *sk = sock->sk;
struct sockaddr_irda *addr = (struct sockaddr_irda *) uaddr;
struct irda_sock *self = irda_sk(sk);
int err;
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
if (addr_len != sizeof(struct sockaddr_irda))
return -EINVAL;
lock_sock(sk);
#ifdef CONFIG_IRDA_ULTRA
/* Special care for Ultra sockets */
if ((sk->sk_type == SOCK_DGRAM) &&
(sk->sk_protocol == IRDAPROTO_ULTRA)) {
self->pid = addr->sir_lsap_sel;
err = -EOPNOTSUPP;
if (self->pid & 0x80) {
IRDA_DEBUG(0, "%s(), extension in PID not supp!\n", __func__);
goto out;
}
err = irda_open_lsap(self, self->pid);
if (err < 0)
goto out;
/* Pretend we are connected */
sock->state = SS_CONNECTED;
sk->sk_state = TCP_ESTABLISHED;
err = 0;
goto out;
}
#endif /* CONFIG_IRDA_ULTRA */
self->ias_obj = irias_new_object(addr->sir_name, jiffies);
err = -ENOMEM;
if (self->ias_obj == NULL)
goto out;
err = irda_open_tsap(self, addr->sir_lsap_sel, addr->sir_name);
if (err < 0) {
irias_delete_object(self->ias_obj);
self->ias_obj = NULL;
goto out;
}
/* Register with LM-IAS */
irias_add_integer_attrib(self->ias_obj, "IrDA:TinyTP:LsapSel",
self->stsap_sel, IAS_KERNEL_ATTR);
irias_insert_object(self->ias_obj);
err = 0;
out:
release_sock(sk);
return err;
}
/*
* Function irda_accept (sock, newsock, flags)
*
* Wait for incoming connection
*
*/
static int irda_accept(struct socket *sock, struct socket *newsock, int flags)
{
struct sock *sk = sock->sk;
struct irda_sock *new, *self = irda_sk(sk);
struct sock *newsk;
struct sk_buff *skb;
int err;
IRDA_DEBUG(2, "%s()\n", __func__);
err = irda_create(sock_net(sk), newsock, sk->sk_protocol, 0);
if (err)
return err;
err = -EINVAL;
lock_sock(sk);
if (sock->state != SS_UNCONNECTED)
goto out;
if ((sk = sock->sk) == NULL)
goto out;
err = -EOPNOTSUPP;
if ((sk->sk_type != SOCK_STREAM) && (sk->sk_type != SOCK_SEQPACKET) &&
(sk->sk_type != SOCK_DGRAM))
goto out;
err = -EINVAL;
if (sk->sk_state != TCP_LISTEN)
goto out;
/*
* The read queue this time is holding sockets ready to use
* hooked into the SABM we saved
*/
/*
* We can perform the accept only if there is incoming data
* on the listening socket.
* So, we will block the caller until we receive any data.
* If the caller was waiting on select() or poll() before
* calling us, the data is waiting for us ;-)
* Jean II
*/
while (1) {
skb = skb_dequeue(&sk->sk_receive_queue);
if (skb)
break;
/* Non blocking operation */
err = -EWOULDBLOCK;
if (flags & O_NONBLOCK)
goto out;
err = wait_event_interruptible(*(sk_sleep(sk)),
skb_peek(&sk->sk_receive_queue));
if (err)
goto out;
}
newsk = newsock->sk;
err = -EIO;
if (newsk == NULL)
goto out;
newsk->sk_state = TCP_ESTABLISHED;
new = irda_sk(newsk);
/* Now attach up the new socket */
new->tsap = irttp_dup(self->tsap, new);
err = -EPERM; /* value does not seem to make sense. -arnd */
if (!new->tsap) {
IRDA_DEBUG(0, "%s(), dup failed!\n", __func__);
kfree_skb(skb);
goto out;
}
new->stsap_sel = new->tsap->stsap_sel;
new->dtsap_sel = new->tsap->dtsap_sel;
new->saddr = irttp_get_saddr(new->tsap);
new->daddr = irttp_get_daddr(new->tsap);
new->max_sdu_size_tx = self->max_sdu_size_tx;
new->max_sdu_size_rx = self->max_sdu_size_rx;
new->max_data_size = self->max_data_size;
new->max_header_size = self->max_header_size;
memcpy(&new->qos_tx, &self->qos_tx, sizeof(struct qos_info));
/* Clean up the original one to keep it in listen state */
irttp_listen(self->tsap);
kfree_skb(skb);
sk->sk_ack_backlog--;
newsock->state = SS_CONNECTED;
irda_connect_response(new);
err = 0;
out:
release_sock(sk);
return err;
}
/*
* Function irda_connect (sock, uaddr, addr_len, flags)
*
* Connect to a IrDA device
*
* The main difference with a "standard" connect is that with IrDA we need
* to resolve the service name into a TSAP selector (in TCP, port number
* doesn't have to be resolved).
* Because of this service name resolution, we can offer "auto-connect",
* where we connect to a service without specifying a destination address.
*
* Note : by consulting "errno", the user space caller may learn the cause
* of the failure. Most of them are visible in the function, others may come
* from subroutines called and are listed here :
* o EBUSY : already processing a connect
* o EHOSTUNREACH : bad addr->sir_addr argument
* o EADDRNOTAVAIL : bad addr->sir_name argument
* o ENOTUNIQ : more than one node has addr->sir_name (auto-connect)
* o ENETUNREACH : no node found on the network (auto-connect)
*/
static int irda_connect(struct socket *sock, struct sockaddr *uaddr,
int addr_len, int flags)
{
struct sock *sk = sock->sk;
struct sockaddr_irda *addr = (struct sockaddr_irda *) uaddr;
struct irda_sock *self = irda_sk(sk);
int err;
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
lock_sock(sk);
/* Don't allow connect for Ultra sockets */
err = -ESOCKTNOSUPPORT;
if ((sk->sk_type == SOCK_DGRAM) && (sk->sk_protocol == IRDAPROTO_ULTRA))
goto out;
if (sk->sk_state == TCP_ESTABLISHED && sock->state == SS_CONNECTING) {
sock->state = SS_CONNECTED;
err = 0;
goto out; /* Connect completed during a ERESTARTSYS event */
}
if (sk->sk_state == TCP_CLOSE && sock->state == SS_CONNECTING) {
sock->state = SS_UNCONNECTED;
err = -ECONNREFUSED;
goto out;
}
err = -EISCONN; /* No reconnect on a seqpacket socket */
if (sk->sk_state == TCP_ESTABLISHED)
goto out;
sk->sk_state = TCP_CLOSE;
sock->state = SS_UNCONNECTED;
err = -EINVAL;
if (addr_len != sizeof(struct sockaddr_irda))
goto out;
/* Check if user supplied any destination device address */
if ((!addr->sir_addr) || (addr->sir_addr == DEV_ADDR_ANY)) {
/* Try to find one suitable */
err = irda_discover_daddr_and_lsap_sel(self, addr->sir_name);
if (err) {
IRDA_DEBUG(0, "%s(), auto-connect failed!\n", __func__);
goto out;
}
} else {
/* Use the one provided by the user */
self->daddr = addr->sir_addr;
IRDA_DEBUG(1, "%s(), daddr = %08x\n", __func__, self->daddr);
/* If we don't have a valid service name, we assume the
* user want to connect on a specific LSAP. Prevent
* the use of invalid LSAPs (IrLMP 1.1 p10). Jean II */
if((addr->sir_name[0] != '\0') ||
(addr->sir_lsap_sel >= 0x70)) {
/* Query remote LM-IAS using service name */
err = irda_find_lsap_sel(self, addr->sir_name);
if (err) {
IRDA_DEBUG(0, "%s(), connect failed!\n", __func__);
goto out;
}
} else {
/* Directly connect to the remote LSAP
* specified by the sir_lsap field.
* Please use with caution, in IrDA LSAPs are
* dynamic and there is no "well-known" LSAP. */
self->dtsap_sel = addr->sir_lsap_sel;
}
}
/* Check if we have opened a local TSAP */
if (!self->tsap)
irda_open_tsap(self, LSAP_ANY, addr->sir_name);
/* Move to connecting socket, start sending Connect Requests */
sock->state = SS_CONNECTING;
sk->sk_state = TCP_SYN_SENT;
/* Connect to remote device */
err = irttp_connect_request(self->tsap, self->dtsap_sel,
self->saddr, self->daddr, NULL,
self->max_sdu_size_rx, NULL);
if (err) {
IRDA_DEBUG(0, "%s(), connect failed!\n", __func__);
goto out;
}
/* Now the loop */
err = -EINPROGRESS;
if (sk->sk_state != TCP_ESTABLISHED && (flags & O_NONBLOCK))
goto out;
err = -ERESTARTSYS;
if (wait_event_interruptible(*(sk_sleep(sk)),
(sk->sk_state != TCP_SYN_SENT)))
goto out;
if (sk->sk_state != TCP_ESTABLISHED) {
sock->state = SS_UNCONNECTED;
if (sk->sk_prot->disconnect(sk, flags))
sock->state = SS_DISCONNECTING;
err = sock_error(sk);
if (!err)
err = -ECONNRESET;
goto out;
}
sock->state = SS_CONNECTED;
/* At this point, IrLMP has assigned our source address */
self->saddr = irttp_get_saddr(self->tsap);
err = 0;
out:
release_sock(sk);
return err;
}
static struct proto irda_proto = {
.name = "IRDA",
.owner = THIS_MODULE,
.obj_size = sizeof(struct irda_sock),
};
/*
* Function irda_create (sock, protocol)
*
* Create IrDA socket
*
*/
static int irda_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
struct irda_sock *self;
IRDA_DEBUG(2, "%s()\n", __func__);
if (net != &init_net)
return -EAFNOSUPPORT;
/* Check for valid socket type */
switch (sock->type) {
case SOCK_STREAM: /* For TTP connections with SAR disabled */
case SOCK_SEQPACKET: /* For TTP connections with SAR enabled */
case SOCK_DGRAM: /* For TTP Unitdata or LMP Ultra transfers */
break;
default:
return -ESOCKTNOSUPPORT;
}
/* Allocate networking socket */
sk = sk_alloc(net, PF_IRDA, GFP_KERNEL, &irda_proto);
if (sk == NULL)
return -ENOMEM;
self = irda_sk(sk);
IRDA_DEBUG(2, "%s() : self is %p\n", __func__, self);
init_waitqueue_head(&self->query_wait);
switch (sock->type) {
case SOCK_STREAM:
sock->ops = &irda_stream_ops;
self->max_sdu_size_rx = TTP_SAR_DISABLE;
break;
case SOCK_SEQPACKET:
sock->ops = &irda_seqpacket_ops;
self->max_sdu_size_rx = TTP_SAR_UNBOUND;
break;
case SOCK_DGRAM:
switch (protocol) {
#ifdef CONFIG_IRDA_ULTRA
case IRDAPROTO_ULTRA:
sock->ops = &irda_ultra_ops;
/* Initialise now, because we may send on unbound
* sockets. Jean II */
self->max_data_size = ULTRA_MAX_DATA - LMP_PID_HEADER;
self->max_header_size = IRDA_MAX_HEADER + LMP_PID_HEADER;
break;
#endif /* CONFIG_IRDA_ULTRA */
case IRDAPROTO_UNITDATA:
sock->ops = &irda_dgram_ops;
/* We let Unitdata conn. be like seqpack conn. */
self->max_sdu_size_rx = TTP_SAR_UNBOUND;
break;
default:
sk_free(sk);
return -ESOCKTNOSUPPORT;
}
break;
default:
sk_free(sk);
return -ESOCKTNOSUPPORT;
}
/* Initialise networking socket struct */
sock_init_data(sock, sk); /* Note : set sk->sk_refcnt to 1 */
sk->sk_family = PF_IRDA;
sk->sk_protocol = protocol;
/* Register as a client with IrLMP */
self->ckey = irlmp_register_client(0, NULL, NULL, NULL);
self->mask.word = 0xffff;
self->rx_flow = self->tx_flow = FLOW_START;
self->nslots = DISCOVERY_DEFAULT_SLOTS;
self->daddr = DEV_ADDR_ANY; /* Until we get connected */
self->saddr = 0x0; /* so IrLMP assign us any link */
return 0;
}
/*
* Function irda_destroy_socket (self)
*
* Destroy socket
*
*/
static void irda_destroy_socket(struct irda_sock *self)
{
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
/* Unregister with IrLMP */
irlmp_unregister_client(self->ckey);
irlmp_unregister_service(self->skey);
/* Unregister with LM-IAS */
if (self->ias_obj) {
irias_delete_object(self->ias_obj);
self->ias_obj = NULL;
}
if (self->iriap) {
iriap_close(self->iriap);
self->iriap = NULL;
}
if (self->tsap) {
irttp_disconnect_request(self->tsap, NULL, P_NORMAL);
irttp_close_tsap(self->tsap);
self->tsap = NULL;
}
#ifdef CONFIG_IRDA_ULTRA
if (self->lsap) {
irlmp_close_lsap(self->lsap);
self->lsap = NULL;
}
#endif /* CONFIG_IRDA_ULTRA */
}
/*
* Function irda_release (sock)
*/
static int irda_release(struct socket *sock)
{
struct sock *sk = sock->sk;
IRDA_DEBUG(2, "%s()\n", __func__);
if (sk == NULL)
return 0;
lock_sock(sk);
sk->sk_state = TCP_CLOSE;
sk->sk_shutdown |= SEND_SHUTDOWN;
sk->sk_state_change(sk);
/* Destroy IrDA socket */
irda_destroy_socket(irda_sk(sk));
sock_orphan(sk);
sock->sk = NULL;
release_sock(sk);
/* Purge queues (see sock_init_data()) */
skb_queue_purge(&sk->sk_receive_queue);
/* Destroy networking socket if we are the last reference on it,
* i.e. if(sk->sk_refcnt == 0) -> sk_free(sk) */
sock_put(sk);
/* Notes on socket locking and deallocation... - Jean II
* In theory we should put pairs of sock_hold() / sock_put() to
* prevent the socket to be destroyed whenever there is an
* outstanding request or outstanding incoming packet or event.
*
* 1) This may include IAS request, both in connect and getsockopt.
* Unfortunately, the situation is a bit more messy than it looks,
* because we close iriap and kfree(self) above.
*
* 2) This may include selective discovery in getsockopt.
* Same stuff as above, irlmp registration and self are gone.
*
* Probably 1 and 2 may not matter, because it's all triggered
* by a process and the socket layer already prevent the
* socket to go away while a process is holding it, through
* sockfd_put() and fput()...
*
* 3) This may include deferred TSAP closure. In particular,
* we may receive a late irda_disconnect_indication()
* Fortunately, (tsap_cb *)->close_pend should protect us
* from that.
*
* I did some testing on SMP, and it looks solid. And the socket
* memory leak is now gone... - Jean II
*/
return 0;
}
/*
* Function irda_sendmsg (iocb, sock, msg, len)
*
* Send message down to TinyTP. This function is used for both STREAM and
* SEQPACK services. This is possible since it forces the client to
* fragment the message if necessary
*/
static int irda_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct irda_sock *self;
struct sk_buff *skb;
int err = -EPIPE;
IRDA_DEBUG(4, "%s(), len=%zd\n", __func__, len);
/* Note : socket.c set MSG_EOR on SEQPACKET sockets */
if (msg->msg_flags & ~(MSG_DONTWAIT | MSG_EOR | MSG_CMSG_COMPAT |
MSG_NOSIGNAL)) {
return -EINVAL;
}
lock_sock(sk);
if (sk->sk_shutdown & SEND_SHUTDOWN)
goto out_err;
if (sk->sk_state != TCP_ESTABLISHED) {
err = -ENOTCONN;
goto out;
}
self = irda_sk(sk);
/* Check if IrTTP is wants us to slow down */
if (wait_event_interruptible(*(sk_sleep(sk)),
(self->tx_flow != FLOW_STOP || sk->sk_state != TCP_ESTABLISHED))) {
err = -ERESTARTSYS;
goto out;
}
/* Check if we are still connected */
if (sk->sk_state != TCP_ESTABLISHED) {
err = -ENOTCONN;
goto out;
}
/* Check that we don't send out too big frames */
if (len > self->max_data_size) {
IRDA_DEBUG(2, "%s(), Chopping frame from %zd to %d bytes!\n",
__func__, len, self->max_data_size);
len = self->max_data_size;
}
skb = sock_alloc_send_skb(sk, len + self->max_header_size + 16,
msg->msg_flags & MSG_DONTWAIT, &err);
if (!skb)
goto out_err;
skb_reserve(skb, self->max_header_size + 16);
skb_reset_transport_header(skb);
skb_put(skb, len);
err = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len);
if (err) {
kfree_skb(skb);
goto out_err;
}
/*
* Just send the message to TinyTP, and let it deal with possible
* errors. No need to duplicate all that here
*/
err = irttp_data_request(self->tsap, skb);
if (err) {
IRDA_DEBUG(0, "%s(), err=%d\n", __func__, err);
goto out_err;
}
release_sock(sk);
/* Tell client how much data we actually sent */
return len;
out_err:
err = sk_stream_error(sk, msg->msg_flags, err);
out:
release_sock(sk);
return err;
}
/*
* Function irda_recvmsg_dgram (iocb, sock, msg, size, flags)
*
* Try to receive message and copy it to user. The frame is discarded
* after being read, regardless of how much the user actually read
*/
static int irda_recvmsg_dgram(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
struct sk_buff *skb;
size_t copied;
int err;
IRDA_DEBUG(4, "%s()\n", __func__);
msg->msg_namelen = 0;
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &err);
if (!skb)
return err;
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
IRDA_DEBUG(2, "%s(), Received truncated frame (%zd < %zd)!\n",
__func__, copied, size);
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
skb_free_datagram(sk, skb);
/*
* Check if we have previously stopped IrTTP and we know
* have more free space in our rx_queue. If so tell IrTTP
* to start delivering frames again before our rx_queue gets
* empty
*/
if (self->rx_flow == FLOW_STOP) {
if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) {
IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__);
self->rx_flow = FLOW_START;
irttp_flow_request(self->tsap, FLOW_START);
}
}
return copied;
}
/*
* Function irda_recvmsg_stream (iocb, sock, msg, size, flags)
*/
static int irda_recvmsg_stream(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
int noblock = flags & MSG_DONTWAIT;
size_t copied = 0;
int target, err;
long timeo;
IRDA_DEBUG(3, "%s()\n", __func__);
if ((err = sock_error(sk)) < 0)
return err;
if (sock->flags & __SO_ACCEPTCON)
return -EINVAL;
err =-EOPNOTSUPP;
if (flags & MSG_OOB)
return -EOPNOTSUPP;
err = 0;
target = sock_rcvlowat(sk, flags & MSG_WAITALL, size);
timeo = sock_rcvtimeo(sk, noblock);
msg->msg_namelen = 0;
do {
int chunk;
struct sk_buff *skb = skb_dequeue(&sk->sk_receive_queue);
if (skb == NULL) {
DEFINE_WAIT(wait);
err = 0;
if (copied >= target)
break;
prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
/*
* POSIX 1003.1g mandates this order.
*/
err = sock_error(sk);
if (err)
;
else if (sk->sk_shutdown & RCV_SHUTDOWN)
;
else if (noblock)
err = -EAGAIN;
else if (signal_pending(current))
err = sock_intr_errno(timeo);
else if (sk->sk_state != TCP_ESTABLISHED)
err = -ENOTCONN;
else if (skb_peek(&sk->sk_receive_queue) == NULL)
/* Wait process until data arrives */
schedule();
finish_wait(sk_sleep(sk), &wait);
if (err)
return err;
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
continue;
}
chunk = min_t(unsigned int, skb->len, size);
if (memcpy_toiovec(msg->msg_iov, skb->data, chunk)) {
skb_queue_head(&sk->sk_receive_queue, skb);
if (copied == 0)
copied = -EFAULT;
break;
}
copied += chunk;
size -= chunk;
/* Mark read part of skb as used */
if (!(flags & MSG_PEEK)) {
skb_pull(skb, chunk);
/* put the skb back if we didn't use it up.. */
if (skb->len) {
IRDA_DEBUG(1, "%s(), back on q!\n",
__func__);
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
kfree_skb(skb);
} else {
IRDA_DEBUG(0, "%s() questionable!?\n", __func__);
/* put message back and return */
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
} while (size);
/*
* Check if we have previously stopped IrTTP and we know
* have more free space in our rx_queue. If so tell IrTTP
* to start delivering frames again before our rx_queue gets
* empty
*/
if (self->rx_flow == FLOW_STOP) {
if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) {
IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__);
self->rx_flow = FLOW_START;
irttp_flow_request(self->tsap, FLOW_START);
}
}
return copied;
}
/*
* Function irda_sendmsg_dgram (iocb, sock, msg, len)
*
* Send message down to TinyTP for the unreliable sequenced
* packet service...
*
*/
static int irda_sendmsg_dgram(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct irda_sock *self;
struct sk_buff *skb;
int err;
IRDA_DEBUG(4, "%s(), len=%zd\n", __func__, len);
if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_CMSG_COMPAT))
return -EINVAL;
lock_sock(sk);
if (sk->sk_shutdown & SEND_SHUTDOWN) {
send_sig(SIGPIPE, current, 0);
err = -EPIPE;
goto out;
}
err = -ENOTCONN;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
self = irda_sk(sk);
/*
* Check that we don't send out too big frames. This is an unreliable
* service, so we have no fragmentation and no coalescence
*/
if (len > self->max_data_size) {
IRDA_DEBUG(0, "%s(), Warning to much data! "
"Chopping frame from %zd to %d bytes!\n",
__func__, len, self->max_data_size);
len = self->max_data_size;
}
skb = sock_alloc_send_skb(sk, len + self->max_header_size,
msg->msg_flags & MSG_DONTWAIT, &err);
err = -ENOBUFS;
if (!skb)
goto out;
skb_reserve(skb, self->max_header_size);
skb_reset_transport_header(skb);
IRDA_DEBUG(4, "%s(), appending user data\n", __func__);
skb_put(skb, len);
err = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len);
if (err) {
kfree_skb(skb);
goto out;
}
/*
* Just send the message to TinyTP, and let it deal with possible
* errors. No need to duplicate all that here
*/
err = irttp_udata_request(self->tsap, skb);
if (err) {
IRDA_DEBUG(0, "%s(), err=%d\n", __func__, err);
goto out;
}
release_sock(sk);
return len;
out:
release_sock(sk);
return err;
}
/*
* Function irda_sendmsg_ultra (iocb, sock, msg, len)
*
* Send message down to IrLMP for the unreliable Ultra
* packet service...
*/
#ifdef CONFIG_IRDA_ULTRA
static int irda_sendmsg_ultra(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct irda_sock *self;
__u8 pid = 0;
int bound = 0;
struct sk_buff *skb;
int err;
IRDA_DEBUG(4, "%s(), len=%zd\n", __func__, len);
err = -EINVAL;
if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_CMSG_COMPAT))
return -EINVAL;
lock_sock(sk);
err = -EPIPE;
if (sk->sk_shutdown & SEND_SHUTDOWN) {
send_sig(SIGPIPE, current, 0);
goto out;
}
self = irda_sk(sk);
/* Check if an address was specified with sendto. Jean II */
if (msg->msg_name) {
struct sockaddr_irda *addr = (struct sockaddr_irda *) msg->msg_name;
err = -EINVAL;
/* Check address, extract pid. Jean II */
if (msg->msg_namelen < sizeof(*addr))
goto out;
if (addr->sir_family != AF_IRDA)
goto out;
pid = addr->sir_lsap_sel;
if (pid & 0x80) {
IRDA_DEBUG(0, "%s(), extension in PID not supp!\n", __func__);
err = -EOPNOTSUPP;
goto out;
}
} else {
/* Check that the socket is properly bound to an Ultra
* port. Jean II */
if ((self->lsap == NULL) ||
(sk->sk_state != TCP_ESTABLISHED)) {
IRDA_DEBUG(0, "%s(), socket not bound to Ultra PID.\n",
__func__);
err = -ENOTCONN;
goto out;
}
/* Use PID from socket */
bound = 1;
}
/*
* Check that we don't send out too big frames. This is an unreliable
* service, so we have no fragmentation and no coalescence
*/
if (len > self->max_data_size) {
IRDA_DEBUG(0, "%s(), Warning to much data! "
"Chopping frame from %zd to %d bytes!\n",
__func__, len, self->max_data_size);
len = self->max_data_size;
}
skb = sock_alloc_send_skb(sk, len + self->max_header_size,
msg->msg_flags & MSG_DONTWAIT, &err);
err = -ENOBUFS;
if (!skb)
goto out;
skb_reserve(skb, self->max_header_size);
skb_reset_transport_header(skb);
IRDA_DEBUG(4, "%s(), appending user data\n", __func__);
skb_put(skb, len);
err = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len);
if (err) {
kfree_skb(skb);
goto out;
}
err = irlmp_connless_data_request((bound ? self->lsap : NULL),
skb, pid);
if (err)
IRDA_DEBUG(0, "%s(), err=%d\n", __func__, err);
out:
release_sock(sk);
return err ? : len;
}
#endif /* CONFIG_IRDA_ULTRA */
/*
* Function irda_shutdown (sk, how)
*/
static int irda_shutdown(struct socket *sock, int how)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
IRDA_DEBUG(1, "%s(%p)\n", __func__, self);
lock_sock(sk);
sk->sk_state = TCP_CLOSE;
sk->sk_shutdown |= SEND_SHUTDOWN;
sk->sk_state_change(sk);
if (self->iriap) {
iriap_close(self->iriap);
self->iriap = NULL;
}
if (self->tsap) {
irttp_disconnect_request(self->tsap, NULL, P_NORMAL);
irttp_close_tsap(self->tsap);
self->tsap = NULL;
}
/* A few cleanup so the socket look as good as new... */
self->rx_flow = self->tx_flow = FLOW_START; /* needed ??? */
self->daddr = DEV_ADDR_ANY; /* Until we get re-connected */
self->saddr = 0x0; /* so IrLMP assign us any link */
release_sock(sk);
return 0;
}
/*
* Function irda_poll (file, sock, wait)
*/
static unsigned int irda_poll(struct file * file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
unsigned int mask;
IRDA_DEBUG(4, "%s()\n", __func__);
poll_wait(file, sk_sleep(sk), wait);
mask = 0;
/* Exceptional events? */
if (sk->sk_err)
mask |= POLLERR;
if (sk->sk_shutdown & RCV_SHUTDOWN) {
IRDA_DEBUG(0, "%s(), POLLHUP\n", __func__);
mask |= POLLHUP;
}
/* Readable? */
if (!skb_queue_empty(&sk->sk_receive_queue)) {
IRDA_DEBUG(4, "Socket is readable\n");
mask |= POLLIN | POLLRDNORM;
}
/* Connection-based need to check for termination and startup */
switch (sk->sk_type) {
case SOCK_STREAM:
if (sk->sk_state == TCP_CLOSE) {
IRDA_DEBUG(0, "%s(), POLLHUP\n", __func__);
mask |= POLLHUP;
}
if (sk->sk_state == TCP_ESTABLISHED) {
if ((self->tx_flow == FLOW_START) &&
sock_writeable(sk))
{
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
}
}
break;
case SOCK_SEQPACKET:
if ((self->tx_flow == FLOW_START) &&
sock_writeable(sk))
{
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
}
break;
case SOCK_DGRAM:
if (sock_writeable(sk))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
break;
default:
break;
}
return mask;
}
/*
* Function irda_ioctl (sock, cmd, arg)
*/
static int irda_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk = sock->sk;
int err;
IRDA_DEBUG(4, "%s(), cmd=%#x\n", __func__, cmd);
err = -EINVAL;
switch (cmd) {
case TIOCOUTQ: {
long amount;
amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
if (amount < 0)
amount = 0;
err = put_user(amount, (unsigned int __user *)arg);
break;
}
case TIOCINQ: {
struct sk_buff *skb;
long amount = 0L;
/* These two are safe on a single CPU system as only user tasks fiddle here */
if ((skb = skb_peek(&sk->sk_receive_queue)) != NULL)
amount = skb->len;
err = put_user(amount, (unsigned int __user *)arg);
break;
}
case SIOCGSTAMP:
if (sk != NULL)
err = sock_get_timestamp(sk, (struct timeval __user *)arg);
break;
case SIOCGIFADDR:
case SIOCSIFADDR:
case SIOCGIFDSTADDR:
case SIOCSIFDSTADDR:
case SIOCGIFBRDADDR:
case SIOCSIFBRDADDR:
case SIOCGIFNETMASK:
case SIOCSIFNETMASK:
case SIOCGIFMETRIC:
case SIOCSIFMETRIC:
break;
default:
IRDA_DEBUG(1, "%s(), doing device ioctl!\n", __func__);
err = -ENOIOCTLCMD;
}
return err;
}
#ifdef CONFIG_COMPAT
/*
* Function irda_ioctl (sock, cmd, arg)
*/
static int irda_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
/*
* All IRDA's ioctl are standard ones.
*/
return -ENOIOCTLCMD;
}
#endif
/*
* Function irda_setsockopt (sock, level, optname, optval, optlen)
*
* Set some options for the socket
*
*/
static int irda_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
struct irda_ias_set *ias_opt;
struct ias_object *ias_obj;
struct ias_attrib * ias_attr; /* Attribute in IAS object */
int opt, free_ias = 0, err = 0;
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
if (level != SOL_IRLMP)
return -ENOPROTOOPT;
lock_sock(sk);
switch (optname) {
case IRLMP_IAS_SET:
/* The user want to add an attribute to an existing IAS object
* (in the IAS database) or to create a new object with this
* attribute.
* We first query IAS to know if the object exist, and then
* create the right attribute...
*/
if (optlen != sizeof(struct irda_ias_set)) {
err = -EINVAL;
goto out;
}
ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC);
if (ias_opt == NULL) {
err = -ENOMEM;
goto out;
}
/* Copy query to the driver. */
if (copy_from_user(ias_opt, optval, optlen)) {
kfree(ias_opt);
err = -EFAULT;
goto out;
}
/* Find the object we target.
* If the user gives us an empty string, we use the object
* associated with this socket. This will workaround
* duplicated class name - Jean II */
if(ias_opt->irda_class_name[0] == '\0') {
if(self->ias_obj == NULL) {
kfree(ias_opt);
err = -EINVAL;
goto out;
}
ias_obj = self->ias_obj;
} else
ias_obj = irias_find_object(ias_opt->irda_class_name);
/* Only ROOT can mess with the global IAS database.
* Users can only add attributes to the object associated
* with the socket they own - Jean II */
if((!capable(CAP_NET_ADMIN)) &&
((ias_obj == NULL) || (ias_obj != self->ias_obj))) {
kfree(ias_opt);
err = -EPERM;
goto out;
}
/* If the object doesn't exist, create it */
if(ias_obj == (struct ias_object *) NULL) {
/* Create a new object */
ias_obj = irias_new_object(ias_opt->irda_class_name,
jiffies);
if (ias_obj == NULL) {
kfree(ias_opt);
err = -ENOMEM;
goto out;
}
free_ias = 1;
}
/* Do we have the attribute already ? */
if(irias_find_attrib(ias_obj, ias_opt->irda_attrib_name)) {
kfree(ias_opt);
if (free_ias) {
kfree(ias_obj->name);
kfree(ias_obj);
}
err = -EINVAL;
goto out;
}
/* Look at the type */
switch(ias_opt->irda_attrib_type) {
case IAS_INTEGER:
/* Add an integer attribute */
irias_add_integer_attrib(
ias_obj,
ias_opt->irda_attrib_name,
ias_opt->attribute.irda_attrib_int,
IAS_USER_ATTR);
break;
case IAS_OCT_SEQ:
/* Check length */
if(ias_opt->attribute.irda_attrib_octet_seq.len >
IAS_MAX_OCTET_STRING) {
kfree(ias_opt);
if (free_ias) {
kfree(ias_obj->name);
kfree(ias_obj);
}
err = -EINVAL;
goto out;
}
/* Add an octet sequence attribute */
irias_add_octseq_attrib(
ias_obj,
ias_opt->irda_attrib_name,
ias_opt->attribute.irda_attrib_octet_seq.octet_seq,
ias_opt->attribute.irda_attrib_octet_seq.len,
IAS_USER_ATTR);
break;
case IAS_STRING:
/* Should check charset & co */
/* Check length */
/* The length is encoded in a __u8, and
* IAS_MAX_STRING == 256, so there is no way
* userspace can pass us a string too large.
* Jean II */
/* NULL terminate the string (avoid troubles) */
ias_opt->attribute.irda_attrib_string.string[ias_opt->attribute.irda_attrib_string.len] = '\0';
/* Add a string attribute */
irias_add_string_attrib(
ias_obj,
ias_opt->irda_attrib_name,
ias_opt->attribute.irda_attrib_string.string,
IAS_USER_ATTR);
break;
default :
kfree(ias_opt);
if (free_ias) {
kfree(ias_obj->name);
kfree(ias_obj);
}
err = -EINVAL;
goto out;
}
irias_insert_object(ias_obj);
kfree(ias_opt);
break;
case IRLMP_IAS_DEL:
/* The user want to delete an object from our local IAS
* database. We just need to query the IAS, check is the
* object is not owned by the kernel and delete it.
*/
if (optlen != sizeof(struct irda_ias_set)) {
err = -EINVAL;
goto out;
}
ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC);
if (ias_opt == NULL) {
err = -ENOMEM;
goto out;
}
/* Copy query to the driver. */
if (copy_from_user(ias_opt, optval, optlen)) {
kfree(ias_opt);
err = -EFAULT;
goto out;
}
/* Find the object we target.
* If the user gives us an empty string, we use the object
* associated with this socket. This will workaround
* duplicated class name - Jean II */
if(ias_opt->irda_class_name[0] == '\0')
ias_obj = self->ias_obj;
else
ias_obj = irias_find_object(ias_opt->irda_class_name);
if(ias_obj == (struct ias_object *) NULL) {
kfree(ias_opt);
err = -EINVAL;
goto out;
}
/* Only ROOT can mess with the global IAS database.
* Users can only del attributes from the object associated
* with the socket they own - Jean II */
if((!capable(CAP_NET_ADMIN)) &&
((ias_obj == NULL) || (ias_obj != self->ias_obj))) {
kfree(ias_opt);
err = -EPERM;
goto out;
}
/* Find the attribute (in the object) we target */
ias_attr = irias_find_attrib(ias_obj,
ias_opt->irda_attrib_name);
if(ias_attr == (struct ias_attrib *) NULL) {
kfree(ias_opt);
err = -EINVAL;
goto out;
}
/* Check is the user space own the object */
if(ias_attr->value->owner != IAS_USER_ATTR) {
IRDA_DEBUG(1, "%s(), attempting to delete a kernel attribute\n", __func__);
kfree(ias_opt);
err = -EPERM;
goto out;
}
/* Remove the attribute (and maybe the object) */
irias_delete_attrib(ias_obj, ias_attr, 1);
kfree(ias_opt);
break;
case IRLMP_MAX_SDU_SIZE:
if (optlen < sizeof(int)) {
err = -EINVAL;
goto out;
}
if (get_user(opt, (int __user *)optval)) {
err = -EFAULT;
goto out;
}
/* Only possible for a seqpacket service (TTP with SAR) */
if (sk->sk_type != SOCK_SEQPACKET) {
IRDA_DEBUG(2, "%s(), setting max_sdu_size = %d\n",
__func__, opt);
self->max_sdu_size_rx = opt;
} else {
IRDA_WARNING("%s: not allowed to set MAXSDUSIZE for this socket type!\n",
__func__);
err = -ENOPROTOOPT;
goto out;
}
break;
case IRLMP_HINTS_SET:
if (optlen < sizeof(int)) {
err = -EINVAL;
goto out;
}
/* The input is really a (__u8 hints[2]), easier as an int */
if (get_user(opt, (int __user *)optval)) {
err = -EFAULT;
goto out;
}
/* Unregister any old registration */
if (self->skey)
irlmp_unregister_service(self->skey);
self->skey = irlmp_register_service((__u16) opt);
break;
case IRLMP_HINT_MASK_SET:
/* As opposed to the previous case which set the hint bits
* that we advertise, this one set the filter we use when
* making a discovery (nodes which don't match any hint
* bit in the mask are not reported).
*/
if (optlen < sizeof(int)) {
err = -EINVAL;
goto out;
}
/* The input is really a (__u8 hints[2]), easier as an int */
if (get_user(opt, (int __user *)optval)) {
err = -EFAULT;
goto out;
}
/* Set the new hint mask */
self->mask.word = (__u16) opt;
/* Mask out extension bits */
self->mask.word &= 0x7f7f;
/* Check if no bits */
if(!self->mask.word)
self->mask.word = 0xFFFF;
break;
default:
err = -ENOPROTOOPT;
break;
}
out:
release_sock(sk);
return err;
}
/*
* Function irda_extract_ias_value(ias_opt, ias_value)
*
* Translate internal IAS value structure to the user space representation
*
* The external representation of IAS values, as we exchange them with
* user space program is quite different from the internal representation,
* as stored in the IAS database (because we need a flat structure for
* crossing kernel boundary).
* This function transform the former in the latter. We also check
* that the value type is valid.
*/
static int irda_extract_ias_value(struct irda_ias_set *ias_opt,
struct ias_value *ias_value)
{
/* Look at the type */
switch (ias_value->type) {
case IAS_INTEGER:
/* Copy the integer */
ias_opt->attribute.irda_attrib_int = ias_value->t.integer;
break;
case IAS_OCT_SEQ:
/* Set length */
ias_opt->attribute.irda_attrib_octet_seq.len = ias_value->len;
/* Copy over */
memcpy(ias_opt->attribute.irda_attrib_octet_seq.octet_seq,
ias_value->t.oct_seq, ias_value->len);
break;
case IAS_STRING:
/* Set length */
ias_opt->attribute.irda_attrib_string.len = ias_value->len;
ias_opt->attribute.irda_attrib_string.charset = ias_value->charset;
/* Copy over */
memcpy(ias_opt->attribute.irda_attrib_string.string,
ias_value->t.string, ias_value->len);
/* NULL terminate the string (avoid troubles) */
ias_opt->attribute.irda_attrib_string.string[ias_value->len] = '\0';
break;
case IAS_MISSING:
default :
return -EINVAL;
}
/* Copy type over */
ias_opt->irda_attrib_type = ias_value->type;
return 0;
}
/*
* Function irda_getsockopt (sock, level, optname, optval, optlen)
*/
static int irda_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
struct irda_device_list list;
struct irda_device_info *discoveries;
struct irda_ias_set * ias_opt; /* IAS get/query params */
struct ias_object * ias_obj; /* Object in IAS */
struct ias_attrib * ias_attr; /* Attribute in IAS object */
int daddr = DEV_ADDR_ANY; /* Dest address for IAS queries */
int val = 0;
int len = 0;
int err = 0;
int offset, total;
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
if (level != SOL_IRLMP)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
if(len < 0)
return -EINVAL;
lock_sock(sk);
switch (optname) {
case IRLMP_ENUMDEVICES:
/* Offset to first device entry */
offset = sizeof(struct irda_device_list) -
sizeof(struct irda_device_info);
if (len < offset) {
err = -EINVAL;
goto out;
}
/* Ask lmp for the current discovery log */
discoveries = irlmp_get_discoveries(&list.len, self->mask.word,
self->nslots);
/* Check if the we got some results */
if (discoveries == NULL) {
err = -EAGAIN;
goto out; /* Didn't find any devices */
}
/* Write total list length back to client */
if (copy_to_user(optval, &list, offset))
err = -EFAULT;
/* Copy the list itself - watch for overflow */
if (list.len > 2048) {
err = -EINVAL;
goto bed;
}
total = offset + (list.len * sizeof(struct irda_device_info));
if (total > len)
total = len;
if (copy_to_user(optval+offset, discoveries, total - offset))
err = -EFAULT;
/* Write total number of bytes used back to client */
if (put_user(total, optlen))
err = -EFAULT;
bed:
/* Free up our buffer */
kfree(discoveries);
break;
case IRLMP_MAX_SDU_SIZE:
val = self->max_data_size;
len = sizeof(int);
if (put_user(len, optlen)) {
err = -EFAULT;
goto out;
}
if (copy_to_user(optval, &val, len)) {
err = -EFAULT;
goto out;
}
break;
case IRLMP_IAS_GET:
/* The user want an object from our local IAS database.
* We just need to query the IAS and return the value
* that we found */
/* Check that the user has allocated the right space for us */
if (len != sizeof(struct irda_ias_set)) {
err = -EINVAL;
goto out;
}
ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC);
if (ias_opt == NULL) {
err = -ENOMEM;
goto out;
}
/* Copy query to the driver. */
if (copy_from_user(ias_opt, optval, len)) {
kfree(ias_opt);
err = -EFAULT;
goto out;
}
/* Find the object we target.
* If the user gives us an empty string, we use the object
* associated with this socket. This will workaround
* duplicated class name - Jean II */
if(ias_opt->irda_class_name[0] == '\0')
ias_obj = self->ias_obj;
else
ias_obj = irias_find_object(ias_opt->irda_class_name);
if(ias_obj == (struct ias_object *) NULL) {
kfree(ias_opt);
err = -EINVAL;
goto out;
}
/* Find the attribute (in the object) we target */
ias_attr = irias_find_attrib(ias_obj,
ias_opt->irda_attrib_name);
if(ias_attr == (struct ias_attrib *) NULL) {
kfree(ias_opt);
err = -EINVAL;
goto out;
}
/* Translate from internal to user structure */
err = irda_extract_ias_value(ias_opt, ias_attr->value);
if(err) {
kfree(ias_opt);
goto out;
}
/* Copy reply to the user */
if (copy_to_user(optval, ias_opt,
sizeof(struct irda_ias_set))) {
kfree(ias_opt);
err = -EFAULT;
goto out;
}
/* Note : don't need to put optlen, we checked it */
kfree(ias_opt);
break;
case IRLMP_IAS_QUERY:
/* The user want an object from a remote IAS database.
* We need to use IAP to query the remote database and
* then wait for the answer to come back. */
/* Check that the user has allocated the right space for us */
if (len != sizeof(struct irda_ias_set)) {
err = -EINVAL;
goto out;
}
ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC);
if (ias_opt == NULL) {
err = -ENOMEM;
goto out;
}
/* Copy query to the driver. */
if (copy_from_user(ias_opt, optval, len)) {
kfree(ias_opt);
err = -EFAULT;
goto out;
}
/* At this point, there are two cases...
* 1) the socket is connected - that's the easy case, we
* just query the device we are connected to...
* 2) the socket is not connected - the user doesn't want
* to connect and/or may not have a valid service name
* (so can't create a fake connection). In this case,
* we assume that the user pass us a valid destination
* address in the requesting structure...
*/
if(self->daddr != DEV_ADDR_ANY) {
/* We are connected - reuse known daddr */
daddr = self->daddr;
} else {
/* We are not connected, we must specify a valid
* destination address */
daddr = ias_opt->daddr;
if((!daddr) || (daddr == DEV_ADDR_ANY)) {
kfree(ias_opt);
err = -EINVAL;
goto out;
}
}
/* Check that we can proceed with IAP */
if (self->iriap) {
IRDA_WARNING("%s: busy with a previous query\n",
__func__);
kfree(ias_opt);
err = -EBUSY;
goto out;
}
self->iriap = iriap_open(LSAP_ANY, IAS_CLIENT, self,
irda_getvalue_confirm);
if (self->iriap == NULL) {
kfree(ias_opt);
err = -ENOMEM;
goto out;
}
/* Treat unexpected wakeup as disconnect */
self->errno = -EHOSTUNREACH;
/* Query remote LM-IAS */
iriap_getvaluebyclass_request(self->iriap,
self->saddr, daddr,
ias_opt->irda_class_name,
ias_opt->irda_attrib_name);
/* Wait for answer, if not yet finished (or failed) */
if (wait_event_interruptible(self->query_wait,
(self->iriap == NULL))) {
/* pending request uses copy of ias_opt-content
* we can free it regardless! */
kfree(ias_opt);
/* Treat signals as disconnect */
err = -EHOSTUNREACH;
goto out;
}
/* Check what happened */
if (self->errno)
{
kfree(ias_opt);
/* Requested object/attribute doesn't exist */
if((self->errno == IAS_CLASS_UNKNOWN) ||
(self->errno == IAS_ATTRIB_UNKNOWN))
err = -EADDRNOTAVAIL;
else
err = -EHOSTUNREACH;
goto out;
}
/* Translate from internal to user structure */
err = irda_extract_ias_value(ias_opt, self->ias_result);
if (self->ias_result)
irias_delete_value(self->ias_result);
if (err) {
kfree(ias_opt);
goto out;
}
/* Copy reply to the user */
if (copy_to_user(optval, ias_opt,
sizeof(struct irda_ias_set))) {
kfree(ias_opt);
err = -EFAULT;
goto out;
}
/* Note : don't need to put optlen, we checked it */
kfree(ias_opt);
break;
case IRLMP_WAITDEVICE:
/* This function is just another way of seeing life ;-)
* IRLMP_ENUMDEVICES assumes that you have a static network,
* and that you just want to pick one of the devices present.
* On the other hand, in here we assume that no device is
* present and that at some point in the future a device will
* come into range. When this device arrive, we just wake
* up the caller, so that he has time to connect to it before
* the device goes away...
* Note : once the node has been discovered for more than a
* few second, it won't trigger this function, unless it
* goes away and come back changes its hint bits (so we
* might call it IRLMP_WAITNEWDEVICE).
*/
/* Check that the user is passing us an int */
if (len != sizeof(int)) {
err = -EINVAL;
goto out;
}
/* Get timeout in ms (max time we block the caller) */
if (get_user(val, (int __user *)optval)) {
err = -EFAULT;
goto out;
}
/* Tell IrLMP we want to be notified */
irlmp_update_client(self->ckey, self->mask.word,
irda_selective_discovery_indication,
NULL, (void *) self);
/* Do some discovery (and also return cached results) */
irlmp_discovery_request(self->nslots);
/* Wait until a node is discovered */
if (!self->cachedaddr) {
IRDA_DEBUG(1, "%s(), nothing discovered yet, going to sleep...\n", __func__);
/* Set watchdog timer to expire in <val> ms. */
self->errno = 0;
setup_timer(&self->watchdog, irda_discovery_timeout,
(unsigned long)self);
mod_timer(&self->watchdog,
jiffies + msecs_to_jiffies(val));
/* Wait for IR-LMP to call us back */
err = __wait_event_interruptible(self->query_wait,
(self->cachedaddr != 0 || self->errno == -ETIME));
/* If watchdog is still activated, kill it! */
del_timer(&(self->watchdog));
IRDA_DEBUG(1, "%s(), ...waking up !\n", __func__);
if (err != 0)
goto out;
}
else
IRDA_DEBUG(1, "%s(), found immediately !\n",
__func__);
/* Tell IrLMP that we have been notified */
irlmp_update_client(self->ckey, self->mask.word,
NULL, NULL, NULL);
/* Check if the we got some results */
if (!self->cachedaddr) {
err = -EAGAIN; /* Didn't find any devices */
goto out;
}
daddr = self->cachedaddr;
/* Cleanup */
self->cachedaddr = 0;
/* We return the daddr of the device that trigger the
* wakeup. As irlmp pass us only the new devices, we
* are sure that it's not an old device.
* If the user want more details, he should query
* the whole discovery log and pick one device...
*/
if (put_user(daddr, (int __user *)optval)) {
err = -EFAULT;
goto out;
}
break;
default:
err = -ENOPROTOOPT;
}
out:
release_sock(sk);
return err;
}
static const struct net_proto_family irda_family_ops = {
.family = PF_IRDA,
.create = irda_create,
.owner = THIS_MODULE,
};
static const struct proto_ops irda_stream_ops = {
.family = PF_IRDA,
.owner = THIS_MODULE,
.release = irda_release,
.bind = irda_bind,
.connect = irda_connect,
.socketpair = sock_no_socketpair,
.accept = irda_accept,
.getname = irda_getname,
.poll = irda_poll,
.ioctl = irda_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = irda_compat_ioctl,
#endif
.listen = irda_listen,
.shutdown = irda_shutdown,
.setsockopt = irda_setsockopt,
.getsockopt = irda_getsockopt,
.sendmsg = irda_sendmsg,
.recvmsg = irda_recvmsg_stream,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static const struct proto_ops irda_seqpacket_ops = {
.family = PF_IRDA,
.owner = THIS_MODULE,
.release = irda_release,
.bind = irda_bind,
.connect = irda_connect,
.socketpair = sock_no_socketpair,
.accept = irda_accept,
.getname = irda_getname,
.poll = datagram_poll,
.ioctl = irda_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = irda_compat_ioctl,
#endif
.listen = irda_listen,
.shutdown = irda_shutdown,
.setsockopt = irda_setsockopt,
.getsockopt = irda_getsockopt,
.sendmsg = irda_sendmsg,
.recvmsg = irda_recvmsg_dgram,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static const struct proto_ops irda_dgram_ops = {
.family = PF_IRDA,
.owner = THIS_MODULE,
.release = irda_release,
.bind = irda_bind,
.connect = irda_connect,
.socketpair = sock_no_socketpair,
.accept = irda_accept,
.getname = irda_getname,
.poll = datagram_poll,
.ioctl = irda_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = irda_compat_ioctl,
#endif
.listen = irda_listen,
.shutdown = irda_shutdown,
.setsockopt = irda_setsockopt,
.getsockopt = irda_getsockopt,
.sendmsg = irda_sendmsg_dgram,
.recvmsg = irda_recvmsg_dgram,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
#ifdef CONFIG_IRDA_ULTRA
static const struct proto_ops irda_ultra_ops = {
.family = PF_IRDA,
.owner = THIS_MODULE,
.release = irda_release,
.bind = irda_bind,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = irda_getname,
.poll = datagram_poll,
.ioctl = irda_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = irda_compat_ioctl,
#endif
.listen = sock_no_listen,
.shutdown = irda_shutdown,
.setsockopt = irda_setsockopt,
.getsockopt = irda_getsockopt,
.sendmsg = irda_sendmsg_ultra,
.recvmsg = irda_recvmsg_dgram,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
#endif /* CONFIG_IRDA_ULTRA */
/*
* Function irsock_init (pro)
*
* Initialize IrDA protocol
*
*/
int __init irsock_init(void)
{
int rc = proto_register(&irda_proto, 0);
if (rc == 0)
rc = sock_register(&irda_family_ops);
return rc;
}
/*
* Function irsock_cleanup (void)
*
* Remove IrDA protocol
*
*/
void irsock_cleanup(void)
{
sock_unregister(PF_IRDA);
proto_unregister(&irda_proto);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5845_16 |
crossvul-cpp_data_good_2433_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD DDDD SSSSS %
% D D D D SS %
% D D D D SSS %
% D D D D SS %
% DDDD DDDD SSSSS %
% %
% %
% Read/Write Microsoft Direct Draw Surface Image Format %
% %
% Software Design %
% Bianca van Schaik %
% March 2008 %
% Dirk Lemstra %
% September 2013 %
% %
% %
% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/quantum.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/module.h"
#include "magick/transform.h"
/*
Definitions
*/
#define DDSD_CAPS 0x00000001
#define DDSD_HEIGHT 0x00000002
#define DDSD_WIDTH 0x00000004
#define DDSD_PITCH 0x00000008
#define DDSD_PIXELFORMAT 0x00001000
#define DDSD_MIPMAPCOUNT 0x00020000
#define DDSD_LINEARSIZE 0x00080000
#define DDSD_DEPTH 0x00800000
#define DDPF_ALPHAPIXELS 0x00000001
#define DDPF_FOURCC 0x00000004
#define DDPF_RGB 0x00000040
#define DDPF_LUMINANCE 0x00020000
#define FOURCC_DXT1 0x31545844
#define FOURCC_DXT3 0x33545844
#define FOURCC_DXT5 0x35545844
#define DDSCAPS_COMPLEX 0x00000008
#define DDSCAPS_TEXTURE 0x00001000
#define DDSCAPS_MIPMAP 0x00400000
#define DDSCAPS2_CUBEMAP 0x00000200
#define DDSCAPS2_CUBEMAP_POSITIVEX 0x00000400
#define DDSCAPS2_CUBEMAP_NEGATIVEX 0x00000800
#define DDSCAPS2_CUBEMAP_POSITIVEY 0x00001000
#define DDSCAPS2_CUBEMAP_NEGATIVEY 0x00002000
#define DDSCAPS2_CUBEMAP_POSITIVEZ 0x00004000
#define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x00008000
#define DDSCAPS2_VOLUME 0x00200000
#ifndef SIZE_MAX
#define SIZE_MAX ((size_t) -1)
#endif
/*
Structure declarations.
*/
typedef struct _DDSPixelFormat
{
size_t
flags,
fourcc,
rgb_bitcount,
r_bitmask,
g_bitmask,
b_bitmask,
alpha_bitmask;
} DDSPixelFormat;
typedef struct _DDSInfo
{
size_t
flags,
height,
width,
pitchOrLinearSize,
depth,
mipmapcount,
ddscaps1,
ddscaps2;
DDSPixelFormat
pixelformat;
} DDSInfo;
typedef struct _DDSColors
{
unsigned char
r[4],
g[4],
b[4],
a[4];
} DDSColors;
typedef struct _DDSVector4
{
float
x,
y,
z,
w;
} DDSVector4;
typedef struct _DDSVector3
{
float
x,
y,
z;
} DDSVector3;
typedef struct _DDSSourceBlock
{
unsigned char
start,
end,
error;
} DDSSourceBlock;
typedef struct _DDSSingleColourLookup
{
DDSSourceBlock sources[2];
} DDSSingleColourLookup;
typedef MagickBooleanType
DDSDecoder(Image *, DDSInfo *, ExceptionInfo *);
static const DDSSingleColourLookup DDSLookup_5_4[] =
{
{ { { 0, 0, 0 }, { 0, 0, 0 } } },
{ { { 0, 0, 1 }, { 0, 1, 1 } } },
{ { { 0, 0, 2 }, { 0, 1, 0 } } },
{ { { 0, 0, 3 }, { 0, 1, 1 } } },
{ { { 0, 0, 4 }, { 0, 2, 1 } } },
{ { { 1, 0, 3 }, { 0, 2, 0 } } },
{ { { 1, 0, 2 }, { 0, 2, 1 } } },
{ { { 1, 0, 1 }, { 0, 3, 1 } } },
{ { { 1, 0, 0 }, { 0, 3, 0 } } },
{ { { 1, 0, 1 }, { 1, 2, 1 } } },
{ { { 1, 0, 2 }, { 1, 2, 0 } } },
{ { { 1, 0, 3 }, { 0, 4, 0 } } },
{ { { 1, 0, 4 }, { 0, 5, 1 } } },
{ { { 2, 0, 3 }, { 0, 5, 0 } } },
{ { { 2, 0, 2 }, { 0, 5, 1 } } },
{ { { 2, 0, 1 }, { 0, 6, 1 } } },
{ { { 2, 0, 0 }, { 0, 6, 0 } } },
{ { { 2, 0, 1 }, { 2, 3, 1 } } },
{ { { 2, 0, 2 }, { 2, 3, 0 } } },
{ { { 2, 0, 3 }, { 0, 7, 0 } } },
{ { { 2, 0, 4 }, { 1, 6, 1 } } },
{ { { 3, 0, 3 }, { 1, 6, 0 } } },
{ { { 3, 0, 2 }, { 0, 8, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 0 }, { 0, 9, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 2 }, { 0, 10, 1 } } },
{ { { 3, 0, 3 }, { 0, 10, 0 } } },
{ { { 3, 0, 4 }, { 2, 7, 1 } } },
{ { { 4, 0, 4 }, { 2, 7, 0 } } },
{ { { 4, 0, 3 }, { 0, 11, 0 } } },
{ { { 4, 0, 2 }, { 1, 10, 1 } } },
{ { { 4, 0, 1 }, { 1, 10, 0 } } },
{ { { 4, 0, 0 }, { 0, 12, 0 } } },
{ { { 4, 0, 1 }, { 0, 13, 1 } } },
{ { { 4, 0, 2 }, { 0, 13, 0 } } },
{ { { 4, 0, 3 }, { 0, 13, 1 } } },
{ { { 4, 0, 4 }, { 0, 14, 1 } } },
{ { { 5, 0, 3 }, { 0, 14, 0 } } },
{ { { 5, 0, 2 }, { 2, 11, 1 } } },
{ { { 5, 0, 1 }, { 2, 11, 0 } } },
{ { { 5, 0, 0 }, { 0, 15, 0 } } },
{ { { 5, 0, 1 }, { 1, 14, 1 } } },
{ { { 5, 0, 2 }, { 1, 14, 0 } } },
{ { { 5, 0, 3 }, { 0, 16, 0 } } },
{ { { 5, 0, 4 }, { 0, 17, 1 } } },
{ { { 6, 0, 3 }, { 0, 17, 0 } } },
{ { { 6, 0, 2 }, { 0, 17, 1 } } },
{ { { 6, 0, 1 }, { 0, 18, 1 } } },
{ { { 6, 0, 0 }, { 0, 18, 0 } } },
{ { { 6, 0, 1 }, { 2, 15, 1 } } },
{ { { 6, 0, 2 }, { 2, 15, 0 } } },
{ { { 6, 0, 3 }, { 0, 19, 0 } } },
{ { { 6, 0, 4 }, { 1, 18, 1 } } },
{ { { 7, 0, 3 }, { 1, 18, 0 } } },
{ { { 7, 0, 2 }, { 0, 20, 0 } } },
{ { { 7, 0, 1 }, { 0, 21, 1 } } },
{ { { 7, 0, 0 }, { 0, 21, 0 } } },
{ { { 7, 0, 1 }, { 0, 21, 1 } } },
{ { { 7, 0, 2 }, { 0, 22, 1 } } },
{ { { 7, 0, 3 }, { 0, 22, 0 } } },
{ { { 7, 0, 4 }, { 2, 19, 1 } } },
{ { { 8, 0, 4 }, { 2, 19, 0 } } },
{ { { 8, 0, 3 }, { 0, 23, 0 } } },
{ { { 8, 0, 2 }, { 1, 22, 1 } } },
{ { { 8, 0, 1 }, { 1, 22, 0 } } },
{ { { 8, 0, 0 }, { 0, 24, 0 } } },
{ { { 8, 0, 1 }, { 0, 25, 1 } } },
{ { { 8, 0, 2 }, { 0, 25, 0 } } },
{ { { 8, 0, 3 }, { 0, 25, 1 } } },
{ { { 8, 0, 4 }, { 0, 26, 1 } } },
{ { { 9, 0, 3 }, { 0, 26, 0 } } },
{ { { 9, 0, 2 }, { 2, 23, 1 } } },
{ { { 9, 0, 1 }, { 2, 23, 0 } } },
{ { { 9, 0, 0 }, { 0, 27, 0 } } },
{ { { 9, 0, 1 }, { 1, 26, 1 } } },
{ { { 9, 0, 2 }, { 1, 26, 0 } } },
{ { { 9, 0, 3 }, { 0, 28, 0 } } },
{ { { 9, 0, 4 }, { 0, 29, 1 } } },
{ { { 10, 0, 3 }, { 0, 29, 0 } } },
{ { { 10, 0, 2 }, { 0, 29, 1 } } },
{ { { 10, 0, 1 }, { 0, 30, 1 } } },
{ { { 10, 0, 0 }, { 0, 30, 0 } } },
{ { { 10, 0, 1 }, { 2, 27, 1 } } },
{ { { 10, 0, 2 }, { 2, 27, 0 } } },
{ { { 10, 0, 3 }, { 0, 31, 0 } } },
{ { { 10, 0, 4 }, { 1, 30, 1 } } },
{ { { 11, 0, 3 }, { 1, 30, 0 } } },
{ { { 11, 0, 2 }, { 4, 24, 0 } } },
{ { { 11, 0, 1 }, { 1, 31, 1 } } },
{ { { 11, 0, 0 }, { 1, 31, 0 } } },
{ { { 11, 0, 1 }, { 1, 31, 1 } } },
{ { { 11, 0, 2 }, { 2, 30, 1 } } },
{ { { 11, 0, 3 }, { 2, 30, 0 } } },
{ { { 11, 0, 4 }, { 2, 31, 1 } } },
{ { { 12, 0, 4 }, { 2, 31, 0 } } },
{ { { 12, 0, 3 }, { 4, 27, 0 } } },
{ { { 12, 0, 2 }, { 3, 30, 1 } } },
{ { { 12, 0, 1 }, { 3, 30, 0 } } },
{ { { 12, 0, 0 }, { 4, 28, 0 } } },
{ { { 12, 0, 1 }, { 3, 31, 1 } } },
{ { { 12, 0, 2 }, { 3, 31, 0 } } },
{ { { 12, 0, 3 }, { 3, 31, 1 } } },
{ { { 12, 0, 4 }, { 4, 30, 1 } } },
{ { { 13, 0, 3 }, { 4, 30, 0 } } },
{ { { 13, 0, 2 }, { 6, 27, 1 } } },
{ { { 13, 0, 1 }, { 6, 27, 0 } } },
{ { { 13, 0, 0 }, { 4, 31, 0 } } },
{ { { 13, 0, 1 }, { 5, 30, 1 } } },
{ { { 13, 0, 2 }, { 5, 30, 0 } } },
{ { { 13, 0, 3 }, { 8, 24, 0 } } },
{ { { 13, 0, 4 }, { 5, 31, 1 } } },
{ { { 14, 0, 3 }, { 5, 31, 0 } } },
{ { { 14, 0, 2 }, { 5, 31, 1 } } },
{ { { 14, 0, 1 }, { 6, 30, 1 } } },
{ { { 14, 0, 0 }, { 6, 30, 0 } } },
{ { { 14, 0, 1 }, { 6, 31, 1 } } },
{ { { 14, 0, 2 }, { 6, 31, 0 } } },
{ { { 14, 0, 3 }, { 8, 27, 0 } } },
{ { { 14, 0, 4 }, { 7, 30, 1 } } },
{ { { 15, 0, 3 }, { 7, 30, 0 } } },
{ { { 15, 0, 2 }, { 8, 28, 0 } } },
{ { { 15, 0, 1 }, { 7, 31, 1 } } },
{ { { 15, 0, 0 }, { 7, 31, 0 } } },
{ { { 15, 0, 1 }, { 7, 31, 1 } } },
{ { { 15, 0, 2 }, { 8, 30, 1 } } },
{ { { 15, 0, 3 }, { 8, 30, 0 } } },
{ { { 15, 0, 4 }, { 10, 27, 1 } } },
{ { { 16, 0, 4 }, { 10, 27, 0 } } },
{ { { 16, 0, 3 }, { 8, 31, 0 } } },
{ { { 16, 0, 2 }, { 9, 30, 1 } } },
{ { { 16, 0, 1 }, { 9, 30, 0 } } },
{ { { 16, 0, 0 }, { 12, 24, 0 } } },
{ { { 16, 0, 1 }, { 9, 31, 1 } } },
{ { { 16, 0, 2 }, { 9, 31, 0 } } },
{ { { 16, 0, 3 }, { 9, 31, 1 } } },
{ { { 16, 0, 4 }, { 10, 30, 1 } } },
{ { { 17, 0, 3 }, { 10, 30, 0 } } },
{ { { 17, 0, 2 }, { 10, 31, 1 } } },
{ { { 17, 0, 1 }, { 10, 31, 0 } } },
{ { { 17, 0, 0 }, { 12, 27, 0 } } },
{ { { 17, 0, 1 }, { 11, 30, 1 } } },
{ { { 17, 0, 2 }, { 11, 30, 0 } } },
{ { { 17, 0, 3 }, { 12, 28, 0 } } },
{ { { 17, 0, 4 }, { 11, 31, 1 } } },
{ { { 18, 0, 3 }, { 11, 31, 0 } } },
{ { { 18, 0, 2 }, { 11, 31, 1 } } },
{ { { 18, 0, 1 }, { 12, 30, 1 } } },
{ { { 18, 0, 0 }, { 12, 30, 0 } } },
{ { { 18, 0, 1 }, { 14, 27, 1 } } },
{ { { 18, 0, 2 }, { 14, 27, 0 } } },
{ { { 18, 0, 3 }, { 12, 31, 0 } } },
{ { { 18, 0, 4 }, { 13, 30, 1 } } },
{ { { 19, 0, 3 }, { 13, 30, 0 } } },
{ { { 19, 0, 2 }, { 16, 24, 0 } } },
{ { { 19, 0, 1 }, { 13, 31, 1 } } },
{ { { 19, 0, 0 }, { 13, 31, 0 } } },
{ { { 19, 0, 1 }, { 13, 31, 1 } } },
{ { { 19, 0, 2 }, { 14, 30, 1 } } },
{ { { 19, 0, 3 }, { 14, 30, 0 } } },
{ { { 19, 0, 4 }, { 14, 31, 1 } } },
{ { { 20, 0, 4 }, { 14, 31, 0 } } },
{ { { 20, 0, 3 }, { 16, 27, 0 } } },
{ { { 20, 0, 2 }, { 15, 30, 1 } } },
{ { { 20, 0, 1 }, { 15, 30, 0 } } },
{ { { 20, 0, 0 }, { 16, 28, 0 } } },
{ { { 20, 0, 1 }, { 15, 31, 1 } } },
{ { { 20, 0, 2 }, { 15, 31, 0 } } },
{ { { 20, 0, 3 }, { 15, 31, 1 } } },
{ { { 20, 0, 4 }, { 16, 30, 1 } } },
{ { { 21, 0, 3 }, { 16, 30, 0 } } },
{ { { 21, 0, 2 }, { 18, 27, 1 } } },
{ { { 21, 0, 1 }, { 18, 27, 0 } } },
{ { { 21, 0, 0 }, { 16, 31, 0 } } },
{ { { 21, 0, 1 }, { 17, 30, 1 } } },
{ { { 21, 0, 2 }, { 17, 30, 0 } } },
{ { { 21, 0, 3 }, { 20, 24, 0 } } },
{ { { 21, 0, 4 }, { 17, 31, 1 } } },
{ { { 22, 0, 3 }, { 17, 31, 0 } } },
{ { { 22, 0, 2 }, { 17, 31, 1 } } },
{ { { 22, 0, 1 }, { 18, 30, 1 } } },
{ { { 22, 0, 0 }, { 18, 30, 0 } } },
{ { { 22, 0, 1 }, { 18, 31, 1 } } },
{ { { 22, 0, 2 }, { 18, 31, 0 } } },
{ { { 22, 0, 3 }, { 20, 27, 0 } } },
{ { { 22, 0, 4 }, { 19, 30, 1 } } },
{ { { 23, 0, 3 }, { 19, 30, 0 } } },
{ { { 23, 0, 2 }, { 20, 28, 0 } } },
{ { { 23, 0, 1 }, { 19, 31, 1 } } },
{ { { 23, 0, 0 }, { 19, 31, 0 } } },
{ { { 23, 0, 1 }, { 19, 31, 1 } } },
{ { { 23, 0, 2 }, { 20, 30, 1 } } },
{ { { 23, 0, 3 }, { 20, 30, 0 } } },
{ { { 23, 0, 4 }, { 22, 27, 1 } } },
{ { { 24, 0, 4 }, { 22, 27, 0 } } },
{ { { 24, 0, 3 }, { 20, 31, 0 } } },
{ { { 24, 0, 2 }, { 21, 30, 1 } } },
{ { { 24, 0, 1 }, { 21, 30, 0 } } },
{ { { 24, 0, 0 }, { 24, 24, 0 } } },
{ { { 24, 0, 1 }, { 21, 31, 1 } } },
{ { { 24, 0, 2 }, { 21, 31, 0 } } },
{ { { 24, 0, 3 }, { 21, 31, 1 } } },
{ { { 24, 0, 4 }, { 22, 30, 1 } } },
{ { { 25, 0, 3 }, { 22, 30, 0 } } },
{ { { 25, 0, 2 }, { 22, 31, 1 } } },
{ { { 25, 0, 1 }, { 22, 31, 0 } } },
{ { { 25, 0, 0 }, { 24, 27, 0 } } },
{ { { 25, 0, 1 }, { 23, 30, 1 } } },
{ { { 25, 0, 2 }, { 23, 30, 0 } } },
{ { { 25, 0, 3 }, { 24, 28, 0 } } },
{ { { 25, 0, 4 }, { 23, 31, 1 } } },
{ { { 26, 0, 3 }, { 23, 31, 0 } } },
{ { { 26, 0, 2 }, { 23, 31, 1 } } },
{ { { 26, 0, 1 }, { 24, 30, 1 } } },
{ { { 26, 0, 0 }, { 24, 30, 0 } } },
{ { { 26, 0, 1 }, { 26, 27, 1 } } },
{ { { 26, 0, 2 }, { 26, 27, 0 } } },
{ { { 26, 0, 3 }, { 24, 31, 0 } } },
{ { { 26, 0, 4 }, { 25, 30, 1 } } },
{ { { 27, 0, 3 }, { 25, 30, 0 } } },
{ { { 27, 0, 2 }, { 28, 24, 0 } } },
{ { { 27, 0, 1 }, { 25, 31, 1 } } },
{ { { 27, 0, 0 }, { 25, 31, 0 } } },
{ { { 27, 0, 1 }, { 25, 31, 1 } } },
{ { { 27, 0, 2 }, { 26, 30, 1 } } },
{ { { 27, 0, 3 }, { 26, 30, 0 } } },
{ { { 27, 0, 4 }, { 26, 31, 1 } } },
{ { { 28, 0, 4 }, { 26, 31, 0 } } },
{ { { 28, 0, 3 }, { 28, 27, 0 } } },
{ { { 28, 0, 2 }, { 27, 30, 1 } } },
{ { { 28, 0, 1 }, { 27, 30, 0 } } },
{ { { 28, 0, 0 }, { 28, 28, 0 } } },
{ { { 28, 0, 1 }, { 27, 31, 1 } } },
{ { { 28, 0, 2 }, { 27, 31, 0 } } },
{ { { 28, 0, 3 }, { 27, 31, 1 } } },
{ { { 28, 0, 4 }, { 28, 30, 1 } } },
{ { { 29, 0, 3 }, { 28, 30, 0 } } },
{ { { 29, 0, 2 }, { 30, 27, 1 } } },
{ { { 29, 0, 1 }, { 30, 27, 0 } } },
{ { { 29, 0, 0 }, { 28, 31, 0 } } },
{ { { 29, 0, 1 }, { 29, 30, 1 } } },
{ { { 29, 0, 2 }, { 29, 30, 0 } } },
{ { { 29, 0, 3 }, { 29, 30, 1 } } },
{ { { 29, 0, 4 }, { 29, 31, 1 } } },
{ { { 30, 0, 3 }, { 29, 31, 0 } } },
{ { { 30, 0, 2 }, { 29, 31, 1 } } },
{ { { 30, 0, 1 }, { 30, 30, 1 } } },
{ { { 30, 0, 0 }, { 30, 30, 0 } } },
{ { { 30, 0, 1 }, { 30, 31, 1 } } },
{ { { 30, 0, 2 }, { 30, 31, 0 } } },
{ { { 30, 0, 3 }, { 30, 31, 1 } } },
{ { { 30, 0, 4 }, { 31, 30, 1 } } },
{ { { 31, 0, 3 }, { 31, 30, 0 } } },
{ { { 31, 0, 2 }, { 31, 30, 1 } } },
{ { { 31, 0, 1 }, { 31, 31, 1 } } },
{ { { 31, 0, 0 }, { 31, 31, 0 } } }
};
static const DDSSingleColourLookup DDSLookup_6_4[] =
{
{ { { 0, 0, 0 }, { 0, 0, 0 } } },
{ { { 0, 0, 1 }, { 0, 1, 0 } } },
{ { { 0, 0, 2 }, { 0, 2, 0 } } },
{ { { 1, 0, 1 }, { 0, 3, 1 } } },
{ { { 1, 0, 0 }, { 0, 3, 0 } } },
{ { { 1, 0, 1 }, { 0, 4, 0 } } },
{ { { 1, 0, 2 }, { 0, 5, 0 } } },
{ { { 2, 0, 1 }, { 0, 6, 1 } } },
{ { { 2, 0, 0 }, { 0, 6, 0 } } },
{ { { 2, 0, 1 }, { 0, 7, 0 } } },
{ { { 2, 0, 2 }, { 0, 8, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 0 }, { 0, 9, 0 } } },
{ { { 3, 0, 1 }, { 0, 10, 0 } } },
{ { { 3, 0, 2 }, { 0, 11, 0 } } },
{ { { 4, 0, 1 }, { 0, 12, 1 } } },
{ { { 4, 0, 0 }, { 0, 12, 0 } } },
{ { { 4, 0, 1 }, { 0, 13, 0 } } },
{ { { 4, 0, 2 }, { 0, 14, 0 } } },
{ { { 5, 0, 1 }, { 0, 15, 1 } } },
{ { { 5, 0, 0 }, { 0, 15, 0 } } },
{ { { 5, 0, 1 }, { 0, 16, 0 } } },
{ { { 5, 0, 2 }, { 1, 15, 0 } } },
{ { { 6, 0, 1 }, { 0, 17, 0 } } },
{ { { 6, 0, 0 }, { 0, 18, 0 } } },
{ { { 6, 0, 1 }, { 0, 19, 0 } } },
{ { { 6, 0, 2 }, { 3, 14, 0 } } },
{ { { 7, 0, 1 }, { 0, 20, 0 } } },
{ { { 7, 0, 0 }, { 0, 21, 0 } } },
{ { { 7, 0, 1 }, { 0, 22, 0 } } },
{ { { 7, 0, 2 }, { 4, 15, 0 } } },
{ { { 8, 0, 1 }, { 0, 23, 0 } } },
{ { { 8, 0, 0 }, { 0, 24, 0 } } },
{ { { 8, 0, 1 }, { 0, 25, 0 } } },
{ { { 8, 0, 2 }, { 6, 14, 0 } } },
{ { { 9, 0, 1 }, { 0, 26, 0 } } },
{ { { 9, 0, 0 }, { 0, 27, 0 } } },
{ { { 9, 0, 1 }, { 0, 28, 0 } } },
{ { { 9, 0, 2 }, { 7, 15, 0 } } },
{ { { 10, 0, 1 }, { 0, 29, 0 } } },
{ { { 10, 0, 0 }, { 0, 30, 0 } } },
{ { { 10, 0, 1 }, { 0, 31, 0 } } },
{ { { 10, 0, 2 }, { 9, 14, 0 } } },
{ { { 11, 0, 1 }, { 0, 32, 0 } } },
{ { { 11, 0, 0 }, { 0, 33, 0 } } },
{ { { 11, 0, 1 }, { 2, 30, 0 } } },
{ { { 11, 0, 2 }, { 0, 34, 0 } } },
{ { { 12, 0, 1 }, { 0, 35, 0 } } },
{ { { 12, 0, 0 }, { 0, 36, 0 } } },
{ { { 12, 0, 1 }, { 3, 31, 0 } } },
{ { { 12, 0, 2 }, { 0, 37, 0 } } },
{ { { 13, 0, 1 }, { 0, 38, 0 } } },
{ { { 13, 0, 0 }, { 0, 39, 0 } } },
{ { { 13, 0, 1 }, { 5, 30, 0 } } },
{ { { 13, 0, 2 }, { 0, 40, 0 } } },
{ { { 14, 0, 1 }, { 0, 41, 0 } } },
{ { { 14, 0, 0 }, { 0, 42, 0 } } },
{ { { 14, 0, 1 }, { 6, 31, 0 } } },
{ { { 14, 0, 2 }, { 0, 43, 0 } } },
{ { { 15, 0, 1 }, { 0, 44, 0 } } },
{ { { 15, 0, 0 }, { 0, 45, 0 } } },
{ { { 15, 0, 1 }, { 8, 30, 0 } } },
{ { { 15, 0, 2 }, { 0, 46, 0 } } },
{ { { 16, 0, 2 }, { 0, 47, 0 } } },
{ { { 16, 0, 1 }, { 1, 46, 0 } } },
{ { { 16, 0, 0 }, { 0, 48, 0 } } },
{ { { 16, 0, 1 }, { 0, 49, 0 } } },
{ { { 16, 0, 2 }, { 0, 50, 0 } } },
{ { { 17, 0, 1 }, { 2, 47, 0 } } },
{ { { 17, 0, 0 }, { 0, 51, 0 } } },
{ { { 17, 0, 1 }, { 0, 52, 0 } } },
{ { { 17, 0, 2 }, { 0, 53, 0 } } },
{ { { 18, 0, 1 }, { 4, 46, 0 } } },
{ { { 18, 0, 0 }, { 0, 54, 0 } } },
{ { { 18, 0, 1 }, { 0, 55, 0 } } },
{ { { 18, 0, 2 }, { 0, 56, 0 } } },
{ { { 19, 0, 1 }, { 5, 47, 0 } } },
{ { { 19, 0, 0 }, { 0, 57, 0 } } },
{ { { 19, 0, 1 }, { 0, 58, 0 } } },
{ { { 19, 0, 2 }, { 0, 59, 0 } } },
{ { { 20, 0, 1 }, { 7, 46, 0 } } },
{ { { 20, 0, 0 }, { 0, 60, 0 } } },
{ { { 20, 0, 1 }, { 0, 61, 0 } } },
{ { { 20, 0, 2 }, { 0, 62, 0 } } },
{ { { 21, 0, 1 }, { 8, 47, 0 } } },
{ { { 21, 0, 0 }, { 0, 63, 0 } } },
{ { { 21, 0, 1 }, { 1, 62, 0 } } },
{ { { 21, 0, 2 }, { 1, 63, 0 } } },
{ { { 22, 0, 1 }, { 10, 46, 0 } } },
{ { { 22, 0, 0 }, { 2, 62, 0 } } },
{ { { 22, 0, 1 }, { 2, 63, 0 } } },
{ { { 22, 0, 2 }, { 3, 62, 0 } } },
{ { { 23, 0, 1 }, { 11, 47, 0 } } },
{ { { 23, 0, 0 }, { 3, 63, 0 } } },
{ { { 23, 0, 1 }, { 4, 62, 0 } } },
{ { { 23, 0, 2 }, { 4, 63, 0 } } },
{ { { 24, 0, 1 }, { 13, 46, 0 } } },
{ { { 24, 0, 0 }, { 5, 62, 0 } } },
{ { { 24, 0, 1 }, { 5, 63, 0 } } },
{ { { 24, 0, 2 }, { 6, 62, 0 } } },
{ { { 25, 0, 1 }, { 14, 47, 0 } } },
{ { { 25, 0, 0 }, { 6, 63, 0 } } },
{ { { 25, 0, 1 }, { 7, 62, 0 } } },
{ { { 25, 0, 2 }, { 7, 63, 0 } } },
{ { { 26, 0, 1 }, { 16, 45, 0 } } },
{ { { 26, 0, 0 }, { 8, 62, 0 } } },
{ { { 26, 0, 1 }, { 8, 63, 0 } } },
{ { { 26, 0, 2 }, { 9, 62, 0 } } },
{ { { 27, 0, 1 }, { 16, 48, 0 } } },
{ { { 27, 0, 0 }, { 9, 63, 0 } } },
{ { { 27, 0, 1 }, { 10, 62, 0 } } },
{ { { 27, 0, 2 }, { 10, 63, 0 } } },
{ { { 28, 0, 1 }, { 16, 51, 0 } } },
{ { { 28, 0, 0 }, { 11, 62, 0 } } },
{ { { 28, 0, 1 }, { 11, 63, 0 } } },
{ { { 28, 0, 2 }, { 12, 62, 0 } } },
{ { { 29, 0, 1 }, { 16, 54, 0 } } },
{ { { 29, 0, 0 }, { 12, 63, 0 } } },
{ { { 29, 0, 1 }, { 13, 62, 0 } } },
{ { { 29, 0, 2 }, { 13, 63, 0 } } },
{ { { 30, 0, 1 }, { 16, 57, 0 } } },
{ { { 30, 0, 0 }, { 14, 62, 0 } } },
{ { { 30, 0, 1 }, { 14, 63, 0 } } },
{ { { 30, 0, 2 }, { 15, 62, 0 } } },
{ { { 31, 0, 1 }, { 16, 60, 0 } } },
{ { { 31, 0, 0 }, { 15, 63, 0 } } },
{ { { 31, 0, 1 }, { 24, 46, 0 } } },
{ { { 31, 0, 2 }, { 16, 62, 0 } } },
{ { { 32, 0, 2 }, { 16, 63, 0 } } },
{ { { 32, 0, 1 }, { 17, 62, 0 } } },
{ { { 32, 0, 0 }, { 25, 47, 0 } } },
{ { { 32, 0, 1 }, { 17, 63, 0 } } },
{ { { 32, 0, 2 }, { 18, 62, 0 } } },
{ { { 33, 0, 1 }, { 18, 63, 0 } } },
{ { { 33, 0, 0 }, { 27, 46, 0 } } },
{ { { 33, 0, 1 }, { 19, 62, 0 } } },
{ { { 33, 0, 2 }, { 19, 63, 0 } } },
{ { { 34, 0, 1 }, { 20, 62, 0 } } },
{ { { 34, 0, 0 }, { 28, 47, 0 } } },
{ { { 34, 0, 1 }, { 20, 63, 0 } } },
{ { { 34, 0, 2 }, { 21, 62, 0 } } },
{ { { 35, 0, 1 }, { 21, 63, 0 } } },
{ { { 35, 0, 0 }, { 30, 46, 0 } } },
{ { { 35, 0, 1 }, { 22, 62, 0 } } },
{ { { 35, 0, 2 }, { 22, 63, 0 } } },
{ { { 36, 0, 1 }, { 23, 62, 0 } } },
{ { { 36, 0, 0 }, { 31, 47, 0 } } },
{ { { 36, 0, 1 }, { 23, 63, 0 } } },
{ { { 36, 0, 2 }, { 24, 62, 0 } } },
{ { { 37, 0, 1 }, { 24, 63, 0 } } },
{ { { 37, 0, 0 }, { 32, 47, 0 } } },
{ { { 37, 0, 1 }, { 25, 62, 0 } } },
{ { { 37, 0, 2 }, { 25, 63, 0 } } },
{ { { 38, 0, 1 }, { 26, 62, 0 } } },
{ { { 38, 0, 0 }, { 32, 50, 0 } } },
{ { { 38, 0, 1 }, { 26, 63, 0 } } },
{ { { 38, 0, 2 }, { 27, 62, 0 } } },
{ { { 39, 0, 1 }, { 27, 63, 0 } } },
{ { { 39, 0, 0 }, { 32, 53, 0 } } },
{ { { 39, 0, 1 }, { 28, 62, 0 } } },
{ { { 39, 0, 2 }, { 28, 63, 0 } } },
{ { { 40, 0, 1 }, { 29, 62, 0 } } },
{ { { 40, 0, 0 }, { 32, 56, 0 } } },
{ { { 40, 0, 1 }, { 29, 63, 0 } } },
{ { { 40, 0, 2 }, { 30, 62, 0 } } },
{ { { 41, 0, 1 }, { 30, 63, 0 } } },
{ { { 41, 0, 0 }, { 32, 59, 0 } } },
{ { { 41, 0, 1 }, { 31, 62, 0 } } },
{ { { 41, 0, 2 }, { 31, 63, 0 } } },
{ { { 42, 0, 1 }, { 32, 61, 0 } } },
{ { { 42, 0, 0 }, { 32, 62, 0 } } },
{ { { 42, 0, 1 }, { 32, 63, 0 } } },
{ { { 42, 0, 2 }, { 41, 46, 0 } } },
{ { { 43, 0, 1 }, { 33, 62, 0 } } },
{ { { 43, 0, 0 }, { 33, 63, 0 } } },
{ { { 43, 0, 1 }, { 34, 62, 0 } } },
{ { { 43, 0, 2 }, { 42, 47, 0 } } },
{ { { 44, 0, 1 }, { 34, 63, 0 } } },
{ { { 44, 0, 0 }, { 35, 62, 0 } } },
{ { { 44, 0, 1 }, { 35, 63, 0 } } },
{ { { 44, 0, 2 }, { 44, 46, 0 } } },
{ { { 45, 0, 1 }, { 36, 62, 0 } } },
{ { { 45, 0, 0 }, { 36, 63, 0 } } },
{ { { 45, 0, 1 }, { 37, 62, 0 } } },
{ { { 45, 0, 2 }, { 45, 47, 0 } } },
{ { { 46, 0, 1 }, { 37, 63, 0 } } },
{ { { 46, 0, 0 }, { 38, 62, 0 } } },
{ { { 46, 0, 1 }, { 38, 63, 0 } } },
{ { { 46, 0, 2 }, { 47, 46, 0 } } },
{ { { 47, 0, 1 }, { 39, 62, 0 } } },
{ { { 47, 0, 0 }, { 39, 63, 0 } } },
{ { { 47, 0, 1 }, { 40, 62, 0 } } },
{ { { 47, 0, 2 }, { 48, 46, 0 } } },
{ { { 48, 0, 2 }, { 40, 63, 0 } } },
{ { { 48, 0, 1 }, { 41, 62, 0 } } },
{ { { 48, 0, 0 }, { 41, 63, 0 } } },
{ { { 48, 0, 1 }, { 48, 49, 0 } } },
{ { { 48, 0, 2 }, { 42, 62, 0 } } },
{ { { 49, 0, 1 }, { 42, 63, 0 } } },
{ { { 49, 0, 0 }, { 43, 62, 0 } } },
{ { { 49, 0, 1 }, { 48, 52, 0 } } },
{ { { 49, 0, 2 }, { 43, 63, 0 } } },
{ { { 50, 0, 1 }, { 44, 62, 0 } } },
{ { { 50, 0, 0 }, { 44, 63, 0 } } },
{ { { 50, 0, 1 }, { 48, 55, 0 } } },
{ { { 50, 0, 2 }, { 45, 62, 0 } } },
{ { { 51, 0, 1 }, { 45, 63, 0 } } },
{ { { 51, 0, 0 }, { 46, 62, 0 } } },
{ { { 51, 0, 1 }, { 48, 58, 0 } } },
{ { { 51, 0, 2 }, { 46, 63, 0 } } },
{ { { 52, 0, 1 }, { 47, 62, 0 } } },
{ { { 52, 0, 0 }, { 47, 63, 0 } } },
{ { { 52, 0, 1 }, { 48, 61, 0 } } },
{ { { 52, 0, 2 }, { 48, 62, 0 } } },
{ { { 53, 0, 1 }, { 56, 47, 0 } } },
{ { { 53, 0, 0 }, { 48, 63, 0 } } },
{ { { 53, 0, 1 }, { 49, 62, 0 } } },
{ { { 53, 0, 2 }, { 49, 63, 0 } } },
{ { { 54, 0, 1 }, { 58, 46, 0 } } },
{ { { 54, 0, 0 }, { 50, 62, 0 } } },
{ { { 54, 0, 1 }, { 50, 63, 0 } } },
{ { { 54, 0, 2 }, { 51, 62, 0 } } },
{ { { 55, 0, 1 }, { 59, 47, 0 } } },
{ { { 55, 0, 0 }, { 51, 63, 0 } } },
{ { { 55, 0, 1 }, { 52, 62, 0 } } },
{ { { 55, 0, 2 }, { 52, 63, 0 } } },
{ { { 56, 0, 1 }, { 61, 46, 0 } } },
{ { { 56, 0, 0 }, { 53, 62, 0 } } },
{ { { 56, 0, 1 }, { 53, 63, 0 } } },
{ { { 56, 0, 2 }, { 54, 62, 0 } } },
{ { { 57, 0, 1 }, { 62, 47, 0 } } },
{ { { 57, 0, 0 }, { 54, 63, 0 } } },
{ { { 57, 0, 1 }, { 55, 62, 0 } } },
{ { { 57, 0, 2 }, { 55, 63, 0 } } },
{ { { 58, 0, 1 }, { 56, 62, 1 } } },
{ { { 58, 0, 0 }, { 56, 62, 0 } } },
{ { { 58, 0, 1 }, { 56, 63, 0 } } },
{ { { 58, 0, 2 }, { 57, 62, 0 } } },
{ { { 59, 0, 1 }, { 57, 63, 1 } } },
{ { { 59, 0, 0 }, { 57, 63, 0 } } },
{ { { 59, 0, 1 }, { 58, 62, 0 } } },
{ { { 59, 0, 2 }, { 58, 63, 0 } } },
{ { { 60, 0, 1 }, { 59, 62, 1 } } },
{ { { 60, 0, 0 }, { 59, 62, 0 } } },
{ { { 60, 0, 1 }, { 59, 63, 0 } } },
{ { { 60, 0, 2 }, { 60, 62, 0 } } },
{ { { 61, 0, 1 }, { 60, 63, 1 } } },
{ { { 61, 0, 0 }, { 60, 63, 0 } } },
{ { { 61, 0, 1 }, { 61, 62, 0 } } },
{ { { 61, 0, 2 }, { 61, 63, 0 } } },
{ { { 62, 0, 1 }, { 62, 62, 1 } } },
{ { { 62, 0, 0 }, { 62, 62, 0 } } },
{ { { 62, 0, 1 }, { 62, 63, 0 } } },
{ { { 62, 0, 2 }, { 63, 62, 0 } } },
{ { { 63, 0, 1 }, { 63, 63, 1 } } },
{ { { 63, 0, 0 }, { 63, 63, 0 } } }
};
static const DDSSingleColourLookup*
DDS_LOOKUP[] =
{
DDSLookup_5_4,
DDSLookup_6_4,
DDSLookup_5_4
};
/*
Macros
*/
#define C565_r(x) (((x) & 0xF800) >> 11)
#define C565_g(x) (((x) & 0x07E0) >> 5)
#define C565_b(x) ((x) & 0x001F)
#define C565_red(x) ( (C565_r(x) << 3 | C565_r(x) >> 2))
#define C565_green(x) ( (C565_g(x) << 2 | C565_g(x) >> 4))
#define C565_blue(x) ( (C565_b(x) << 3 | C565_b(x) >> 2))
#define DIV2(x) ((x) > 1 ? ((x) >> 1) : 1)
#define FixRange(min, max, steps) \
if (min > max) \
min = max; \
if (max - min < steps) \
max = MagickMin(min + steps, 255); \
if (max - min < steps) \
min = MagickMax(min - steps, 0)
#define Dot(left, right) (left.x*right.x) + (left.y*right.y) + (left.z*right.z)
#define VectorInit(vector, value) vector.x = vector.y = vector.z = vector.w \
= value
#define VectorInit3(vector, value) vector.x = vector.y = vector.z = value
#define IsBitMask(mask, r, g, b, a) (mask.r_bitmask == r && mask.g_bitmask == \
g && mask.b_bitmask == b && mask.alpha_bitmask == a)
/*
Forward declarations
*/
static MagickBooleanType
ConstructOrdering(const size_t,const DDSVector4 *,const DDSVector3,
DDSVector4 *,DDSVector4 *,unsigned char *,size_t),
ReadDDSInfo(Image *,DDSInfo *),
ReadDXT1(Image *,DDSInfo *,ExceptionInfo *),
ReadDXT3(Image *,DDSInfo *,ExceptionInfo *),
ReadDXT5(Image *,DDSInfo *,ExceptionInfo *),
ReadUncompressedRGB(Image *,DDSInfo *,ExceptionInfo *),
ReadUncompressedRGBA(Image *,DDSInfo *,ExceptionInfo *),
SkipDXTMipmaps(Image *,DDSInfo *,int,ExceptionInfo *),
SkipRGBMipmaps(Image *,DDSInfo *,int,ExceptionInfo *),
WriteDDSImage(const ImageInfo *,Image *),
WriteMipmaps(Image *,const size_t,const size_t,const size_t,
const MagickBooleanType,const MagickBooleanType,ExceptionInfo *);
static void
RemapIndices(const ssize_t *,const unsigned char *,unsigned char *),
WriteDDSInfo(Image *,const size_t,const size_t,const size_t),
WriteFourCC(Image *,const size_t,const MagickBooleanType,
const MagickBooleanType,ExceptionInfo *),
WriteImageData(Image *,const size_t,const size_t,const MagickBooleanType,
const MagickBooleanType,ExceptionInfo *),
WriteIndices(Image *,const DDSVector3,const DDSVector3, unsigned char *),
WriteSingleColorFit(Image *,const DDSVector4 *,const ssize_t *),
WriteUncompressed(Image *,ExceptionInfo *);
static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right,
DDSVector4 *destination)
{
destination->x = left.x + right.x;
destination->y = left.y + right.y;
destination->z = left.z + right.z;
destination->w = left.w + right.w;
}
static inline void VectorClamp(DDSVector4 *value)
{
value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));
value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));
value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));
value->w = MagickMin(1.0f,MagickMax(0.0f,value->w));
}
static inline void VectorClamp3(DDSVector3 *value)
{
value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));
value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));
value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));
}
static inline void VectorCopy43(const DDSVector4 source,
DDSVector3 *destination)
{
destination->x = source.x;
destination->y = source.y;
destination->z = source.z;
}
static inline void VectorCopy44(const DDSVector4 source,
DDSVector4 *destination)
{
destination->x = source.x;
destination->y = source.y;
destination->z = source.z;
destination->w = source.w;
}
static inline void VectorNegativeMultiplySubtract(const DDSVector4 a,
const DDSVector4 b, const DDSVector4 c, DDSVector4 *destination)
{
destination->x = c.x - (a.x * b.x);
destination->y = c.y - (a.y * b.y);
destination->z = c.z - (a.z * b.z);
destination->w = c.w - (a.w * b.w);
}
static inline void VectorMultiply(const DDSVector4 left,
const DDSVector4 right, DDSVector4 *destination)
{
destination->x = left.x * right.x;
destination->y = left.y * right.y;
destination->z = left.z * right.z;
destination->w = left.w * right.w;
}
static inline void VectorMultiply3(const DDSVector3 left,
const DDSVector3 right, DDSVector3 *destination)
{
destination->x = left.x * right.x;
destination->y = left.y * right.y;
destination->z = left.z * right.z;
}
static inline void VectorMultiplyAdd(const DDSVector4 a, const DDSVector4 b,
const DDSVector4 c, DDSVector4 *destination)
{
destination->x = (a.x * b.x) + c.x;
destination->y = (a.y * b.y) + c.y;
destination->z = (a.z * b.z) + c.z;
destination->w = (a.w * b.w) + c.w;
}
static inline void VectorMultiplyAdd3(const DDSVector3 a, const DDSVector3 b,
const DDSVector3 c, DDSVector3 *destination)
{
destination->x = (a.x * b.x) + c.x;
destination->y = (a.y * b.y) + c.y;
destination->z = (a.z * b.z) + c.z;
}
static inline void VectorReciprocal(const DDSVector4 value,
DDSVector4 *destination)
{
destination->x = 1.0f / value.x;
destination->y = 1.0f / value.y;
destination->z = 1.0f / value.z;
destination->w = 1.0f / value.w;
}
static inline void VectorSubtract(const DDSVector4 left,
const DDSVector4 right, DDSVector4 *destination)
{
destination->x = left.x - right.x;
destination->y = left.y - right.y;
destination->z = left.z - right.z;
destination->w = left.w - right.w;
}
static inline void VectorSubtract3(const DDSVector3 left,
const DDSVector3 right, DDSVector3 *destination)
{
destination->x = left.x - right.x;
destination->y = left.y - right.y;
destination->z = left.z - right.z;
}
static inline void VectorTruncate(DDSVector4 *value)
{
value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x);
value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y);
value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z);
value->w = value->w > 0.0f ? floor(value->w) : ceil(value->w);
}
static inline void VectorTruncate3(DDSVector3 *value)
{
value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x);
value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y);
value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z);
}
static void CalculateColors(unsigned short c0, unsigned short c1,
DDSColors *c, MagickBooleanType ignoreAlpha)
{
c->a[0] = c->a[1] = c->a[2] = c->a[3] = 0;
c->r[0] = (unsigned char) C565_red(c0);
c->g[0] = (unsigned char) C565_green(c0);
c->b[0] = (unsigned char) C565_blue(c0);
c->r[1] = (unsigned char) C565_red(c1);
c->g[1] = (unsigned char) C565_green(c1);
c->b[1] = (unsigned char) C565_blue(c1);
if (ignoreAlpha != MagickFalse || c0 > c1)
{
c->r[2] = (unsigned char) ((2 * c->r[0] + c->r[1]) / 3);
c->g[2] = (unsigned char) ((2 * c->g[0] + c->g[1]) / 3);
c->b[2] = (unsigned char) ((2 * c->b[0] + c->b[1]) / 3);
c->r[3] = (unsigned char) ((c->r[0] + 2 * c->r[1]) / 3);
c->g[3] = (unsigned char) ((c->g[0] + 2 * c->g[1]) / 3);
c->b[3] = (unsigned char) ((c->b[0] + 2 * c->b[1]) / 3);
}
else
{
c->r[2] = (unsigned char) ((c->r[0] + c->r[1]) / 2);
c->g[2] = (unsigned char) ((c->g[0] + c->g[1]) / 2);
c->b[2] = (unsigned char) ((c->b[0] + c->b[1]) / 2);
c->r[3] = c->g[3] = c->b[3] = 0;
c->a[3] = 255;
}
}
static size_t CompressAlpha(const size_t min, const size_t max,
const size_t steps, const ssize_t *alphas, unsigned char* indices)
{
unsigned char
codes[8];
register ssize_t
i;
size_t
error,
index,
j,
least,
value;
codes[0] = (unsigned char) min;
codes[1] = (unsigned char) max;
codes[6] = 0;
codes[7] = 255;
for (i=1; i < (ssize_t) steps; i++)
codes[i+1] = (unsigned char) (((steps-i)*min + i*max) / steps);
error = 0;
for (i=0; i<16; i++)
{
if (alphas[i] == -1)
{
indices[i] = 0;
continue;
}
value = alphas[i];
least = SIZE_MAX;
index = 0;
for (j=0; j<8; j++)
{
size_t
dist;
dist = value - (size_t)codes[j];
dist *= dist;
if (dist < least)
{
least = dist;
index = j;
}
}
indices[i] = (unsigned char)index;
error += least;
}
return error;
}
static void CompressClusterFit(const size_t count,
const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle,
const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end,
unsigned char *indices)
{
DDSVector3
axis;
DDSVector4
grid,
gridrcp,
half,
onethird_onethird2,
pointsWeights[16],
two,
twonineths,
twothirds_twothirds2,
xSumwSum;
float
bestError = 1e+37f;
size_t
bestIteration = 0,
besti = 0,
bestj = 0,
bestk = 0,
iterationIndex;
ssize_t
i;
unsigned char
*o,
order[128],
unordered[16];
VectorInit(half,0.5f);
VectorInit(two,2.0f);
VectorInit(onethird_onethird2,1.0f/3.0f);
onethird_onethird2.w = 1.0f/9.0f;
VectorInit(twothirds_twothirds2,2.0f/3.0f);
twothirds_twothirds2.w = 4.0f/9.0f;
VectorInit(twonineths,2.0f/9.0f);
grid.x = 31.0f;
grid.y = 63.0f;
grid.z = 31.0f;
grid.w = 0.0f;
gridrcp.x = 1.0f/31.0f;
gridrcp.y = 1.0f/63.0f;
gridrcp.z = 1.0f/31.0f;
gridrcp.w = 0.0f;
xSumwSum.x = 0.0f;
xSumwSum.y = 0.0f;
xSumwSum.z = 0.0f;
xSumwSum.w = 0.0f;
ConstructOrdering(count,points,principle,pointsWeights,&xSumwSum,order,0);
for (iterationIndex = 0;;)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,1) \
num_threads(GetMagickResourceLimit(ThreadResource))
#endif
for (i=0; i < (ssize_t) count; i++)
{
DDSVector4
part0,
part1,
part2;
size_t
ii,
j,
k,
kmin;
VectorInit(part0,0.0f);
for(ii=0; ii < (size_t) i; ii++)
VectorAdd(pointsWeights[ii],part0,&part0);
VectorInit(part1,0.0f);
for (j=(size_t) i;;)
{
if (j == 0)
{
VectorCopy44(pointsWeights[0],&part2);
kmin = 1;
}
else
{
VectorInit(part2,0.0f);
kmin = j;
}
for (k=kmin;;)
{
DDSVector4
a,
alpha2_sum,
alphax_sum,
alphabeta_sum,
b,
beta2_sum,
betax_sum,
e1,
e2,
factor,
part3;
float
error;
VectorSubtract(xSumwSum,part2,&part3);
VectorSubtract(part3,part1,&part3);
VectorSubtract(part3,part0,&part3);
VectorMultiplyAdd(part1,twothirds_twothirds2,part0,&alphax_sum);
VectorMultiplyAdd(part2,onethird_onethird2,alphax_sum,&alphax_sum);
VectorInit(alpha2_sum,alphax_sum.w);
VectorMultiplyAdd(part2,twothirds_twothirds2,part3,&betax_sum);
VectorMultiplyAdd(part1,onethird_onethird2,betax_sum,&betax_sum);
VectorInit(beta2_sum,betax_sum.w);
VectorAdd(part1,part2,&alphabeta_sum);
VectorInit(alphabeta_sum,alphabeta_sum.w);
VectorMultiply(twonineths,alphabeta_sum,&alphabeta_sum);
VectorMultiply(alpha2_sum,beta2_sum,&factor);
VectorNegativeMultiplySubtract(alphabeta_sum,alphabeta_sum,factor,
&factor);
VectorReciprocal(factor,&factor);
VectorMultiply(alphax_sum,beta2_sum,&a);
VectorNegativeMultiplySubtract(betax_sum,alphabeta_sum,a,&a);
VectorMultiply(a,factor,&a);
VectorMultiply(betax_sum,alpha2_sum,&b);
VectorNegativeMultiplySubtract(alphax_sum,alphabeta_sum,b,&b);
VectorMultiply(b,factor,&b);
VectorClamp(&a);
VectorMultiplyAdd(grid,a,half,&a);
VectorTruncate(&a);
VectorMultiply(a,gridrcp,&a);
VectorClamp(&b);
VectorMultiplyAdd(grid,b,half,&b);
VectorTruncate(&b);
VectorMultiply(b,gridrcp,&b);
VectorMultiply(b,b,&e1);
VectorMultiply(e1,beta2_sum,&e1);
VectorMultiply(a,a,&e2);
VectorMultiplyAdd(e2,alpha2_sum,e1,&e1);
VectorMultiply(a,b,&e2);
VectorMultiply(e2,alphabeta_sum,&e2);
VectorNegativeMultiplySubtract(a,alphax_sum,e2,&e2);
VectorNegativeMultiplySubtract(b,betax_sum,e2,&e2);
VectorMultiplyAdd(two,e2,e1,&e2);
VectorMultiply(e2,metric,&e2);
error = e2.x + e2.y + e2.z;
if (error < bestError)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (DDS_CompressClusterFit)
#endif
{
if (error < bestError)
{
VectorCopy43(a,start);
VectorCopy43(b,end);
bestError = error;
besti = i;
bestj = j;
bestk = k;
bestIteration = iterationIndex;
}
}
}
if (k == count)
break;
VectorAdd(pointsWeights[k],part2,&part2);
k++;
}
if (j == count)
break;
VectorAdd(pointsWeights[j],part1,&part1);
j++;
}
}
if (bestIteration != iterationIndex)
break;
iterationIndex++;
if (iterationIndex == 8)
break;
VectorSubtract3(*end,*start,&axis);
if (ConstructOrdering(count,points,axis,pointsWeights,&xSumwSum,order,
iterationIndex) == MagickFalse)
break;
}
o = order + (16*bestIteration);
for (i=0; i < (ssize_t) besti; i++)
unordered[o[i]] = 0;
for (i=besti; i < (ssize_t) bestj; i++)
unordered[o[i]] = 2;
for (i=bestj; i < (ssize_t) bestk; i++)
unordered[o[i]] = 3;
for (i=bestk; i < (ssize_t) count; i++)
unordered[o[i]] = 1;
RemapIndices(map,unordered,indices);
}
static void CompressRangeFit(const size_t count,
const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle,
const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end,
unsigned char *indices)
{
float
d,
bestDist,
max,
min,
val;
DDSVector3
codes[4],
grid,
gridrcp,
half,
dist;
register ssize_t
i;
size_t
bestj,
j;
unsigned char
closest[16];
VectorInit3(half,0.5f);
grid.x = 31.0f;
grid.y = 63.0f;
grid.z = 31.0f;
gridrcp.x = 1.0f/31.0f;
gridrcp.y = 1.0f/63.0f;
gridrcp.z = 1.0f/31.0f;
if (count > 0)
{
VectorCopy43(points[0],start);
VectorCopy43(points[0],end);
min = max = Dot(points[0],principle);
for (i=1; i < (ssize_t) count; i++)
{
val = Dot(points[i],principle);
if (val < min)
{
VectorCopy43(points[i],start);
min = val;
}
else if (val > max)
{
VectorCopy43(points[i],end);
max = val;
}
}
}
VectorClamp3(start);
VectorMultiplyAdd3(grid,*start,half,start);
VectorTruncate3(start);
VectorMultiply3(*start,gridrcp,start);
VectorClamp3(end);
VectorMultiplyAdd3(grid,*end,half,end);
VectorTruncate3(end);
VectorMultiply3(*end,gridrcp,end);
codes[0] = *start;
codes[1] = *end;
codes[2].x = (start->x * (2.0f/3.0f)) + (end->x * (1.0f/3.0f));
codes[2].y = (start->y * (2.0f/3.0f)) + (end->y * (1.0f/3.0f));
codes[2].z = (start->z * (2.0f/3.0f)) + (end->z * (1.0f/3.0f));
codes[3].x = (start->x * (1.0f/3.0f)) + (end->x * (2.0f/3.0f));
codes[3].y = (start->y * (1.0f/3.0f)) + (end->y * (2.0f/3.0f));
codes[3].z = (start->z * (1.0f/3.0f)) + (end->z * (2.0f/3.0f));
for (i=0; i < (ssize_t) count; i++)
{
bestDist = 1e+37f;
bestj = 0;
for (j=0; j < 4; j++)
{
dist.x = (points[i].x - codes[j].x) * metric.x;
dist.y = (points[i].y - codes[j].y) * metric.y;
dist.z = (points[i].z - codes[j].z) * metric.z;
d = Dot(dist,dist);
if (d < bestDist)
{
bestDist = d;
bestj = j;
}
}
closest[i] = (unsigned char) bestj;
}
RemapIndices(map, closest, indices);
}
static void ComputeEndPoints(const DDSSingleColourLookup *lookup[],
const unsigned char *color, DDSVector3 *start, DDSVector3 *end,
unsigned char *index)
{
register ssize_t
i;
size_t
c,
maxError = SIZE_MAX;
for (i=0; i < 2; i++)
{
const DDSSourceBlock*
sources[3];
size_t
error = 0;
for (c=0; c < 3; c++)
{
sources[c] = &lookup[c][color[c]].sources[i];
error += ((size_t) sources[c]->error) * ((size_t) sources[c]->error);
}
if (error > maxError)
continue;
start->x = (float) sources[0]->start / 31.0f;
start->y = (float) sources[1]->start / 63.0f;
start->z = (float) sources[2]->start / 31.0f;
end->x = (float) sources[0]->end / 31.0f;
end->y = (float) sources[1]->end / 63.0f;
end->z = (float) sources[2]->end / 31.0f;
*index = (unsigned char) (2*i);
maxError = error;
}
}
static void ComputePrincipleComponent(const float *covariance,
DDSVector3 *principle)
{
DDSVector4
row0,
row1,
row2,
v;
register ssize_t
i;
row0.x = covariance[0];
row0.y = covariance[1];
row0.z = covariance[2];
row0.w = 0.0f;
row1.x = covariance[1];
row1.y = covariance[3];
row1.z = covariance[4];
row1.w = 0.0f;
row2.x = covariance[2];
row2.y = covariance[4];
row2.z = covariance[5];
row2.w = 0.0f;
VectorInit(v,1.0f);
for (i=0; i < 8; i++)
{
DDSVector4
w;
float
a;
w.x = row0.x * v.x;
w.y = row0.y * v.x;
w.z = row0.z * v.x;
w.w = row0.w * v.x;
w.x = (row1.x * v.y) + w.x;
w.y = (row1.y * v.y) + w.y;
w.z = (row1.z * v.y) + w.z;
w.w = (row1.w * v.y) + w.w;
w.x = (row2.x * v.z) + w.x;
w.y = (row2.y * v.z) + w.y;
w.z = (row2.z * v.z) + w.z;
w.w = (row2.w * v.z) + w.w;
a = 1.0f / MagickMax(w.x,MagickMax(w.y,w.z));
v.x = w.x * a;
v.y = w.y * a;
v.z = w.z * a;
v.w = w.w * a;
}
VectorCopy43(v,principle);
}
static void ComputeWeightedCovariance(const size_t count,
const DDSVector4 *points, float *covariance)
{
DDSVector3
centroid;
float
total;
size_t
i;
total = 0.0f;
VectorInit3(centroid,0.0f);
for (i=0; i < count; i++)
{
total += points[i].w;
centroid.x += (points[i].x * points[i].w);
centroid.y += (points[i].y * points[i].w);
centroid.z += (points[i].z * points[i].w);
}
if( total > 1.192092896e-07F)
{
centroid.x /= total;
centroid.y /= total;
centroid.z /= total;
}
for (i=0; i < 6; i++)
covariance[i] = 0.0f;
for (i = 0; i < count; i++)
{
DDSVector3
a,
b;
a.x = points[i].x - centroid.x;
a.y = points[i].y - centroid.y;
a.z = points[i].z - centroid.z;
b.x = points[i].w * a.x;
b.y = points[i].w * a.y;
b.z = points[i].w * a.z;
covariance[0] += a.x*b.x;
covariance[1] += a.x*b.y;
covariance[2] += a.x*b.z;
covariance[3] += a.y*b.y;
covariance[4] += a.y*b.z;
covariance[5] += a.z*b.z;
}
}
static MagickBooleanType ConstructOrdering(const size_t count,
const DDSVector4 *points, const DDSVector3 axis, DDSVector4 *pointsWeights,
DDSVector4 *xSumwSum, unsigned char *order, size_t iteration)
{
float
dps[16],
f;
register ssize_t
i;
size_t
j;
unsigned char
c,
*o,
*p;
o = order + (16*iteration);
for (i=0; i < (ssize_t) count; i++)
{
dps[i] = Dot(points[i],axis);
o[i] = (unsigned char)i;
}
for (i=0; i < (ssize_t) count; i++)
{
for (j=i; j > 0 && dps[j] < dps[j - 1]; j--)
{
f = dps[j];
dps[j] = dps[j - 1];
dps[j - 1] = f;
c = o[j];
o[j] = o[j - 1];
o[j - 1] = c;
}
}
for (i=0; i < (ssize_t) iteration; i++)
{
MagickBooleanType
same;
p = order + (16*i);
same = MagickTrue;
for (j=0; j < count; j++)
{
if (o[j] != p[j])
{
same = MagickFalse;
break;
}
}
if (same != MagickFalse)
return MagickFalse;
}
xSumwSum->x = 0;
xSumwSum->y = 0;
xSumwSum->z = 0;
xSumwSum->w = 0;
for (i=0; i < (ssize_t) count; i++)
{
DDSVector4
v;
j = (size_t) o[i];
v.x = points[j].w * points[j].x;
v.y = points[j].w * points[j].y;
v.z = points[j].w * points[j].z;
v.w = points[j].w * 1.0f;
VectorCopy44(v,&pointsWeights[i]);
VectorAdd(*xSumwSum,v,xSumwSum);
}
return MagickTrue;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s D D S %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsDDS() returns MagickTrue if the image format type, identified by the
% magick string, is DDS.
%
% The format of the IsDDS method is:
%
% MagickBooleanType IsDDS(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsDDS(const unsigned char *magick, const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((char *) magick,"DDS ", 4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadDDSImage() reads a DirectDraw Surface image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadDDSImage method is:
%
% Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: The image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status,
cubemap = MagickFalse,
volume = MagickFalse,
matte;
CompressionType
compression;
DDSInfo
dds_info;
DDSDecoder
*decoder;
size_t
n,
num_images;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
if (ReadDDSInfo(image, &dds_info) != MagickTrue) {
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)
cubemap = MagickTrue;
if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)
volume = MagickTrue;
(void) SeekBlob(image, 128, SEEK_SET);
/*
Determine pixel format
*/
if (dds_info.pixelformat.flags & DDPF_RGB)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
matte = MagickTrue;
decoder = ReadUncompressedRGBA;
}
else
{
matte = MagickTrue;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_LUMINANCE)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
/* Not sure how to handle this */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
else
{
matte = MagickFalse;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_FOURCC)
{
switch (dds_info.pixelformat.fourcc)
{
case FOURCC_DXT1:
{
matte = MagickFalse;
compression = DXT1Compression;
decoder = ReadDXT1;
break;
}
case FOURCC_DXT3:
{
matte = MagickTrue;
compression = DXT3Compression;
decoder = ReadDXT3;
break;
}
case FOURCC_DXT5:
{
matte = MagickTrue;
compression = DXT5Compression;
decoder = ReadDXT5;
break;
}
default:
{
/* Unknown FOURCC */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
}
}
else
{
/* Neither compressed nor uncompressed... thus unsupported */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
num_images = 1;
if (cubemap)
{
/*
Determine number of faces defined in the cubemap
*/
num_images = 0;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++;
}
if (volume)
num_images = dds_info.depth;
for (n = 0; n < num_images; n++)
{
if (n != 0)
{
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
/* Start a new image */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
image->matte = matte;
image->compression = compression;
image->columns = dds_info.width;
image->rows = dds_info.height;
image->storage_class = DirectClass;
image->endian = LSBEndian;
image->depth = 8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if ((decoder)(image, &dds_info, exception) != MagickTrue)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
static MagickBooleanType ReadDDSInfo(Image *image, DDSInfo *dds_info)
{
size_t
hdr_size,
required;
/* Seek to start of header */
(void) SeekBlob(image, 4, SEEK_SET);
/* Check header field */
hdr_size = ReadBlobLSBLong(image);
if (hdr_size != 124)
return MagickFalse;
/* Fill in DDS info struct */
dds_info->flags = ReadBlobLSBLong(image);
/* Check required flags */
required=(size_t) (DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT);
if ((dds_info->flags & required) != required)
return MagickFalse;
dds_info->height = ReadBlobLSBLong(image);
dds_info->width = ReadBlobLSBLong(image);
dds_info->pitchOrLinearSize = ReadBlobLSBLong(image);
dds_info->depth = ReadBlobLSBLong(image);
dds_info->mipmapcount = ReadBlobLSBLong(image);
(void) SeekBlob(image, 44, SEEK_CUR); /* reserved region of 11 DWORDs */
/* Read pixel format structure */
hdr_size = ReadBlobLSBLong(image);
if (hdr_size != 32)
return MagickFalse;
dds_info->pixelformat.flags = ReadBlobLSBLong(image);
dds_info->pixelformat.fourcc = ReadBlobLSBLong(image);
dds_info->pixelformat.rgb_bitcount = ReadBlobLSBLong(image);
dds_info->pixelformat.r_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.g_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.b_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.alpha_bitmask = ReadBlobLSBLong(image);
dds_info->ddscaps1 = ReadBlobLSBLong(image);
dds_info->ddscaps2 = ReadBlobLSBLong(image);
(void) SeekBlob(image, 12, SEEK_CUR); /* 3 reserved DWORDs */
return MagickTrue;
}
static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
PixelPacket
*q;
register ssize_t
i,
x;
size_t
bits;
ssize_t
j,
y;
unsigned char
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),
MagickMin(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickFalse);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (unsigned char) ((bits >> ((j*4+i)*2)) & 0x3);
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
SetPixelOpacity(q,ScaleCharToQuantum(colors.a[code]));
if (colors.a[code] && image->matte == MagickFalse)
/* Correct matte */
image->matte = MagickTrue;
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
return(SkipDXTMipmaps(image,dds_info,8,exception));
}
static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
ssize_t
j,
y;
PixelPacket
*q;
register ssize_t
i,
x;
unsigned char
alpha;
size_t
a0,
a1,
bits,
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),
MagickMin(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = ReadBlobLSBLong(image);
a1 = ReadBlobLSBLong(image);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
/*
Extract alpha value: multiply 0..15 by 17 to get range 0..255
*/
if (j < 2)
alpha = 17U * (unsigned char) ((a0 >> (4*(4*j+i))) & 0xf);
else
alpha = 17U * (unsigned char) ((a1 >> (4*(4*(j-2)+i))) & 0xf);
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
alpha));
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
return(SkipDXTMipmaps(image,dds_info,16,exception));
}
static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
ssize_t
j,
y;
MagickSizeType
alpha_bits;
PixelPacket
*q;
register ssize_t
i,
x;
unsigned char
a0,
a1;
size_t
alpha,
bits,
code,
alpha_code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),
MagickMin(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = (unsigned char) ReadBlobByte(image);
a1 = (unsigned char) ReadBlobByte(image);
alpha_bits = (MagickSizeType)ReadBlobLSBLong(image);
alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
/* Extract alpha value */
alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7;
if (alpha_code == 0)
alpha = a0;
else if (alpha_code == 1)
alpha = a1;
else if (a0 > a1)
alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7;
else if (alpha_code == 6)
alpha = 0;
else if (alpha_code == 7)
alpha = 255;
else
alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5);
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
alpha));
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
return(SkipDXTMipmaps(image,dds_info,16,exception));
}
static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
PixelPacket
*q;
ssize_t
x, y;
unsigned short
color;
if (dds_info->pixelformat.rgb_bitcount == 8)
(void) SetImageType(image,GrayscaleType);
else if (dds_info->pixelformat.rgb_bitcount == 16 && !IsBitMask(
dds_info->pixelformat,0xf800,0x07e0,0x001f,0x0000))
ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
image->filename);
for (y = 0; y < (ssize_t) dds_info->height; y++)
{
q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
for (x = 0; x < (ssize_t) dds_info->width; x++)
{
if (dds_info->pixelformat.rgb_bitcount == 8)
SetPixelGray(q,ScaleCharToQuantum(ReadBlobByte(image)));
else if (dds_info->pixelformat.rgb_bitcount == 16)
{
color=ReadBlobShort(image);
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
(((color >> 11)/31.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 5) >> 10)/63.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 11) >> 11)/31.0)*255)));
}
else
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
if (dds_info->pixelformat.rgb_bitcount == 32)
(void) ReadBlobByte(image);
}
SetPixelAlpha(q,QuantumRange);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
return(SkipRGBMipmaps(image,dds_info,3,exception));
}
static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
PixelPacket
*q;
ssize_t
alphaBits,
x,
y;
unsigned short
color;
alphaBits=0;
if (dds_info->pixelformat.rgb_bitcount == 16)
{
if (IsBitMask(dds_info->pixelformat,0x7c00,0x03e0,0x001f,0x8000))
alphaBits=1;
else if (IsBitMask(dds_info->pixelformat,0x00ff,0x00ff,0x00ff,0xff00))
{
alphaBits=2;
(void) SetImageType(image,GrayscaleMatteType);
}
else if (IsBitMask(dds_info->pixelformat,0x0f00,0x00f0,0x000f,0xf000))
alphaBits=4;
else
ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
image->filename);
}
for (y = 0; y < (ssize_t) dds_info->height; y++)
{
q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
for (x = 0; x < (ssize_t) dds_info->width; x++)
{
if (dds_info->pixelformat.rgb_bitcount == 16)
{
color=ReadBlobShort(image);
if (alphaBits == 1)
{
SetPixelAlpha(q,(color & (1 << 15)) ? QuantumRange : 0);
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 1) >> 11)/31.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 6) >> 11)/31.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 11) >> 11)/31.0)*255)));
}
else if (alphaBits == 2)
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
(color >> 8)));
SetPixelGray(q,ScaleCharToQuantum((unsigned char)color));
}
else
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
(((color >> 12)/15.0)*255)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 4) >> 12)/15.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 8) >> 12)/15.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 12) >> 12)/15.0)*255)));
}
}
else
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
return(SkipRGBMipmaps(image,dds_info,4,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterDDSImage() adds attributes for the DDS image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterDDSImage method is:
%
% RegisterDDSImage(void)
%
*/
ModuleExport size_t RegisterDDSImage(void)
{
MagickInfo
*entry;
entry = SetMagickInfo("DDS");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
entry = SetMagickInfo("DXT1");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
entry = SetMagickInfo("DXT5");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
static void RemapIndices(const ssize_t *map, const unsigned char *source,
unsigned char *target)
{
register ssize_t
i;
for (i = 0; i < 16; i++)
{
if (map[i] == -1)
target[i] = 3;
else
target[i] = source[map[i]];
}
}
/*
Skip the mipmap images for compressed (DXTn) dds files
*/
static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info,
int texel_size,ExceptionInfo *exception)
{
register ssize_t
i;
MagickOffsetType
offset;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
/*
Skip the mipmap images for uncompressed (RGB or RGBA) dds files
*/
static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,
int pixel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterDDSImage() removes format registrations made by the
% DDS module from the list of supported formats.
%
% The format of the UnregisterDDSImage method is:
%
% UnregisterDDSImage(void)
%
*/
ModuleExport void UnregisterDDSImage(void)
{
(void) UnregisterMagickInfo("DDS");
(void) UnregisterMagickInfo("DXT1");
(void) UnregisterMagickInfo("DXT5");
}
static void WriteAlphas(Image *image, const ssize_t* alphas, size_t min5,
size_t max5, size_t min7, size_t max7)
{
register ssize_t
i;
size_t
err5,
err7,
j;
unsigned char
indices5[16],
indices7[16];
FixRange(min5,max5,5);
err5 = CompressAlpha(min5,max5,5,alphas,indices5);
FixRange(min7,max7,7);
err7 = CompressAlpha(min7,max7,7,alphas,indices7);
if (err7 < err5)
{
for (i=0; i < 16; i++)
{
unsigned char
index;
index = indices7[i];
if( index == 0 )
indices5[i] = 1;
else if (index == 1)
indices5[i] = 0;
else
indices5[i] = 9 - index;
}
min5 = max7;
max5 = min7;
}
(void) WriteBlobByte(image,(unsigned char) min5);
(void) WriteBlobByte(image,(unsigned char) max5);
for(i=0; i < 2; i++)
{
size_t
value = 0;
for (j=0; j < 8; j++)
{
size_t index = (size_t) indices5[j + i*8];
value |= ( index << 3*j );
}
for (j=0; j < 3; j++)
{
size_t byte = (value >> 8*j) & 0xff;
(void) WriteBlobByte(image,(unsigned char) byte);
}
}
}
static void WriteCompressed(Image *image, const size_t count,
DDSVector4* points, const ssize_t* map, const MagickBooleanType clusterFit)
{
float
covariance[16];
DDSVector3
end,
principle,
start;
DDSVector4
metric;
unsigned char
indices[16];
VectorInit(metric,1.0f);
VectorInit3(start,0.0f);
VectorInit3(end,0.0f);
ComputeWeightedCovariance(count,points,covariance);
ComputePrincipleComponent(covariance,&principle);
if (clusterFit == MagickFalse || count == 0)
CompressRangeFit(count,points,map,principle,metric,&start,&end,indices);
else
CompressClusterFit(count,points,map,principle,metric,&start,&end,indices);
WriteIndices(image,start,end,indices);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteDDSImage() writes a DirectDraw Surface image file in the DXT5 format.
%
% The format of the WriteBMPImage method is:
%
% MagickBooleanType WriteDDSImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteDDSImage(const ImageInfo *image_info,
Image *image)
{
const char
*option;
size_t
compression,
columns,
maxMipmaps,
mipmaps,
pixelFormat,
rows;
MagickBooleanType
clusterFit,
status,
weightByAlpha;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
pixelFormat=DDPF_FOURCC;
compression=FOURCC_DXT5;
if (!image->matte)
compression=FOURCC_DXT1;
if (LocaleCompare(image_info->magick,"dxt1") == 0)
compression=FOURCC_DXT1;
option=GetImageOption(image_info,"dds:compression");
if (option != (char *) NULL)
{
if (LocaleCompare(option,"dxt1") == 0)
compression=FOURCC_DXT1;
if (LocaleCompare(option,"none") == 0)
pixelFormat=DDPF_RGB;
}
clusterFit=MagickFalse;
weightByAlpha=MagickFalse;
if (pixelFormat == DDPF_FOURCC)
{
option=GetImageOption(image_info,"dds:cluster-fit");
if (option != (char *) NULL && LocaleCompare(option,"true") == 0)
{
clusterFit=MagickTrue;
if (compression != FOURCC_DXT1)
{
option=GetImageOption(image_info,"dds:weight-by-alpha");
if (option != (char *) NULL && LocaleCompare(option,"true") == 0)
weightByAlpha=MagickTrue;
}
}
}
maxMipmaps=SIZE_MAX;
mipmaps=0;
if ((image->columns & (image->columns - 1)) == 0 &&
(image->rows & (image->rows - 1)) == 0)
{
option=GetImageOption(image_info,"dds:mipmaps");
if (option != (char *) NULL)
maxMipmaps=StringToUnsignedLong(option);
if (maxMipmaps != 0)
{
columns=image->columns;
rows=image->rows;
while (columns != 1 && rows != 1 && mipmaps != maxMipmaps)
{
columns=DIV2(columns);
rows=DIV2(rows);
mipmaps++;
}
}
}
WriteDDSInfo(image,pixelFormat,compression,mipmaps);
WriteImageData(image,pixelFormat,compression,clusterFit,weightByAlpha,
&image->exception);
if (mipmaps > 0 && WriteMipmaps(image,pixelFormat,compression,mipmaps,
clusterFit,weightByAlpha,&image->exception) == MagickFalse)
return(MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
static void WriteDDSInfo(Image *image, const size_t pixelFormat,
const size_t compression, const size_t mipmaps)
{
char
software[MaxTextExtent];
register ssize_t
i;
unsigned int
format,
caps,
flags;
flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT |
DDSD_PIXELFORMAT | DDSD_LINEARSIZE);
caps=(unsigned int) DDSCAPS_TEXTURE;
format=(unsigned int) pixelFormat;
if (mipmaps > 0)
{
flags=flags | (unsigned int) DDSD_MIPMAPCOUNT;
caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX);
}
if (format != DDPF_FOURCC && image->matte)
format=format | DDPF_ALPHAPIXELS;
(void) WriteBlob(image,4,(unsigned char *) "DDS ");
(void) WriteBlobLSBLong(image,124);
(void) WriteBlobLSBLong(image,flags);
(void) WriteBlobLSBLong(image,(unsigned int) image->rows);
(void) WriteBlobLSBLong(image,(unsigned int) image->columns);
if (compression == FOURCC_DXT1)
(void) WriteBlobLSBLong(image,
(unsigned int) (MagickMax(1,(image->columns+3)/4) * 8));
else
(void) WriteBlobLSBLong(image,
(unsigned int) (MagickMax(1,(image->columns+3)/4) * 16));
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1);
(void) ResetMagickMemory(software,0,sizeof(software));
(void) strcpy(software,"IMAGEMAGICK");
(void) WriteBlob(image,44,(unsigned char *) software);
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,format);
if (pixelFormat == DDPF_FOURCC)
{
(void) WriteBlobLSBLong(image,(unsigned int) compression);
for(i=0;i < 5;i++) // bitcount / masks
(void) WriteBlobLSBLong(image,0x00);
}
else
{
(void) WriteBlobLSBLong(image,0x00);
if (image->matte)
{
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,0xff0000);
(void) WriteBlobLSBLong(image,0xff00);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0xff000000);
}
else
{
(void) WriteBlobLSBLong(image,24);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,0x00);
}
}
(void) WriteBlobLSBLong(image,caps);
for(i=0;i < 4;i++) // ddscaps2 + reserved region
(void) WriteBlobLSBLong(image,0x00);
}
static void WriteFourCC(Image *image, const size_t compression,
const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha,
ExceptionInfo *exception)
{
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
i,
y,
bx,
by;
for (y=0; y < (ssize_t) image->rows; y+=4)
{
for (x=0; x < (ssize_t) image->columns; x+=4)
{
MagickBooleanType
match;
DDSVector4
point,
points[16];
size_t
count = 0,
max5 = 0,
max7 = 0,
min5 = 255,
min7 = 255,
columns = 4,
rows = 4;
ssize_t
alphas[16],
map[16];
unsigned char
alpha;
if (x + columns >= image->columns)
columns = image->columns - x;
if (y + rows >= image->rows)
rows = image->rows - y;
p=GetVirtualPixels(image,x,y,columns,rows,exception);
if (p == (const PixelPacket *) NULL)
break;
for (i=0; i<16; i++)
{
map[i] = -1;
alphas[i] = -1;
}
for (by=0; by < (ssize_t) rows; by++)
{
for (bx=0; bx < (ssize_t) columns; bx++)
{
if (compression == FOURCC_DXT5)
alpha = ScaleQuantumToChar(GetPixelAlpha(p));
else
alpha = 255;
alphas[4*by + bx] = (size_t)alpha;
point.x = (float)ScaleQuantumToChar(GetPixelRed(p)) / 255.0f;
point.y = (float)ScaleQuantumToChar(GetPixelGreen(p)) / 255.0f;
point.z = (float)ScaleQuantumToChar(GetPixelBlue(p)) / 255.0f;
point.w = weightByAlpha ? (float)(alpha + 1) / 256.0f : 1.0f;
p++;
match = MagickFalse;
for (i=0; i < (ssize_t) count; i++)
{
if ((points[i].x == point.x) &&
(points[i].y == point.y) &&
(points[i].z == point.z) &&
(alpha >= 128 || compression == FOURCC_DXT5))
{
points[i].w += point.w;
map[4*by + bx] = i;
match = MagickTrue;
break;
}
}
if (match != MagickFalse)
continue;
points[count].x = point.x;
points[count].y = point.y;
points[count].z = point.z;
points[count].w = point.w;
map[4*by + bx] = count;
count++;
if (compression == FOURCC_DXT5)
{
if (alpha < min7)
min7 = alpha;
if (alpha > max7)
max7 = alpha;
if (alpha != 0 && alpha < min5)
min5 = alpha;
if (alpha != 255 && alpha > max5)
max5 = alpha;
}
}
}
for (i=0; i < (ssize_t) count; i++)
points[i].w = sqrt(points[i].w);
if (compression == FOURCC_DXT5)
WriteAlphas(image,alphas,min5,max5,min7,max7);
if (count == 1)
WriteSingleColorFit(image,points,map);
else
WriteCompressed(image,count,points,map,clusterFit);
}
}
}
static void WriteImageData(Image *image, const size_t pixelFormat,
const size_t compression, const MagickBooleanType clusterFit,
const MagickBooleanType weightByAlpha, ExceptionInfo *exception)
{
if (pixelFormat == DDPF_FOURCC)
WriteFourCC(image,compression,clusterFit,weightByAlpha,exception);
else
WriteUncompressed(image,exception);
}
static inline size_t ClampToLimit(const float value,
const size_t limit)
{
size_t
result = (int) (value + 0.5f);
if (result < 0.0f)
return(0);
if (result > limit)
return(limit);
return result;
}
static inline size_t ColorTo565(const DDSVector3 point)
{
size_t r = ClampToLimit(31.0f*point.x,31);
size_t g = ClampToLimit(63.0f*point.y,63);
size_t b = ClampToLimit(31.0f*point.z,31);
return (r << 11) | (g << 5) | b;
}
static void WriteIndices(Image *image, const DDSVector3 start,
const DDSVector3 end, unsigned char* indices)
{
register ssize_t
i;
size_t
a,
b;
unsigned char
remapped[16];
const unsigned char
*ind;
a = ColorTo565(start);
b = ColorTo565(end);
for (i=0; i<16; i++)
{
if( a < b )
remapped[i] = (indices[i] ^ 0x1) & 0x3;
else if( a == b )
remapped[i] = 0;
else
remapped[i] = indices[i];
}
if( a < b )
Swap(a,b);
(void) WriteBlobByte(image,(unsigned char) (a & 0xff));
(void) WriteBlobByte(image,(unsigned char) (a >> 8));
(void) WriteBlobByte(image,(unsigned char) (b & 0xff));
(void) WriteBlobByte(image,(unsigned char) (b >> 8));
for (i=0; i<4; i++)
{
ind = remapped + 4*i;
(void) WriteBlobByte(image,ind[0] | (ind[1] << 2) | (ind[2] << 4) |
(ind[3] << 6));
}
}
static MagickBooleanType WriteMipmaps(Image *image, const size_t pixelFormat,
const size_t compression, const size_t mipmaps,
const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha,
ExceptionInfo *exception)
{
Image*
resize_image;
register ssize_t
i;
size_t
columns,
rows;
columns = image->columns;
rows = image->rows;
for (i=0; i< (ssize_t) mipmaps; i++)
{
resize_image = ResizeImage(image,columns/2,rows/2,TriangleFilter,1.0,
exception);
if (resize_image == (Image *) NULL)
return(MagickFalse);
DestroyBlob(resize_image);
resize_image->blob=ReferenceBlob(image->blob);
WriteImageData(resize_image,pixelFormat,compression,weightByAlpha,
clusterFit,exception);
resize_image=DestroyImage(resize_image);
columns = DIV2(columns);
rows = DIV2(rows);
}
return(MagickTrue);
}
static void WriteSingleColorFit(Image *image, const DDSVector4* points,
const ssize_t* map)
{
DDSVector3
start,
end;
register ssize_t
i;
unsigned char
color[3],
index,
indexes[16],
indices[16];
color[0] = (unsigned char) ClampToLimit(255.0f*points->x,255);
color[1] = (unsigned char) ClampToLimit(255.0f*points->y,255);
color[2] = (unsigned char) ClampToLimit(255.0f*points->z,255);
index=0;
ComputeEndPoints(DDS_LOOKUP,color,&start,&end,&index);
for (i=0; i< 16; i++)
indexes[i]=index;
RemapIndices(map,indexes,indices);
WriteIndices(image,start,end,indices);
}
static void WriteUncompressed(Image *image, ExceptionInfo *exception)
{
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
y;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelBlue(p)));
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelGreen(p)));
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelRed(p)));
if (image->matte)
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelAlpha(p)));
p++;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2433_0 |
crossvul-cpp_data_bad_1563_0 | #include <gio/gio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include "libabrt.h"
#include "abrt-polkit.h"
#include "abrt_glib.h"
#include <libreport/dump_dir.h>
#include "problem_api.h"
static GMainLoop *loop;
static guint g_timeout_source;
/* default, settable with -t: */
static unsigned g_timeout_value = 120;
/* ---------------------------------------------------------------------------------------------------- */
static GDBusNodeInfo *introspection_data = NULL;
/* Introspection data for the service we are exporting */
static const gchar introspection_xml[] =
"<node>"
" <interface name='"ABRT_DBUS_IFACE"'>"
" <method name='NewProblem'>"
" <arg type='a{ss}' name='problem_data' direction='in'/>"
" <arg type='s' name='problem_id' direction='out'/>"
" </method>"
" <method name='GetProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetAllProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetForeignProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetInfo'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='as' name='element_names' direction='in'/>"
" <arg type='a{ss}' name='response' direction='out'/>"
" </method>"
" <method name='SetElement'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" <arg type='s' name='value' direction='in'/>"
" </method>"
" <method name='DeleteElement'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" </method>"
" <method name='ChownProblemDir'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" </method>"
" <method name='DeleteProblem'>"
" <arg type='as' name='problem_dir' direction='in'/>"
" </method>"
" <method name='FindProblemByElementInTimeRange'>"
" <arg type='s' name='element' direction='in'/>"
" <arg type='s' name='value' direction='in'/>"
" <arg type='x' name='timestamp_from' direction='in'/>"
" <arg type='x' name='timestamp_to' direction='in'/>"
" <arg type='b' name='all_users' direction='in'/>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='Quit' />"
" </interface>"
"</node>";
/* ---------------------------------------------------------------------------------------------------- */
/* forward */
static gboolean on_timeout_cb(gpointer user_data);
static void reset_timeout(void)
{
if (g_timeout_source > 0)
{
log_info("Removing timeout");
g_source_remove(g_timeout_source);
}
log_info("Setting a new timeout");
g_timeout_source = g_timeout_add_seconds(g_timeout_value, on_timeout_cb, NULL);
}
static uid_t get_caller_uid(GDBusConnection *connection, GDBusMethodInvocation *invocation, const char *caller)
{
GError *error = NULL;
guint caller_uid;
GDBusProxy * proxy = g_dbus_proxy_new_sync(connection,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
NULL,
&error);
GVariant *result = g_dbus_proxy_call_sync(proxy,
"GetConnectionUnixUser",
g_variant_new ("(s)", caller),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
if (result == NULL)
{
/* we failed to get the uid, so return (uid_t) -1 to indicate the error
*/
if (error)
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidUser",
error->message);
g_error_free(error);
}
else
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidUser",
_("Unknown error"));
}
return (uid_t) -1;
}
g_variant_get(result, "(u)", &caller_uid);
g_variant_unref(result);
log_info("Caller uid: %i", caller_uid);
return caller_uid;
}
bool allowed_problem_dir(const char *dir_name)
{
if (!dir_is_in_dump_location(dir_name))
{
error_msg("Bad problem directory name '%s', should start with: '%s'", dir_name, g_settings_dump_location);
return false;
}
/* We cannot test correct permissions yet because we still need to chown
* dump directories before reporting and Chowing changes the file owner to
* the reporter, which causes this test to fail and prevents users from
* getting problem data after reporting it.
*
* Fortunately, libreport has been hardened against hard link and symbolic
* link attacks and refuses to work with such files, so this test isn't
* really necessary, however, we will use it once we get rid of the
* chowning files.
*
* abrt-server refuses to run post-create on directories that have
* incorrect owner (not "root:(abrt|root)"), incorrect permissions (other
* bits are not 0) and are complete (post-create finished). So, there is no
* way to run security sensitive event scripts (post-create) on crafted
* problem directories.
*/
#if 0
if (!dir_has_correct_permissions(dir_name))
{
error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dir_name);
return false;
}
#endif
return true;
}
static char *handle_new_problem(GVariant *problem_info, uid_t caller_uid, char **error)
{
problem_data_t *pd = problem_data_new();
GVariantIter *iter;
g_variant_get(problem_info, "a{ss}", &iter);
gchar *key, *value;
while (g_variant_iter_loop(iter, "{ss}", &key, &value))
{
problem_data_add_text_editable(pd, key, value);
}
if (caller_uid != 0 || problem_data_get_content_or_NULL(pd, FILENAME_UID) == NULL)
{ /* set uid field to caller's uid if caller is not root or root doesn't pass own uid */
log_info("Adding UID %d to problem data", caller_uid);
char buf[sizeof(uid_t) * 3 + 2];
snprintf(buf, sizeof(buf), "%d", caller_uid);
problem_data_add_text_noteditable(pd, FILENAME_UID, buf);
}
/* At least it should generate local problem identifier UUID */
problem_data_add_basics(pd);
char *problem_id = problem_data_save(pd);
if (problem_id)
notify_new_path(problem_id);
else if (error)
*error = xasprintf("Cannot create a new problem");
problem_data_free(pd);
return problem_id;
}
static void return_InvalidProblemDir_error(GDBusMethodInvocation *invocation, const char *dir_name)
{
char *msg = xasprintf(_("'%s' is not a valid problem directory"), dir_name);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidProblemDir",
msg);
free(msg);
}
/*
* Checks element's rights and does not open directory if element is protected.
* Checks problem's rights and does not open directory if user hasn't got
* access to a problem.
*
* Returns a dump directory opend for writing or NULL.
*
* If any operation from the above listed fails, immediately returns D-Bus
* error to a D-Bus caller.
*/
static struct dump_dir *open_directory_for_modification_of_element(
GDBusMethodInvocation *invocation,
uid_t caller_uid,
const char *problem_id,
const char *element)
{
static const char *const protected_elements[] = {
FILENAME_TIME,
FILENAME_UID,
NULL,
};
for (const char *const *protected = protected_elements; *protected; ++protected)
{
if (strcmp(*protected, element) == 0)
{
log_notice("'%s' element of '%s' can't be modified", element, problem_id);
char *error = xasprintf(_("'%s' element can't be modified"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ProtectedElement",
error);
free(error);
return NULL;
}
}
if (!dump_dir_accessible_by_uid(problem_id, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("'%s' is not a valid problem directory", problem_id);
return_InvalidProblemDir_error(invocation, problem_id);
}
else
{
log_notice("UID(%d) is not Authorized to access '%s'", caller_uid, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
}
return NULL;
}
struct dump_dir *dd = dd_opendir(problem_id, /* flags : */ 0);
if (!dd)
{ /* This should not happen because of the access check above */
log_notice("Can't access the problem '%s' for modification", problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("Can't access the problem for modification"));
return NULL;
}
return dd;
}
/*
* Lists problems which have given element and were seen in given time interval
*/
struct field_and_time_range {
GList *list;
const char *element;
const char *value;
unsigned long timestamp_from;
unsigned long timestamp_to;
};
static int add_dirname_to_GList_if_matches(struct dump_dir *dd, void *arg)
{
struct field_and_time_range *me = arg;
char *field_data = dd_load_text(dd, me->element);
int brk = (strcmp(field_data, me->value) != 0);
free(field_data);
if (brk)
return 0;
field_data = dd_load_text(dd, FILENAME_LAST_OCCURRENCE);
long val = atol(field_data);
free(field_data);
if (val < me->timestamp_from || val > me->timestamp_to)
return 0;
me->list = g_list_prepend(me->list, xstrdup(dd->dd_dirname));
return 0;
}
static GList *get_problem_dirs_for_element_in_time(uid_t uid,
const char *element,
const char *value,
unsigned long timestamp_from,
unsigned long timestamp_to)
{
if (timestamp_to == 0) /* not sure this is possible, but... */
timestamp_to = time(NULL);
struct field_and_time_range me = {
.list = NULL,
.element = element,
.value = value,
.timestamp_from = timestamp_from,
.timestamp_to = timestamp_to,
};
for_each_problem_in_dir(g_settings_dump_location, uid, add_dirname_to_GList_if_matches, &me);
return g_list_reverse(me.list);
}
static void handle_method_call(GDBusConnection *connection,
const gchar *caller,
const gchar *object_path,
const gchar *interface_name,
const gchar *method_name,
GVariant *parameters,
GDBusMethodInvocation *invocation,
gpointer user_data)
{
reset_timeout();
uid_t caller_uid;
GVariant *response;
caller_uid = get_caller_uid(connection, invocation, caller);
log_notice("caller_uid:%ld method:'%s'", (long)caller_uid, method_name);
if (caller_uid == (uid_t) -1)
return;
if (g_strcmp0(method_name, "NewProblem") == 0)
{
char *error = NULL;
char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error);
if (!problem_id)
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
free(error);
return;
}
/* else */
response = g_variant_new("(s)", problem_id);
g_dbus_method_invocation_return_value(invocation, response);
free(problem_id);
return;
}
if (g_strcmp0(method_name, "GetProblems") == 0)
{
GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
//I was told that g_dbus_method frees the response
//g_variant_unref(response);
return;
}
if (g_strcmp0(method_name, "GetAllProblems") == 0)
{
/*
- so, we have UID,
- if it's 0, then we don't have to check anything and just return all directories
- if uid != 0 then we want to ask for authorization
*/
if (caller_uid != 0)
{
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes)
caller_uid = 0;
}
GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "GetForeignProblems") == 0)
{
GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "ChownProblemDir") == 0)
{
const gchar *problem_dir;
g_variant_get(parameters, "(&s)", &problem_dir);
log_notice("problem_dir:'%s'", problem_dir);
if (!allowed_problem_dir(problem_dir))
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int ddstat = dump_dir_stat_for_uid(problem_dir, caller_uid);
if (ddstat < 0)
{
if (errno == ENOTDIR)
{
log_notice("requested directory does not exist '%s'", problem_dir);
}
else
{
perror_msg("can't get stat of '%s'", problem_dir);
}
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
if (ddstat & DD_STAT_OWNED_BY_UID)
{ //caller seems to be in group with access to this dir, so no action needed
log_notice("caller has access to the requested directory %s", problem_dir);
g_dbus_method_invocation_return_value(invocation, NULL);
return;
}
if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 &&
polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{
log_notice("not authorized");
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
return;
}
struct dump_dir *dd = dd_opendir(problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);
if (!dd)
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int chown_res = dd_chown(dd, caller_uid);
if (chown_res != 0)
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ChownError",
_("Chowning directory failed. Check system logs for more details."));
else
g_dbus_method_invocation_return_value(invocation, NULL);
dd_close(dd);
return;
}
if (g_strcmp0(method_name, "GetInfo") == 0)
{
/* Parameter tuple is (sas) */
/* Get 1st param - problem dir name */
const gchar *problem_dir;
g_variant_get_child(parameters, 0, "&s", &problem_dir);
log_notice("problem_dir:'%s'", problem_dir);
if (!allowed_problem_dir(problem_dir))
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
if (!dump_dir_accessible_by_uid(problem_dir, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("Requested directory does not exist '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{
log_notice("not authorized");
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
return;
}
}
struct dump_dir *dd = dd_opendir(problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);
if (!dd)
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
/* Get 2nd param - vector of element names */
GVariant *array = g_variant_get_child_value(parameters, 1);
GList *elements = string_list_from_variant(array);
g_variant_unref(array);
GVariantBuilder *builder = NULL;
for (GList *l = elements; l; l = l->next)
{
const char *element_name = (const char*)l->data;
char *value = dd_load_text_ext(dd, element_name, 0
| DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE
| DD_FAIL_QUIETLY_ENOENT
| DD_FAIL_QUIETLY_EACCES);
log_notice("element '%s' %s", element_name, value ? "fetched" : "not found");
if (value)
{
if (!builder)
builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
/* g_variant_builder_add makes a copy. No need to xstrdup here */
g_variant_builder_add(builder, "{ss}", element_name, value);
free(value);
}
}
list_free_with_free(elements);
dd_close(dd);
/* It is OK to call g_variant_new("(a{ss})", NULL) because */
/* G_VARIANT_TYPE_TUPLE allows NULL value */
GVariant *response = g_variant_new("(a{ss})", builder);
if (builder)
g_variant_builder_unref(builder);
log_info("GetInfo: returning value for '%s'", problem_dir);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "SetElement") == 0)
{
const char *problem_id;
const char *element;
const char *value;
g_variant_get(parameters, "(&s&s&s)", &problem_id, &element, &value);
if (element == NULL || element[0] == '\0' || strlen(element) > 64)
{
log_notice("'%s' is not a valid element name of '%s'", element, problem_id);
char *error = xasprintf(_("'%s' is not a valid element name"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidElement",
error);
free(error);
return;
}
struct dump_dir *dd = open_directory_for_modification_of_element(
invocation, caller_uid, problem_id, element);
if (!dd)
/* Already logged from open_directory_for_modification_of_element() */
return;
/* Is it good idea to make it static? Is it possible to change the max size while a single run? */
const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024);
const long item_size = dd_get_item_size(dd, element);
if (item_size < 0)
{
log_notice("Can't get size of '%s/%s'", problem_id, element);
char *error = xasprintf(_("Can't get size of '%s'"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
return;
}
const double requested_size = (double)strlen(value) - item_size;
/* Don't want to check the size limit in case of reducing of size */
if (requested_size > 0
&& requested_size > (max_dir_size - get_dirsize(g_settings_dump_location)))
{
log_notice("No problem space left in '%s' (requested Bytes %f)", problem_id, requested_size);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("No problem space left"));
}
else
{
dd_save_text(dd, element, value);
g_dbus_method_invocation_return_value(invocation, NULL);
}
dd_close(dd);
return;
}
if (g_strcmp0(method_name, "DeleteElement") == 0)
{
const char *problem_id;
const char *element;
g_variant_get(parameters, "(&s&s)", &problem_id, &element);
struct dump_dir *dd = open_directory_for_modification_of_element(
invocation, caller_uid, problem_id, element);
if (!dd)
/* Already logged from open_directory_for_modification_of_element() */
return;
const int res = dd_delete_item(dd, element);
dd_close(dd);
if (res != 0)
{
log_notice("Can't delete the element '%s' from the problem directory '%s'", element, problem_id);
char *error = xasprintf(_("Can't delete the element '%s' from the problem directory '%s'"), element, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
free(error);
return;
}
g_dbus_method_invocation_return_value(invocation, NULL);
return;
}
if (g_strcmp0(method_name, "DeleteProblem") == 0)
{
/* Dbus parameters are always tuples.
* In this case, it's (as) - a tuple of one element (array of strings).
* Need to fetch the array:
*/
GVariant *array = g_variant_get_child_value(parameters, 0);
GList *problem_dirs = string_list_from_variant(array);
g_variant_unref(array);
for (GList *l = problem_dirs; l; l = l->next)
{
const char *dir_name = (const char*)l->data;
log_notice("dir_name:'%s'", dir_name);
if (!allowed_problem_dir(dir_name))
{
return_InvalidProblemDir_error(invocation, dir_name);
goto ret;
}
}
for (GList *l = problem_dirs; l; l = l->next)
{
const char *dir_name = (const char*)l->data;
if (!dump_dir_accessible_by_uid(dir_name, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("Requested directory does not exist '%s'", dir_name);
continue;
}
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{ // if user didn't provide correct credentials, just move to the next dir
continue;
}
}
delete_dump_dir(dir_name);
}
g_dbus_method_invocation_return_value(invocation, NULL);
ret:
list_free_with_free(problem_dirs);
return;
}
if (g_strcmp0(method_name, "FindProblemByElementInTimeRange") == 0)
{
const gchar *element;
const gchar *value;
glong timestamp_from;
glong timestamp_to;
gboolean all;
g_variant_get_child(parameters, 0, "&s", &element);
g_variant_get_child(parameters, 1, "&s", &value);
g_variant_get_child(parameters, 2, "x", ×tamp_from);
g_variant_get_child(parameters, 3, "x", ×tamp_to);
g_variant_get_child(parameters, 4, "b", &all);
if (all && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes)
caller_uid = 0;
GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from,
timestamp_to);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "Quit") == 0)
{
g_dbus_method_invocation_return_value(invocation, NULL);
g_main_loop_quit(loop);
return;
}
}
static gboolean on_timeout_cb(gpointer user_data)
{
g_main_loop_quit(loop);
return TRUE;
}
static const GDBusInterfaceVTable interface_vtable =
{
.method_call = handle_method_call,
.get_property = NULL,
.set_property = NULL,
};
static void on_bus_acquired(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
guint registration_id;
registration_id = g_dbus_connection_register_object(connection,
ABRT_DBUS_OBJECT,
introspection_data->interfaces[0],
&interface_vtable,
NULL, /* user_data */
NULL, /* user_data_free_func */
NULL); /* GError** */
g_assert(registration_id > 0);
reset_timeout();
}
/* not used
static void on_name_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
}
*/
static void on_name_lost(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
g_print(_("The name '%s' has been lost, please check if other "
"service owning the name is not running.\n"), name);
exit(1);
}
int main(int argc, char *argv[])
{
/* I18n */
setlocale(LC_ALL, "");
#if ENABLE_NLS
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
#endif
guint owner_id;
abrt_init(argv);
const char *program_usage_string = _(
"& [options]"
);
enum {
OPT_v = 1 << 0,
OPT_t = 1 << 1,
};
/* Keep enum above and order of options below in sync! */
struct options program_options[] = {
OPT__VERBOSE(&g_verbose),
OPT_INTEGER('t', NULL, &g_timeout_value, _("Exit after NUM seconds of inactivity")),
OPT_END()
};
/*unsigned opts =*/ parse_opts(argc, argv, program_options, program_usage_string);
export_abrt_envvars(0);
/* When dbus daemon starts us, it doesn't set PATH
* (I saw it set only DBUS_STARTER_ADDRESS and DBUS_STARTER_BUS_TYPE).
* In this case, set something sane:
*/
const char *env_path = getenv("PATH");
if (!env_path || !env_path[0])
putenv((char*)"PATH=/usr/sbin:/usr/bin:/sbin:/bin");
msg_prefix = "abrt-dbus"; /* for log(), error_msg() and such */
if (getuid() != 0)
error_msg_and_die(_("This program must be run as root."));
glib_init();
/* We are lazy here - we don't want to manually provide
* the introspection data structures - so we just build
* them from XML.
*/
introspection_data = g_dbus_node_info_new_for_xml(introspection_xml, NULL);
g_assert(introspection_data != NULL);
owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
ABRT_DBUS_NAME,
G_BUS_NAME_OWNER_FLAGS_NONE,
on_bus_acquired,
NULL,
on_name_lost,
NULL,
NULL);
/* initialize the g_settings_dump_location */
load_abrt_conf();
loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(loop);
log_notice("Cleaning up");
g_bus_unown_name(owner_id);
g_dbus_node_info_unref(introspection_data);
free_abrt_conf_data();
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1563_0 |
crossvul-cpp_data_good_3290_0 | /*
* Central processing for nfsd.
*
* Authors: Olaf Kirch (okir@monad.swb.de)
*
* Copyright (C) 1995, 1996, 1997 Olaf Kirch <okir@monad.swb.de>
*/
#include <linux/sched/signal.h>
#include <linux/freezer.h>
#include <linux/module.h>
#include <linux/fs_struct.h>
#include <linux/swap.h>
#include <linux/sunrpc/stats.h>
#include <linux/sunrpc/svcsock.h>
#include <linux/sunrpc/svc_xprt.h>
#include <linux/lockd/bind.h>
#include <linux/nfsacl.h>
#include <linux/seq_file.h>
#include <linux/inetdevice.h>
#include <net/addrconf.h>
#include <net/ipv6.h>
#include <net/net_namespace.h>
#include "nfsd.h"
#include "cache.h"
#include "vfs.h"
#include "netns.h"
#define NFSDDBG_FACILITY NFSDDBG_SVC
extern struct svc_program nfsd_program;
static int nfsd(void *vrqstp);
/*
* nfsd_mutex protects nn->nfsd_serv -- both the pointer itself and the members
* of the svc_serv struct. In particular, ->sv_nrthreads but also to some
* extent ->sv_temp_socks and ->sv_permsocks. It also protects nfsdstats.th_cnt
*
* If (out side the lock) nn->nfsd_serv is non-NULL, then it must point to a
* properly initialised 'struct svc_serv' with ->sv_nrthreads > 0. That number
* of nfsd threads must exist and each must listed in ->sp_all_threads in each
* entry of ->sv_pools[].
*
* Transitions of the thread count between zero and non-zero are of particular
* interest since the svc_serv needs to be created and initialized at that
* point, or freed.
*
* Finally, the nfsd_mutex also protects some of the global variables that are
* accessed when nfsd starts and that are settable via the write_* routines in
* nfsctl.c. In particular:
*
* user_recovery_dirname
* user_lease_time
* nfsd_versions
*/
DEFINE_MUTEX(nfsd_mutex);
/*
* nfsd_drc_lock protects nfsd_drc_max_pages and nfsd_drc_pages_used.
* nfsd_drc_max_pages limits the total amount of memory available for
* version 4.1 DRC caches.
* nfsd_drc_pages_used tracks the current version 4.1 DRC memory usage.
*/
spinlock_t nfsd_drc_lock;
unsigned long nfsd_drc_max_mem;
unsigned long nfsd_drc_mem_used;
#if defined(CONFIG_NFSD_V2_ACL) || defined(CONFIG_NFSD_V3_ACL)
static struct svc_stat nfsd_acl_svcstats;
static struct svc_version * nfsd_acl_version[] = {
[2] = &nfsd_acl_version2,
[3] = &nfsd_acl_version3,
};
#define NFSD_ACL_MINVERS 2
#define NFSD_ACL_NRVERS ARRAY_SIZE(nfsd_acl_version)
static struct svc_version *nfsd_acl_versions[NFSD_ACL_NRVERS];
static struct svc_program nfsd_acl_program = {
.pg_prog = NFS_ACL_PROGRAM,
.pg_nvers = NFSD_ACL_NRVERS,
.pg_vers = nfsd_acl_versions,
.pg_name = "nfsacl",
.pg_class = "nfsd",
.pg_stats = &nfsd_acl_svcstats,
.pg_authenticate = &svc_set_client,
};
static struct svc_stat nfsd_acl_svcstats = {
.program = &nfsd_acl_program,
};
#endif /* defined(CONFIG_NFSD_V2_ACL) || defined(CONFIG_NFSD_V3_ACL) */
static struct svc_version * nfsd_version[] = {
[2] = &nfsd_version2,
#if defined(CONFIG_NFSD_V3)
[3] = &nfsd_version3,
#endif
#if defined(CONFIG_NFSD_V4)
[4] = &nfsd_version4,
#endif
};
#define NFSD_MINVERS 2
#define NFSD_NRVERS ARRAY_SIZE(nfsd_version)
static struct svc_version *nfsd_versions[NFSD_NRVERS];
struct svc_program nfsd_program = {
#if defined(CONFIG_NFSD_V2_ACL) || defined(CONFIG_NFSD_V3_ACL)
.pg_next = &nfsd_acl_program,
#endif
.pg_prog = NFS_PROGRAM, /* program number */
.pg_nvers = NFSD_NRVERS, /* nr of entries in nfsd_version */
.pg_vers = nfsd_versions, /* version table */
.pg_name = "nfsd", /* program name */
.pg_class = "nfsd", /* authentication class */
.pg_stats = &nfsd_svcstats, /* version table */
.pg_authenticate = &svc_set_client, /* export authentication */
};
static bool nfsd_supported_minorversions[NFSD_SUPPORTED_MINOR_VERSION + 1] = {
[0] = 1,
[1] = 1,
[2] = 1,
};
int nfsd_vers(int vers, enum vers_op change)
{
if (vers < NFSD_MINVERS || vers >= NFSD_NRVERS)
return 0;
switch(change) {
case NFSD_SET:
nfsd_versions[vers] = nfsd_version[vers];
#if defined(CONFIG_NFSD_V2_ACL) || defined(CONFIG_NFSD_V3_ACL)
if (vers < NFSD_ACL_NRVERS)
nfsd_acl_versions[vers] = nfsd_acl_version[vers];
#endif
break;
case NFSD_CLEAR:
nfsd_versions[vers] = NULL;
#if defined(CONFIG_NFSD_V2_ACL) || defined(CONFIG_NFSD_V3_ACL)
if (vers < NFSD_ACL_NRVERS)
nfsd_acl_versions[vers] = NULL;
#endif
break;
case NFSD_TEST:
return nfsd_versions[vers] != NULL;
case NFSD_AVAIL:
return nfsd_version[vers] != NULL;
}
return 0;
}
static void
nfsd_adjust_nfsd_versions4(void)
{
unsigned i;
for (i = 0; i <= NFSD_SUPPORTED_MINOR_VERSION; i++) {
if (nfsd_supported_minorversions[i])
return;
}
nfsd_vers(4, NFSD_CLEAR);
}
int nfsd_minorversion(u32 minorversion, enum vers_op change)
{
if (minorversion > NFSD_SUPPORTED_MINOR_VERSION &&
change != NFSD_AVAIL)
return -1;
switch(change) {
case NFSD_SET:
nfsd_supported_minorversions[minorversion] = true;
nfsd_vers(4, NFSD_SET);
break;
case NFSD_CLEAR:
nfsd_supported_minorversions[minorversion] = false;
nfsd_adjust_nfsd_versions4();
break;
case NFSD_TEST:
return nfsd_supported_minorversions[minorversion];
case NFSD_AVAIL:
return minorversion <= NFSD_SUPPORTED_MINOR_VERSION;
}
return 0;
}
/*
* Maximum number of nfsd processes
*/
#define NFSD_MAXSERVS 8192
int nfsd_nrthreads(struct net *net)
{
int rv = 0;
struct nfsd_net *nn = net_generic(net, nfsd_net_id);
mutex_lock(&nfsd_mutex);
if (nn->nfsd_serv)
rv = nn->nfsd_serv->sv_nrthreads;
mutex_unlock(&nfsd_mutex);
return rv;
}
static int nfsd_init_socks(struct net *net)
{
int error;
struct nfsd_net *nn = net_generic(net, nfsd_net_id);
if (!list_empty(&nn->nfsd_serv->sv_permsocks))
return 0;
error = svc_create_xprt(nn->nfsd_serv, "udp", net, PF_INET, NFS_PORT,
SVC_SOCK_DEFAULTS);
if (error < 0)
return error;
error = svc_create_xprt(nn->nfsd_serv, "tcp", net, PF_INET, NFS_PORT,
SVC_SOCK_DEFAULTS);
if (error < 0)
return error;
return 0;
}
static int nfsd_users = 0;
static int nfsd_startup_generic(int nrservs)
{
int ret;
if (nfsd_users++)
return 0;
/*
* Readahead param cache - will no-op if it already exists.
* (Note therefore results will be suboptimal if number of
* threads is modified after nfsd start.)
*/
ret = nfsd_racache_init(2*nrservs);
if (ret)
goto dec_users;
ret = nfs4_state_start();
if (ret)
goto out_racache;
return 0;
out_racache:
nfsd_racache_shutdown();
dec_users:
nfsd_users--;
return ret;
}
static void nfsd_shutdown_generic(void)
{
if (--nfsd_users)
return;
nfs4_state_shutdown();
nfsd_racache_shutdown();
}
static bool nfsd_needs_lockd(void)
{
#if defined(CONFIG_NFSD_V3)
return (nfsd_versions[2] != NULL) || (nfsd_versions[3] != NULL);
#else
return (nfsd_versions[2] != NULL);
#endif
}
static int nfsd_startup_net(int nrservs, struct net *net)
{
struct nfsd_net *nn = net_generic(net, nfsd_net_id);
int ret;
if (nn->nfsd_net_up)
return 0;
ret = nfsd_startup_generic(nrservs);
if (ret)
return ret;
ret = nfsd_init_socks(net);
if (ret)
goto out_socks;
if (nfsd_needs_lockd() && !nn->lockd_up) {
ret = lockd_up(net);
if (ret)
goto out_socks;
nn->lockd_up = 1;
}
ret = nfs4_state_start_net(net);
if (ret)
goto out_lockd;
nn->nfsd_net_up = true;
return 0;
out_lockd:
if (nn->lockd_up) {
lockd_down(net);
nn->lockd_up = 0;
}
out_socks:
nfsd_shutdown_generic();
return ret;
}
static void nfsd_shutdown_net(struct net *net)
{
struct nfsd_net *nn = net_generic(net, nfsd_net_id);
nfs4_state_shutdown_net(net);
if (nn->lockd_up) {
lockd_down(net);
nn->lockd_up = 0;
}
nn->nfsd_net_up = false;
nfsd_shutdown_generic();
}
static int nfsd_inetaddr_event(struct notifier_block *this, unsigned long event,
void *ptr)
{
struct in_ifaddr *ifa = (struct in_ifaddr *)ptr;
struct net_device *dev = ifa->ifa_dev->dev;
struct net *net = dev_net(dev);
struct nfsd_net *nn = net_generic(net, nfsd_net_id);
struct sockaddr_in sin;
if (event != NETDEV_DOWN)
goto out;
if (nn->nfsd_serv) {
dprintk("nfsd_inetaddr_event: removed %pI4\n", &ifa->ifa_local);
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = ifa->ifa_local;
svc_age_temp_xprts_now(nn->nfsd_serv, (struct sockaddr *)&sin);
}
out:
return NOTIFY_DONE;
}
static struct notifier_block nfsd_inetaddr_notifier = {
.notifier_call = nfsd_inetaddr_event,
};
#if IS_ENABLED(CONFIG_IPV6)
static int nfsd_inet6addr_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct inet6_ifaddr *ifa = (struct inet6_ifaddr *)ptr;
struct net_device *dev = ifa->idev->dev;
struct net *net = dev_net(dev);
struct nfsd_net *nn = net_generic(net, nfsd_net_id);
struct sockaddr_in6 sin6;
if (event != NETDEV_DOWN)
goto out;
if (nn->nfsd_serv) {
dprintk("nfsd_inet6addr_event: removed %pI6\n", &ifa->addr);
sin6.sin6_family = AF_INET6;
sin6.sin6_addr = ifa->addr;
if (ipv6_addr_type(&sin6.sin6_addr) & IPV6_ADDR_LINKLOCAL)
sin6.sin6_scope_id = ifa->idev->dev->ifindex;
svc_age_temp_xprts_now(nn->nfsd_serv, (struct sockaddr *)&sin6);
}
out:
return NOTIFY_DONE;
}
static struct notifier_block nfsd_inet6addr_notifier = {
.notifier_call = nfsd_inet6addr_event,
};
#endif
/* Only used under nfsd_mutex, so this atomic may be overkill: */
static atomic_t nfsd_notifier_refcount = ATOMIC_INIT(0);
static void nfsd_last_thread(struct svc_serv *serv, struct net *net)
{
struct nfsd_net *nn = net_generic(net, nfsd_net_id);
/* check if the notifier still has clients */
if (atomic_dec_return(&nfsd_notifier_refcount) == 0) {
unregister_inetaddr_notifier(&nfsd_inetaddr_notifier);
#if IS_ENABLED(CONFIG_IPV6)
unregister_inet6addr_notifier(&nfsd_inet6addr_notifier);
#endif
}
/*
* write_ports can create the server without actually starting
* any threads--if we get shut down before any threads are
* started, then nfsd_last_thread will be run before any of this
* other initialization has been done except the rpcb information.
*/
svc_rpcb_cleanup(serv, net);
if (!nn->nfsd_net_up)
return;
nfsd_shutdown_net(net);
printk(KERN_WARNING "nfsd: last server has exited, flushing export "
"cache\n");
nfsd_export_flush(net);
}
void nfsd_reset_versions(void)
{
int i;
for (i = 0; i < NFSD_NRVERS; i++)
if (nfsd_vers(i, NFSD_TEST))
return;
for (i = 0; i < NFSD_NRVERS; i++)
if (i != 4)
nfsd_vers(i, NFSD_SET);
else {
int minor = 0;
while (nfsd_minorversion(minor, NFSD_SET) >= 0)
minor++;
}
}
/*
* Each session guarantees a negotiated per slot memory cache for replies
* which in turn consumes memory beyond the v2/v3/v4.0 server. A dedicated
* NFSv4.1 server might want to use more memory for a DRC than a machine
* with mutiple services.
*
* Impose a hard limit on the number of pages for the DRC which varies
* according to the machines free pages. This is of course only a default.
*
* For now this is a #defined shift which could be under admin control
* in the future.
*/
static void set_max_drc(void)
{
#define NFSD_DRC_SIZE_SHIFT 10
nfsd_drc_max_mem = (nr_free_buffer_pages()
>> NFSD_DRC_SIZE_SHIFT) * PAGE_SIZE;
nfsd_drc_mem_used = 0;
spin_lock_init(&nfsd_drc_lock);
dprintk("%s nfsd_drc_max_mem %lu \n", __func__, nfsd_drc_max_mem);
}
static int nfsd_get_default_max_blksize(void)
{
struct sysinfo i;
unsigned long long target;
unsigned long ret;
si_meminfo(&i);
target = (i.totalram - i.totalhigh) << PAGE_SHIFT;
/*
* Aim for 1/4096 of memory per thread This gives 1MB on 4Gig
* machines, but only uses 32K on 128M machines. Bottom out at
* 8K on 32M and smaller. Of course, this is only a default.
*/
target >>= 12;
ret = NFSSVC_MAXBLKSIZE;
while (ret > target && ret >= 8*1024*2)
ret /= 2;
return ret;
}
static struct svc_serv_ops nfsd_thread_sv_ops = {
.svo_shutdown = nfsd_last_thread,
.svo_function = nfsd,
.svo_enqueue_xprt = svc_xprt_do_enqueue,
.svo_setup = svc_set_num_threads,
.svo_module = THIS_MODULE,
};
int nfsd_create_serv(struct net *net)
{
int error;
struct nfsd_net *nn = net_generic(net, nfsd_net_id);
WARN_ON(!mutex_is_locked(&nfsd_mutex));
if (nn->nfsd_serv) {
svc_get(nn->nfsd_serv);
return 0;
}
if (nfsd_max_blksize == 0)
nfsd_max_blksize = nfsd_get_default_max_blksize();
nfsd_reset_versions();
nn->nfsd_serv = svc_create_pooled(&nfsd_program, nfsd_max_blksize,
&nfsd_thread_sv_ops);
if (nn->nfsd_serv == NULL)
return -ENOMEM;
nn->nfsd_serv->sv_maxconn = nn->max_connections;
error = svc_bind(nn->nfsd_serv, net);
if (error < 0) {
svc_destroy(nn->nfsd_serv);
return error;
}
set_max_drc();
/* check if the notifier is already set */
if (atomic_inc_return(&nfsd_notifier_refcount) == 1) {
register_inetaddr_notifier(&nfsd_inetaddr_notifier);
#if IS_ENABLED(CONFIG_IPV6)
register_inet6addr_notifier(&nfsd_inet6addr_notifier);
#endif
}
do_gettimeofday(&nn->nfssvc_boot); /* record boot time */
return 0;
}
int nfsd_nrpools(struct net *net)
{
struct nfsd_net *nn = net_generic(net, nfsd_net_id);
if (nn->nfsd_serv == NULL)
return 0;
else
return nn->nfsd_serv->sv_nrpools;
}
int nfsd_get_nrthreads(int n, int *nthreads, struct net *net)
{
int i = 0;
struct nfsd_net *nn = net_generic(net, nfsd_net_id);
if (nn->nfsd_serv != NULL) {
for (i = 0; i < nn->nfsd_serv->sv_nrpools && i < n; i++)
nthreads[i] = nn->nfsd_serv->sv_pools[i].sp_nrthreads;
}
return 0;
}
void nfsd_destroy(struct net *net)
{
struct nfsd_net *nn = net_generic(net, nfsd_net_id);
int destroy = (nn->nfsd_serv->sv_nrthreads == 1);
if (destroy)
svc_shutdown_net(nn->nfsd_serv, net);
svc_destroy(nn->nfsd_serv);
if (destroy)
nn->nfsd_serv = NULL;
}
int nfsd_set_nrthreads(int n, int *nthreads, struct net *net)
{
int i = 0;
int tot = 0;
int err = 0;
struct nfsd_net *nn = net_generic(net, nfsd_net_id);
WARN_ON(!mutex_is_locked(&nfsd_mutex));
if (nn->nfsd_serv == NULL || n <= 0)
return 0;
if (n > nn->nfsd_serv->sv_nrpools)
n = nn->nfsd_serv->sv_nrpools;
/* enforce a global maximum number of threads */
tot = 0;
for (i = 0; i < n; i++) {
nthreads[i] = min(nthreads[i], NFSD_MAXSERVS);
tot += nthreads[i];
}
if (tot > NFSD_MAXSERVS) {
/* total too large: scale down requested numbers */
for (i = 0; i < n && tot > 0; i++) {
int new = nthreads[i] * NFSD_MAXSERVS / tot;
tot -= (nthreads[i] - new);
nthreads[i] = new;
}
for (i = 0; i < n && tot > 0; i++) {
nthreads[i]--;
tot--;
}
}
/*
* There must always be a thread in pool 0; the admin
* can't shut down NFS completely using pool_threads.
*/
if (nthreads[0] == 0)
nthreads[0] = 1;
/* apply the new numbers */
svc_get(nn->nfsd_serv);
for (i = 0; i < n; i++) {
err = nn->nfsd_serv->sv_ops->svo_setup(nn->nfsd_serv,
&nn->nfsd_serv->sv_pools[i], nthreads[i]);
if (err)
break;
}
nfsd_destroy(net);
return err;
}
/*
* Adjust the number of threads and return the new number of threads.
* This is also the function that starts the server if necessary, if
* this is the first time nrservs is nonzero.
*/
int
nfsd_svc(int nrservs, struct net *net)
{
int error;
bool nfsd_up_before;
struct nfsd_net *nn = net_generic(net, nfsd_net_id);
mutex_lock(&nfsd_mutex);
dprintk("nfsd: creating service\n");
nrservs = max(nrservs, 0);
nrservs = min(nrservs, NFSD_MAXSERVS);
error = 0;
if (nrservs == 0 && nn->nfsd_serv == NULL)
goto out;
error = nfsd_create_serv(net);
if (error)
goto out;
nfsd_up_before = nn->nfsd_net_up;
error = nfsd_startup_net(nrservs, net);
if (error)
goto out_destroy;
error = nn->nfsd_serv->sv_ops->svo_setup(nn->nfsd_serv,
NULL, nrservs);
if (error)
goto out_shutdown;
/* We are holding a reference to nn->nfsd_serv which
* we don't want to count in the return value,
* so subtract 1
*/
error = nn->nfsd_serv->sv_nrthreads - 1;
out_shutdown:
if (error < 0 && !nfsd_up_before)
nfsd_shutdown_net(net);
out_destroy:
nfsd_destroy(net); /* Release server */
out:
mutex_unlock(&nfsd_mutex);
return error;
}
/*
* This is the NFS server kernel thread
*/
static int
nfsd(void *vrqstp)
{
struct svc_rqst *rqstp = (struct svc_rqst *) vrqstp;
struct svc_xprt *perm_sock = list_entry(rqstp->rq_server->sv_permsocks.next, typeof(struct svc_xprt), xpt_list);
struct net *net = perm_sock->xpt_net;
struct nfsd_net *nn = net_generic(net, nfsd_net_id);
int err;
/* Lock module and set up kernel thread */
mutex_lock(&nfsd_mutex);
/* At this point, the thread shares current->fs
* with the init process. We need to create files with the
* umask as defined by the client instead of init's umask. */
if (unshare_fs_struct() < 0) {
printk("Unable to start nfsd thread: out of memory\n");
goto out;
}
current->fs->umask = 0;
/*
* thread is spawned with all signals set to SIG_IGN, re-enable
* the ones that will bring down the thread
*/
allow_signal(SIGKILL);
allow_signal(SIGHUP);
allow_signal(SIGINT);
allow_signal(SIGQUIT);
nfsdstats.th_cnt++;
mutex_unlock(&nfsd_mutex);
set_freezable();
/*
* The main request loop
*/
for (;;) {
/* Update sv_maxconn if it has changed */
rqstp->rq_server->sv_maxconn = nn->max_connections;
/*
* Find a socket with data available and call its
* recvfrom routine.
*/
while ((err = svc_recv(rqstp, 60*60*HZ)) == -EAGAIN)
;
if (err == -EINTR)
break;
validate_process_creds();
svc_process(rqstp);
validate_process_creds();
}
/* Clear signals before calling svc_exit_thread() */
flush_signals(current);
mutex_lock(&nfsd_mutex);
nfsdstats.th_cnt --;
out:
rqstp->rq_server = NULL;
/* Release the thread */
svc_exit_thread(rqstp);
nfsd_destroy(net);
/* Release module */
mutex_unlock(&nfsd_mutex);
module_put_and_exit(0);
return 0;
}
static __be32 map_new_errors(u32 vers, __be32 nfserr)
{
if (nfserr == nfserr_jukebox && vers == 2)
return nfserr_dropit;
if (nfserr == nfserr_wrongsec && vers < 4)
return nfserr_acces;
return nfserr;
}
/*
* A write procedure can have a large argument, and a read procedure can
* have a large reply, but no NFSv2 or NFSv3 procedure has argument and
* reply that can both be larger than a page. The xdr code has taken
* advantage of this assumption to be a sloppy about bounds checking in
* some cases. Pending a rewrite of the NFSv2/v3 xdr code to fix that
* problem, we enforce these assumptions here:
*/
static bool nfs_request_too_big(struct svc_rqst *rqstp,
struct svc_procedure *proc)
{
/*
* The ACL code has more careful bounds-checking and is not
* susceptible to this problem:
*/
if (rqstp->rq_prog != NFS_PROGRAM)
return false;
/*
* Ditto NFSv4 (which can in theory have argument and reply both
* more than a page):
*/
if (rqstp->rq_vers >= 4)
return false;
/* The reply will be small, we're OK: */
if (proc->pc_xdrressize > 0 &&
proc->pc_xdrressize < XDR_QUADLEN(PAGE_SIZE))
return false;
return rqstp->rq_arg.len > PAGE_SIZE;
}
int
nfsd_dispatch(struct svc_rqst *rqstp, __be32 *statp)
{
struct svc_procedure *proc;
kxdrproc_t xdr;
__be32 nfserr;
__be32 *nfserrp;
dprintk("nfsd_dispatch: vers %d proc %d\n",
rqstp->rq_vers, rqstp->rq_proc);
proc = rqstp->rq_procinfo;
if (nfs_request_too_big(rqstp, proc)) {
dprintk("nfsd: NFSv%d argument too large\n", rqstp->rq_vers);
*statp = rpc_garbage_args;
return 1;
}
/*
* Give the xdr decoder a chance to change this if it wants
* (necessary in the NFSv4.0 compound case)
*/
rqstp->rq_cachetype = proc->pc_cachetype;
/* Decode arguments */
xdr = proc->pc_decode;
if (xdr && !xdr(rqstp, (__be32*)rqstp->rq_arg.head[0].iov_base,
rqstp->rq_argp)) {
dprintk("nfsd: failed to decode arguments!\n");
*statp = rpc_garbage_args;
return 1;
}
/* Check whether we have this call in the cache. */
switch (nfsd_cache_lookup(rqstp)) {
case RC_DROPIT:
return 0;
case RC_REPLY:
return 1;
case RC_DOIT:;
/* do it */
}
/* need to grab the location to store the status, as
* nfsv4 does some encoding while processing
*/
nfserrp = rqstp->rq_res.head[0].iov_base
+ rqstp->rq_res.head[0].iov_len;
rqstp->rq_res.head[0].iov_len += sizeof(__be32);
/* Now call the procedure handler, and encode NFS status. */
nfserr = proc->pc_func(rqstp, rqstp->rq_argp, rqstp->rq_resp);
nfserr = map_new_errors(rqstp->rq_vers, nfserr);
if (nfserr == nfserr_dropit || test_bit(RQ_DROPME, &rqstp->rq_flags)) {
dprintk("nfsd: Dropping request; may be revisited later\n");
nfsd_cache_update(rqstp, RC_NOCACHE, NULL);
return 0;
}
if (rqstp->rq_proc != 0)
*nfserrp++ = nfserr;
/* Encode result.
* For NFSv2, additional info is never returned in case of an error.
*/
if (!(nfserr && rqstp->rq_vers == 2)) {
xdr = proc->pc_encode;
if (xdr && !xdr(rqstp, nfserrp,
rqstp->rq_resp)) {
/* Failed to encode result. Release cache entry */
dprintk("nfsd: failed to encode result!\n");
nfsd_cache_update(rqstp, RC_NOCACHE, NULL);
*statp = rpc_system_err;
return 1;
}
}
/* Store reply in cache. */
nfsd_cache_update(rqstp, rqstp->rq_cachetype, statp + 1);
return 1;
}
int nfsd_pool_stats_open(struct inode *inode, struct file *file)
{
int ret;
struct nfsd_net *nn = net_generic(inode->i_sb->s_fs_info, nfsd_net_id);
mutex_lock(&nfsd_mutex);
if (nn->nfsd_serv == NULL) {
mutex_unlock(&nfsd_mutex);
return -ENODEV;
}
/* bump up the psudo refcount while traversing */
svc_get(nn->nfsd_serv);
ret = svc_pool_stats_open(nn->nfsd_serv, file);
mutex_unlock(&nfsd_mutex);
return ret;
}
int nfsd_pool_stats_release(struct inode *inode, struct file *file)
{
int ret = seq_release(inode, file);
struct net *net = inode->i_sb->s_fs_info;
mutex_lock(&nfsd_mutex);
/* this function really, really should have been called svc_put() */
nfsd_destroy(net);
mutex_unlock(&nfsd_mutex);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3290_0 |
crossvul-cpp_data_bad_5415_1 | /*
* Copyright (c) 1999-2000 Image Power, Inc. and the University of
* British Columbia.
* Copyright (c) 2001-2003 Michael David Adams.
* All rights reserved.
*/
/* __START_OF_JASPER_LICENSE__
*
* JasPer License Version 2.0
*
* Copyright (c) 2001-2006 Michael David Adams
* Copyright (c) 1999-2000 Image Power, Inc.
* Copyright (c) 1999-2000 The University of British Columbia
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person (the
* "User") obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* 1. The above copyright notices and this permission notice (which
* includes the disclaimer below) shall be included in all copies or
* substantial portions of the Software.
*
* 2. The name of a copyright holder shall not be used to endorse or
* promote products derived from the Software without specific prior
* written permission.
*
* THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
* LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
* THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
* "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
* EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
* PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
* THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
* EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
* BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
* PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
* GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
* ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
* IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
* SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
* AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
* SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
* THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
* PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
* RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
* EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
*
* __END_OF_JASPER_LICENSE__
*/
/*
* $Id$
*/
/******************************************************************************\
* Includes.
\******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <inttypes.h>
#include "jasper/jas_types.h"
#include "jasper/jas_math.h"
#include "jasper/jas_tvp.h"
#include "jasper/jas_malloc.h"
#include "jasper/jas_debug.h"
#include "jpc_fix.h"
#include "jpc_dec.h"
#include "jpc_cs.h"
#include "jpc_mct.h"
#include "jpc_t2dec.h"
#include "jpc_t1dec.h"
#include "jpc_math.h"
/******************************************************************************\
*
\******************************************************************************/
#define JPC_MHSOC 0x0001
/* In the main header, expecting a SOC marker segment. */
#define JPC_MHSIZ 0x0002
/* In the main header, expecting a SIZ marker segment. */
#define JPC_MH 0x0004
/* In the main header, expecting "other" marker segments. */
#define JPC_TPHSOT 0x0008
/* In a tile-part header, expecting a SOT marker segment. */
#define JPC_TPH 0x0010
/* In a tile-part header, expecting "other" marker segments. */
#define JPC_MT 0x0020
/* In the main trailer. */
typedef struct {
uint_fast16_t id;
/* The marker segment type. */
int validstates;
/* The states in which this type of marker segment can be
validly encountered. */
int (*action)(jpc_dec_t *dec, jpc_ms_t *ms);
/* The action to take upon encountering this type of marker segment. */
} jpc_dec_mstabent_t;
/******************************************************************************\
*
\******************************************************************************/
/* COD/COC parameters have been specified. */
#define JPC_CSET 0x0001
/* QCD/QCC parameters have been specified. */
#define JPC_QSET 0x0002
/* COD/COC parameters set from a COC marker segment. */
#define JPC_COC 0x0004
/* QCD/QCC parameters set from a QCC marker segment. */
#define JPC_QCC 0x0008
/******************************************************************************\
* Local function prototypes.
\******************************************************************************/
static int jpc_dec_dump(jpc_dec_t *dec, FILE *out);
jpc_ppxstab_t *jpc_ppxstab_create(void);
void jpc_ppxstab_destroy(jpc_ppxstab_t *tab);
int jpc_ppxstab_grow(jpc_ppxstab_t *tab, int maxents);
int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent);
jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab);
int jpc_pptstabwrite(jas_stream_t *out, jpc_ppxstab_t *tab);
jpc_ppxstabent_t *jpc_ppxstabent_create(void);
void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent);
int jpc_streamlist_numstreams(jpc_streamlist_t *streamlist);
jpc_streamlist_t *jpc_streamlist_create(void);
int jpc_streamlist_insert(jpc_streamlist_t *streamlist, int streamno,
jas_stream_t *stream);
jas_stream_t *jpc_streamlist_remove(jpc_streamlist_t *streamlist, int streamno);
void jpc_streamlist_destroy(jpc_streamlist_t *streamlist);
jas_stream_t *jpc_streamlist_get(jpc_streamlist_t *streamlist, int streamno);
static void jpc_dec_cp_resetflags(jpc_dec_cp_t *cp);
static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps);
static int jpc_dec_cp_isvalid(jpc_dec_cp_t *cp);
static jpc_dec_cp_t *jpc_dec_cp_copy(jpc_dec_cp_t *cp);
static int jpc_dec_cp_setfromcod(jpc_dec_cp_t *cp, jpc_cod_t *cod);
static int jpc_dec_cp_setfromcoc(jpc_dec_cp_t *cp, jpc_coc_t *coc);
static int jpc_dec_cp_setfromcox(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp,
jpc_coxcp_t *compparms, int flags);
static int jpc_dec_cp_setfromqcd(jpc_dec_cp_t *cp, jpc_qcd_t *qcd);
static int jpc_dec_cp_setfromqcc(jpc_dec_cp_t *cp, jpc_qcc_t *qcc);
static int jpc_dec_cp_setfromqcx(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp,
jpc_qcxcp_t *compparms, int flags);
static int jpc_dec_cp_setfromrgn(jpc_dec_cp_t *cp, jpc_rgn_t *rgn);
static int jpc_dec_cp_prepare(jpc_dec_cp_t *cp);
static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp);
static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, jpc_poc_t *poc, int reset);
static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, jpc_poc_t *poc);
static int jpc_dec_decode(jpc_dec_t *dec);
static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in);
static void jpc_dec_destroy(jpc_dec_t *dec);
static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize);
static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps);
static jpc_fix_t jpc_calcabsstepsize(int stepsize, int numbits);
static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile);
static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile);
static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile);
static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_parseopts(char *optstr, jpc_dec_importopts_t *opts);
static jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id);
/******************************************************************************\
* Global data.
\******************************************************************************/
jpc_dec_mstabent_t jpc_dec_mstab[] = {
{JPC_MS_SOC, JPC_MHSOC, jpc_dec_process_soc},
{JPC_MS_SOT, JPC_MH | JPC_TPHSOT, jpc_dec_process_sot},
{JPC_MS_SOD, JPC_TPH, jpc_dec_process_sod},
{JPC_MS_EOC, JPC_TPHSOT, jpc_dec_process_eoc},
{JPC_MS_SIZ, JPC_MHSIZ, jpc_dec_process_siz},
{JPC_MS_COD, JPC_MH | JPC_TPH, jpc_dec_process_cod},
{JPC_MS_COC, JPC_MH | JPC_TPH, jpc_dec_process_coc},
{JPC_MS_RGN, JPC_MH | JPC_TPH, jpc_dec_process_rgn},
{JPC_MS_QCD, JPC_MH | JPC_TPH, jpc_dec_process_qcd},
{JPC_MS_QCC, JPC_MH | JPC_TPH, jpc_dec_process_qcc},
{JPC_MS_POC, JPC_MH | JPC_TPH, jpc_dec_process_poc},
{JPC_MS_TLM, JPC_MH, 0},
{JPC_MS_PLM, JPC_MH, 0},
{JPC_MS_PLT, JPC_TPH, 0},
{JPC_MS_PPM, JPC_MH, jpc_dec_process_ppm},
{JPC_MS_PPT, JPC_TPH, jpc_dec_process_ppt},
{JPC_MS_SOP, 0, 0},
{JPC_MS_CRG, JPC_MH, jpc_dec_process_crg},
{JPC_MS_COM, JPC_MH | JPC_TPH, jpc_dec_process_com},
{0, JPC_MH | JPC_TPH, jpc_dec_process_unk}
};
/******************************************************************************\
* The main entry point for the JPEG-2000 decoder.
\******************************************************************************/
jas_image_t *jpc_decode(jas_stream_t *in, char *optstr)
{
jpc_dec_importopts_t opts;
jpc_dec_t *dec;
jas_image_t *image;
dec = 0;
if (jpc_dec_parseopts(optstr, &opts)) {
goto error;
}
jpc_initluts();
if (!(dec = jpc_dec_create(&opts, in))) {
goto error;
}
/* Do most of the work. */
if (jpc_dec_decode(dec)) {
goto error;
}
if (jas_image_numcmpts(dec->image) >= 3) {
jas_image_setclrspc(dec->image, JAS_CLRSPC_SRGB);
jas_image_setcmpttype(dec->image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
jas_image_setcmpttype(dec->image, 1,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
jas_image_setcmpttype(dec->image, 2,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
} else {
jas_image_setclrspc(dec->image, JAS_CLRSPC_SGRAY);
jas_image_setcmpttype(dec->image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
}
/* Save the return value. */
image = dec->image;
/* Stop the image from being discarded. */
dec->image = 0;
/* Destroy decoder. */
jpc_dec_destroy(dec);
return image;
error:
if (dec) {
jpc_dec_destroy(dec);
}
return 0;
}
typedef enum {
OPT_MAXLYRS,
OPT_MAXPKTS,
OPT_DEBUG
} optid_t;
jas_taginfo_t decopts[] = {
{OPT_MAXLYRS, "maxlyrs"},
{OPT_MAXPKTS, "maxpkts"},
{OPT_DEBUG, "debug"},
{-1, 0}
};
static int jpc_dec_parseopts(char *optstr, jpc_dec_importopts_t *opts)
{
jas_tvparser_t *tvp;
opts->debug = 0;
opts->maxlyrs = JPC_MAXLYRS;
opts->maxpkts = -1;
if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) {
return -1;
}
while (!jas_tvparser_next(tvp)) {
switch (jas_taginfo_nonull(jas_taginfos_lookup(decopts,
jas_tvparser_gettag(tvp)))->id) {
case OPT_MAXLYRS:
opts->maxlyrs = atoi(jas_tvparser_getval(tvp));
break;
case OPT_DEBUG:
opts->debug = atoi(jas_tvparser_getval(tvp));
break;
case OPT_MAXPKTS:
opts->maxpkts = atoi(jas_tvparser_getval(tvp));
break;
default:
jas_eprintf("warning: ignoring invalid option %s\n",
jas_tvparser_gettag(tvp));
break;
}
}
jas_tvparser_destroy(tvp);
return 0;
}
/******************************************************************************\
* Code for table-driven code stream decoder.
\******************************************************************************/
static jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id)
{
jpc_dec_mstabent_t *mstabent;
for (mstabent = jpc_dec_mstab; mstabent->id != 0; ++mstabent) {
if (mstabent->id == id) {
break;
}
}
return mstabent;
}
static int jpc_dec_decode(jpc_dec_t *dec)
{
jpc_ms_t *ms;
jpc_dec_mstabent_t *mstabent;
int ret;
jpc_cstate_t *cstate;
if (!(cstate = jpc_cstate_create())) {
return -1;
}
dec->cstate = cstate;
/* Initially, we should expect to encounter a SOC marker segment. */
dec->state = JPC_MHSOC;
for (;;) {
/* Get the next marker segment in the code stream. */
if (!(ms = jpc_getms(dec->in, cstate))) {
jas_eprintf("cannot get marker segment\n");
return -1;
}
mstabent = jpc_dec_mstab_lookup(ms->id);
assert(mstabent);
/* Ensure that this type of marker segment is permitted
at this point in the code stream. */
if (!(dec->state & mstabent->validstates)) {
jas_eprintf("unexpected marker segment type\n");
jpc_ms_destroy(ms);
return -1;
}
/* Process the marker segment. */
if (mstabent->action) {
ret = (*mstabent->action)(dec, ms);
} else {
/* No explicit action is required. */
ret = 0;
}
/* Destroy the marker segment. */
jpc_ms_destroy(ms);
if (ret < 0) {
return -1;
} else if (ret > 0) {
break;
}
}
return 0;
}
static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms)
{
int cmptno;
jpc_dec_cmpt_t *cmpt;
jpc_crg_t *crg;
crg = &ms->parms.crg;
for (cmptno = 0, cmpt = dec->cmpts; cmptno < dec->numcomps; ++cmptno,
++cmpt) {
/* Ignore the information in the CRG marker segment for now.
This information serves no useful purpose for decoding anyhow.
Some other parts of the code need to be changed if these lines
are uncommented.
cmpt->hsubstep = crg->comps[cmptno].hoff;
cmpt->vsubstep = crg->comps[cmptno].voff;
*/
}
return 0;
}
static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms)
{
/* Eliminate warnings about unused variables. */
ms = 0;
/* We should expect to encounter a SIZ marker segment next. */
dec->state = JPC_MHSIZ;
return 0;
}
static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_dec_tile_t *tile;
jpc_sot_t *sot = &ms->parms.sot;
jas_image_cmptparm_t *compinfos;
jas_image_cmptparm_t *compinfo;
jpc_dec_cmpt_t *cmpt;
int cmptno;
if (dec->state == JPC_MH) {
if (!(compinfos = jas_alloc2(dec->numcomps,
sizeof(jas_image_cmptparm_t)))) {
abort();
}
for (cmptno = 0, cmpt = dec->cmpts, compinfo = compinfos;
cmptno < dec->numcomps; ++cmptno, ++cmpt, ++compinfo) {
compinfo->tlx = 0;
compinfo->tly = 0;
compinfo->prec = cmpt->prec;
compinfo->sgnd = cmpt->sgnd;
compinfo->width = cmpt->width;
compinfo->height = cmpt->height;
compinfo->hstep = cmpt->hstep;
compinfo->vstep = cmpt->vstep;
}
if (!(dec->image = jas_image_create(dec->numcomps, compinfos,
JAS_CLRSPC_UNKNOWN))) {
jas_free(compinfos);
return -1;
}
jas_free(compinfos);
/* Is the packet header information stored in PPM marker segments in
the main header? */
if (dec->ppmstab) {
/* Convert the PPM marker segment data into a collection of streams
(one stream per tile-part). */
if (!(dec->pkthdrstreams = jpc_ppmstabtostreams(dec->ppmstab))) {
abort();
}
jpc_ppxstab_destroy(dec->ppmstab);
dec->ppmstab = 0;
}
}
if (sot->len > 0) {
dec->curtileendoff = jas_stream_getrwcount(dec->in) - ms->len -
4 + sot->len;
} else {
dec->curtileendoff = 0;
}
if (JAS_CAST(int, sot->tileno) >= dec->numtiles) {
jas_eprintf("invalid tile number in SOT marker segment\n");
return -1;
}
/* Set the current tile. */
dec->curtile = &dec->tiles[sot->tileno];
tile = dec->curtile;
/* Ensure that this is the expected part number. */
if (sot->partno != tile->partno) {
return -1;
}
if (tile->numparts > 0 && sot->partno >= tile->numparts) {
return -1;
}
if (!tile->numparts && sot->numparts > 0) {
tile->numparts = sot->numparts;
}
tile->pptstab = 0;
switch (tile->state) {
case JPC_TILE_INIT:
/* This is the first tile-part for this tile. */
tile->state = JPC_TILE_ACTIVE;
assert(!tile->cp);
if (!(tile->cp = jpc_dec_cp_copy(dec->cp))) {
return -1;
}
jpc_dec_cp_resetflags(dec->cp);
break;
default:
if (sot->numparts == sot->partno - 1) {
tile->state = JPC_TILE_ACTIVELAST;
}
break;
}
/* Note: We do not increment the expected tile-part number until
all processing for this tile-part is complete. */
/* We should expect to encounter other tile-part header marker
segments next. */
dec->state = JPC_TPH;
return 0;
}
static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_dec_tile_t *tile;
int pos;
/* Eliminate compiler warnings about unused variables. */
ms = 0;
if (!(tile = dec->curtile)) {
return -1;
}
if (!tile->partno) {
if (!jpc_dec_cp_isvalid(tile->cp)) {
return -1;
}
jpc_dec_cp_prepare(tile->cp);
if (jpc_dec_tileinit(dec, tile)) {
return -1;
}
}
/* Are packet headers stored in the main header or tile-part header? */
if (dec->pkthdrstreams) {
/* Get the stream containing the packet header data for this
tile-part. */
if (!(tile->pkthdrstream = jpc_streamlist_remove(dec->pkthdrstreams, 0))) {
return -1;
}
}
if (tile->pptstab) {
if (!tile->pkthdrstream) {
if (!(tile->pkthdrstream = jas_stream_memopen(0, 0))) {
return -1;
}
}
pos = jas_stream_tell(tile->pkthdrstream);
jas_stream_seek(tile->pkthdrstream, 0, SEEK_END);
if (jpc_pptstabwrite(tile->pkthdrstream, tile->pptstab)) {
return -1;
}
jas_stream_seek(tile->pkthdrstream, pos, SEEK_SET);
jpc_ppxstab_destroy(tile->pptstab);
tile->pptstab = 0;
}
if (jas_getdbglevel() >= 10) {
jpc_dec_dump(dec, stderr);
}
if (jpc_dec_decodepkts(dec, (tile->pkthdrstream) ? tile->pkthdrstream :
dec->in, dec->in)) {
jas_eprintf("jpc_dec_decodepkts failed\n");
return -1;
}
/* Gobble any unconsumed tile data. */
if (dec->curtileendoff > 0) {
long curoff;
uint_fast32_t n;
curoff = jas_stream_getrwcount(dec->in);
if (curoff < dec->curtileendoff) {
n = dec->curtileendoff - curoff;
jas_eprintf("warning: ignoring trailing garbage (%lu bytes)\n",
(unsigned long) n);
while (n-- > 0) {
if (jas_stream_getc(dec->in) == EOF) {
jas_eprintf("read error\n");
return -1;
}
}
} else if (curoff > dec->curtileendoff) {
jas_eprintf("warning: not enough tile data (%lu bytes)\n",
(unsigned long) curoff - dec->curtileendoff);
}
}
if (tile->numparts > 0 && tile->partno == tile->numparts - 1) {
if (jpc_dec_tiledecode(dec, tile)) {
return -1;
}
jpc_dec_tilefini(dec, tile);
}
dec->curtile = 0;
/* Increment the expected tile-part number. */
++tile->partno;
/* We should expect to encounter a SOT marker segment next. */
dec->state = JPC_TPHSOT;
return 0;
}
static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile)
{
jpc_dec_tcomp_t *tcomp;
int compno;
int rlvlno;
jpc_dec_rlvl_t *rlvl;
jpc_dec_band_t *band;
jpc_dec_prc_t *prc;
int bndno;
jpc_tsfb_band_t *bnd;
int bandno;
jpc_dec_ccp_t *ccp;
int prccnt;
jpc_dec_cblk_t *cblk;
int cblkcnt;
uint_fast32_t tlprcxstart;
uint_fast32_t tlprcystart;
uint_fast32_t brprcxend;
uint_fast32_t brprcyend;
uint_fast32_t tlcbgxstart;
uint_fast32_t tlcbgystart;
uint_fast32_t brcbgxend;
uint_fast32_t brcbgyend;
uint_fast32_t cbgxstart;
uint_fast32_t cbgystart;
uint_fast32_t cbgxend;
uint_fast32_t cbgyend;
uint_fast32_t tlcblkxstart;
uint_fast32_t tlcblkystart;
uint_fast32_t brcblkxend;
uint_fast32_t brcblkyend;
uint_fast32_t cblkxstart;
uint_fast32_t cblkystart;
uint_fast32_t cblkxend;
uint_fast32_t cblkyend;
uint_fast32_t tmpxstart;
uint_fast32_t tmpystart;
uint_fast32_t tmpxend;
uint_fast32_t tmpyend;
jpc_dec_cp_t *cp;
jpc_tsfb_band_t bnds[64];
jpc_pchg_t *pchg;
int pchgno;
jpc_dec_cmpt_t *cmpt;
cp = tile->cp;
tile->realmode = 0;
if (cp->mctid == JPC_MCT_ICT) {
tile->realmode = 1;
}
for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
dec->numcomps; ++compno, ++tcomp, ++cmpt) {
ccp = &tile->cp->ccps[compno];
if (ccp->qmfbid == JPC_COX_INS) {
tile->realmode = 1;
}
tcomp->numrlvls = ccp->numrlvls;
if (!(tcomp->rlvls = jas_alloc2(tcomp->numrlvls,
sizeof(jpc_dec_rlvl_t)))) {
return -1;
}
if (!(tcomp->data = jas_seq2d_create(JPC_CEILDIV(tile->xstart,
cmpt->hstep), JPC_CEILDIV(tile->ystart, cmpt->vstep),
JPC_CEILDIV(tile->xend, cmpt->hstep), JPC_CEILDIV(tile->yend,
cmpt->vstep)))) {
return -1;
}
if (!(tcomp->tsfb = jpc_cod_gettsfb(ccp->qmfbid,
tcomp->numrlvls - 1))) {
return -1;
}
{
jpc_tsfb_getbands(tcomp->tsfb, jas_seq2d_xstart(tcomp->data),
jas_seq2d_ystart(tcomp->data), jas_seq2d_xend(tcomp->data),
jas_seq2d_yend(tcomp->data), bnds);
}
for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
++rlvlno, ++rlvl) {
rlvl->bands = 0;
rlvl->xstart = JPC_CEILDIVPOW2(tcomp->xstart,
tcomp->numrlvls - 1 - rlvlno);
rlvl->ystart = JPC_CEILDIVPOW2(tcomp->ystart,
tcomp->numrlvls - 1 - rlvlno);
rlvl->xend = JPC_CEILDIVPOW2(tcomp->xend,
tcomp->numrlvls - 1 - rlvlno);
rlvl->yend = JPC_CEILDIVPOW2(tcomp->yend,
tcomp->numrlvls - 1 - rlvlno);
rlvl->prcwidthexpn = ccp->prcwidthexpns[rlvlno];
rlvl->prcheightexpn = ccp->prcheightexpns[rlvlno];
tlprcxstart = JPC_FLOORDIVPOW2(rlvl->xstart,
rlvl->prcwidthexpn) << rlvl->prcwidthexpn;
tlprcystart = JPC_FLOORDIVPOW2(rlvl->ystart,
rlvl->prcheightexpn) << rlvl->prcheightexpn;
brprcxend = JPC_CEILDIVPOW2(rlvl->xend,
rlvl->prcwidthexpn) << rlvl->prcwidthexpn;
brprcyend = JPC_CEILDIVPOW2(rlvl->yend,
rlvl->prcheightexpn) << rlvl->prcheightexpn;
rlvl->numhprcs = (brprcxend - tlprcxstart) >>
rlvl->prcwidthexpn;
rlvl->numvprcs = (brprcyend - tlprcystart) >>
rlvl->prcheightexpn;
rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs;
if (rlvl->xstart >= rlvl->xend || rlvl->ystart >= rlvl->yend) {
rlvl->bands = 0;
rlvl->numprcs = 0;
rlvl->numhprcs = 0;
rlvl->numvprcs = 0;
continue;
}
if (!rlvlno) {
tlcbgxstart = tlprcxstart;
tlcbgystart = tlprcystart;
brcbgxend = brprcxend;
brcbgyend = brprcyend;
rlvl->cbgwidthexpn = rlvl->prcwidthexpn;
rlvl->cbgheightexpn = rlvl->prcheightexpn;
} else {
tlcbgxstart = JPC_CEILDIVPOW2(tlprcxstart, 1);
tlcbgystart = JPC_CEILDIVPOW2(tlprcystart, 1);
brcbgxend = JPC_CEILDIVPOW2(brprcxend, 1);
brcbgyend = JPC_CEILDIVPOW2(brprcyend, 1);
rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1;
rlvl->cbgheightexpn = rlvl->prcheightexpn - 1;
}
rlvl->cblkwidthexpn = JAS_MIN(ccp->cblkwidthexpn,
rlvl->cbgwidthexpn);
rlvl->cblkheightexpn = JAS_MIN(ccp->cblkheightexpn,
rlvl->cbgheightexpn);
rlvl->numbands = (!rlvlno) ? 1 : 3;
if (!(rlvl->bands = jas_alloc2(rlvl->numbands,
sizeof(jpc_dec_band_t)))) {
return -1;
}
for (bandno = 0, band = rlvl->bands;
bandno < rlvl->numbands; ++bandno, ++band) {
bndno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) +
bandno + 1);
bnd = &bnds[bndno];
band->orient = bnd->orient;
band->stepsize = ccp->stepsizes[bndno];
band->analgain = JPC_NOMINALGAIN(ccp->qmfbid,
tcomp->numrlvls - 1, rlvlno, band->orient);
band->absstepsize = jpc_calcabsstepsize(band->stepsize,
cmpt->prec + band->analgain);
band->numbps = ccp->numguardbits +
JPC_QCX_GETEXPN(band->stepsize) - 1;
band->roishift = (ccp->roishift + band->numbps >= JPC_PREC) ?
(JPC_PREC - 1 - band->numbps) : ccp->roishift;
band->data = 0;
band->prcs = 0;
if (bnd->xstart == bnd->xend || bnd->ystart == bnd->yend) {
continue;
}
if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) {
return -1;
}
jas_seq2d_bindsub(band->data, tcomp->data, bnd->locxstart,
bnd->locystart, bnd->locxend, bnd->locyend);
jas_seq2d_setshift(band->data, bnd->xstart, bnd->ystart);
assert(rlvl->numprcs);
if (!(band->prcs = jas_alloc2(rlvl->numprcs,
sizeof(jpc_dec_prc_t)))) {
return -1;
}
/************************************************/
cbgxstart = tlcbgxstart;
cbgystart = tlcbgystart;
for (prccnt = rlvl->numprcs, prc = band->prcs;
prccnt > 0; --prccnt, ++prc) {
cbgxend = cbgxstart + (1 << rlvl->cbgwidthexpn);
cbgyend = cbgystart + (1 << rlvl->cbgheightexpn);
prc->xstart = JAS_MAX(cbgxstart, JAS_CAST(uint_fast32_t,
jas_seq2d_xstart(band->data)));
prc->ystart = JAS_MAX(cbgystart, JAS_CAST(uint_fast32_t,
jas_seq2d_ystart(band->data)));
prc->xend = JAS_MIN(cbgxend, JAS_CAST(uint_fast32_t,
jas_seq2d_xend(band->data)));
prc->yend = JAS_MIN(cbgyend, JAS_CAST(uint_fast32_t,
jas_seq2d_yend(band->data)));
if (prc->xend > prc->xstart && prc->yend > prc->ystart) {
tlcblkxstart = JPC_FLOORDIVPOW2(prc->xstart,
rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn;
tlcblkystart = JPC_FLOORDIVPOW2(prc->ystart,
rlvl->cblkheightexpn) << rlvl->cblkheightexpn;
brcblkxend = JPC_CEILDIVPOW2(prc->xend,
rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn;
brcblkyend = JPC_CEILDIVPOW2(prc->yend,
rlvl->cblkheightexpn) << rlvl->cblkheightexpn;
prc->numhcblks = (brcblkxend - tlcblkxstart) >>
rlvl->cblkwidthexpn;
prc->numvcblks = (brcblkyend - tlcblkystart) >>
rlvl->cblkheightexpn;
prc->numcblks = prc->numhcblks * prc->numvcblks;
assert(prc->numcblks > 0);
if (!(prc->incltagtree = jpc_tagtree_create(
prc->numhcblks, prc->numvcblks))) {
return -1;
}
if (!(prc->numimsbstagtree = jpc_tagtree_create(
prc->numhcblks, prc->numvcblks))) {
return -1;
}
if (!(prc->cblks = jas_alloc2(prc->numcblks,
sizeof(jpc_dec_cblk_t)))) {
return -1;
}
cblkxstart = cbgxstart;
cblkystart = cbgystart;
for (cblkcnt = prc->numcblks, cblk = prc->cblks;
cblkcnt > 0;) {
cblkxend = cblkxstart + (1 << rlvl->cblkwidthexpn);
cblkyend = cblkystart + (1 << rlvl->cblkheightexpn);
tmpxstart = JAS_MAX(cblkxstart, prc->xstart);
tmpystart = JAS_MAX(cblkystart, prc->ystart);
tmpxend = JAS_MIN(cblkxend, prc->xend);
tmpyend = JAS_MIN(cblkyend, prc->yend);
if (tmpxend > tmpxstart && tmpyend > tmpystart) {
cblk->firstpassno = -1;
cblk->mqdec = 0;
cblk->nulldec = 0;
cblk->flags = 0;
cblk->numpasses = 0;
cblk->segs.head = 0;
cblk->segs.tail = 0;
cblk->curseg = 0;
cblk->numimsbs = 0;
cblk->numlenbits = 3;
cblk->flags = 0;
if (!(cblk->data = jas_seq2d_create(0, 0, 0,
0))) {
return -1;
}
jas_seq2d_bindsub(cblk->data, band->data,
tmpxstart, tmpystart, tmpxend, tmpyend);
++cblk;
--cblkcnt;
}
cblkxstart += 1 << rlvl->cblkwidthexpn;
if (cblkxstart >= cbgxend) {
cblkxstart = cbgxstart;
cblkystart += 1 << rlvl->cblkheightexpn;
}
}
} else {
prc->cblks = 0;
prc->incltagtree = 0;
prc->numimsbstagtree = 0;
}
cbgxstart += 1 << rlvl->cbgwidthexpn;
if (cbgxstart >= brcbgxend) {
cbgxstart = tlcbgxstart;
cbgystart += 1 << rlvl->cbgheightexpn;
}
}
/********************************************/
}
}
}
if (!(tile->pi = jpc_dec_pi_create(dec, tile))) {
return -1;
}
for (pchgno = 0; pchgno < jpc_pchglist_numpchgs(tile->cp->pchglist);
++pchgno) {
pchg = jpc_pchg_copy(jpc_pchglist_get(tile->cp->pchglist, pchgno));
assert(pchg);
jpc_pi_addpchg(tile->pi, pchg);
}
jpc_pi_init(tile->pi);
return 0;
}
static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile)
{
jpc_dec_tcomp_t *tcomp;
int compno;
int bandno;
int rlvlno;
jpc_dec_band_t *band;
jpc_dec_rlvl_t *rlvl;
int prcno;
jpc_dec_prc_t *prc;
jpc_dec_seg_t *seg;
jpc_dec_cblk_t *cblk;
int cblkno;
if (tile->tcomps) {
for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
++compno, ++tcomp) {
for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
++rlvlno, ++rlvl) {
if (!rlvl->bands) {
continue;
}
for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
++bandno, ++band) {
if (band->prcs) {
for (prcno = 0, prc = band->prcs; prcno <
rlvl->numprcs; ++prcno, ++prc) {
if (!prc->cblks) {
continue;
}
for (cblkno = 0, cblk = prc->cblks; cblkno <
prc->numcblks; ++cblkno, ++cblk) {
while (cblk->segs.head) {
seg = cblk->segs.head;
jpc_seglist_remove(&cblk->segs, seg);
jpc_seg_destroy(seg);
}
jas_matrix_destroy(cblk->data);
if (cblk->mqdec) {
jpc_mqdec_destroy(cblk->mqdec);
}
if (cblk->nulldec) {
jpc_bitstream_close(cblk->nulldec);
}
if (cblk->flags) {
jas_matrix_destroy(cblk->flags);
}
}
if (prc->incltagtree) {
jpc_tagtree_destroy(prc->incltagtree);
}
if (prc->numimsbstagtree) {
jpc_tagtree_destroy(prc->numimsbstagtree);
}
if (prc->cblks) {
jas_free(prc->cblks);
}
}
}
if (band->data) {
jas_matrix_destroy(band->data);
}
if (band->prcs) {
jas_free(band->prcs);
}
}
if (rlvl->bands) {
jas_free(rlvl->bands);
}
}
if (tcomp->rlvls) {
jas_free(tcomp->rlvls);
}
if (tcomp->data) {
jas_matrix_destroy(tcomp->data);
}
if (tcomp->tsfb) {
jpc_tsfb_destroy(tcomp->tsfb);
}
}
}
if (tile->cp) {
jpc_dec_cp_destroy(tile->cp);
//tile->cp = 0;
}
if (tile->tcomps) {
jas_free(tile->tcomps);
//tile->tcomps = 0;
}
if (tile->pi) {
jpc_pi_destroy(tile->pi);
//tile->pi = 0;
}
if (tile->pkthdrstream) {
jas_stream_close(tile->pkthdrstream);
//tile->pkthdrstream = 0;
}
if (tile->pptstab) {
jpc_ppxstab_destroy(tile->pptstab);
//tile->pptstab = 0;
}
tile->state = JPC_TILE_DONE;
return 0;
}
static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile)
{
int i;
int j;
jpc_dec_tcomp_t *tcomp;
jpc_dec_rlvl_t *rlvl;
jpc_dec_band_t *band;
int compno;
int rlvlno;
int bandno;
int adjust;
int v;
jpc_dec_ccp_t *ccp;
jpc_dec_cmpt_t *cmpt;
if (jpc_dec_decodecblks(dec, tile)) {
jas_eprintf("jpc_dec_decodecblks failed\n");
return -1;
}
/* Perform dequantization. */
for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
++compno, ++tcomp) {
ccp = &tile->cp->ccps[compno];
for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
++rlvlno, ++rlvl) {
if (!rlvl->bands) {
continue;
}
for (bandno = 0, band = rlvl->bands;
bandno < rlvl->numbands; ++bandno, ++band) {
if (!band->data) {
continue;
}
jpc_undo_roi(band->data, band->roishift, ccp->roishift -
band->roishift, band->numbps);
if (tile->realmode) {
jas_matrix_asl(band->data, JPC_FIX_FRACBITS);
jpc_dequantize(band->data, band->absstepsize);
}
}
}
}
/* Apply an inverse wavelet transform if necessary. */
for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
++compno, ++tcomp) {
ccp = &tile->cp->ccps[compno];
jpc_tsfb_synthesize(tcomp->tsfb, tcomp->data);
}
/* Apply an inverse intercomponent transform if necessary. */
switch (tile->cp->mctid) {
case JPC_MCT_RCT:
if (dec->numcomps < 3) {
jas_eprintf("RCT requires at least three components\n");
return -1;
}
if (!jas_image_cmpt_domains_same(dec->image)) {
jas_eprintf("RCT requires all components have the same domain\n");
return -1;
}
jpc_irct(tile->tcomps[0].data, tile->tcomps[1].data,
tile->tcomps[2].data);
break;
case JPC_MCT_ICT:
if (dec->numcomps < 3) {
jas_eprintf("ICT requires at least three components\n");
return -1;
}
if (!jas_image_cmpt_domains_same(dec->image)) {
jas_eprintf("RCT requires all components have the same domain\n");
return -1;
}
jpc_iict(tile->tcomps[0].data, tile->tcomps[1].data,
tile->tcomps[2].data);
break;
}
/* Perform rounding and convert to integer values. */
if (tile->realmode) {
for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
++compno, ++tcomp) {
for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) {
for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) {
v = jas_matrix_get(tcomp->data, i, j);
v = jpc_fix_round(v);
jas_matrix_set(tcomp->data, i, j, jpc_fixtoint(v));
}
}
}
}
/* Perform level shift. */
for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
dec->numcomps; ++compno, ++tcomp, ++cmpt) {
adjust = cmpt->sgnd ? 0 : (1 << (cmpt->prec - 1));
for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) {
for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) {
*jas_matrix_getref(tcomp->data, i, j) += adjust;
}
}
}
/* Perform clipping. */
for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
dec->numcomps; ++compno, ++tcomp, ++cmpt) {
jpc_fix_t mn;
jpc_fix_t mx;
mn = cmpt->sgnd ? (-(1 << (cmpt->prec - 1))) : (0);
mx = cmpt->sgnd ? ((1 << (cmpt->prec - 1)) - 1) : ((1 <<
cmpt->prec) - 1);
jas_matrix_clip(tcomp->data, mn, mx);
}
/* XXX need to free tsfb struct */
/* Write the data for each component of the image. */
for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
dec->numcomps; ++compno, ++tcomp, ++cmpt) {
if (jas_image_writecmpt(dec->image, compno, tcomp->xstart -
JPC_CEILDIV(dec->xstart, cmpt->hstep), tcomp->ystart -
JPC_CEILDIV(dec->ystart, cmpt->vstep), jas_matrix_numcols(
tcomp->data), jas_matrix_numrows(tcomp->data), tcomp->data)) {
jas_eprintf("write component failed\n");
return -1;
}
}
return 0;
}
static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms)
{
int tileno;
jpc_dec_tile_t *tile;
/* Eliminate compiler warnings about unused variables. */
ms = 0;
for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
++tile) {
if (tile->state == JPC_TILE_ACTIVE) {
if (jpc_dec_tiledecode(dec, tile)) {
return -1;
}
}
/* If the tile has not yet been finalized, finalize it. */
// OLD CODE: jpc_dec_tilefini(dec, tile);
if (tile->state != JPC_TILE_DONE) {
jpc_dec_tilefini(dec, tile);
}
}
/* We are done processing the code stream. */
dec->state = JPC_MT;
return 1;
}
static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_siz_t *siz = &ms->parms.siz;
int compno;
int tileno;
jpc_dec_tile_t *tile;
jpc_dec_tcomp_t *tcomp;
int htileno;
int vtileno;
jpc_dec_cmpt_t *cmpt;
size_t size;
dec->xstart = siz->xoff;
dec->ystart = siz->yoff;
dec->xend = siz->width;
dec->yend = siz->height;
dec->tilewidth = siz->tilewidth;
dec->tileheight = siz->tileheight;
dec->tilexoff = siz->tilexoff;
dec->tileyoff = siz->tileyoff;
dec->numcomps = siz->numcomps;
if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {
return -1;
}
if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,
++cmpt) {
cmpt->prec = siz->comps[compno].prec;
cmpt->sgnd = siz->comps[compno].sgnd;
cmpt->hstep = siz->comps[compno].hsamp;
cmpt->vstep = siz->comps[compno].vsamp;
cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -
JPC_CEILDIV(dec->xstart, cmpt->hstep);
cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -
JPC_CEILDIV(dec->ystart, cmpt->vstep);
cmpt->hsubstep = 0;
cmpt->vsubstep = 0;
}
dec->image = 0;
dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);
dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);
if (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size)) {
return -1;
}
dec->numtiles = size;
JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n",
dec->numtiles, dec->numhtiles, dec->numvtiles));
if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {
return -1;
}
for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
++tile) {
htileno = tileno % dec->numhtiles;
vtileno = tileno / dec->numhtiles;
tile->realmode = 0;
tile->state = JPC_TILE_INIT;
tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,
dec->xstart);
tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,
dec->ystart);
tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *
dec->tilewidth, dec->xend);
tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *
dec->tileheight, dec->yend);
tile->numparts = 0;
tile->partno = 0;
tile->pkthdrstream = 0;
tile->pkthdrstreampos = 0;
tile->pptstab = 0;
tile->cp = 0;
tile->pi = 0;
if (!(tile->tcomps = jas_alloc2(dec->numcomps,
sizeof(jpc_dec_tcomp_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;
compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {
tcomp->rlvls = 0;
tcomp->numrlvls = 0;
tcomp->data = 0;
tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);
tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);
tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);
tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);
tcomp->tsfb = 0;
}
}
dec->pkthdrstreams = 0;
/* We should expect to encounter other main header marker segments
or an SOT marker segment next. */
dec->state = JPC_MH;
return 0;
}
static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_cod_t *cod = &ms->parms.cod;
jpc_dec_tile_t *tile;
switch (dec->state) {
case JPC_MH:
jpc_dec_cp_setfromcod(dec->cp, cod);
break;
case JPC_TPH:
if (!(tile = dec->curtile)) {
return -1;
}
if (tile->partno != 0) {
return -1;
}
jpc_dec_cp_setfromcod(tile->cp, cod);
break;
}
return 0;
}
static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_coc_t *coc = &ms->parms.coc;
jpc_dec_tile_t *tile;
if (JAS_CAST(int, coc->compno) >= dec->numcomps) {
jas_eprintf("invalid component number in COC marker segment\n");
return -1;
}
switch (dec->state) {
case JPC_MH:
jpc_dec_cp_setfromcoc(dec->cp, coc);
break;
case JPC_TPH:
if (!(tile = dec->curtile)) {
return -1;
}
if (tile->partno > 0) {
return -1;
}
jpc_dec_cp_setfromcoc(tile->cp, coc);
break;
}
return 0;
}
static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_rgn_t *rgn = &ms->parms.rgn;
jpc_dec_tile_t *tile;
if (JAS_CAST(int, rgn->compno) >= dec->numcomps) {
jas_eprintf("invalid component number in RGN marker segment\n");
return -1;
}
switch (dec->state) {
case JPC_MH:
jpc_dec_cp_setfromrgn(dec->cp, rgn);
break;
case JPC_TPH:
if (!(tile = dec->curtile)) {
return -1;
}
if (tile->partno > 0) {
return -1;
}
jpc_dec_cp_setfromrgn(tile->cp, rgn);
break;
}
return 0;
}
static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_qcd_t *qcd = &ms->parms.qcd;
jpc_dec_tile_t *tile;
switch (dec->state) {
case JPC_MH:
jpc_dec_cp_setfromqcd(dec->cp, qcd);
break;
case JPC_TPH:
if (!(tile = dec->curtile)) {
return -1;
}
if (tile->partno > 0) {
return -1;
}
jpc_dec_cp_setfromqcd(tile->cp, qcd);
break;
}
return 0;
}
static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_qcc_t *qcc = &ms->parms.qcc;
jpc_dec_tile_t *tile;
if (JAS_CAST(int, qcc->compno) >= dec->numcomps) {
jas_eprintf("invalid component number in QCC marker segment\n");
return -1;
}
switch (dec->state) {
case JPC_MH:
jpc_dec_cp_setfromqcc(dec->cp, qcc);
break;
case JPC_TPH:
if (!(tile = dec->curtile)) {
return -1;
}
if (tile->partno > 0) {
return -1;
}
jpc_dec_cp_setfromqcc(tile->cp, qcc);
break;
}
return 0;
}
static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_poc_t *poc = &ms->parms.poc;
jpc_dec_tile_t *tile;
switch (dec->state) {
case JPC_MH:
if (jpc_dec_cp_setfrompoc(dec->cp, poc, 1)) {
return -1;
}
break;
case JPC_TPH:
if (!(tile = dec->curtile)) {
return -1;
}
if (!tile->partno) {
if (jpc_dec_cp_setfrompoc(tile->cp, poc, (!tile->partno))) {
return -1;
}
} else {
jpc_pi_addpchgfrompoc(tile->pi, poc);
}
break;
}
return 0;
}
static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_ppm_t *ppm = &ms->parms.ppm;
jpc_ppxstabent_t *ppmstabent;
if (!dec->ppmstab) {
if (!(dec->ppmstab = jpc_ppxstab_create())) {
return -1;
}
}
if (!(ppmstabent = jpc_ppxstabent_create())) {
return -1;
}
ppmstabent->ind = ppm->ind;
ppmstabent->data = ppm->data;
ppm->data = 0;
ppmstabent->len = ppm->len;
if (jpc_ppxstab_insert(dec->ppmstab, ppmstabent)) {
return -1;
}
return 0;
}
static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_ppt_t *ppt = &ms->parms.ppt;
jpc_dec_tile_t *tile;
jpc_ppxstabent_t *pptstabent;
tile = dec->curtile;
if (!tile->pptstab) {
if (!(tile->pptstab = jpc_ppxstab_create())) {
return -1;
}
}
if (!(pptstabent = jpc_ppxstabent_create())) {
return -1;
}
pptstabent->ind = ppt->ind;
pptstabent->data = ppt->data;
ppt->data = 0;
pptstabent->len = ppt->len;
if (jpc_ppxstab_insert(tile->pptstab, pptstabent)) {
return -1;
}
return 0;
}
static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms)
{
/* Eliminate compiler warnings about unused variables. */
dec = 0;
ms = 0;
return 0;
}
static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms)
{
/* Eliminate compiler warnings about unused variables. */
dec = 0;
jas_eprintf("warning: ignoring unknown marker segment\n");
jpc_ms_dump(ms, stderr);
return 0;
}
/******************************************************************************\
*
\******************************************************************************/
static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps)
{
jpc_dec_cp_t *cp;
jpc_dec_ccp_t *ccp;
int compno;
if (!(cp = jas_malloc(sizeof(jpc_dec_cp_t)))) {
return 0;
}
cp->flags = 0;
cp->numcomps = numcomps;
cp->prgord = 0;
cp->numlyrs = 0;
cp->mctid = 0;
cp->csty = 0;
if (!(cp->ccps = jas_alloc2(cp->numcomps, sizeof(jpc_dec_ccp_t)))) {
goto error;
}
if (!(cp->pchglist = jpc_pchglist_create())) {
goto error;
}
for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
++compno, ++ccp) {
ccp->flags = 0;
ccp->numrlvls = 0;
ccp->cblkwidthexpn = 0;
ccp->cblkheightexpn = 0;
ccp->qmfbid = 0;
ccp->numstepsizes = 0;
ccp->numguardbits = 0;
ccp->roishift = 0;
ccp->cblkctx = 0;
}
return cp;
error:
if (cp) {
jpc_dec_cp_destroy(cp);
}
return 0;
}
static jpc_dec_cp_t *jpc_dec_cp_copy(jpc_dec_cp_t *cp)
{
jpc_dec_cp_t *newcp;
jpc_dec_ccp_t *newccp;
jpc_dec_ccp_t *ccp;
int compno;
if (!(newcp = jpc_dec_cp_create(cp->numcomps))) {
return 0;
}
newcp->flags = cp->flags;
newcp->prgord = cp->prgord;
newcp->numlyrs = cp->numlyrs;
newcp->mctid = cp->mctid;
newcp->csty = cp->csty;
jpc_pchglist_destroy(newcp->pchglist);
newcp->pchglist = 0;
if (!(newcp->pchglist = jpc_pchglist_copy(cp->pchglist))) {
jas_free(newcp);
return 0;
}
for (compno = 0, newccp = newcp->ccps, ccp = cp->ccps;
compno < cp->numcomps;
++compno, ++newccp, ++ccp) {
*newccp = *ccp;
}
return newcp;
}
static void jpc_dec_cp_resetflags(jpc_dec_cp_t *cp)
{
int compno;
jpc_dec_ccp_t *ccp;
cp->flags &= (JPC_CSET | JPC_QSET);
for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
++compno, ++ccp) {
ccp->flags = 0;
}
}
static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp)
{
if (cp->ccps) {
jas_free(cp->ccps);
}
if (cp->pchglist) {
jpc_pchglist_destroy(cp->pchglist);
}
jas_free(cp);
}
static int jpc_dec_cp_isvalid(jpc_dec_cp_t *cp)
{
uint_fast16_t compcnt;
jpc_dec_ccp_t *ccp;
if (!(cp->flags & JPC_CSET) || !(cp->flags & JPC_QSET)) {
return 0;
}
for (compcnt = cp->numcomps, ccp = cp->ccps; compcnt > 0; --compcnt,
++ccp) {
/* Is there enough step sizes for the number of bands? */
if ((ccp->qsty != JPC_QCX_SIQNT && JAS_CAST(int, ccp->numstepsizes) < 3 *
ccp->numrlvls - 2) || (ccp->qsty == JPC_QCX_SIQNT &&
ccp->numstepsizes != 1)) {
return 0;
}
}
return 1;
}
static void calcstepsizes(uint_fast16_t refstepsize, int numrlvls,
uint_fast16_t *stepsizes)
{
int bandno;
int numbands;
uint_fast16_t expn;
uint_fast16_t mant;
expn = JPC_QCX_GETEXPN(refstepsize);
mant = JPC_QCX_GETMANT(refstepsize);
numbands = 3 * numrlvls - 2;
for (bandno = 0; bandno < numbands; ++bandno) {
//jas_eprintf("DEBUG %d %d %d %d %d\n", bandno, expn, numrlvls, bandno, ((numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))));
stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn +
(numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0))));
}
}
static int jpc_dec_cp_prepare(jpc_dec_cp_t *cp)
{
jpc_dec_ccp_t *ccp;
int compno;
int i;
for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
++compno, ++ccp) {
if (!(ccp->csty & JPC_COX_PRT)) {
for (i = 0; i < JPC_MAXRLVLS; ++i) {
ccp->prcwidthexpns[i] = 15;
ccp->prcheightexpns[i] = 15;
}
}
if (ccp->qsty == JPC_QCX_SIQNT) {
calcstepsizes(ccp->stepsizes[0], ccp->numrlvls, ccp->stepsizes);
}
}
return 0;
}
static int jpc_dec_cp_setfromcod(jpc_dec_cp_t *cp, jpc_cod_t *cod)
{
jpc_dec_ccp_t *ccp;
int compno;
cp->flags |= JPC_CSET;
cp->prgord = cod->prg;
if (cod->mctrans) {
cp->mctid = (cod->compparms.qmfbid == JPC_COX_INS) ? (JPC_MCT_ICT) : (JPC_MCT_RCT);
} else {
cp->mctid = JPC_MCT_NONE;
}
cp->numlyrs = cod->numlyrs;
cp->csty = cod->csty & (JPC_COD_SOP | JPC_COD_EPH);
for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
++compno, ++ccp) {
jpc_dec_cp_setfromcox(cp, ccp, &cod->compparms, 0);
}
cp->flags |= JPC_CSET;
return 0;
}
static int jpc_dec_cp_setfromcoc(jpc_dec_cp_t *cp, jpc_coc_t *coc)
{
jpc_dec_cp_setfromcox(cp, &cp->ccps[coc->compno], &coc->compparms, JPC_COC);
return 0;
}
static int jpc_dec_cp_setfromcox(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp,
jpc_coxcp_t *compparms, int flags)
{
int rlvlno;
/* Eliminate compiler warnings about unused variables. */
cp = 0;
if ((flags & JPC_COC) || !(ccp->flags & JPC_COC)) {
ccp->numrlvls = compparms->numdlvls + 1;
ccp->cblkwidthexpn = JPC_COX_GETCBLKSIZEEXPN(
compparms->cblkwidthval);
ccp->cblkheightexpn = JPC_COX_GETCBLKSIZEEXPN(
compparms->cblkheightval);
ccp->qmfbid = compparms->qmfbid;
ccp->cblkctx = compparms->cblksty;
ccp->csty = compparms->csty & JPC_COX_PRT;
for (rlvlno = 0; rlvlno < compparms->numrlvls; ++rlvlno) {
ccp->prcwidthexpns[rlvlno] =
compparms->rlvls[rlvlno].parwidthval;
ccp->prcheightexpns[rlvlno] =
compparms->rlvls[rlvlno].parheightval;
}
ccp->flags |= flags | JPC_CSET;
}
return 0;
}
static int jpc_dec_cp_setfromqcd(jpc_dec_cp_t *cp, jpc_qcd_t *qcd)
{
int compno;
jpc_dec_ccp_t *ccp;
for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
++compno, ++ccp) {
jpc_dec_cp_setfromqcx(cp, ccp, &qcd->compparms, 0);
}
cp->flags |= JPC_QSET;
return 0;
}
static int jpc_dec_cp_setfromqcc(jpc_dec_cp_t *cp, jpc_qcc_t *qcc)
{
return jpc_dec_cp_setfromqcx(cp, &cp->ccps[qcc->compno], &qcc->compparms, JPC_QCC);
}
static int jpc_dec_cp_setfromqcx(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp,
jpc_qcxcp_t *compparms, int flags)
{
int bandno;
/* Eliminate compiler warnings about unused variables. */
cp = 0;
if ((flags & JPC_QCC) || !(ccp->flags & JPC_QCC)) {
ccp->flags |= flags | JPC_QSET;
for (bandno = 0; bandno < compparms->numstepsizes; ++bandno) {
ccp->stepsizes[bandno] = compparms->stepsizes[bandno];
}
ccp->numstepsizes = compparms->numstepsizes;
ccp->numguardbits = compparms->numguard;
ccp->qsty = compparms->qntsty;
}
return 0;
}
static int jpc_dec_cp_setfromrgn(jpc_dec_cp_t *cp, jpc_rgn_t *rgn)
{
jpc_dec_ccp_t *ccp;
ccp = &cp->ccps[rgn->compno];
ccp->roishift = rgn->roishift;
return 0;
}
static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, jpc_poc_t *poc)
{
int pchgno;
jpc_pchg_t *pchg;
for (pchgno = 0; pchgno < poc->numpchgs; ++pchgno) {
if (!(pchg = jpc_pchg_copy(&poc->pchgs[pchgno]))) {
return -1;
}
if (jpc_pchglist_insert(pi->pchglist, -1, pchg)) {
return -1;
}
}
return 0;
}
static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, jpc_poc_t *poc, int reset)
{
int pchgno;
jpc_pchg_t *pchg;
if (reset) {
while (jpc_pchglist_numpchgs(cp->pchglist) > 0) {
pchg = jpc_pchglist_remove(cp->pchglist, 0);
jpc_pchg_destroy(pchg);
}
}
for (pchgno = 0; pchgno < poc->numpchgs; ++pchgno) {
if (!(pchg = jpc_pchg_copy(&poc->pchgs[pchgno]))) {
return -1;
}
if (jpc_pchglist_insert(cp->pchglist, -1, pchg)) {
return -1;
}
}
return 0;
}
static jpc_fix_t jpc_calcabsstepsize(int stepsize, int numbits)
{
jpc_fix_t absstepsize;
int n;
absstepsize = jpc_inttofix(1);
n = JPC_FIX_FRACBITS - 11;
absstepsize |= (n >= 0) ? (JPC_QCX_GETMANT(stepsize) << n) :
(JPC_QCX_GETMANT(stepsize) >> (-n));
n = numbits - JPC_QCX_GETEXPN(stepsize);
absstepsize = (n >= 0) ? (absstepsize << n) : (absstepsize >> (-n));
return absstepsize;
}
static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize)
{
int i;
int j;
int t;
assert(absstepsize >= 0);
if (absstepsize == jpc_inttofix(1)) {
return;
}
for (i = 0; i < jas_matrix_numrows(x); ++i) {
for (j = 0; j < jas_matrix_numcols(x); ++j) {
t = jas_matrix_get(x, i, j);
if (t) {
t = jpc_fix_mul(t, absstepsize);
} else {
t = 0;
}
jas_matrix_set(x, i, j, t);
}
}
}
static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps)
{
int i;
int j;
int thresh;
jpc_fix_t val;
jpc_fix_t mag;
bool warn;
uint_fast32_t mask;
if (roishift < 0) {
/* We could instead return an error here. */
/* I do not think it matters much. */
jas_eprintf("warning: forcing negative ROI shift to zero "
"(bitstream is probably corrupt)\n");
roishift = 0;
}
if (roishift == 0 && bgshift == 0) {
return;
}
thresh = 1 << roishift;
warn = false;
for (i = 0; i < jas_matrix_numrows(x); ++i) {
for (j = 0; j < jas_matrix_numcols(x); ++j) {
val = jas_matrix_get(x, i, j);
mag = JAS_ABS(val);
if (mag >= thresh) {
/* We are dealing with ROI data. */
mag >>= roishift;
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
} else {
/* We are dealing with non-ROI (i.e., background) data. */
mag <<= bgshift;
mask = (JAS_CAST(uint_fast32_t, 1) << numbps) - 1;
/* Perform a basic sanity check on the sample value. */
/* Some implementations write garbage in the unused
most-significant bit planes introduced by ROI shifting.
Here we ensure that any such bits are masked off. */
if (mag & (~mask)) {
if (!warn) {
jas_eprintf("warning: possibly corrupt code stream\n");
warn = true;
}
mag &= mask;
}
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
}
}
}
}
static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in)
{
jpc_dec_t *dec;
if (!(dec = jas_malloc(sizeof(jpc_dec_t)))) {
return 0;
}
dec->image = 0;
dec->xstart = 0;
dec->ystart = 0;
dec->xend = 0;
dec->yend = 0;
dec->tilewidth = 0;
dec->tileheight = 0;
dec->tilexoff = 0;
dec->tileyoff = 0;
dec->numhtiles = 0;
dec->numvtiles = 0;
dec->numtiles = 0;
dec->tiles = 0;
dec->curtile = 0;
dec->numcomps = 0;
dec->in = in;
dec->cp = 0;
dec->maxlyrs = impopts->maxlyrs;
dec->maxpkts = impopts->maxpkts;
dec->numpkts = 0;
dec->ppmseqno = 0;
dec->state = 0;
dec->cmpts = 0;
dec->pkthdrstreams = 0;
dec->ppmstab = 0;
dec->curtileendoff = 0;
return dec;
}
static void jpc_dec_destroy(jpc_dec_t *dec)
{
if (dec->cstate) {
jpc_cstate_destroy(dec->cstate);
}
if (dec->pkthdrstreams) {
jpc_streamlist_destroy(dec->pkthdrstreams);
}
if (dec->image) {
jas_image_destroy(dec->image);
}
if (dec->cp) {
jpc_dec_cp_destroy(dec->cp);
}
if (dec->cmpts) {
jas_free(dec->cmpts);
}
if (dec->tiles) {
jas_free(dec->tiles);
}
jas_free(dec);
}
/******************************************************************************\
*
\******************************************************************************/
void jpc_seglist_insert(jpc_dec_seglist_t *list, jpc_dec_seg_t *ins, jpc_dec_seg_t *node)
{
jpc_dec_seg_t *prev;
jpc_dec_seg_t *next;
prev = ins;
node->prev = prev;
next = prev ? (prev->next) : 0;
node->prev = prev;
node->next = next;
if (prev) {
prev->next = node;
} else {
list->head = node;
}
if (next) {
next->prev = node;
} else {
list->tail = node;
}
}
void jpc_seglist_remove(jpc_dec_seglist_t *list, jpc_dec_seg_t *seg)
{
jpc_dec_seg_t *prev;
jpc_dec_seg_t *next;
prev = seg->prev;
next = seg->next;
if (prev) {
prev->next = next;
} else {
list->head = next;
}
if (next) {
next->prev = prev;
} else {
list->tail = prev;
}
seg->prev = 0;
seg->next = 0;
}
jpc_dec_seg_t *jpc_seg_alloc()
{
jpc_dec_seg_t *seg;
if (!(seg = jas_malloc(sizeof(jpc_dec_seg_t)))) {
return 0;
}
seg->prev = 0;
seg->next = 0;
seg->passno = -1;
seg->numpasses = 0;
seg->maxpasses = 0;
seg->type = JPC_SEG_INVALID;
seg->stream = 0;
seg->cnt = 0;
seg->complete = 0;
seg->lyrno = -1;
return seg;
}
void jpc_seg_destroy(jpc_dec_seg_t *seg)
{
if (seg->stream) {
jas_stream_close(seg->stream);
}
jas_free(seg);
}
static int jpc_dec_dump(jpc_dec_t *dec, FILE *out)
{
jpc_dec_tile_t *tile;
int tileno;
jpc_dec_tcomp_t *tcomp;
int compno;
jpc_dec_rlvl_t *rlvl;
int rlvlno;
jpc_dec_band_t *band;
int bandno;
jpc_dec_prc_t *prc;
int prcno;
jpc_dec_cblk_t *cblk;
int cblkno;
assert(!dec->numtiles || dec->tiles);
for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles;
++tileno, ++tile) {
assert(!dec->numcomps || tile->tcomps);
for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
++compno, ++tcomp) {
for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno <
tcomp->numrlvls; ++rlvlno, ++rlvl) {
fprintf(out, "RESOLUTION LEVEL %d\n", rlvlno);
fprintf(out, "xs = %"PRIuFAST32", ys = %"PRIuFAST32", xe = %"PRIuFAST32", ye = %"PRIuFAST32", w = %"PRIuFAST32", h = %"PRIuFAST32"\n",
rlvl->xstart, rlvl->ystart, rlvl->xend, rlvl->yend,
rlvl->xend - rlvl->xstart, rlvl->yend - rlvl->ystart);
assert(!rlvl->numbands || rlvl->bands);
for (bandno = 0, band = rlvl->bands;
bandno < rlvl->numbands; ++bandno, ++band) {
fprintf(out, "BAND %d\n", bandno);
if (!band->data) {
fprintf(out, "band has no data (null pointer)\n");
assert(!band->prcs);
continue;
}
fprintf(out, "xs = %"PRIiFAST32", ys = %"PRIiFAST32", xe = %"PRIiFAST32", ye = %"PRIiFAST32", w = %"PRIiFAST32", h = %"PRIiFAST32"\n",
jas_seq2d_xstart(band->data),
jas_seq2d_ystart(band->data),
jas_seq2d_xend(band->data),
jas_seq2d_yend(band->data),
jas_seq2d_xend(band->data) -
jas_seq2d_xstart(band->data),
jas_seq2d_yend(band->data) -
jas_seq2d_ystart(band->data));
assert(!rlvl->numprcs || band->prcs);
for (prcno = 0, prc = band->prcs;
prcno < rlvl->numprcs; ++prcno,
++prc) {
fprintf(out, "CODE BLOCK GROUP %d\n", prcno);
fprintf(out, "xs = %"PRIuFAST32", ys = %"PRIuFAST32", xe = %"PRIuFAST32", ye = %"PRIuFAST32", w = %"PRIuFAST32", h = %"PRIuFAST32"\n",
prc->xstart, prc->ystart, prc->xend, prc->yend,
prc->xend - prc->xstart, prc->yend - prc->ystart);
assert(!prc->numcblks || prc->cblks);
for (cblkno = 0, cblk =
prc->cblks; cblkno <
prc->numcblks; ++cblkno,
++cblk) {
fprintf(out, "CODE BLOCK %d\n", cblkno);
fprintf(out, "xs = %"PRIiFAST32", ys = %"PRIiFAST32", xe = %"PRIiFAST32", ye = %"PRIiFAST32", w = %"PRIiFAST32", h = %"PRIiFAST32"\n",
jas_seq2d_xstart(cblk->data),
jas_seq2d_ystart(cblk->data),
jas_seq2d_xend(cblk->data),
jas_seq2d_yend(cblk->data),
jas_seq2d_xend(cblk->data) -
jas_seq2d_xstart(cblk->data),
jas_seq2d_yend(cblk->data) -
jas_seq2d_ystart(cblk->data));
}
}
}
}
}
}
return 0;
}
jpc_streamlist_t *jpc_streamlist_create()
{
jpc_streamlist_t *streamlist;
int i;
if (!(streamlist = jas_malloc(sizeof(jpc_streamlist_t)))) {
return 0;
}
streamlist->numstreams = 0;
streamlist->maxstreams = 100;
if (!(streamlist->streams = jas_alloc2(streamlist->maxstreams,
sizeof(jas_stream_t *)))) {
jas_free(streamlist);
return 0;
}
for (i = 0; i < streamlist->maxstreams; ++i) {
streamlist->streams[i] = 0;
}
return streamlist;
}
int jpc_streamlist_insert(jpc_streamlist_t *streamlist, int streamno,
jas_stream_t *stream)
{
jas_stream_t **newstreams;
int newmaxstreams;
int i;
/* Grow the array of streams if necessary. */
if (streamlist->numstreams >= streamlist->maxstreams) {
newmaxstreams = streamlist->maxstreams + 1024;
if (!(newstreams = jas_realloc2(streamlist->streams,
(newmaxstreams + 1024), sizeof(jas_stream_t *)))) {
return -1;
}
for (i = streamlist->numstreams; i < streamlist->maxstreams; ++i) {
streamlist->streams[i] = 0;
}
streamlist->maxstreams = newmaxstreams;
streamlist->streams = newstreams;
}
if (streamno != streamlist->numstreams) {
/* Can only handle insertion at start of list. */
return -1;
}
streamlist->streams[streamno] = stream;
++streamlist->numstreams;
return 0;
}
jas_stream_t *jpc_streamlist_remove(jpc_streamlist_t *streamlist, int streamno)
{
jas_stream_t *stream;
int i;
if (streamno >= streamlist->numstreams) {
abort();
}
stream = streamlist->streams[streamno];
for (i = streamno + 1; i < streamlist->numstreams; ++i) {
streamlist->streams[i - 1] = streamlist->streams[i];
}
--streamlist->numstreams;
return stream;
}
void jpc_streamlist_destroy(jpc_streamlist_t *streamlist)
{
int streamno;
if (streamlist->streams) {
for (streamno = 0; streamno < streamlist->numstreams;
++streamno) {
jas_stream_close(streamlist->streams[streamno]);
}
jas_free(streamlist->streams);
}
jas_free(streamlist);
}
jas_stream_t *jpc_streamlist_get(jpc_streamlist_t *streamlist, int streamno)
{
assert(streamno < streamlist->numstreams);
return streamlist->streams[streamno];
}
int jpc_streamlist_numstreams(jpc_streamlist_t *streamlist)
{
return streamlist->numstreams;
}
jpc_ppxstab_t *jpc_ppxstab_create()
{
jpc_ppxstab_t *tab;
if (!(tab = jas_malloc(sizeof(jpc_ppxstab_t)))) {
return 0;
}
tab->numents = 0;
tab->maxents = 0;
tab->ents = 0;
return tab;
}
void jpc_ppxstab_destroy(jpc_ppxstab_t *tab)
{
int i;
for (i = 0; i < tab->numents; ++i) {
jpc_ppxstabent_destroy(tab->ents[i]);
}
if (tab->ents) {
jas_free(tab->ents);
}
jas_free(tab);
}
int jpc_ppxstab_grow(jpc_ppxstab_t *tab, int maxents)
{
jpc_ppxstabent_t **newents;
if (tab->maxents < maxents) {
newents = (tab->ents) ? jas_realloc2(tab->ents, maxents,
sizeof(jpc_ppxstabent_t *)) : jas_alloc2(maxents, sizeof(jpc_ppxstabent_t *));
if (!newents) {
return -1;
}
tab->ents = newents;
tab->maxents = maxents;
}
return 0;
}
int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent)
{
int inspt;
int i;
for (i = 0; i < tab->numents; ++i) {
if (tab->ents[i]->ind > ent->ind) {
break;
}
}
inspt = i;
if (tab->numents >= tab->maxents) {
if (jpc_ppxstab_grow(tab, tab->maxents + 128)) {
return -1;
}
}
for (i = tab->numents; i > inspt; --i) {
tab->ents[i] = tab->ents[i - 1];
}
tab->ents[i] = ent;
++tab->numents;
return 0;
}
jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab)
{
jpc_streamlist_t *streams;
uchar *dataptr;
uint_fast32_t datacnt;
uint_fast32_t tpcnt;
jpc_ppxstabent_t *ent;
int entno;
jas_stream_t *stream;
int n;
if (!(streams = jpc_streamlist_create())) {
goto error;
}
if (!tab->numents) {
return streams;
}
entno = 0;
ent = tab->ents[entno];
dataptr = ent->data;
datacnt = ent->len;
for (;;) {
/* Get the length of the packet header data for the current
tile-part. */
if (datacnt < 4) {
goto error;
}
if (!(stream = jas_stream_memopen(0, 0))) {
goto error;
}
if (jpc_streamlist_insert(streams, jpc_streamlist_numstreams(streams),
stream)) {
goto error;
}
tpcnt = (dataptr[0] << 24) | (dataptr[1] << 16) | (dataptr[2] << 8)
| dataptr[3];
datacnt -= 4;
dataptr += 4;
/* Get the packet header data for the current tile-part. */
while (tpcnt) {
if (!datacnt) {
if (++entno >= tab->numents) {
goto error;
}
ent = tab->ents[entno];
dataptr = ent->data;
datacnt = ent->len;
}
n = JAS_MIN(tpcnt, datacnt);
if (jas_stream_write(stream, dataptr, n) != n) {
goto error;
}
tpcnt -= n;
dataptr += n;
datacnt -= n;
}
jas_stream_rewind(stream);
if (!datacnt) {
if (++entno >= tab->numents) {
break;
}
ent = tab->ents[entno];
dataptr = ent->data;
datacnt = ent->len;
}
}
return streams;
error:
if (streams) {
jpc_streamlist_destroy(streams);
}
return 0;
}
int jpc_pptstabwrite(jas_stream_t *out, jpc_ppxstab_t *tab)
{
int i;
jpc_ppxstabent_t *ent;
for (i = 0; i < tab->numents; ++i) {
ent = tab->ents[i];
if (jas_stream_write(out, ent->data, ent->len) != JAS_CAST(int, ent->len)) {
return -1;
}
}
return 0;
}
jpc_ppxstabent_t *jpc_ppxstabent_create()
{
jpc_ppxstabent_t *ent;
if (!(ent = jas_malloc(sizeof(jpc_ppxstabent_t)))) {
return 0;
}
ent->data = 0;
ent->len = 0;
ent->ind = 0;
return ent;
}
void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent)
{
if (ent->data) {
jas_free(ent->data);
}
jas_free(ent);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5415_1 |
crossvul-cpp_data_good_2253_1 | /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* Monkey HTTP Server
* ==================
* Copyright 2001-2014 Monkey Software LLC <eduardo@monkey.io>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <time.h>
#include <netdb.h>
#include <sys/wait.h>
#include <signal.h>
#include <ctype.h>
#include <errno.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <fcntl.h>
#include <monkey/monkey.h>
#include <monkey/mk_request.h>
#include <monkey/mk_http.h>
#include <monkey/mk_http_status.h>
#include <monkey/mk_string.h>
#include <monkey/mk_config.h>
#include <monkey/mk_scheduler.h>
#include <monkey/mk_epoll.h>
#include <monkey/mk_utils.h>
#include <monkey/mk_header.h>
#include <monkey/mk_user.h>
#include <monkey/mk_method.h>
#include <monkey/mk_memory.h>
#include <monkey/mk_socket.h>
#include <monkey/mk_cache.h>
#include <monkey/mk_clock.h>
#include <monkey/mk_plugin.h>
#include <monkey/mk_macros.h>
#include <monkey/mk_vhost.h>
#include <monkey/mk_server.h>
const mk_ptr_t mk_crlf = mk_ptr_init(MK_CRLF);
const mk_ptr_t mk_endblock = mk_ptr_init(MK_ENDBLOCK);
const mk_ptr_t mk_rh_accept = mk_ptr_init(RH_ACCEPT);
const mk_ptr_t mk_rh_accept_charset = mk_ptr_init(RH_ACCEPT_CHARSET);
const mk_ptr_t mk_rh_accept_encoding = mk_ptr_init(RH_ACCEPT_ENCODING);
const mk_ptr_t mk_rh_accept_language = mk_ptr_init(RH_ACCEPT_LANGUAGE);
const mk_ptr_t mk_rh_connection = mk_ptr_init(RH_CONNECTION);
const mk_ptr_t mk_rh_cookie = mk_ptr_init(RH_COOKIE);
const mk_ptr_t mk_rh_content_length = mk_ptr_init(RH_CONTENT_LENGTH);
const mk_ptr_t mk_rh_content_range = mk_ptr_init(RH_CONTENT_RANGE);
const mk_ptr_t mk_rh_content_type = mk_ptr_init(RH_CONTENT_TYPE);
const mk_ptr_t mk_rh_if_modified_since = mk_ptr_init(RH_IF_MODIFIED_SINCE);
const mk_ptr_t mk_rh_host = mk_ptr_init(RH_HOST);
const mk_ptr_t mk_rh_last_modified = mk_ptr_init(RH_LAST_MODIFIED);
const mk_ptr_t mk_rh_last_modified_since = mk_ptr_init(RH_LAST_MODIFIED_SINCE);
const mk_ptr_t mk_rh_referer = mk_ptr_init(RH_REFERER);
const mk_ptr_t mk_rh_range = mk_ptr_init(RH_RANGE);
const mk_ptr_t mk_rh_user_agent = mk_ptr_init(RH_USER_AGENT);
pthread_key_t request_list;
/* Create a memory allocation in order to handle the request data */
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);
}
void mk_request_free(struct session_request *sr)
{
if (sr->fd_file > 0) {
if (sr->fd_is_fdt == MK_TRUE) {
mk_vhost_close(sr);
}
else {
close(sr->fd_file);
}
}
if (sr->headers.location) {
mk_mem_free(sr->headers.location);
}
if (sr->uri_processed.data != sr->uri.data) {
mk_ptr_free(&sr->uri_processed);
}
if (sr->real_path.data != sr->real_path_static) {
mk_ptr_free(&sr->real_path);
}
}
int mk_request_header_toc_parse(struct headers_toc *toc, const char *data, int len)
{
int i = 0;
int header_len;
int colon;
char *q;
char *p = (char *) data;
char *l = p;
toc->length = 0;
for (i = 0; l < (data + len) && p && i < MK_HEADERS_TOC_LEN; i++) {
if (*p == '\r') goto out;
/* Locate the colon character and the end of the line by CRLF */
colon = -1;
for (q = p; *q != 0x0D; ++q) {
if (*q == ':' && colon == -1) {
colon = (q - p);
}
}
/* it must be a LF after CR */
if (*(q + 1) != 0x0A) {
return -1;
}
/*
* Check if we reach the last header, take in count the first one can
* be also the last.
*/
if (data + len == (q - 1) && colon == -1) {
break;
}
/*
* By this version we force that after the colon must exists a white
* space before the value field
*/
if (*(p + colon + 1) != 0x20) {
return -1;
}
/* Each header key must have a value */
header_len = q - p - colon - 2;
if (header_len == 0) {
return -1;
}
/* Register the entry */
toc->rows[i].init = p;
toc->rows[i].end = q;
toc->rows[i].status = 0;
p = (q + mk_crlf.len);
l = p;
toc->length++;
}
out:
return toc->length;
}
/* Return a struct with method, URI , protocol version
and all static headers defined here sent in request */
static int mk_request_header_process(struct session_request *sr)
{
int uri_init = 0, uri_end = 0;
int query_init = 0;
int prot_init = 0, prot_end = 0, pos_sep = 0;
int fh_limit;
char *headers;
char *temp = 0;
mk_ptr_t host;
/* Method */
sr->method_p = mk_http_method_check_str(sr->method);
/* Request URI */
temp = index(sr->body.data, ' ');
if (mk_unlikely(!temp)) {
MK_TRACE("Error, invalid first header");
return -1;
}
uri_init = (temp - sr->body.data) + 1;
temp = index(sr->body.data, '\n');
if (mk_unlikely(!temp)) {
MK_TRACE("Error, invalid header CRLF");
return -1;
}
fh_limit = (temp - sr->body.data);
uri_end = mk_string_char_search_r(sr->body.data, ' ', fh_limit) - 1;
if (mk_unlikely(uri_end <= 0)) {
MK_TRACE("Error, first header bad formed");
return -1;
}
prot_init = uri_end + 2;
if (mk_unlikely(uri_end < uri_init)) {
return -1;
}
/* Query String */
query_init = mk_string_char_search(sr->body.data + uri_init, '?', prot_init - uri_init);
if (query_init > 0) {
int init, end;
init = query_init + uri_init;
if (init <= uri_end) {
end = uri_end;
uri_end = init - 1;
sr->query_string = mk_ptr_create(sr->body.data,
init + 1, end + 1);
}
}
/* Request URI Part 2 */
sr->uri = mk_ptr_create(sr->body.data, uri_init, uri_end + 1);
if (mk_unlikely(sr->uri.len < 1)) {
return -1;
}
/* HTTP Version */
prot_end = fh_limit - 1;
if (mk_unlikely(prot_init == prot_end)) {
return -1;
}
if (prot_end != prot_init && prot_end > 0) {
sr->protocol = mk_http_protocol_check(sr->body.data + prot_init,
prot_end - prot_init);
sr->protocol_p = mk_http_protocol_check_str(sr->protocol);
}
headers = sr->body.data + prot_end + mk_crlf.len;
/*
* Process URI, if it contains ASCII encoded strings like '%20',
* it will return a new memory buffer with the decoded string, otherwise
* it returns NULL
*/
temp = mk_utils_url_decode(sr->uri);
if (temp) {
sr->uri_processed.data = temp;
sr->uri_processed.len = strlen(temp);
}
else {
sr->uri_processed.data = sr->uri.data;
sr->uri_processed.len = sr->uri.len;
}
/* Creating Table of Content (index) for HTTP headers */
sr->headers_len = sr->body.len - (prot_end + mk_crlf.len);
if (mk_request_header_toc_parse(&sr->headers_toc, headers, sr->headers_len) < 0) {
MK_TRACE("Invalid headers");
return -1;
}
/* Host */
host = mk_request_header_get(&sr->headers_toc,
mk_rh_host.data,
mk_rh_host.len);
if (host.data) {
if ((pos_sep = mk_string_char_search_r(host.data, ':', host.len)) >= 0) {
/* TCP port should not be higher than 65535 */
char *p;
short int port_len, port_size = 6;
char port[port_size];
/* just the host */
sr->host.data = host.data;
sr->host.len = pos_sep;
/* including the port */
sr->host_port = host;
/* Port string length */
port_len = (host.len - pos_sep - 1);
if (port_len >= port_size) {
return -1;
}
/* Copy to buffer */
memcpy(port, host.data + pos_sep + 1, port_len);
port[port_len] = '\0';
/* Validate that the input port is numeric */
p = port;
while (*p) {
if (!isdigit(*p)) return -1;
p++;
}
/* Convert to base 10 */
errno = 0;
sr->port = strtol(port, (char **) NULL, 10);
if ((errno == ERANGE && (sr->port == LONG_MAX || sr->port == LONG_MIN))
|| sr->port == 0) {
return -1;
}
}
else {
sr->host = host; /* maybe null */
sr->port = config->standard_port;
}
}
else {
sr->host.data = NULL;
}
/* Looking for headers that ONLY Monkey uses */
sr->connection = mk_request_header_get(&sr->headers_toc,
mk_rh_connection.data,
mk_rh_connection.len);
sr->range = mk_request_header_get(&sr->headers_toc,
mk_rh_range.data,
mk_rh_range.len);
sr->if_modified_since = mk_request_header_get(&sr->headers_toc,
mk_rh_if_modified_since.data,
mk_rh_if_modified_since.len);
/* Default Keepalive is off */
if (sr->protocol == MK_HTTP_PROTOCOL_10) {
sr->keep_alive = MK_FALSE;
sr->close_now = MK_TRUE;
}
else if(sr->protocol == MK_HTTP_PROTOCOL_11) {
sr->keep_alive = MK_TRUE;
sr->close_now = MK_FALSE;
}
if (sr->connection.data) {
if (mk_string_search_n(sr->connection.data, "Keep-Alive",
MK_STR_INSENSITIVE, sr->connection.len) >= 0) {
sr->keep_alive = MK_TRUE;
sr->close_now = MK_FALSE;
}
else if (mk_string_search_n(sr->connection.data, "Close",
MK_STR_INSENSITIVE, sr->connection.len) >= 0) {
sr->keep_alive = MK_FALSE;
sr->close_now = MK_TRUE;
}
else {
/* Set as a non-valid connection header value */
sr->connection.len = 0;
}
}
return 0;
}
static int mk_request_parse(struct client_session *cs)
{
int i, end;
int blocks = 0;
struct session_request *sr_node;
struct mk_list *sr_list, *sr_head;
for (i = 0; i <= cs->body_pos_end; i++) {
/*
* Pipelining can just exists in a persistent connection or
* well known as KeepAlive, so if we are in keepalive mode
* we should check if we have multiple request in our body buffer
*/
end = mk_string_search(cs->body + i, mk_endblock.data, MK_STR_SENSITIVE) + i;
if (end < 0) {
return -1;
}
/* Allocating request block */
if (blocks == 0) {
sr_node = &cs->sr_fixed;
memset(sr_node, '\0', sizeof(struct session_request));
}
else {
sr_node = mk_mem_malloc_z(sizeof(struct session_request));
}
mk_request_init(sr_node);
/* We point the block with a mk_ptr_t */
sr_node->body.data = cs->body + i;
sr_node->body.len = end - i;
/* Method, previous catch in mk_http_pending_request */
if (i == 0) {
sr_node->method = cs->first_method;
}
else {
sr_node->method = mk_http_method_get(sr_node->body.data);
}
/* Looking for POST data */
if (sr_node->method == MK_HTTP_METHOD_POST) {
int offset;
offset = end + mk_endblock.len;
sr_node->data = mk_method_get_data(cs->body + offset,
cs->body_length - offset);
}
/* Increase index to the end of the current block */
i = (end + mk_endblock.len) - 1;
/* Link block */
mk_list_add(&sr_node->_head, &cs->request_list);
/* Update counter */
blocks++;
}
/* DEBUG BLOCKS
struct mk_list *head;
struct session_request *entry;
printf("\n*******************\n");
mk_list_foreach(head, &cs->request_list) {
entry = mk_list_entry(head, struct session_request, _head);
mk_ptr_print(entry->body);
fflush(stdout);
}
*/
/* Checking pipelining connection */
if (blocks > 1) {
sr_list = &cs->request_list;
mk_list_foreach(sr_head, sr_list) {
sr_node = mk_list_entry(sr_head, struct session_request, _head);
/* Pipelining request must use GET or HEAD methods */
if (sr_node->method != MK_HTTP_METHOD_GET &&
sr_node->method != MK_HTTP_METHOD_HEAD) {
return -1;
}
}
cs->pipelined = MK_TRUE;
}
#ifdef TRACE
int b = 0;
if (cs->pipelined == MK_TRUE) {
MK_TRACE("[FD %i] Pipeline Requests: %i blocks", cs->socket, blocks);
sr_list = &cs->request_list;
mk_list_foreach(sr_head, sr_list) {
sr_node = mk_list_entry(sr_head, struct session_request, _head);
MK_TRACE("[FD %i] Pipeline Block #%i: %p", cs->socket, b, sr_node);
b++;
}
}
#endif
return 0;
}
/* This function allow the core to invoke the closing connection process
* when some connection was not proceesed due to a premature close or similar
* exception, it also take care of invoke the STAGE_40 and STAGE_50 plugins events
*/
static void mk_request_premature_close(int http_status, struct client_session *cs)
{
struct session_request *sr;
struct mk_list *sr_list = &cs->request_list;
struct mk_list *host_list = &config->hosts;
/*
* If the connection is too premature, we need to allocate a temporal session_request
* to do not break the plugins stages
*/
if (mk_list_is_empty(sr_list) == 0) {
sr = &cs->sr_fixed;
memset(sr, 0, sizeof(struct session_request));
mk_request_init(sr);
mk_list_add(&sr->_head, &cs->request_list);
}
else {
sr = mk_list_entry_first(sr_list, struct session_request, _head);
}
/* Raise error */
if (http_status > 0) {
if (!sr->host_conf) {
sr->host_conf = mk_list_entry_first(host_list, struct host, _head);
}
mk_request_error(http_status, cs, sr);
/* STAGE_40, request has ended */
mk_plugin_stage_run(MK_PLUGIN_STAGE_40, cs->socket,
NULL, cs, sr);
}
/* STAGE_50, connection closed and remove client_session*/
mk_plugin_stage_run(MK_PLUGIN_STAGE_50, cs->socket, NULL, NULL, NULL);
mk_session_remove(cs->socket);
}
static int mk_request_process(struct client_session *cs, struct session_request *sr)
{
int status = 0;
int socket = cs->socket;
struct mk_list *hosts = &config->hosts;
struct mk_list *alias;
/* Always assign the first node 'default vhost' */
sr->host_conf = mk_list_entry_first(hosts, struct host, _head);
/* Parse request */
status = mk_request_header_process(sr);
if (status < 0) {
mk_header_set_http_status(sr, MK_CLIENT_BAD_REQUEST);
mk_request_error(MK_CLIENT_BAD_REQUEST, cs, sr);
return EXIT_ABORT;
}
sr->user_home = MK_FALSE;
/* Valid request URI? */
if (sr->uri_processed.data[0] != '/') {
mk_request_error(MK_CLIENT_BAD_REQUEST, cs, sr);
return EXIT_NORMAL;
}
/* HTTP/1.1 needs Host header */
if (!sr->host.data && sr->protocol == MK_HTTP_PROTOCOL_11) {
mk_request_error(MK_CLIENT_BAD_REQUEST, cs, sr);
return EXIT_NORMAL;
}
/* Validating protocol version */
if (sr->protocol == MK_HTTP_PROTOCOL_UNKNOWN) {
mk_request_error(MK_SERVER_HTTP_VERSION_UNSUP, cs, sr);
return EXIT_ABORT;
}
/* Assign the first node alias */
alias = &sr->host_conf->server_names;
sr->host_alias = mk_list_entry_first(alias,
struct host_alias, _head);
if (sr->host.data) {
/* Match the virtual host */
mk_vhost_get(sr->host, &sr->host_conf, &sr->host_alias);
/* Check if this virtual host have some redirection */
if (sr->host_conf->header_redirect.data) {
mk_header_set_http_status(sr, MK_REDIR_MOVED);
sr->headers.location = mk_string_dup(sr->host_conf->header_redirect.data);
sr->headers.content_length = 0;
mk_header_send(cs->socket, cs, sr);
sr->headers.location = NULL;
mk_server_cork_flag(cs->socket, TCP_CORK_OFF);
return 0;
}
}
/* Is requesting an user home directory ? */
if (config->user_dir &&
sr->uri_processed.len > 2 &&
sr->uri_processed.data[1] == MK_USER_HOME) {
if (mk_user_init(cs, sr) != 0) {
mk_request_error(MK_CLIENT_NOT_FOUND, cs, sr);
return EXIT_ABORT;
}
}
/* Handling method requested */
if (sr->method == MK_HTTP_METHOD_POST || sr->method == MK_HTTP_METHOD_PUT) {
if ((status = mk_method_parse_data(cs, sr)) != 0) {
return status;
}
}
/* Plugins Stage 20 */
int ret;
ret = mk_plugin_stage_run(MK_PLUGIN_STAGE_20, socket, NULL, cs, sr);
if (ret == MK_PLUGIN_RET_CLOSE_CONX) {
MK_TRACE("STAGE 20 requested close conexion");
return EXIT_ABORT;
}
/* Normal HTTP process */
status = mk_http_init(cs, sr);
MK_TRACE("[FD %i] HTTP Init returning %i", socket, status);
return status;
}
/* Build error page */
static mk_ptr_t *mk_request_set_default_page(char *title, mk_ptr_t message,
char *signature)
{
char *temp;
mk_ptr_t *p;
p = mk_mem_malloc(sizeof(mk_ptr_t));
p->data = NULL;
temp = mk_ptr_to_buf(message);
mk_string_build(&p->data, &p->len,
MK_REQUEST_DEFAULT_PAGE, title, temp, signature);
mk_mem_free(temp);
return p;
}
int mk_handler_read(int socket, struct client_session *cs)
{
int bytes;
int max_read;
int available = 0;
int new_size;
int total_bytes = 0;
char *tmp = 0;
MK_TRACE("MAX REQUEST SIZE: %i", config->max_request_size);
try_pending:
available = cs->body_size - cs->body_length;
if (available <= 0) {
/* Reallocate buffer size if pending data does not have space */
new_size = cs->body_size + config->transport_buffer_size;
if (new_size > config->max_request_size) {
MK_TRACE("Requested size is > config->max_request_size");
mk_request_premature_close(MK_CLIENT_REQUEST_ENTITY_TOO_LARGE, cs);
return -1;
}
/*
* Check if the body field still points to the initial body_fixed, if so,
* allow the new space required in body, otherwise perform a realloc over
* body.
*/
if (cs->body == cs->body_fixed) {
cs->body = mk_mem_malloc(new_size + 1);
cs->body_size = new_size;
memcpy(cs->body, cs->body_fixed, cs->body_length);
MK_TRACE("[FD %i] New size: %i, length: %i",
cs->socket, new_size, cs->body_length);
}
else {
MK_TRACE("[FD %i] Realloc from %i to %i",
cs->socket, cs->body_size, new_size);
tmp = mk_mem_realloc(cs->body, new_size + 1);
if (tmp) {
cs->body = tmp;
cs->body_size = new_size;
}
else {
mk_request_premature_close(MK_SERVER_INTERNAL_ERROR, cs);
return -1;
}
}
}
/* Read content */
max_read = (cs->body_size - cs->body_length);
bytes = mk_socket_read(socket, cs->body + cs->body_length, max_read);
MK_TRACE("[FD %i] read %i", socket, bytes);
if (bytes < 0) {
if (errno == EAGAIN) {
return 1;
}
else {
mk_session_remove(socket);
return -1;
}
}
if (bytes == 0) {
mk_session_remove(socket);
return -1;
}
if (bytes > 0) {
if (bytes > max_read) {
MK_TRACE("[FD %i] Buffer still have data: %i",
cs->socket, bytes - max_read);
cs->body_length += max_read;
cs->body[cs->body_length] = '\0';
total_bytes += max_read;
goto try_pending;
}
else {
cs->body_length += bytes;
cs->body[cs->body_length] = '\0';
total_bytes += bytes;
}
MK_TRACE("[FD %i] Retry total bytes: %i",
cs->socket, total_bytes);
return total_bytes;
}
return bytes;
}
int mk_handler_write(int socket, struct client_session *cs)
{
int final_status = 0;
struct session_request *sr_node;
struct mk_list *sr_list;
if (mk_list_is_empty(&cs->request_list) == 0) {
if (mk_request_parse(cs) != 0) {
return -1;
}
}
sr_list = &cs->request_list;
sr_node = mk_list_entry_first(sr_list, struct session_request, _head);
if (sr_node->bytes_to_send > 0) {
/* Request with data to send by static file sender */
final_status = mk_http_send_file(cs, sr_node);
}
else if (sr_node->bytes_to_send < 0) {
final_status = mk_request_process(cs, sr_node);
}
/*
* If we got an error, we don't want to parse
* and send information for another pipelined request
*/
if (final_status > 0) {
return final_status;
}
else {
/* STAGE_40, request has ended */
mk_plugin_stage_run(MK_PLUGIN_STAGE_40, socket,
NULL, cs, sr_node);
switch (final_status) {
case EXIT_NORMAL:
case EXIT_ERROR:
if (sr_node->close_now == MK_TRUE) {
return -1;
}
break;
case EXIT_ABORT:
return -1;
}
}
/*
* If we are here, is because all pipelined request were
* processed successfully, let's return 0
*/
return 0;
}
/* Look for some index.xxx in pathfile */
mk_ptr_t mk_request_index(char *pathfile, char *file_aux, const unsigned int flen)
{
unsigned long len;
mk_ptr_t f;
struct mk_string_line *entry;
struct mk_list *head;
mk_ptr_reset(&f);
if (!config->index_files) return f;
mk_list_foreach(head, config->index_files) {
entry = mk_list_entry(head, struct mk_string_line, _head);
len = snprintf(file_aux, flen, "%s%s", pathfile, entry->val);
if (mk_unlikely(len > flen)) {
len = flen - 1;
mk_warn("Path too long, truncated! '%s'", file_aux);
}
if (access(file_aux, F_OK) == 0) {
f.data = file_aux;
f.len = len;
return f;
}
}
return f;
}
/* Send error responses */
int mk_request_error(int http_status, struct client_session *cs,
struct session_request *sr) {
int ret, fd;
mk_ptr_t message, *page = 0;
struct error_page *entry;
struct mk_list *head;
struct file_info finfo;
mk_header_set_http_status(sr, http_status);
/*
* We are nice sending error pages for clients who at least respect
* the especification
*/
if (http_status != MK_CLIENT_LENGTH_REQUIRED &&
http_status != MK_CLIENT_BAD_REQUEST &&
http_status != MK_CLIENT_REQUEST_ENTITY_TOO_LARGE) {
/* Lookup a customized error page */
mk_list_foreach(head, &sr->host_conf->error_pages) {
entry = mk_list_entry(head, struct error_page, _head);
if (entry->status != http_status) {
continue;
}
/* validate error file */
ret = mk_file_get_info(entry->real_path, &finfo);
if (ret == -1) {
break;
}
/* open file */
fd = open(entry->real_path, config->open_flags);
if (fd == -1) {
break;
}
sr->fd_file = fd;
sr->fd_is_fdt = MK_FALSE;
sr->bytes_to_send = finfo.size;
sr->headers.content_length = finfo.size;
sr->headers.real_length = finfo.size;
memcpy(&sr->file_info, &finfo, sizeof(struct file_info));
mk_header_send(cs->socket, cs, sr);
return mk_http_send_file(cs, sr);
}
}
mk_ptr_reset(&message);
switch (http_status) {
case MK_CLIENT_BAD_REQUEST:
page = mk_request_set_default_page("Bad Request",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_FORBIDDEN:
page = mk_request_set_default_page("Forbidden",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_NOT_FOUND:
mk_string_build(&message.data, &message.len,
"The requested URL was not found on this server.");
page = mk_request_set_default_page("Not Found",
message,
sr->host_conf->host_signature);
mk_ptr_free(&message);
break;
case MK_CLIENT_REQUEST_ENTITY_TOO_LARGE:
mk_string_build(&message.data, &message.len,
"The request entity is too large.");
page = mk_request_set_default_page("Entity too large",
message,
sr->host_conf->host_signature);
mk_ptr_free(&message);
break;
case MK_CLIENT_METHOD_NOT_ALLOWED:
page = mk_request_set_default_page("Method Not Allowed",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_REQUEST_TIMEOUT:
case MK_CLIENT_LENGTH_REQUIRED:
break;
case MK_SERVER_NOT_IMPLEMENTED:
page = mk_request_set_default_page("Method Not Implemented",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_SERVER_INTERNAL_ERROR:
page = mk_request_set_default_page("Internal Server Error",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_SERVER_HTTP_VERSION_UNSUP:
mk_ptr_reset(&message);
page = mk_request_set_default_page("HTTP Version Not Supported",
message,
sr->host_conf->host_signature);
break;
}
if (page) {
sr->headers.content_length = page->len;
}
sr->headers.location = NULL;
sr->headers.cgi = SH_NOCGI;
sr->headers.pconnections_left = 0;
sr->headers.last_modified = -1;
if (!page) {
mk_ptr_reset(&sr->headers.content_type);
}
else {
mk_ptr_set(&sr->headers.content_type, "text/html\r\n");
}
mk_header_send(cs->socket, cs, sr);
if (page) {
if (sr->method != MK_HTTP_METHOD_HEAD)
mk_socket_send(cs->socket, page->data, page->len);
mk_ptr_free(page);
mk_mem_free(page);
}
/* Turn off TCP_CORK */
mk_server_cork_flag(cs->socket, TCP_CORK_OFF);
return EXIT_ERROR;
}
void mk_request_free_list(struct client_session *cs)
{
struct session_request *sr_node;
struct mk_list *sr_head, *temp;
/* sr = last node */
MK_TRACE("[FD %i] Free struct client_session", cs->socket);
mk_list_foreach_safe(sr_head, temp, &cs->request_list) {
sr_node = mk_list_entry(sr_head, struct session_request, _head);
mk_list_del(sr_head);
mk_request_free(sr_node);
if (sr_node != &cs->sr_fixed) {
mk_mem_free(sr_node);
}
}
}
/* Create a client request struct and put it on the
* main list
*/
struct client_session *mk_session_create(int socket, struct sched_list_node *sched)
{
struct client_session *cs;
struct sched_connection *sc;
sc = mk_sched_get_connection(sched, socket);
if (!sc) {
MK_TRACE("[FD %i] No sched node, could not create session", socket);
return NULL;
}
/* Alloc memory for node */
cs = mk_mem_malloc(sizeof(struct client_session));
cs->pipelined = MK_FALSE;
cs->counter_connections = 0;
cs->socket = socket;
cs->status = MK_REQUEST_STATUS_INCOMPLETE;
mk_list_add(&cs->request_incomplete, cs_incomplete);
/* creation time in unix time */
cs->init_time = sc->arrive_time;
/* alloc space for body content */
if (config->transport_buffer_size > MK_REQUEST_CHUNK) {
cs->body = mk_mem_malloc(config->transport_buffer_size);
cs->body_size = config->transport_buffer_size;
}
else {
/* Buffer size based in Chunk bytes */
cs->body = cs->body_fixed;
cs->body_size = MK_REQUEST_CHUNK;
}
/* Current data length */
cs->body_length = 0;
cs->body_pos_end = -1;
cs->first_method = MK_HTTP_METHOD_UNKNOWN;
/* Init session request list */
mk_list_init(&cs->request_list);
/* Add this SESSION to the thread list */
/* Add node to list */
/* Red-Black tree insert routine */
struct rb_node **new = &(cs_list->rb_node);
struct rb_node *parent = NULL;
/* Figure out where to put new node */
while (*new) {
struct client_session *this = container_of(*new, struct client_session, _rb_head);
parent = *new;
if (cs->socket < this->socket)
new = &((*new)->rb_left);
else if (cs->socket > this->socket)
new = &((*new)->rb_right);
else {
break;
}
}
/* Add new node and rebalance tree. */
rb_link_node(&cs->_rb_head, parent, new);
rb_insert_color(&cs->_rb_head, cs_list);
return cs;
}
struct client_session *mk_session_get(int socket)
{
struct client_session *cs;
struct rb_node *node;
node = cs_list->rb_node;
while (node) {
cs = container_of(node, struct client_session, _rb_head);
if (socket < cs->socket)
node = node->rb_left;
else if (socket > cs->socket)
node = node->rb_right;
else {
return cs;
}
}
return NULL;
}
/*
* From thread sched_list_node "list", remove the client_session
* struct information
*/
void mk_session_remove(int socket)
{
struct client_session *cs_node;
cs_node = mk_session_get(socket);
if (cs_node) {
rb_erase(&cs_node->_rb_head, cs_list);
if (cs_node->body != cs_node->body_fixed) {
mk_mem_free(cs_node->body);
}
if (mk_list_entry_orphan(&cs_node->request_incomplete) == 0) {
mk_list_del(&cs_node->request_incomplete);
}
mk_list_del(&cs_node->request_list);
mk_mem_free(cs_node);
}
}
/* Return value of some variable sent in request */
mk_ptr_t mk_request_header_get(struct headers_toc *toc, const char *key_name, int key_len)
{
int i;
struct header_toc_row *row;
mk_ptr_t var;
var.data = NULL;
var.len = 0;
row = toc->rows;
for (i = 0; i < toc->length; i++) {
/*
* status = 1 means that the toc entry was already
* checked by Monkey
*/
if (row[i].status == 1) {
continue;
}
if (strncasecmp(row[i].init, key_name, key_len) == 0) {
var.data = row[i].init + key_len + 1;
var.len = row[i].end - var.data;
row[i].status = 1;
break;
}
}
return var;
}
void mk_request_ka_next(struct client_session *cs)
{
cs->first_method = -1;
cs->body_pos_end = -1;
cs->body_length = 0;
cs->counter_connections++;
/* Update data for scheduler */
cs->init_time = log_current_utime;
cs->status = MK_REQUEST_STATUS_INCOMPLETE;
mk_list_add(&cs->request_incomplete, cs_incomplete);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2253_1 |
crossvul-cpp_data_good_3987_1 | #include "clar_libgit2.h"
#include "checkout_helpers.h"
#include "git2/checkout.h"
#include "repository.h"
#include "buffer.h"
#include "futils.h"
static const char *repo_name = "nasty";
static git_repository *repo;
static git_checkout_options checkout_opts;
void test_checkout_nasty__initialize(void)
{
repo = cl_git_sandbox_init(repo_name);
GIT_INIT_STRUCTURE(&checkout_opts, GIT_CHECKOUT_OPTIONS_VERSION);
checkout_opts.checkout_strategy = GIT_CHECKOUT_FORCE;
}
void test_checkout_nasty__cleanup(void)
{
cl_git_sandbox_cleanup();
}
static void test_checkout_passes(const char *refname, const char *filename)
{
git_oid commit_id;
git_commit *commit;
git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
git_buf path = GIT_BUF_INIT;
cl_git_pass(git_buf_joinpath(&path, repo_name, filename));
cl_git_pass(git_reference_name_to_id(&commit_id, repo, refname));
cl_git_pass(git_commit_lookup(&commit, repo, &commit_id));
opts.checkout_strategy = GIT_CHECKOUT_FORCE |
GIT_CHECKOUT_DONT_UPDATE_INDEX;
cl_git_pass(git_checkout_tree(repo, (const git_object *)commit, &opts));
cl_assert(!git_path_exists(path.ptr));
git_commit_free(commit);
git_buf_dispose(&path);
}
static void test_checkout_fails(const char *refname, const char *filename)
{
git_oid commit_id;
git_commit *commit;
git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
git_buf path = GIT_BUF_INIT;
cl_git_pass(git_buf_joinpath(&path, repo_name, filename));
cl_git_pass(git_reference_name_to_id(&commit_id, repo, refname));
cl_git_pass(git_commit_lookup(&commit, repo, &commit_id));
opts.checkout_strategy = GIT_CHECKOUT_FORCE;
cl_git_fail(git_checkout_tree(repo, (const git_object *)commit, &opts));
cl_assert(!git_path_exists(path.ptr));
git_commit_free(commit);
git_buf_dispose(&path);
}
/* A tree that contains ".git" as a tree, with a blob inside
* (".git/foobar").
*/
void test_checkout_nasty__dotgit_tree(void)
{
test_checkout_fails("refs/heads/dotgit_tree", ".git/foobar");
}
/* A tree that contains ".GIT" as a tree, with a blob inside
* (".GIT/foobar").
*/
void test_checkout_nasty__dotcapitalgit_tree(void)
{
test_checkout_fails("refs/heads/dotcapitalgit_tree", ".GIT/foobar");
}
/* A tree that contains a tree ".", with a blob inside ("./foobar").
*/
void test_checkout_nasty__dot_tree(void)
{
test_checkout_fails("refs/heads/dot_tree", "foobar");
}
/* A tree that contains a tree ".", with a tree ".git", with a blob
* inside ("./.git/foobar").
*/
void test_checkout_nasty__dot_dotgit_tree(void)
{
test_checkout_fails("refs/heads/dot_dotgit_tree", ".git/foobar");
}
/* A tree that contains a tree, with a tree "..", with a tree ".git", with a
* blob inside ("foo/../.git/foobar").
*/
void test_checkout_nasty__dotdot_dotgit_tree(void)
{
test_checkout_fails("refs/heads/dotdot_dotgit_tree", ".git/foobar");
}
/* A tree that contains a tree, with a tree "..", with a blob inside
* ("foo/../foobar").
*/
void test_checkout_nasty__dotdot_tree(void)
{
test_checkout_fails("refs/heads/dotdot_tree", "foobar");
}
/* A tree that contains a blob with the rogue name ".git/foobar" */
void test_checkout_nasty__dotgit_path(void)
{
test_checkout_fails("refs/heads/dotgit_path", ".git/foobar");
}
/* A tree that contains a blob with the rogue name ".GIT/foobar" */
void test_checkout_nasty__dotcapitalgit_path(void)
{
test_checkout_fails("refs/heads/dotcapitalgit_path", ".GIT/foobar");
}
/* A tree that contains a blob with the rogue name "./.git/foobar" */
void test_checkout_nasty__dot_dotgit_path(void)
{
test_checkout_fails("refs/heads/dot_dotgit_path", ".git/foobar");
}
/* A tree that contains a blob with the rogue name "./.GIT/foobar" */
void test_checkout_nasty__dot_dotcapitalgit_path(void)
{
test_checkout_fails("refs/heads/dot_dotcapitalgit_path", ".GIT/foobar");
}
/* A tree that contains a blob with the rogue name "foo/../.git/foobar" */
void test_checkout_nasty__dotdot_dotgit_path(void)
{
test_checkout_fails("refs/heads/dotdot_dotgit_path", ".git/foobar");
}
/* A tree that contains a blob with the rogue name "foo/../.GIT/foobar" */
void test_checkout_nasty__dotdot_dotcapitalgit_path(void)
{
test_checkout_fails("refs/heads/dotdot_dotcapitalgit_path", ".GIT/foobar");
}
/* A tree that contains a blob with the rogue name "foo/." */
void test_checkout_nasty__dot_path(void)
{
test_checkout_fails("refs/heads/dot_path", "./foobar");
}
/* A tree that contains a blob with the rogue name "foo/." */
void test_checkout_nasty__dot_path_two(void)
{
test_checkout_fails("refs/heads/dot_path_two", "foo/.");
}
/* A tree that contains a blob with the rogue name "foo/../foobar" */
void test_checkout_nasty__dotdot_path(void)
{
test_checkout_fails("refs/heads/dotdot_path", "foobar");
}
/* A tree that contains an entry with a backslash ".git\foobar" */
void test_checkout_nasty__dotgit_backslash_path(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dotgit_backslash_path", ".git/foobar");
#endif
}
/* A tree that contains an entry with a backslash ".GIT\foobar" */
void test_checkout_nasty__dotcapitalgit_backslash_path(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dotcapitalgit_backslash_path", ".GIT/foobar");
#endif
}
/* A tree that contains an entry with a backslash ".\.GIT\foobar" */
void test_checkout_nasty__dot_backslash_dotcapitalgit_path(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dot_backslash_dotcapitalgit_path", ".GIT/foobar");
#endif
}
/* A tree that contains an entry ".git.", because Win32 APIs will drop the
* trailing slash.
*/
void test_checkout_nasty__dot_git_dot(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dot_git_dot", ".git/foobar");
#endif
}
/* A tree that contains an entry "git~1", because that is typically the
* short name for ".git".
*/
void test_checkout_nasty__git_tilde1(void)
{
test_checkout_fails("refs/heads/git_tilde1", ".git/foobar");
test_checkout_fails("refs/heads/git_tilde1", "git~1/foobar");
}
/* A tree that contains an entry "git~2", when we have forced the short
* name for ".git" into "GIT~2".
*/
void test_checkout_nasty__git_custom_shortname(void)
{
#ifdef GIT_WIN32
if (!cl_sandbox_supports_8dot3())
clar__skip();
cl_must_pass(p_rename("nasty/.git", "nasty/_temp"));
cl_git_write2file("nasty/git~1", "", 0, O_RDWR|O_CREAT, 0666);
cl_must_pass(p_rename("nasty/_temp", "nasty/.git"));
test_checkout_fails("refs/heads/git_tilde2", ".git/foobar");
#endif
}
/* A tree that contains an entry "git~3", which should be allowed, since
* it is not the typical short name ("GIT~1") or the actual short name
* ("GIT~2") for ".git".
*/
void test_checkout_nasty__only_looks_like_a_git_shortname(void)
{
#ifdef GIT_WIN32
git_oid commit_id;
git_commit *commit;
git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
cl_must_pass(p_rename("nasty/.git", "nasty/_temp"));
cl_git_write2file("nasty/git~1", "", 0, O_RDWR|O_CREAT, 0666);
cl_must_pass(p_rename("nasty/_temp", "nasty/.git"));
cl_git_pass(git_reference_name_to_id(&commit_id, repo, "refs/heads/git_tilde3"));
cl_git_pass(git_commit_lookup(&commit, repo, &commit_id));
opts.checkout_strategy = GIT_CHECKOUT_FORCE;
cl_git_pass(git_checkout_tree(repo, (const git_object *)commit, &opts));
cl_assert(git_path_exists("nasty/git~3/foobar"));
git_commit_free(commit);
#endif
}
/* A tree that contains an entry "git:", because Win32 APIs will reject
* that as looking too similar to a drive letter.
*/
void test_checkout_nasty__dot_git_colon(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dot_git_colon", ".git/foobar");
#endif
}
/* A tree that contains an entry "git:foo", because Win32 APIs will turn
* that into ".git".
*/
void test_checkout_nasty__dot_git_colon_stuff(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dot_git_colon_stuff", ".git/foobar");
#endif
}
/* A tree that contains an entry ".git::$INDEX_ALLOCATION" because NTFS
* will interpret that as a synonym to ".git", even when mounted via SMB
* on macOS.
*/
void test_checkout_nasty__dotgit_alternate_data_stream(void)
{
test_checkout_fails("refs/heads/dotgit_alternate_data_stream", ".git/dummy-file");
test_checkout_fails("refs/heads/dotgit_alternate_data_stream", ".git::$INDEX_ALLOCATION/dummy-file");
}
/* Trees that contains entries with a tree ".git" that contain
* byte sequences:
* { 0xe2, 0x80, 0x8c }
* { 0xe2, 0x80, 0x8d }
* { 0xe2, 0x80, 0x8e }
* { 0xe2, 0x80, 0x8f }
* { 0xe2, 0x80, 0xaa }
* { 0xe2, 0x80, 0xab }
* { 0xe2, 0x80, 0xac }
* { 0xe2, 0x80, 0xad }
* { 0xe2, 0x81, 0xae }
* { 0xe2, 0x81, 0xaa }
* { 0xe2, 0x81, 0xab }
* { 0xe2, 0x81, 0xac }
* { 0xe2, 0x81, 0xad }
* { 0xe2, 0x81, 0xae }
* { 0xe2, 0x81, 0xaf }
* { 0xef, 0xbb, 0xbf }
* Because these map to characters that HFS filesystems "ignore". Thus
* ".git<U+200C>" will map to ".git".
*/
void test_checkout_nasty__dot_git_hfs_ignorable(void)
{
#ifdef __APPLE__
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_1", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_2", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_3", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_4", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_5", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_6", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_7", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_8", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_9", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_10", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_11", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_12", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_13", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_14", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_15", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_16", ".git/foobar");
#endif
}
void test_checkout_nasty__honors_core_protecthfs(void)
{
cl_repo_set_bool(repo, "core.protectHFS", true);
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_1", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_2", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_3", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_4", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_5", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_6", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_7", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_8", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_9", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_10", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_11", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_12", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_13", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_14", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_15", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_16", ".git/foobar");
}
void test_checkout_nasty__honors_core_protectntfs(void)
{
cl_repo_set_bool(repo, "core.protectNTFS", true);
test_checkout_fails("refs/heads/dotgit_backslash_path", ".git/foobar");
test_checkout_fails("refs/heads/dotcapitalgit_backslash_path", ".GIT/foobar");
test_checkout_fails("refs/heads/dot_git_dot", ".git/foobar");
test_checkout_fails("refs/heads/git_tilde1", ".git/foobar");
}
void test_checkout_nasty__symlink1(void)
{
test_checkout_passes("refs/heads/symlink1", ".git/foobar");
}
void test_checkout_nasty__symlink2(void)
{
test_checkout_passes("refs/heads/symlink2", ".git/foobar");
}
void test_checkout_nasty__symlink3(void)
{
test_checkout_passes("refs/heads/symlink3", ".git/foobar");
}
void test_checkout_nasty__gitmodules_symlink(void)
{
cl_repo_set_bool(repo, "core.protectHFS", true);
test_checkout_fails("refs/heads/gitmodules-symlink", ".gitmodules");
cl_repo_set_bool(repo, "core.protectHFS", false);
cl_repo_set_bool(repo, "core.protectNTFS", true);
test_checkout_fails("refs/heads/gitmodules-symlink", ".gitmodules");
cl_repo_set_bool(repo, "core.protectNTFS", false);
test_checkout_fails("refs/heads/gitmodules-symlink", ".gitmodules");
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3987_1 |
crossvul-cpp_data_good_3019_0 | /*
* linux/mm/mlock.c
*
* (C) Copyright 1995 Linus Torvalds
* (C) Copyright 2002 Christoph Hellwig
*/
#include <linux/capability.h>
#include <linux/mman.h>
#include <linux/mm.h>
#include <linux/sched/user.h>
#include <linux/swap.h>
#include <linux/swapops.h>
#include <linux/pagemap.h>
#include <linux/pagevec.h>
#include <linux/mempolicy.h>
#include <linux/syscalls.h>
#include <linux/sched.h>
#include <linux/export.h>
#include <linux/rmap.h>
#include <linux/mmzone.h>
#include <linux/hugetlb.h>
#include <linux/memcontrol.h>
#include <linux/mm_inline.h>
#include "internal.h"
bool can_do_mlock(void)
{
if (rlimit(RLIMIT_MEMLOCK) != 0)
return true;
if (capable(CAP_IPC_LOCK))
return true;
return false;
}
EXPORT_SYMBOL(can_do_mlock);
/*
* Mlocked pages are marked with PageMlocked() flag for efficient testing
* in vmscan and, possibly, the fault path; and to support semi-accurate
* statistics.
*
* An mlocked page [PageMlocked(page)] is unevictable. As such, it will
* be placed on the LRU "unevictable" list, rather than the [in]active lists.
* The unevictable list is an LRU sibling list to the [in]active lists.
* PageUnevictable is set to indicate the unevictable state.
*
* When lazy mlocking via vmscan, it is important to ensure that the
* vma's VM_LOCKED status is not concurrently being modified, otherwise we
* may have mlocked a page that is being munlocked. So lazy mlock must take
* the mmap_sem for read, and verify that the vma really is locked
* (see mm/rmap.c).
*/
/*
* LRU accounting for clear_page_mlock()
*/
void clear_page_mlock(struct page *page)
{
if (!TestClearPageMlocked(page))
return;
mod_zone_page_state(page_zone(page), NR_MLOCK,
-hpage_nr_pages(page));
count_vm_event(UNEVICTABLE_PGCLEARED);
if (!isolate_lru_page(page)) {
putback_lru_page(page);
} else {
/*
* We lost the race. the page already moved to evictable list.
*/
if (PageUnevictable(page))
count_vm_event(UNEVICTABLE_PGSTRANDED);
}
}
/*
* Mark page as mlocked if not already.
* If page on LRU, isolate and putback to move to unevictable list.
*/
void mlock_vma_page(struct page *page)
{
/* Serialize with page migration */
BUG_ON(!PageLocked(page));
VM_BUG_ON_PAGE(PageTail(page), page);
VM_BUG_ON_PAGE(PageCompound(page) && PageDoubleMap(page), page);
if (!TestSetPageMlocked(page)) {
mod_zone_page_state(page_zone(page), NR_MLOCK,
hpage_nr_pages(page));
count_vm_event(UNEVICTABLE_PGMLOCKED);
if (!isolate_lru_page(page))
putback_lru_page(page);
}
}
/*
* Isolate a page from LRU with optional get_page() pin.
* Assumes lru_lock already held and page already pinned.
*/
static bool __munlock_isolate_lru_page(struct page *page, bool getpage)
{
if (PageLRU(page)) {
struct lruvec *lruvec;
lruvec = mem_cgroup_page_lruvec(page, page_pgdat(page));
if (getpage)
get_page(page);
ClearPageLRU(page);
del_page_from_lru_list(page, lruvec, page_lru(page));
return true;
}
return false;
}
/*
* Finish munlock after successful page isolation
*
* Page must be locked. This is a wrapper for try_to_munlock()
* and putback_lru_page() with munlock accounting.
*/
static void __munlock_isolated_page(struct page *page)
{
/*
* Optimization: if the page was mapped just once, that's our mapping
* and we don't need to check all the other vmas.
*/
if (page_mapcount(page) > 1)
try_to_munlock(page);
/* Did try_to_unlock() succeed or punt? */
if (!PageMlocked(page))
count_vm_event(UNEVICTABLE_PGMUNLOCKED);
putback_lru_page(page);
}
/*
* Accounting for page isolation fail during munlock
*
* Performs accounting when page isolation fails in munlock. There is nothing
* else to do because it means some other task has already removed the page
* from the LRU. putback_lru_page() will take care of removing the page from
* the unevictable list, if necessary. vmscan [page_referenced()] will move
* the page back to the unevictable list if some other vma has it mlocked.
*/
static void __munlock_isolation_failed(struct page *page)
{
if (PageUnevictable(page))
__count_vm_event(UNEVICTABLE_PGSTRANDED);
else
__count_vm_event(UNEVICTABLE_PGMUNLOCKED);
}
/**
* munlock_vma_page - munlock a vma page
* @page - page to be unlocked, either a normal page or THP page head
*
* returns the size of the page as a page mask (0 for normal page,
* HPAGE_PMD_NR - 1 for THP head page)
*
* called from munlock()/munmap() path with page supposedly on the LRU.
* When we munlock a page, because the vma where we found the page is being
* munlock()ed or munmap()ed, we want to check whether other vmas hold the
* page locked so that we can leave it on the unevictable lru list and not
* bother vmscan with it. However, to walk the page's rmap list in
* try_to_munlock() we must isolate the page from the LRU. If some other
* task has removed the page from the LRU, we won't be able to do that.
* So we clear the PageMlocked as we might not get another chance. If we
* can't isolate the page, we leave it for putback_lru_page() and vmscan
* [page_referenced()/try_to_unmap()] to deal with.
*/
unsigned int munlock_vma_page(struct page *page)
{
int nr_pages;
struct zone *zone = page_zone(page);
/* For try_to_munlock() and to serialize with page migration */
BUG_ON(!PageLocked(page));
VM_BUG_ON_PAGE(PageTail(page), page);
/*
* Serialize with any parallel __split_huge_page_refcount() which
* might otherwise copy PageMlocked to part of the tail pages before
* we clear it in the head page. It also stabilizes hpage_nr_pages().
*/
spin_lock_irq(zone_lru_lock(zone));
if (!TestClearPageMlocked(page)) {
/* Potentially, PTE-mapped THP: do not skip the rest PTEs */
nr_pages = 1;
goto unlock_out;
}
nr_pages = hpage_nr_pages(page);
__mod_zone_page_state(zone, NR_MLOCK, -nr_pages);
if (__munlock_isolate_lru_page(page, true)) {
spin_unlock_irq(zone_lru_lock(zone));
__munlock_isolated_page(page);
goto out;
}
__munlock_isolation_failed(page);
unlock_out:
spin_unlock_irq(zone_lru_lock(zone));
out:
return nr_pages - 1;
}
/*
* convert get_user_pages() return value to posix mlock() error
*/
static int __mlock_posix_error_return(long retval)
{
if (retval == -EFAULT)
retval = -ENOMEM;
else if (retval == -ENOMEM)
retval = -EAGAIN;
return retval;
}
/*
* Prepare page for fast batched LRU putback via putback_lru_evictable_pagevec()
*
* The fast path is available only for evictable pages with single mapping.
* Then we can bypass the per-cpu pvec and get better performance.
* when mapcount > 1 we need try_to_munlock() which can fail.
* when !page_evictable(), we need the full redo logic of putback_lru_page to
* avoid leaving evictable page in unevictable list.
*
* In case of success, @page is added to @pvec and @pgrescued is incremented
* in case that the page was previously unevictable. @page is also unlocked.
*/
static bool __putback_lru_fast_prepare(struct page *page, struct pagevec *pvec,
int *pgrescued)
{
VM_BUG_ON_PAGE(PageLRU(page), page);
VM_BUG_ON_PAGE(!PageLocked(page), page);
if (page_mapcount(page) <= 1 && page_evictable(page)) {
pagevec_add(pvec, page);
if (TestClearPageUnevictable(page))
(*pgrescued)++;
unlock_page(page);
return true;
}
return false;
}
/*
* Putback multiple evictable pages to the LRU
*
* Batched putback of evictable pages that bypasses the per-cpu pvec. Some of
* the pages might have meanwhile become unevictable but that is OK.
*/
static void __putback_lru_fast(struct pagevec *pvec, int pgrescued)
{
count_vm_events(UNEVICTABLE_PGMUNLOCKED, pagevec_count(pvec));
/*
*__pagevec_lru_add() calls release_pages() so we don't call
* put_page() explicitly
*/
__pagevec_lru_add(pvec);
count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
}
/*
* Munlock a batch of pages from the same zone
*
* The work is split to two main phases. First phase clears the Mlocked flag
* and attempts to isolate the pages, all under a single zone lru lock.
* The second phase finishes the munlock only for pages where isolation
* succeeded.
*
* Note that the pagevec may be modified during the process.
*/
static void __munlock_pagevec(struct pagevec *pvec, struct zone *zone)
{
int i;
int nr = pagevec_count(pvec);
int delta_munlocked = -nr;
struct pagevec pvec_putback;
int pgrescued = 0;
pagevec_init(&pvec_putback, 0);
/* Phase 1: page isolation */
spin_lock_irq(zone_lru_lock(zone));
for (i = 0; i < nr; i++) {
struct page *page = pvec->pages[i];
if (TestClearPageMlocked(page)) {
/*
* We already have pin from follow_page_mask()
* so we can spare the get_page() here.
*/
if (__munlock_isolate_lru_page(page, false))
continue;
else
__munlock_isolation_failed(page);
} else {
delta_munlocked++;
}
/*
* We won't be munlocking this page in the next phase
* but we still need to release the follow_page_mask()
* pin. We cannot do it under lru_lock however. If it's
* the last pin, __page_cache_release() would deadlock.
*/
pagevec_add(&pvec_putback, pvec->pages[i]);
pvec->pages[i] = NULL;
}
__mod_zone_page_state(zone, NR_MLOCK, delta_munlocked);
spin_unlock_irq(zone_lru_lock(zone));
/* Now we can release pins of pages that we are not munlocking */
pagevec_release(&pvec_putback);
/* Phase 2: page munlock */
for (i = 0; i < nr; i++) {
struct page *page = pvec->pages[i];
if (page) {
lock_page(page);
if (!__putback_lru_fast_prepare(page, &pvec_putback,
&pgrescued)) {
/*
* Slow path. We don't want to lose the last
* pin before unlock_page()
*/
get_page(page); /* for putback_lru_page() */
__munlock_isolated_page(page);
unlock_page(page);
put_page(page); /* from follow_page_mask() */
}
}
}
/*
* Phase 3: page putback for pages that qualified for the fast path
* This will also call put_page() to return pin from follow_page_mask()
*/
if (pagevec_count(&pvec_putback))
__putback_lru_fast(&pvec_putback, pgrescued);
}
/*
* Fill up pagevec for __munlock_pagevec using pte walk
*
* The function expects that the struct page corresponding to @start address is
* a non-TPH page already pinned and in the @pvec, and that it belongs to @zone.
*
* The rest of @pvec is filled by subsequent pages within the same pmd and same
* zone, as long as the pte's are present and vm_normal_page() succeeds. These
* pages also get pinned.
*
* Returns the address of the next page that should be scanned. This equals
* @start + PAGE_SIZE when no page could be added by the pte walk.
*/
static unsigned long __munlock_pagevec_fill(struct pagevec *pvec,
struct vm_area_struct *vma, int zoneid, unsigned long start,
unsigned long end)
{
pte_t *pte;
spinlock_t *ptl;
/*
* Initialize pte walk starting at the already pinned page where we
* are sure that there is a pte, as it was pinned under the same
* mmap_sem write op.
*/
pte = get_locked_pte(vma->vm_mm, start, &ptl);
/* Make sure we do not cross the page table boundary */
end = pgd_addr_end(start, end);
end = p4d_addr_end(start, end);
end = pud_addr_end(start, end);
end = pmd_addr_end(start, end);
/* The page next to the pinned page is the first we will try to get */
start += PAGE_SIZE;
while (start < end) {
struct page *page = NULL;
pte++;
if (pte_present(*pte))
page = vm_normal_page(vma, start, *pte);
/*
* Break if page could not be obtained or the page's node+zone does not
* match
*/
if (!page || page_zone_id(page) != zoneid)
break;
/*
* Do not use pagevec for PTE-mapped THP,
* munlock_vma_pages_range() will handle them.
*/
if (PageTransCompound(page))
break;
get_page(page);
/*
* Increase the address that will be returned *before* the
* eventual break due to pvec becoming full by adding the page
*/
start += PAGE_SIZE;
if (pagevec_add(pvec, page) == 0)
break;
}
pte_unmap_unlock(pte, ptl);
return start;
}
/*
* munlock_vma_pages_range() - munlock all pages in the vma range.'
* @vma - vma containing range to be munlock()ed.
* @start - start address in @vma of the range
* @end - end of range in @vma.
*
* For mremap(), munmap() and exit().
*
* Called with @vma VM_LOCKED.
*
* Returns with VM_LOCKED cleared. Callers must be prepared to
* deal with this.
*
* We don't save and restore VM_LOCKED here because pages are
* still on lru. In unmap path, pages might be scanned by reclaim
* and re-mlocked by try_to_{munlock|unmap} before we unmap and
* free them. This will result in freeing mlocked pages.
*/
void munlock_vma_pages_range(struct vm_area_struct *vma,
unsigned long start, unsigned long end)
{
vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
while (start < end) {
struct page *page;
unsigned int page_mask = 0;
unsigned long page_increm;
struct pagevec pvec;
struct zone *zone;
int zoneid;
pagevec_init(&pvec, 0);
/*
* Although FOLL_DUMP is intended for get_dump_page(),
* it just so happens that its special treatment of the
* ZERO_PAGE (returning an error instead of doing get_page)
* suits munlock very well (and if somehow an abnormal page
* has sneaked into the range, we won't oops here: great).
*/
page = follow_page(vma, start, FOLL_GET | FOLL_DUMP);
if (page && !IS_ERR(page)) {
if (PageTransTail(page)) {
VM_BUG_ON_PAGE(PageMlocked(page), page);
put_page(page); /* follow_page_mask() */
} else if (PageTransHuge(page)) {
lock_page(page);
/*
* Any THP page found by follow_page_mask() may
* have gotten split before reaching
* munlock_vma_page(), so we need to compute
* the page_mask here instead.
*/
page_mask = munlock_vma_page(page);
unlock_page(page);
put_page(page); /* follow_page_mask() */
} else {
/*
* Non-huge pages are handled in batches via
* pagevec. The pin from follow_page_mask()
* prevents them from collapsing by THP.
*/
pagevec_add(&pvec, page);
zone = page_zone(page);
zoneid = page_zone_id(page);
/*
* Try to fill the rest of pagevec using fast
* pte walk. This will also update start to
* the next page to process. Then munlock the
* pagevec.
*/
start = __munlock_pagevec_fill(&pvec, vma,
zoneid, start, end);
__munlock_pagevec(&pvec, zone);
goto next;
}
}
page_increm = 1 + page_mask;
start += page_increm * PAGE_SIZE;
next:
cond_resched();
}
}
/*
* mlock_fixup - handle mlock[all]/munlock[all] requests.
*
* Filters out "special" vmas -- VM_LOCKED never gets set for these, and
* munlock is a no-op. However, for some special vmas, we go ahead and
* populate the ptes.
*
* For vmas that pass the filters, merge/split as appropriate.
*/
static int mlock_fixup(struct vm_area_struct *vma, struct vm_area_struct **prev,
unsigned long start, unsigned long end, vm_flags_t newflags)
{
struct mm_struct *mm = vma->vm_mm;
pgoff_t pgoff;
int nr_pages;
int ret = 0;
int lock = !!(newflags & VM_LOCKED);
vm_flags_t old_flags = vma->vm_flags;
if (newflags == vma->vm_flags || (vma->vm_flags & VM_SPECIAL) ||
is_vm_hugetlb_page(vma) || vma == get_gate_vma(current->mm))
/* don't set VM_LOCKED or VM_LOCKONFAULT and don't count */
goto out;
pgoff = vma->vm_pgoff + ((start - vma->vm_start) >> PAGE_SHIFT);
*prev = vma_merge(mm, *prev, start, end, newflags, vma->anon_vma,
vma->vm_file, pgoff, vma_policy(vma),
vma->vm_userfaultfd_ctx);
if (*prev) {
vma = *prev;
goto success;
}
if (start != vma->vm_start) {
ret = split_vma(mm, vma, start, 1);
if (ret)
goto out;
}
if (end != vma->vm_end) {
ret = split_vma(mm, vma, end, 0);
if (ret)
goto out;
}
success:
/*
* Keep track of amount of locked VM.
*/
nr_pages = (end - start) >> PAGE_SHIFT;
if (!lock)
nr_pages = -nr_pages;
else if (old_flags & VM_LOCKED)
nr_pages = 0;
mm->locked_vm += nr_pages;
/*
* vm_flags is protected by the mmap_sem held in write mode.
* It's okay if try_to_unmap_one unmaps a page just after we
* set VM_LOCKED, populate_vma_page_range will bring it back.
*/
if (lock)
vma->vm_flags = newflags;
else
munlock_vma_pages_range(vma, start, end);
out:
*prev = vma;
return ret;
}
static int apply_vma_lock_flags(unsigned long start, size_t len,
vm_flags_t flags)
{
unsigned long nstart, end, tmp;
struct vm_area_struct * vma, * prev;
int error;
VM_BUG_ON(offset_in_page(start));
VM_BUG_ON(len != PAGE_ALIGN(len));
end = start + len;
if (end < start)
return -EINVAL;
if (end == start)
return 0;
vma = find_vma(current->mm, start);
if (!vma || vma->vm_start > start)
return -ENOMEM;
prev = vma->vm_prev;
if (start > vma->vm_start)
prev = vma;
for (nstart = start ; ; ) {
vm_flags_t newflags = vma->vm_flags & VM_LOCKED_CLEAR_MASK;
newflags |= flags;
/* Here we know that vma->vm_start <= nstart < vma->vm_end. */
tmp = vma->vm_end;
if (tmp > end)
tmp = end;
error = mlock_fixup(vma, &prev, nstart, tmp, newflags);
if (error)
break;
nstart = tmp;
if (nstart < prev->vm_end)
nstart = prev->vm_end;
if (nstart >= end)
break;
vma = prev->vm_next;
if (!vma || vma->vm_start != nstart) {
error = -ENOMEM;
break;
}
}
return error;
}
/*
* Go through vma areas and sum size of mlocked
* vma pages, as return value.
* Note deferred memory locking case(mlock2(,,MLOCK_ONFAULT)
* is also counted.
* Return value: previously mlocked page counts
*/
static int count_mm_mlocked_page_nr(struct mm_struct *mm,
unsigned long start, size_t len)
{
struct vm_area_struct *vma;
int count = 0;
if (mm == NULL)
mm = current->mm;
vma = find_vma(mm, start);
if (vma == NULL)
vma = mm->mmap;
for (; vma ; vma = vma->vm_next) {
if (start >= vma->vm_end)
continue;
if (start + len <= vma->vm_start)
break;
if (vma->vm_flags & VM_LOCKED) {
if (start > vma->vm_start)
count -= (start - vma->vm_start);
if (start + len < vma->vm_end) {
count += start + len - vma->vm_start;
break;
}
count += vma->vm_end - vma->vm_start;
}
}
return count >> PAGE_SHIFT;
}
static __must_check int do_mlock(unsigned long start, size_t len, vm_flags_t flags)
{
unsigned long locked;
unsigned long lock_limit;
int error = -ENOMEM;
if (!can_do_mlock())
return -EPERM;
lru_add_drain_all(); /* flush pagevec */
len = PAGE_ALIGN(len + (offset_in_page(start)));
start &= PAGE_MASK;
lock_limit = rlimit(RLIMIT_MEMLOCK);
lock_limit >>= PAGE_SHIFT;
locked = len >> PAGE_SHIFT;
if (down_write_killable(¤t->mm->mmap_sem))
return -EINTR;
locked += current->mm->locked_vm;
if ((locked > lock_limit) && (!capable(CAP_IPC_LOCK))) {
/*
* It is possible that the regions requested intersect with
* previously mlocked areas, that part area in "mm->locked_vm"
* should not be counted to new mlock increment count. So check
* and adjust locked count if necessary.
*/
locked -= count_mm_mlocked_page_nr(current->mm,
start, len);
}
/* check against resource limits */
if ((locked <= lock_limit) || capable(CAP_IPC_LOCK))
error = apply_vma_lock_flags(start, len, flags);
up_write(¤t->mm->mmap_sem);
if (error)
return error;
error = __mm_populate(start, len, 0);
if (error)
return __mlock_posix_error_return(error);
return 0;
}
SYSCALL_DEFINE2(mlock, unsigned long, start, size_t, len)
{
return do_mlock(start, len, VM_LOCKED);
}
SYSCALL_DEFINE3(mlock2, unsigned long, start, size_t, len, int, flags)
{
vm_flags_t vm_flags = VM_LOCKED;
if (flags & ~MLOCK_ONFAULT)
return -EINVAL;
if (flags & MLOCK_ONFAULT)
vm_flags |= VM_LOCKONFAULT;
return do_mlock(start, len, vm_flags);
}
SYSCALL_DEFINE2(munlock, unsigned long, start, size_t, len)
{
int ret;
len = PAGE_ALIGN(len + (offset_in_page(start)));
start &= PAGE_MASK;
if (down_write_killable(¤t->mm->mmap_sem))
return -EINTR;
ret = apply_vma_lock_flags(start, len, 0);
up_write(¤t->mm->mmap_sem);
return ret;
}
/*
* Take the MCL_* flags passed into mlockall (or 0 if called from munlockall)
* and translate into the appropriate modifications to mm->def_flags and/or the
* flags for all current VMAs.
*
* There are a couple of subtleties with this. If mlockall() is called multiple
* times with different flags, the values do not necessarily stack. If mlockall
* is called once including the MCL_FUTURE flag and then a second time without
* it, VM_LOCKED and VM_LOCKONFAULT will be cleared from mm->def_flags.
*/
static int apply_mlockall_flags(int flags)
{
struct vm_area_struct * vma, * prev = NULL;
vm_flags_t to_add = 0;
current->mm->def_flags &= VM_LOCKED_CLEAR_MASK;
if (flags & MCL_FUTURE) {
current->mm->def_flags |= VM_LOCKED;
if (flags & MCL_ONFAULT)
current->mm->def_flags |= VM_LOCKONFAULT;
if (!(flags & MCL_CURRENT))
goto out;
}
if (flags & MCL_CURRENT) {
to_add |= VM_LOCKED;
if (flags & MCL_ONFAULT)
to_add |= VM_LOCKONFAULT;
}
for (vma = current->mm->mmap; vma ; vma = prev->vm_next) {
vm_flags_t newflags;
newflags = vma->vm_flags & VM_LOCKED_CLEAR_MASK;
newflags |= to_add;
/* Ignore errors */
mlock_fixup(vma, &prev, vma->vm_start, vma->vm_end, newflags);
cond_resched_rcu_qs();
}
out:
return 0;
}
SYSCALL_DEFINE1(mlockall, int, flags)
{
unsigned long lock_limit;
int ret;
if (!flags || (flags & ~(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT)))
return -EINVAL;
if (!can_do_mlock())
return -EPERM;
if (flags & MCL_CURRENT)
lru_add_drain_all(); /* flush pagevec */
lock_limit = rlimit(RLIMIT_MEMLOCK);
lock_limit >>= PAGE_SHIFT;
if (down_write_killable(¤t->mm->mmap_sem))
return -EINTR;
ret = -ENOMEM;
if (!(flags & MCL_CURRENT) || (current->mm->total_vm <= lock_limit) ||
capable(CAP_IPC_LOCK))
ret = apply_mlockall_flags(flags);
up_write(¤t->mm->mmap_sem);
if (!ret && (flags & MCL_CURRENT))
mm_populate(0, TASK_SIZE);
return ret;
}
SYSCALL_DEFINE0(munlockall)
{
int ret;
if (down_write_killable(¤t->mm->mmap_sem))
return -EINTR;
ret = apply_mlockall_flags(0);
up_write(¤t->mm->mmap_sem);
return ret;
}
/*
* Objects with different lifetime than processes (SHM_LOCK and SHM_HUGETLB
* shm segments) get accounted against the user_struct instead.
*/
static DEFINE_SPINLOCK(shmlock_user_lock);
int user_shm_lock(size_t size, struct user_struct *user)
{
unsigned long lock_limit, locked;
int allowed = 0;
locked = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
lock_limit = rlimit(RLIMIT_MEMLOCK);
if (lock_limit == RLIM_INFINITY)
allowed = 1;
lock_limit >>= PAGE_SHIFT;
spin_lock(&shmlock_user_lock);
if (!allowed &&
locked + user->locked_shm > lock_limit && !capable(CAP_IPC_LOCK))
goto out;
get_uid(user);
user->locked_shm += locked;
allowed = 1;
out:
spin_unlock(&shmlock_user_lock);
return allowed;
}
void user_shm_unlock(size_t size, struct user_struct *user)
{
spin_lock(&shmlock_user_lock);
user->locked_shm -= (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
spin_unlock(&shmlock_user_lock);
free_uid(user);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3019_0 |
crossvul-cpp_data_good_5183_0 | /* Crop support
* manual crop using a gdRect or automatic crop using a background
* color (automatic detections or using either the transparent color,
* black or white).
* An alternative method allows to crop using a given color and a
* threshold. It works relatively well but it can be improved.
* Maybe L*a*b* and Delta-E will give better results (and a better
* granularity).
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include "gd.h"
#include "gd_color.h"
static int gdGuessBackgroundColorFromCorners(gdImagePtr im, int *color);
BGD_DECLARE(gdImagePtr) gdImageCrop(gdImagePtr src, const gdRect *crop)
{
gdImagePtr dst;
dst = gdImageCreateTrueColor(crop->width, crop->height);
if (!dst) return NULL;
gdImageCopy(dst, src, 0, 0, crop->x, crop->y, crop->width, crop->height);
return dst;
}
BGD_DECLARE(gdImagePtr) gdImageCropAuto(gdImagePtr im, const unsigned int mode)
{
const int width = gdImageSX(im);
const int height = gdImageSY(im);
int x,y;
int color, match;
gdRect crop;
crop.x = 0;
crop.y = 0;
crop.width = 0;
crop.height = 0;
switch (mode) {
case GD_CROP_TRANSPARENT:
color = gdImageGetTransparent(im);
break;
case GD_CROP_BLACK:
color = gdImageColorClosestAlpha(im, 0, 0, 0, 0);
break;
case GD_CROP_WHITE:
color = gdImageColorClosestAlpha(im, 255, 255, 255, 0);
break;
case GD_CROP_SIDES:
gdGuessBackgroundColorFromCorners(im, &color);
break;
case GD_CROP_DEFAULT:
default:
color = gdImageGetTransparent(im);
break;
}
/* TODO: Add gdImageGetRowPtr and works with ptr at the row level
* for the true color and palette images
* new formats will simply work with ptr
*/
match = 1;
for (y = 0; match && y < height; y++) {
for (x = 0; match && x < width; x++) {
match = (color == gdImageGetPixel(im, x,y));
}
}
/* Nothing to do > bye
* Duplicate the image?
*/
if (y == height - 1) {
return NULL;
}
crop.y = y -1;
match = 1;
for (y = height - 1; match && y >= 0; y--) {
for (x = 0; match && x < width; x++) {
match = (color == gdImageGetPixel(im, x,y));
}
}
if (y == 0) {
crop.height = height - crop.y + 1;
} else {
crop.height = y - crop.y + 2;
}
match = 1;
for (x = 0; match && x < width; x++) {
for (y = 0; match && y < crop.y + crop.height - 1; y++) {
match = (color == gdImageGetPixel(im, x,y));
}
}
crop.x = x - 1;
match = 1;
for (x = width - 1; match && x >= 0; x--) {
for (y = 0; match && y < crop.y + crop.height - 1; y++) {
match = (color == gdImageGetPixel(im, x,y));
}
}
crop.width = x - crop.x + 2;
return gdImageCrop(im, &crop);
}
BGD_DECLARE(gdImagePtr) gdImageCropThreshold(gdImagePtr im, const unsigned int color, const float threshold)
{
const int width = gdImageSX(im);
const int height = gdImageSY(im);
int x,y;
int match;
gdRect crop;
crop.x = 0;
crop.y = 0;
crop.width = 0;
crop.height = 0;
/* Pierre: crop everything sounds bad */
if (threshold > 100.0) {
return NULL;
}
if (color < 0 || (!gdImageTrueColor(im) && color >= gdImageColorsTotal(im))) {
return NULL;
}
/* TODO: Add gdImageGetRowPtr and works with ptr at the row level
* for the true color and palette images
* new formats will simply work with ptr
*/
match = 1;
for (y = 0; match && y < height; y++) {
for (x = 0; match && x < width; x++) {
match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0;
}
}
/* Pierre
* Nothing to do > bye
* Duplicate the image?
*/
if (y == height - 1) {
return NULL;
}
crop.y = y -1;
match = 1;
for (y = height - 1; match && y >= 0; y--) {
for (x = 0; match && x < width; x++) {
match = (gdColorMatch(im, color, gdImageGetPixel(im, x, y), threshold)) > 0;
}
}
if (y == 0) {
crop.height = height - crop.y + 1;
} else {
crop.height = y - crop.y + 2;
}
match = 1;
for (x = 0; match && x < width; x++) {
for (y = 0; match && y < crop.y + crop.height - 1; y++) {
match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0;
}
}
crop.x = x - 1;
match = 1;
for (x = width - 1; match && x >= 0; x--) {
for (y = 0; match && y < crop.y + crop.height - 1; y++) {
match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0;
}
}
crop.width = x - crop.x + 2;
return gdImageCrop(im, &crop);
}
/* This algorithm comes from pnmcrop (http://netpbm.sourceforge.net/)
* Three steps:
* - if 3 corners are equal.
* - if two are equal.
* - Last solution: average the colors
*/
static int gdGuessBackgroundColorFromCorners(gdImagePtr im, int *color)
{
const int tl = gdImageGetPixel(im, 0, 0);
const int tr = gdImageGetPixel(im, gdImageSX(im) - 1, 0);
const int bl = gdImageGetPixel(im, 0, gdImageSY(im) -1);
const int br = gdImageGetPixel(im, gdImageSX(im) - 1, gdImageSY(im) -1);
if (tr == bl && tr == br) {
*color = tr;
return 3;
} else if (tl == bl && tl == br) {
*color = tl;
return 3;
} else if (tl == tr && tl == br) {
*color = tl;
return 3;
} else if (tl == tr && tl == bl) {
*color = tl;
return 3;
} else if (tl == tr || tl == bl || tl == br) {
*color = tl;
return 2;
} else if (tr == bl) {
*color = tr;
return 2;
} else if (br == bl) {
*color = bl;
return 2;
} else {
register int r,b,g,a;
r = (int)(0.5f + (gdImageRed(im, tl) + gdImageRed(im, tr) + gdImageRed(im, bl) + gdImageRed(im, br)) / 4);
g = (int)(0.5f + (gdImageGreen(im, tl) + gdImageGreen(im, tr) + gdImageGreen(im, bl) + gdImageGreen(im, br)) / 4);
b = (int)(0.5f + (gdImageBlue(im, tl) + gdImageBlue(im, tr) + gdImageBlue(im, bl) + gdImageBlue(im, br)) / 4);
a = (int)(0.5f + (gdImageAlpha(im, tl) + gdImageAlpha(im, tr) + gdImageAlpha(im, bl) + gdImageAlpha(im, br)) / 4);
*color = gdImageColorClosestAlpha(im, r, g, b, a);
return 0;
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5183_0 |
crossvul-cpp_data_good_5845_15 | /*
* Implements an IPX socket layer.
*
* This code is derived from work by
* Ross Biro : Writing the original IP stack
* Fred Van Kempen : Tidying up the TCP/IP
*
* Many thanks go to Keith Baker, Institute For Industrial Information
* Technology Ltd, Swansea University for allowing me to work on this
* in my own time even though it was in some ways related to commercial
* work I am currently employed to do there.
*
* All the material in this file is subject to the Gnu license version 2.
* Neither Alan Cox nor the Swansea University Computer Society admit
* liability nor provide warranty for any of this software. This material
* is provided as is and at no charge.
*
* Portions Copyright (c) 2000-2003 Conectiva, Inc. <acme@conectiva.com.br>
* Neither Arnaldo Carvalho de Melo nor Conectiva, Inc. admit liability nor
* provide warranty for any of this software. This material is provided
* "AS-IS" and at no charge.
*
* Portions Copyright (c) 1995 Caldera, Inc. <greg@caldera.com>
* Neither Greg Page nor Caldera, Inc. admit liability nor provide
* warranty for any of this software. This material is provided
* "AS-IS" and at no charge.
*
* See net/ipx/ChangeLog.
*/
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/if_arp.h>
#include <linux/if_ether.h>
#include <linux/init.h>
#include <linux/ipx.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/uio.h>
#include <linux/slab.h>
#include <linux/skbuff.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/termios.h>
#include <net/ipx.h>
#include <net/p8022.h>
#include <net/psnap.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <asm/uaccess.h>
#ifdef CONFIG_SYSCTL
extern void ipx_register_sysctl(void);
extern void ipx_unregister_sysctl(void);
#else
#define ipx_register_sysctl()
#define ipx_unregister_sysctl()
#endif
/* Configuration Variables */
static unsigned char ipxcfg_max_hops = 16;
static char ipxcfg_auto_select_primary;
static char ipxcfg_auto_create_interfaces;
int sysctl_ipx_pprop_broadcasting = 1;
/* Global Variables */
static struct datalink_proto *p8022_datalink;
static struct datalink_proto *pEII_datalink;
static struct datalink_proto *p8023_datalink;
static struct datalink_proto *pSNAP_datalink;
static const struct proto_ops ipx_dgram_ops;
LIST_HEAD(ipx_interfaces);
DEFINE_SPINLOCK(ipx_interfaces_lock);
struct ipx_interface *ipx_primary_net;
struct ipx_interface *ipx_internal_net;
extern int ipxrtr_add_route(__be32 network, struct ipx_interface *intrfc,
unsigned char *node);
extern void ipxrtr_del_routes(struct ipx_interface *intrfc);
extern int ipxrtr_route_packet(struct sock *sk, struct sockaddr_ipx *usipx,
struct iovec *iov, size_t len, int noblock);
extern int ipxrtr_route_skb(struct sk_buff *skb);
extern struct ipx_route *ipxrtr_lookup(__be32 net);
extern int ipxrtr_ioctl(unsigned int cmd, void __user *arg);
struct ipx_interface *ipx_interfaces_head(void)
{
struct ipx_interface *rc = NULL;
if (!list_empty(&ipx_interfaces))
rc = list_entry(ipx_interfaces.next,
struct ipx_interface, node);
return rc;
}
static void ipxcfg_set_auto_select(char val)
{
ipxcfg_auto_select_primary = val;
if (val && !ipx_primary_net)
ipx_primary_net = ipx_interfaces_head();
}
static int ipxcfg_get_config_data(struct ipx_config_data __user *arg)
{
struct ipx_config_data vals;
vals.ipxcfg_auto_create_interfaces = ipxcfg_auto_create_interfaces;
vals.ipxcfg_auto_select_primary = ipxcfg_auto_select_primary;
return copy_to_user(arg, &vals, sizeof(vals)) ? -EFAULT : 0;
}
/*
* Note: Sockets may not be removed _during_ an interrupt or inet_bh
* handler using this technique. They can be added although we do not
* use this facility.
*/
static void ipx_remove_socket(struct sock *sk)
{
/* Determine interface with which socket is associated */
struct ipx_interface *intrfc = ipx_sk(sk)->intrfc;
if (!intrfc)
goto out;
ipxitf_hold(intrfc);
spin_lock_bh(&intrfc->if_sklist_lock);
sk_del_node_init(sk);
spin_unlock_bh(&intrfc->if_sklist_lock);
ipxitf_put(intrfc);
out:
return;
}
static void ipx_destroy_socket(struct sock *sk)
{
ipx_remove_socket(sk);
skb_queue_purge(&sk->sk_receive_queue);
sk_refcnt_debug_dec(sk);
}
/*
* The following code is used to support IPX Interfaces (IPXITF). An
* IPX interface is defined by a physical device and a frame type.
*/
/* ipxitf_clear_primary_net has to be called with ipx_interfaces_lock held */
static void ipxitf_clear_primary_net(void)
{
ipx_primary_net = NULL;
if (ipxcfg_auto_select_primary)
ipx_primary_net = ipx_interfaces_head();
}
static struct ipx_interface *__ipxitf_find_using_phys(struct net_device *dev,
__be16 datalink)
{
struct ipx_interface *i;
list_for_each_entry(i, &ipx_interfaces, node)
if (i->if_dev == dev && i->if_dlink_type == datalink)
goto out;
i = NULL;
out:
return i;
}
static struct ipx_interface *ipxitf_find_using_phys(struct net_device *dev,
__be16 datalink)
{
struct ipx_interface *i;
spin_lock_bh(&ipx_interfaces_lock);
i = __ipxitf_find_using_phys(dev, datalink);
if (i)
ipxitf_hold(i);
spin_unlock_bh(&ipx_interfaces_lock);
return i;
}
struct ipx_interface *ipxitf_find_using_net(__be32 net)
{
struct ipx_interface *i;
spin_lock_bh(&ipx_interfaces_lock);
if (net) {
list_for_each_entry(i, &ipx_interfaces, node)
if (i->if_netnum == net)
goto hold;
i = NULL;
goto unlock;
}
i = ipx_primary_net;
if (i)
hold:
ipxitf_hold(i);
unlock:
spin_unlock_bh(&ipx_interfaces_lock);
return i;
}
/* Sockets are bound to a particular IPX interface. */
static void ipxitf_insert_socket(struct ipx_interface *intrfc, struct sock *sk)
{
ipxitf_hold(intrfc);
spin_lock_bh(&intrfc->if_sklist_lock);
ipx_sk(sk)->intrfc = intrfc;
sk_add_node(sk, &intrfc->if_sklist);
spin_unlock_bh(&intrfc->if_sklist_lock);
ipxitf_put(intrfc);
}
/* caller must hold intrfc->if_sklist_lock */
static struct sock *__ipxitf_find_socket(struct ipx_interface *intrfc,
__be16 port)
{
struct sock *s;
sk_for_each(s, &intrfc->if_sklist)
if (ipx_sk(s)->port == port)
goto found;
s = NULL;
found:
return s;
}
/* caller must hold a reference to intrfc */
static struct sock *ipxitf_find_socket(struct ipx_interface *intrfc,
__be16 port)
{
struct sock *s;
spin_lock_bh(&intrfc->if_sklist_lock);
s = __ipxitf_find_socket(intrfc, port);
if (s)
sock_hold(s);
spin_unlock_bh(&intrfc->if_sklist_lock);
return s;
}
#ifdef CONFIG_IPX_INTERN
static struct sock *ipxitf_find_internal_socket(struct ipx_interface *intrfc,
unsigned char *ipx_node,
__be16 port)
{
struct sock *s;
ipxitf_hold(intrfc);
spin_lock_bh(&intrfc->if_sklist_lock);
sk_for_each(s, &intrfc->if_sklist) {
struct ipx_sock *ipxs = ipx_sk(s);
if (ipxs->port == port &&
!memcmp(ipx_node, ipxs->node, IPX_NODE_LEN))
goto found;
}
s = NULL;
found:
spin_unlock_bh(&intrfc->if_sklist_lock);
ipxitf_put(intrfc);
return s;
}
#endif
static void __ipxitf_down(struct ipx_interface *intrfc)
{
struct sock *s;
struct hlist_node *t;
/* Delete all routes associated with this interface */
ipxrtr_del_routes(intrfc);
spin_lock_bh(&intrfc->if_sklist_lock);
/* error sockets */
sk_for_each_safe(s, t, &intrfc->if_sklist) {
struct ipx_sock *ipxs = ipx_sk(s);
s->sk_err = ENOLINK;
s->sk_error_report(s);
ipxs->intrfc = NULL;
ipxs->port = 0;
sock_set_flag(s, SOCK_ZAPPED); /* Indicates it is no longer bound */
sk_del_node_init(s);
}
INIT_HLIST_HEAD(&intrfc->if_sklist);
spin_unlock_bh(&intrfc->if_sklist_lock);
/* remove this interface from list */
list_del(&intrfc->node);
/* remove this interface from *special* networks */
if (intrfc == ipx_primary_net)
ipxitf_clear_primary_net();
if (intrfc == ipx_internal_net)
ipx_internal_net = NULL;
if (intrfc->if_dev)
dev_put(intrfc->if_dev);
kfree(intrfc);
}
void ipxitf_down(struct ipx_interface *intrfc)
{
spin_lock_bh(&ipx_interfaces_lock);
__ipxitf_down(intrfc);
spin_unlock_bh(&ipx_interfaces_lock);
}
static __inline__ void __ipxitf_put(struct ipx_interface *intrfc)
{
if (atomic_dec_and_test(&intrfc->refcnt))
__ipxitf_down(intrfc);
}
static int ipxitf_device_event(struct notifier_block *notifier,
unsigned long event, void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
struct ipx_interface *i, *tmp;
if (!net_eq(dev_net(dev), &init_net))
return NOTIFY_DONE;
if (event != NETDEV_DOWN && event != NETDEV_UP)
goto out;
spin_lock_bh(&ipx_interfaces_lock);
list_for_each_entry_safe(i, tmp, &ipx_interfaces, node)
if (i->if_dev == dev) {
if (event == NETDEV_UP)
ipxitf_hold(i);
else
__ipxitf_put(i);
}
spin_unlock_bh(&ipx_interfaces_lock);
out:
return NOTIFY_DONE;
}
static __exit void ipxitf_cleanup(void)
{
struct ipx_interface *i, *tmp;
spin_lock_bh(&ipx_interfaces_lock);
list_for_each_entry_safe(i, tmp, &ipx_interfaces, node)
__ipxitf_put(i);
spin_unlock_bh(&ipx_interfaces_lock);
}
static void ipxitf_def_skb_handler(struct sock *sock, struct sk_buff *skb)
{
if (sock_queue_rcv_skb(sock, skb) < 0)
kfree_skb(skb);
}
/*
* On input skb->sk is NULL. Nobody is charged for the memory.
*/
/* caller must hold a reference to intrfc */
#ifdef CONFIG_IPX_INTERN
static int ipxitf_demux_socket(struct ipx_interface *intrfc,
struct sk_buff *skb, int copy)
{
struct ipxhdr *ipx = ipx_hdr(skb);
int is_broadcast = !memcmp(ipx->ipx_dest.node, ipx_broadcast_node,
IPX_NODE_LEN);
struct sock *s;
int rc;
spin_lock_bh(&intrfc->if_sklist_lock);
sk_for_each(s, &intrfc->if_sklist) {
struct ipx_sock *ipxs = ipx_sk(s);
if (ipxs->port == ipx->ipx_dest.sock &&
(is_broadcast || !memcmp(ipx->ipx_dest.node,
ipxs->node, IPX_NODE_LEN))) {
/* We found a socket to which to send */
struct sk_buff *skb1;
if (copy) {
skb1 = skb_clone(skb, GFP_ATOMIC);
rc = -ENOMEM;
if (!skb1)
goto out;
} else {
skb1 = skb;
copy = 1; /* skb may only be used once */
}
ipxitf_def_skb_handler(s, skb1);
/* On an external interface, one socket can listen */
if (intrfc != ipx_internal_net)
break;
}
}
/* skb was solely for us, and we did not make a copy, so free it. */
if (!copy)
kfree_skb(skb);
rc = 0;
out:
spin_unlock_bh(&intrfc->if_sklist_lock);
return rc;
}
#else
static struct sock *ncp_connection_hack(struct ipx_interface *intrfc,
struct ipxhdr *ipx)
{
/* The packet's target is a NCP connection handler. We want to hand it
* to the correct socket directly within the kernel, so that the
* mars_nwe packet distribution process does not have to do it. Here we
* only care about NCP and BURST packets.
*
* You might call this a hack, but believe me, you do not want a
* complete NCP layer in the kernel, and this is VERY fast as well. */
struct sock *sk = NULL;
int connection = 0;
u8 *ncphdr = (u8 *)(ipx + 1);
if (*ncphdr == 0x22 && *(ncphdr + 1) == 0x22) /* NCP request */
connection = (((int) *(ncphdr + 5)) << 8) | (int) *(ncphdr + 3);
else if (*ncphdr == 0x77 && *(ncphdr + 1) == 0x77) /* BURST packet */
connection = (((int) *(ncphdr + 9)) << 8) | (int) *(ncphdr + 8);
if (connection) {
/* Now we have to look for a special NCP connection handling
* socket. Only these sockets have ipx_ncp_conn != 0, set by
* SIOCIPXNCPCONN. */
spin_lock_bh(&intrfc->if_sklist_lock);
sk_for_each(sk, &intrfc->if_sklist)
if (ipx_sk(sk)->ipx_ncp_conn == connection) {
sock_hold(sk);
goto found;
}
sk = NULL;
found:
spin_unlock_bh(&intrfc->if_sklist_lock);
}
return sk;
}
static int ipxitf_demux_socket(struct ipx_interface *intrfc,
struct sk_buff *skb, int copy)
{
struct ipxhdr *ipx = ipx_hdr(skb);
struct sock *sock1 = NULL, *sock2 = NULL;
struct sk_buff *skb1 = NULL, *skb2 = NULL;
int rc;
if (intrfc == ipx_primary_net && ntohs(ipx->ipx_dest.sock) == 0x451)
sock1 = ncp_connection_hack(intrfc, ipx);
if (!sock1)
/* No special socket found, forward the packet the normal way */
sock1 = ipxitf_find_socket(intrfc, ipx->ipx_dest.sock);
/*
* We need to check if there is a primary net and if
* this is addressed to one of the *SPECIAL* sockets because
* these need to be propagated to the primary net.
* The *SPECIAL* socket list contains: 0x452(SAP), 0x453(RIP) and
* 0x456(Diagnostic).
*/
if (ipx_primary_net && intrfc != ipx_primary_net) {
const int dsock = ntohs(ipx->ipx_dest.sock);
if (dsock == 0x452 || dsock == 0x453 || dsock == 0x456)
/* The appropriate thing to do here is to dup the
* packet and route to the primary net interface via
* ipxitf_send; however, we'll cheat and just demux it
* here. */
sock2 = ipxitf_find_socket(ipx_primary_net,
ipx->ipx_dest.sock);
}
/*
* If there is nothing to do return. The kfree will cancel any charging.
*/
rc = 0;
if (!sock1 && !sock2) {
if (!copy)
kfree_skb(skb);
goto out;
}
/*
* This next segment of code is a little awkward, but it sets it up
* so that the appropriate number of copies of the SKB are made and
* that skb1 and skb2 point to it (them) so that it (they) can be
* demuxed to sock1 and/or sock2. If we are unable to make enough
* copies, we do as much as is possible.
*/
if (copy)
skb1 = skb_clone(skb, GFP_ATOMIC);
else
skb1 = skb;
rc = -ENOMEM;
if (!skb1)
goto out_put;
/* Do we need 2 SKBs? */
if (sock1 && sock2)
skb2 = skb_clone(skb1, GFP_ATOMIC);
else
skb2 = skb1;
if (sock1)
ipxitf_def_skb_handler(sock1, skb1);
if (!skb2)
goto out_put;
if (sock2)
ipxitf_def_skb_handler(sock2, skb2);
rc = 0;
out_put:
if (sock1)
sock_put(sock1);
if (sock2)
sock_put(sock2);
out:
return rc;
}
#endif /* CONFIG_IPX_INTERN */
static struct sk_buff *ipxitf_adjust_skbuff(struct ipx_interface *intrfc,
struct sk_buff *skb)
{
struct sk_buff *skb2;
int in_offset = (unsigned char *)ipx_hdr(skb) - skb->head;
int out_offset = intrfc->if_ipx_offset;
int len;
/* Hopefully, most cases */
if (in_offset >= out_offset)
return skb;
/* Need new SKB */
len = skb->len + out_offset;
skb2 = alloc_skb(len, GFP_ATOMIC);
if (skb2) {
skb_reserve(skb2, out_offset);
skb_reset_network_header(skb2);
skb_reset_transport_header(skb2);
skb_put(skb2, skb->len);
memcpy(ipx_hdr(skb2), ipx_hdr(skb), skb->len);
memcpy(skb2->cb, skb->cb, sizeof(skb->cb));
}
kfree_skb(skb);
return skb2;
}
/* caller must hold a reference to intrfc and the skb has to be unshared */
int ipxitf_send(struct ipx_interface *intrfc, struct sk_buff *skb, char *node)
{
struct ipxhdr *ipx = ipx_hdr(skb);
struct net_device *dev = intrfc->if_dev;
struct datalink_proto *dl = intrfc->if_dlink;
char dest_node[IPX_NODE_LEN];
int send_to_wire = 1;
int addr_len;
ipx->ipx_tctrl = IPX_SKB_CB(skb)->ipx_tctrl;
ipx->ipx_dest.net = IPX_SKB_CB(skb)->ipx_dest_net;
ipx->ipx_source.net = IPX_SKB_CB(skb)->ipx_source_net;
/* see if we need to include the netnum in the route list */
if (IPX_SKB_CB(skb)->last_hop.index >= 0) {
__be32 *last_hop = (__be32 *)(((u8 *) skb->data) +
sizeof(struct ipxhdr) +
IPX_SKB_CB(skb)->last_hop.index *
sizeof(__be32));
*last_hop = IPX_SKB_CB(skb)->last_hop.netnum;
IPX_SKB_CB(skb)->last_hop.index = -1;
}
/*
* We need to know how many skbuffs it will take to send out this
* packet to avoid unnecessary copies.
*/
if (!dl || !dev || dev->flags & IFF_LOOPBACK)
send_to_wire = 0; /* No non looped */
/*
* See if this should be demuxed to sockets on this interface
*
* We want to ensure the original was eaten or that we only use
* up clones.
*/
if (ipx->ipx_dest.net == intrfc->if_netnum) {
/*
* To our own node, loop and free the original.
* The internal net will receive on all node address.
*/
if (intrfc == ipx_internal_net ||
!memcmp(intrfc->if_node, node, IPX_NODE_LEN)) {
/* Don't charge sender */
skb_orphan(skb);
/* Will charge receiver */
return ipxitf_demux_socket(intrfc, skb, 0);
}
/* Broadcast, loop and possibly keep to send on. */
if (!memcmp(ipx_broadcast_node, node, IPX_NODE_LEN)) {
if (!send_to_wire)
skb_orphan(skb);
ipxitf_demux_socket(intrfc, skb, send_to_wire);
if (!send_to_wire)
goto out;
}
}
/*
* If the originating net is not equal to our net; this is routed
* We are still charging the sender. Which is right - the driver
* free will handle this fairly.
*/
if (ipx->ipx_source.net != intrfc->if_netnum) {
/*
* Unshare the buffer before modifying the count in
* case it's a flood or tcpdump
*/
skb = skb_unshare(skb, GFP_ATOMIC);
if (!skb)
goto out;
if (++ipx->ipx_tctrl > ipxcfg_max_hops)
send_to_wire = 0;
}
if (!send_to_wire) {
kfree_skb(skb);
goto out;
}
/* Determine the appropriate hardware address */
addr_len = dev->addr_len;
if (!memcmp(ipx_broadcast_node, node, IPX_NODE_LEN))
memcpy(dest_node, dev->broadcast, addr_len);
else
memcpy(dest_node, &(node[IPX_NODE_LEN-addr_len]), addr_len);
/* Make any compensation for differing physical/data link size */
skb = ipxitf_adjust_skbuff(intrfc, skb);
if (!skb)
goto out;
/* set up data link and physical headers */
skb->dev = dev;
skb->protocol = htons(ETH_P_IPX);
/* Send it out */
dl->request(dl, skb, dest_node);
out:
return 0;
}
static int ipxitf_add_local_route(struct ipx_interface *intrfc)
{
return ipxrtr_add_route(intrfc->if_netnum, intrfc, NULL);
}
static void ipxitf_discover_netnum(struct ipx_interface *intrfc,
struct sk_buff *skb);
static int ipxitf_pprop(struct ipx_interface *intrfc, struct sk_buff *skb);
static int ipxitf_rcv(struct ipx_interface *intrfc, struct sk_buff *skb)
{
struct ipxhdr *ipx = ipx_hdr(skb);
int rc = 0;
ipxitf_hold(intrfc);
/* See if we should update our network number */
if (!intrfc->if_netnum) /* net number of intrfc not known yet */
ipxitf_discover_netnum(intrfc, skb);
IPX_SKB_CB(skb)->last_hop.index = -1;
if (ipx->ipx_type == IPX_TYPE_PPROP) {
rc = ipxitf_pprop(intrfc, skb);
if (rc)
goto out_free_skb;
}
/* local processing follows */
if (!IPX_SKB_CB(skb)->ipx_dest_net)
IPX_SKB_CB(skb)->ipx_dest_net = intrfc->if_netnum;
if (!IPX_SKB_CB(skb)->ipx_source_net)
IPX_SKB_CB(skb)->ipx_source_net = intrfc->if_netnum;
/* it doesn't make sense to route a pprop packet, there's no meaning
* in the ipx_dest_net for such packets */
if (ipx->ipx_type != IPX_TYPE_PPROP &&
intrfc->if_netnum != IPX_SKB_CB(skb)->ipx_dest_net) {
/* We only route point-to-point packets. */
if (skb->pkt_type == PACKET_HOST) {
skb = skb_unshare(skb, GFP_ATOMIC);
if (skb)
rc = ipxrtr_route_skb(skb);
goto out_intrfc;
}
goto out_free_skb;
}
/* see if we should keep it */
if (!memcmp(ipx_broadcast_node, ipx->ipx_dest.node, IPX_NODE_LEN) ||
!memcmp(intrfc->if_node, ipx->ipx_dest.node, IPX_NODE_LEN)) {
rc = ipxitf_demux_socket(intrfc, skb, 0);
goto out_intrfc;
}
/* we couldn't pawn it off so unload it */
out_free_skb:
kfree_skb(skb);
out_intrfc:
ipxitf_put(intrfc);
return rc;
}
static void ipxitf_discover_netnum(struct ipx_interface *intrfc,
struct sk_buff *skb)
{
const struct ipx_cb *cb = IPX_SKB_CB(skb);
/* see if this is an intra packet: source_net == dest_net */
if (cb->ipx_source_net == cb->ipx_dest_net && cb->ipx_source_net) {
struct ipx_interface *i =
ipxitf_find_using_net(cb->ipx_source_net);
/* NB: NetWare servers lie about their hop count so we
* dropped the test based on it. This is the best way
* to determine this is a 0 hop count packet. */
if (!i) {
intrfc->if_netnum = cb->ipx_source_net;
ipxitf_add_local_route(intrfc);
} else {
printk(KERN_WARNING "IPX: Network number collision "
"%lx\n %s %s and %s %s\n",
(unsigned long) ntohl(cb->ipx_source_net),
ipx_device_name(i),
ipx_frame_name(i->if_dlink_type),
ipx_device_name(intrfc),
ipx_frame_name(intrfc->if_dlink_type));
ipxitf_put(i);
}
}
}
/**
* ipxitf_pprop - Process packet propagation IPX packet type 0x14, used for
* NetBIOS broadcasts
* @intrfc: IPX interface receiving this packet
* @skb: Received packet
*
* Checks if packet is valid: if its more than %IPX_MAX_PPROP_HOPS hops or if it
* is smaller than a IPX header + the room for %IPX_MAX_PPROP_HOPS hops we drop
* it, not even processing it locally, if it has exact %IPX_MAX_PPROP_HOPS we
* don't broadcast it, but process it locally. See chapter 5 of Novell's "IPX
* RIP and SAP Router Specification", Part Number 107-000029-001.
*
* If it is valid, check if we have pprop broadcasting enabled by the user,
* if not, just return zero for local processing.
*
* If it is enabled check the packet and don't broadcast it if we have already
* seen this packet.
*
* Broadcast: send it to the interfaces that aren't on the packet visited nets
* array, just after the IPX header.
*
* Returns -EINVAL for invalid packets, so that the calling function drops
* the packet without local processing. 0 if packet is to be locally processed.
*/
static int ipxitf_pprop(struct ipx_interface *intrfc, struct sk_buff *skb)
{
struct ipxhdr *ipx = ipx_hdr(skb);
int i, rc = -EINVAL;
struct ipx_interface *ifcs;
char *c;
__be32 *l;
/* Illegal packet - too many hops or too short */
/* We decide to throw it away: no broadcasting, no local processing.
* NetBIOS unaware implementations route them as normal packets -
* tctrl <= 15, any data payload... */
if (IPX_SKB_CB(skb)->ipx_tctrl > IPX_MAX_PPROP_HOPS ||
ntohs(ipx->ipx_pktsize) < sizeof(struct ipxhdr) +
IPX_MAX_PPROP_HOPS * sizeof(u32))
goto out;
/* are we broadcasting this damn thing? */
rc = 0;
if (!sysctl_ipx_pprop_broadcasting)
goto out;
/* We do broadcast packet on the IPX_MAX_PPROP_HOPS hop, but we
* process it locally. All previous hops broadcasted it, and process it
* locally. */
if (IPX_SKB_CB(skb)->ipx_tctrl == IPX_MAX_PPROP_HOPS)
goto out;
c = ((u8 *) ipx) + sizeof(struct ipxhdr);
l = (__be32 *) c;
/* Don't broadcast packet if already seen this net */
for (i = 0; i < IPX_SKB_CB(skb)->ipx_tctrl; i++)
if (*l++ == intrfc->if_netnum)
goto out;
/* < IPX_MAX_PPROP_HOPS hops && input interface not in list. Save the
* position where we will insert recvd netnum into list, later on,
* in ipxitf_send */
IPX_SKB_CB(skb)->last_hop.index = i;
IPX_SKB_CB(skb)->last_hop.netnum = intrfc->if_netnum;
/* xmit on all other interfaces... */
spin_lock_bh(&ipx_interfaces_lock);
list_for_each_entry(ifcs, &ipx_interfaces, node) {
/* Except unconfigured interfaces */
if (!ifcs->if_netnum)
continue;
/* That aren't in the list */
if (ifcs == intrfc)
continue;
l = (__be32 *) c;
/* don't consider the last entry in the packet list,
* it is our netnum, and it is not there yet */
for (i = 0; i < IPX_SKB_CB(skb)->ipx_tctrl; i++)
if (ifcs->if_netnum == *l++)
break;
if (i == IPX_SKB_CB(skb)->ipx_tctrl) {
struct sk_buff *s = skb_copy(skb, GFP_ATOMIC);
if (s) {
IPX_SKB_CB(s)->ipx_dest_net = ifcs->if_netnum;
ipxrtr_route_skb(s);
}
}
}
spin_unlock_bh(&ipx_interfaces_lock);
out:
return rc;
}
static void ipxitf_insert(struct ipx_interface *intrfc)
{
spin_lock_bh(&ipx_interfaces_lock);
list_add_tail(&intrfc->node, &ipx_interfaces);
spin_unlock_bh(&ipx_interfaces_lock);
if (ipxcfg_auto_select_primary && !ipx_primary_net)
ipx_primary_net = intrfc;
}
static struct ipx_interface *ipxitf_alloc(struct net_device *dev, __be32 netnum,
__be16 dlink_type,
struct datalink_proto *dlink,
unsigned char internal,
int ipx_offset)
{
struct ipx_interface *intrfc = kmalloc(sizeof(*intrfc), GFP_ATOMIC);
if (intrfc) {
intrfc->if_dev = dev;
intrfc->if_netnum = netnum;
intrfc->if_dlink_type = dlink_type;
intrfc->if_dlink = dlink;
intrfc->if_internal = internal;
intrfc->if_ipx_offset = ipx_offset;
intrfc->if_sknum = IPX_MIN_EPHEMERAL_SOCKET;
INIT_HLIST_HEAD(&intrfc->if_sklist);
atomic_set(&intrfc->refcnt, 1);
spin_lock_init(&intrfc->if_sklist_lock);
}
return intrfc;
}
static int ipxitf_create_internal(struct ipx_interface_definition *idef)
{
struct ipx_interface *intrfc;
int rc = -EEXIST;
/* Only one primary network allowed */
if (ipx_primary_net)
goto out;
/* Must have a valid network number */
rc = -EADDRNOTAVAIL;
if (!idef->ipx_network)
goto out;
intrfc = ipxitf_find_using_net(idef->ipx_network);
rc = -EADDRINUSE;
if (intrfc) {
ipxitf_put(intrfc);
goto out;
}
intrfc = ipxitf_alloc(NULL, idef->ipx_network, 0, NULL, 1, 0);
rc = -EAGAIN;
if (!intrfc)
goto out;
memcpy((char *)&(intrfc->if_node), idef->ipx_node, IPX_NODE_LEN);
ipx_internal_net = ipx_primary_net = intrfc;
ipxitf_hold(intrfc);
ipxitf_insert(intrfc);
rc = ipxitf_add_local_route(intrfc);
ipxitf_put(intrfc);
out:
return rc;
}
static __be16 ipx_map_frame_type(unsigned char type)
{
__be16 rc = 0;
switch (type) {
case IPX_FRAME_ETHERII: rc = htons(ETH_P_IPX); break;
case IPX_FRAME_8022: rc = htons(ETH_P_802_2); break;
case IPX_FRAME_SNAP: rc = htons(ETH_P_SNAP); break;
case IPX_FRAME_8023: rc = htons(ETH_P_802_3); break;
}
return rc;
}
static int ipxitf_create(struct ipx_interface_definition *idef)
{
struct net_device *dev;
__be16 dlink_type = 0;
struct datalink_proto *datalink = NULL;
struct ipx_interface *intrfc;
int rc;
if (idef->ipx_special == IPX_INTERNAL) {
rc = ipxitf_create_internal(idef);
goto out;
}
rc = -EEXIST;
if (idef->ipx_special == IPX_PRIMARY && ipx_primary_net)
goto out;
intrfc = ipxitf_find_using_net(idef->ipx_network);
rc = -EADDRINUSE;
if (idef->ipx_network && intrfc) {
ipxitf_put(intrfc);
goto out;
}
if (intrfc)
ipxitf_put(intrfc);
dev = dev_get_by_name(&init_net, idef->ipx_device);
rc = -ENODEV;
if (!dev)
goto out;
switch (idef->ipx_dlink_type) {
case IPX_FRAME_8022:
dlink_type = htons(ETH_P_802_2);
datalink = p8022_datalink;
break;
case IPX_FRAME_ETHERII:
if (dev->type != ARPHRD_IEEE802) {
dlink_type = htons(ETH_P_IPX);
datalink = pEII_datalink;
break;
}
/* fall through */
case IPX_FRAME_SNAP:
dlink_type = htons(ETH_P_SNAP);
datalink = pSNAP_datalink;
break;
case IPX_FRAME_8023:
dlink_type = htons(ETH_P_802_3);
datalink = p8023_datalink;
break;
case IPX_FRAME_NONE:
default:
rc = -EPROTONOSUPPORT;
goto out_dev;
}
rc = -ENETDOWN;
if (!(dev->flags & IFF_UP))
goto out_dev;
/* Check addresses are suitable */
rc = -EINVAL;
if (dev->addr_len > IPX_NODE_LEN)
goto out_dev;
intrfc = ipxitf_find_using_phys(dev, dlink_type);
if (!intrfc) {
/* Ok now create */
intrfc = ipxitf_alloc(dev, idef->ipx_network, dlink_type,
datalink, 0, dev->hard_header_len +
datalink->header_length);
rc = -EAGAIN;
if (!intrfc)
goto out_dev;
/* Setup primary if necessary */
if (idef->ipx_special == IPX_PRIMARY)
ipx_primary_net = intrfc;
if (!memcmp(idef->ipx_node, "\000\000\000\000\000\000",
IPX_NODE_LEN)) {
memset(intrfc->if_node, 0, IPX_NODE_LEN);
memcpy(intrfc->if_node + IPX_NODE_LEN - dev->addr_len,
dev->dev_addr, dev->addr_len);
} else
memcpy(intrfc->if_node, idef->ipx_node, IPX_NODE_LEN);
ipxitf_hold(intrfc);
ipxitf_insert(intrfc);
}
/* If the network number is known, add a route */
rc = 0;
if (!intrfc->if_netnum)
goto out_intrfc;
rc = ipxitf_add_local_route(intrfc);
out_intrfc:
ipxitf_put(intrfc);
goto out;
out_dev:
dev_put(dev);
out:
return rc;
}
static int ipxitf_delete(struct ipx_interface_definition *idef)
{
struct net_device *dev = NULL;
__be16 dlink_type = 0;
struct ipx_interface *intrfc;
int rc = 0;
spin_lock_bh(&ipx_interfaces_lock);
if (idef->ipx_special == IPX_INTERNAL) {
if (ipx_internal_net) {
__ipxitf_put(ipx_internal_net);
goto out;
}
rc = -ENOENT;
goto out;
}
dlink_type = ipx_map_frame_type(idef->ipx_dlink_type);
rc = -EPROTONOSUPPORT;
if (!dlink_type)
goto out;
dev = __dev_get_by_name(&init_net, idef->ipx_device);
rc = -ENODEV;
if (!dev)
goto out;
intrfc = __ipxitf_find_using_phys(dev, dlink_type);
rc = -EINVAL;
if (!intrfc)
goto out;
__ipxitf_put(intrfc);
rc = 0;
out:
spin_unlock_bh(&ipx_interfaces_lock);
return rc;
}
static struct ipx_interface *ipxitf_auto_create(struct net_device *dev,
__be16 dlink_type)
{
struct ipx_interface *intrfc = NULL;
struct datalink_proto *datalink;
if (!dev)
goto out;
/* Check addresses are suitable */
if (dev->addr_len > IPX_NODE_LEN)
goto out;
switch (ntohs(dlink_type)) {
case ETH_P_IPX: datalink = pEII_datalink; break;
case ETH_P_802_2: datalink = p8022_datalink; break;
case ETH_P_SNAP: datalink = pSNAP_datalink; break;
case ETH_P_802_3: datalink = p8023_datalink; break;
default: goto out;
}
intrfc = ipxitf_alloc(dev, 0, dlink_type, datalink, 0,
dev->hard_header_len + datalink->header_length);
if (intrfc) {
memset(intrfc->if_node, 0, IPX_NODE_LEN);
memcpy((char *)&(intrfc->if_node[IPX_NODE_LEN-dev->addr_len]),
dev->dev_addr, dev->addr_len);
spin_lock_init(&intrfc->if_sklist_lock);
atomic_set(&intrfc->refcnt, 1);
ipxitf_insert(intrfc);
dev_hold(dev);
}
out:
return intrfc;
}
static int ipxitf_ioctl(unsigned int cmd, void __user *arg)
{
int rc = -EINVAL;
struct ifreq ifr;
int val;
switch (cmd) {
case SIOCSIFADDR: {
struct sockaddr_ipx *sipx;
struct ipx_interface_definition f;
rc = -EFAULT;
if (copy_from_user(&ifr, arg, sizeof(ifr)))
break;
sipx = (struct sockaddr_ipx *)&ifr.ifr_addr;
rc = -EINVAL;
if (sipx->sipx_family != AF_IPX)
break;
f.ipx_network = sipx->sipx_network;
memcpy(f.ipx_device, ifr.ifr_name,
sizeof(f.ipx_device));
memcpy(f.ipx_node, sipx->sipx_node, IPX_NODE_LEN);
f.ipx_dlink_type = sipx->sipx_type;
f.ipx_special = sipx->sipx_special;
if (sipx->sipx_action == IPX_DLTITF)
rc = ipxitf_delete(&f);
else
rc = ipxitf_create(&f);
break;
}
case SIOCGIFADDR: {
struct sockaddr_ipx *sipx;
struct ipx_interface *ipxif;
struct net_device *dev;
rc = -EFAULT;
if (copy_from_user(&ifr, arg, sizeof(ifr)))
break;
sipx = (struct sockaddr_ipx *)&ifr.ifr_addr;
dev = __dev_get_by_name(&init_net, ifr.ifr_name);
rc = -ENODEV;
if (!dev)
break;
ipxif = ipxitf_find_using_phys(dev,
ipx_map_frame_type(sipx->sipx_type));
rc = -EADDRNOTAVAIL;
if (!ipxif)
break;
sipx->sipx_family = AF_IPX;
sipx->sipx_network = ipxif->if_netnum;
memcpy(sipx->sipx_node, ipxif->if_node,
sizeof(sipx->sipx_node));
rc = -EFAULT;
if (copy_to_user(arg, &ifr, sizeof(ifr)))
break;
ipxitf_put(ipxif);
rc = 0;
break;
}
case SIOCAIPXITFCRT:
rc = -EFAULT;
if (get_user(val, (unsigned char __user *) arg))
break;
rc = 0;
ipxcfg_auto_create_interfaces = val;
break;
case SIOCAIPXPRISLT:
rc = -EFAULT;
if (get_user(val, (unsigned char __user *) arg))
break;
rc = 0;
ipxcfg_set_auto_select(val);
break;
}
return rc;
}
/*
* Checksum routine for IPX
*/
/* Note: We assume ipx_tctrl==0 and htons(length)==ipx_pktsize */
/* This functions should *not* mess with packet contents */
__be16 ipx_cksum(struct ipxhdr *packet, int length)
{
/*
* NOTE: sum is a net byte order quantity, which optimizes the
* loop. This only works on big and little endian machines. (I
* don't know of a machine that isn't.)
*/
/* handle the first 3 words separately; checksum should be skipped
* and ipx_tctrl masked out */
__u16 *p = (__u16 *)packet;
__u32 sum = p[1] + (p[2] & (__force u16)htons(0x00ff));
__u32 i = (length >> 1) - 3; /* Number of remaining complete words */
/* Loop through them */
p += 3;
while (i--)
sum += *p++;
/* Add on the last part word if it exists */
if (packet->ipx_pktsize & htons(1))
sum += (__force u16)htons(0xff00) & *p;
/* Do final fixup */
sum = (sum & 0xffff) + (sum >> 16);
/* It's a pity there's no concept of carry in C */
if (sum >= 0x10000)
sum++;
/*
* Leave 0 alone; we don't want 0xffff here. Note that we can't get
* here with 0x10000, so this check is the same as ((__u16)sum)
*/
if (sum)
sum = ~sum;
return (__force __be16)sum;
}
const char *ipx_frame_name(__be16 frame)
{
char* rc = "None";
switch (ntohs(frame)) {
case ETH_P_IPX: rc = "EtherII"; break;
case ETH_P_802_2: rc = "802.2"; break;
case ETH_P_SNAP: rc = "SNAP"; break;
case ETH_P_802_3: rc = "802.3"; break;
}
return rc;
}
const char *ipx_device_name(struct ipx_interface *intrfc)
{
return intrfc->if_internal ? "Internal" :
intrfc->if_dev ? intrfc->if_dev->name : "Unknown";
}
/* Handling for system calls applied via the various interfaces to an IPX
* socket object. */
static int ipx_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
int opt;
int rc = -EINVAL;
lock_sock(sk);
if (optlen != sizeof(int))
goto out;
rc = -EFAULT;
if (get_user(opt, (unsigned int __user *)optval))
goto out;
rc = -ENOPROTOOPT;
if (!(level == SOL_IPX && optname == IPX_TYPE))
goto out;
ipx_sk(sk)->type = opt;
rc = 0;
out:
release_sock(sk);
return rc;
}
static int ipx_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
int val = 0;
int len;
int rc = -ENOPROTOOPT;
lock_sock(sk);
if (!(level == SOL_IPX && optname == IPX_TYPE))
goto out;
val = ipx_sk(sk)->type;
rc = -EFAULT;
if (get_user(len, optlen))
goto out;
len = min_t(unsigned int, len, sizeof(int));
rc = -EINVAL;
if(len < 0)
goto out;
rc = -EFAULT;
if (put_user(len, optlen) || copy_to_user(optval, &val, len))
goto out;
rc = 0;
out:
release_sock(sk);
return rc;
}
static struct proto ipx_proto = {
.name = "IPX",
.owner = THIS_MODULE,
.obj_size = sizeof(struct ipx_sock),
};
static int ipx_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
int rc = -ESOCKTNOSUPPORT;
struct sock *sk;
if (!net_eq(net, &init_net))
return -EAFNOSUPPORT;
/*
* SPX support is not anymore in the kernel sources. If you want to
* ressurrect it, completing it and making it understand shared skbs,
* be fully multithreaded, etc, grab the sources in an early 2.5 kernel
* tree.
*/
if (sock->type != SOCK_DGRAM)
goto out;
rc = -ENOMEM;
sk = sk_alloc(net, PF_IPX, GFP_KERNEL, &ipx_proto);
if (!sk)
goto out;
sk_refcnt_debug_inc(sk);
sock_init_data(sock, sk);
sk->sk_no_check = 1; /* Checksum off by default */
sock->ops = &ipx_dgram_ops;
rc = 0;
out:
return rc;
}
static int ipx_release(struct socket *sock)
{
struct sock *sk = sock->sk;
if (!sk)
goto out;
lock_sock(sk);
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_state_change(sk);
sock_set_flag(sk, SOCK_DEAD);
sock->sk = NULL;
sk_refcnt_debug_release(sk);
ipx_destroy_socket(sk);
release_sock(sk);
sock_put(sk);
out:
return 0;
}
/* caller must hold a reference to intrfc */
static __be16 ipx_first_free_socketnum(struct ipx_interface *intrfc)
{
unsigned short socketNum = intrfc->if_sknum;
spin_lock_bh(&intrfc->if_sklist_lock);
if (socketNum < IPX_MIN_EPHEMERAL_SOCKET)
socketNum = IPX_MIN_EPHEMERAL_SOCKET;
while (__ipxitf_find_socket(intrfc, htons(socketNum)))
if (socketNum > IPX_MAX_EPHEMERAL_SOCKET)
socketNum = IPX_MIN_EPHEMERAL_SOCKET;
else
socketNum++;
spin_unlock_bh(&intrfc->if_sklist_lock);
intrfc->if_sknum = socketNum;
return htons(socketNum);
}
static int __ipx_bind(struct socket *sock,
struct sockaddr *uaddr, int addr_len)
{
struct sock *sk = sock->sk;
struct ipx_sock *ipxs = ipx_sk(sk);
struct ipx_interface *intrfc;
struct sockaddr_ipx *addr = (struct sockaddr_ipx *)uaddr;
int rc = -EINVAL;
if (!sock_flag(sk, SOCK_ZAPPED) || addr_len != sizeof(struct sockaddr_ipx))
goto out;
intrfc = ipxitf_find_using_net(addr->sipx_network);
rc = -EADDRNOTAVAIL;
if (!intrfc)
goto out;
if (!addr->sipx_port) {
addr->sipx_port = ipx_first_free_socketnum(intrfc);
rc = -EINVAL;
if (!addr->sipx_port)
goto out_put;
}
/* protect IPX system stuff like routing/sap */
rc = -EACCES;
if (ntohs(addr->sipx_port) < IPX_MIN_EPHEMERAL_SOCKET &&
!capable(CAP_NET_ADMIN))
goto out_put;
ipxs->port = addr->sipx_port;
#ifdef CONFIG_IPX_INTERN
if (intrfc == ipx_internal_net) {
/* The source address is to be set explicitly if the
* socket is to be bound on the internal network. If a
* node number 0 was specified, the default is used.
*/
rc = -EINVAL;
if (!memcmp(addr->sipx_node, ipx_broadcast_node, IPX_NODE_LEN))
goto out_put;
if (!memcmp(addr->sipx_node, ipx_this_node, IPX_NODE_LEN))
memcpy(ipxs->node, intrfc->if_node, IPX_NODE_LEN);
else
memcpy(ipxs->node, addr->sipx_node, IPX_NODE_LEN);
rc = -EADDRINUSE;
if (ipxitf_find_internal_socket(intrfc, ipxs->node,
ipxs->port)) {
SOCK_DEBUG(sk,
"IPX: bind failed because port %X in use.\n",
ntohs(addr->sipx_port));
goto out_put;
}
} else {
/* Source addresses are easy. It must be our
* network:node pair for an interface routed to IPX
* with the ipx routing ioctl()
*/
memcpy(ipxs->node, intrfc->if_node, IPX_NODE_LEN);
rc = -EADDRINUSE;
if (ipxitf_find_socket(intrfc, addr->sipx_port)) {
SOCK_DEBUG(sk,
"IPX: bind failed because port %X in use.\n",
ntohs(addr->sipx_port));
goto out_put;
}
}
#else /* !def CONFIG_IPX_INTERN */
/* Source addresses are easy. It must be our network:node pair for
an interface routed to IPX with the ipx routing ioctl() */
rc = -EADDRINUSE;
if (ipxitf_find_socket(intrfc, addr->sipx_port)) {
SOCK_DEBUG(sk, "IPX: bind failed because port %X in use.\n",
ntohs((int)addr->sipx_port));
goto out_put;
}
#endif /* CONFIG_IPX_INTERN */
ipxitf_insert_socket(intrfc, sk);
sock_reset_flag(sk, SOCK_ZAPPED);
rc = 0;
out_put:
ipxitf_put(intrfc);
out:
return rc;
}
static int ipx_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sock *sk = sock->sk;
int rc;
lock_sock(sk);
rc = __ipx_bind(sock, uaddr, addr_len);
release_sock(sk);
return rc;
}
static int ipx_connect(struct socket *sock, struct sockaddr *uaddr,
int addr_len, int flags)
{
struct sock *sk = sock->sk;
struct ipx_sock *ipxs = ipx_sk(sk);
struct sockaddr_ipx *addr;
int rc = -EINVAL;
struct ipx_route *rt;
sk->sk_state = TCP_CLOSE;
sock->state = SS_UNCONNECTED;
lock_sock(sk);
if (addr_len != sizeof(*addr))
goto out;
addr = (struct sockaddr_ipx *)uaddr;
/* put the autobinding in */
if (!ipxs->port) {
struct sockaddr_ipx uaddr;
uaddr.sipx_port = 0;
uaddr.sipx_network = 0;
#ifdef CONFIG_IPX_INTERN
rc = -ENETDOWN;
if (!ipxs->intrfc)
goto out; /* Someone zonked the iface */
memcpy(uaddr.sipx_node, ipxs->intrfc->if_node,
IPX_NODE_LEN);
#endif /* CONFIG_IPX_INTERN */
rc = __ipx_bind(sock, (struct sockaddr *)&uaddr,
sizeof(struct sockaddr_ipx));
if (rc)
goto out;
}
/* We can either connect to primary network or somewhere
* we can route to */
rt = ipxrtr_lookup(addr->sipx_network);
rc = -ENETUNREACH;
if (!rt && !(!addr->sipx_network && ipx_primary_net))
goto out;
ipxs->dest_addr.net = addr->sipx_network;
ipxs->dest_addr.sock = addr->sipx_port;
memcpy(ipxs->dest_addr.node, addr->sipx_node, IPX_NODE_LEN);
ipxs->type = addr->sipx_type;
if (sock->type == SOCK_DGRAM) {
sock->state = SS_CONNECTED;
sk->sk_state = TCP_ESTABLISHED;
}
if (rt)
ipxrtr_put(rt);
rc = 0;
out:
release_sock(sk);
return rc;
}
static int ipx_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct ipx_address *addr;
struct sockaddr_ipx sipx;
struct sock *sk = sock->sk;
struct ipx_sock *ipxs = ipx_sk(sk);
int rc;
*uaddr_len = sizeof(struct sockaddr_ipx);
lock_sock(sk);
if (peer) {
rc = -ENOTCONN;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
addr = &ipxs->dest_addr;
sipx.sipx_network = addr->net;
sipx.sipx_port = addr->sock;
memcpy(sipx.sipx_node, addr->node, IPX_NODE_LEN);
} else {
if (ipxs->intrfc) {
sipx.sipx_network = ipxs->intrfc->if_netnum;
#ifdef CONFIG_IPX_INTERN
memcpy(sipx.sipx_node, ipxs->node, IPX_NODE_LEN);
#else
memcpy(sipx.sipx_node, ipxs->intrfc->if_node,
IPX_NODE_LEN);
#endif /* CONFIG_IPX_INTERN */
} else {
sipx.sipx_network = 0;
memset(sipx.sipx_node, '\0', IPX_NODE_LEN);
}
sipx.sipx_port = ipxs->port;
}
sipx.sipx_family = AF_IPX;
sipx.sipx_type = ipxs->type;
sipx.sipx_zero = 0;
memcpy(uaddr, &sipx, sizeof(sipx));
rc = 0;
out:
release_sock(sk);
return rc;
}
static int ipx_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev)
{
/* NULL here for pt means the packet was looped back */
struct ipx_interface *intrfc;
struct ipxhdr *ipx;
u16 ipx_pktsize;
int rc = 0;
if (!net_eq(dev_net(dev), &init_net))
goto drop;
/* Not ours */
if (skb->pkt_type == PACKET_OTHERHOST)
goto drop;
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL)
goto out;
if (!pskb_may_pull(skb, sizeof(struct ipxhdr)))
goto drop;
ipx_pktsize = ntohs(ipx_hdr(skb)->ipx_pktsize);
/* Too small or invalid header? */
if (ipx_pktsize < sizeof(struct ipxhdr) ||
!pskb_may_pull(skb, ipx_pktsize))
goto drop;
ipx = ipx_hdr(skb);
if (ipx->ipx_checksum != IPX_NO_CHECKSUM &&
ipx->ipx_checksum != ipx_cksum(ipx, ipx_pktsize))
goto drop;
IPX_SKB_CB(skb)->ipx_tctrl = ipx->ipx_tctrl;
IPX_SKB_CB(skb)->ipx_dest_net = ipx->ipx_dest.net;
IPX_SKB_CB(skb)->ipx_source_net = ipx->ipx_source.net;
/* Determine what local ipx endpoint this is */
intrfc = ipxitf_find_using_phys(dev, pt->type);
if (!intrfc) {
if (ipxcfg_auto_create_interfaces &&
IPX_SKB_CB(skb)->ipx_dest_net) {
intrfc = ipxitf_auto_create(dev, pt->type);
if (intrfc)
ipxitf_hold(intrfc);
}
if (!intrfc) /* Not one of ours */
/* or invalid packet for auto creation */
goto drop;
}
rc = ipxitf_rcv(intrfc, skb);
ipxitf_put(intrfc);
goto out;
drop:
kfree_skb(skb);
out:
return rc;
}
static int ipx_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct ipx_sock *ipxs = ipx_sk(sk);
struct sockaddr_ipx *usipx = (struct sockaddr_ipx *)msg->msg_name;
struct sockaddr_ipx local_sipx;
int rc = -EINVAL;
int flags = msg->msg_flags;
lock_sock(sk);
/* Socket gets bound below anyway */
/* if (sk->sk_zapped)
return -EIO; */ /* Socket not bound */
if (flags & ~(MSG_DONTWAIT|MSG_CMSG_COMPAT))
goto out;
/* Max possible packet size limited by 16 bit pktsize in header */
if (len >= 65535 - sizeof(struct ipxhdr))
goto out;
if (usipx) {
if (!ipxs->port) {
struct sockaddr_ipx uaddr;
uaddr.sipx_port = 0;
uaddr.sipx_network = 0;
#ifdef CONFIG_IPX_INTERN
rc = -ENETDOWN;
if (!ipxs->intrfc)
goto out; /* Someone zonked the iface */
memcpy(uaddr.sipx_node, ipxs->intrfc->if_node,
IPX_NODE_LEN);
#endif
rc = __ipx_bind(sock, (struct sockaddr *)&uaddr,
sizeof(struct sockaddr_ipx));
if (rc)
goto out;
}
rc = -EINVAL;
if (msg->msg_namelen < sizeof(*usipx) ||
usipx->sipx_family != AF_IPX)
goto out;
} else {
rc = -ENOTCONN;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
usipx = &local_sipx;
usipx->sipx_family = AF_IPX;
usipx->sipx_type = ipxs->type;
usipx->sipx_port = ipxs->dest_addr.sock;
usipx->sipx_network = ipxs->dest_addr.net;
memcpy(usipx->sipx_node, ipxs->dest_addr.node, IPX_NODE_LEN);
}
rc = ipxrtr_route_packet(sk, usipx, msg->msg_iov, len,
flags & MSG_DONTWAIT);
if (rc >= 0)
rc = len;
out:
release_sock(sk);
return rc;
}
static int ipx_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct ipx_sock *ipxs = ipx_sk(sk);
struct sockaddr_ipx *sipx = (struct sockaddr_ipx *)msg->msg_name;
struct ipxhdr *ipx = NULL;
struct sk_buff *skb;
int copied, rc;
lock_sock(sk);
/* put the autobinding in */
if (!ipxs->port) {
struct sockaddr_ipx uaddr;
uaddr.sipx_port = 0;
uaddr.sipx_network = 0;
#ifdef CONFIG_IPX_INTERN
rc = -ENETDOWN;
if (!ipxs->intrfc)
goto out; /* Someone zonked the iface */
memcpy(uaddr.sipx_node, ipxs->intrfc->if_node, IPX_NODE_LEN);
#endif /* CONFIG_IPX_INTERN */
rc = __ipx_bind(sock, (struct sockaddr *)&uaddr,
sizeof(struct sockaddr_ipx));
if (rc)
goto out;
}
rc = -ENOTCONN;
if (sock_flag(sk, SOCK_ZAPPED))
goto out;
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &rc);
if (!skb)
goto out;
ipx = ipx_hdr(skb);
copied = ntohs(ipx->ipx_pktsize) - sizeof(struct ipxhdr);
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
rc = skb_copy_datagram_iovec(skb, sizeof(struct ipxhdr), msg->msg_iov,
copied);
if (rc)
goto out_free;
if (skb->tstamp.tv64)
sk->sk_stamp = skb->tstamp;
if (sipx) {
sipx->sipx_family = AF_IPX;
sipx->sipx_port = ipx->ipx_source.sock;
memcpy(sipx->sipx_node, ipx->ipx_source.node, IPX_NODE_LEN);
sipx->sipx_network = IPX_SKB_CB(skb)->ipx_source_net;
sipx->sipx_type = ipx->ipx_type;
sipx->sipx_zero = 0;
msg->msg_namelen = sizeof(*sipx);
}
rc = copied;
out_free:
skb_free_datagram(sk, skb);
out:
release_sock(sk);
return rc;
}
static int ipx_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
int rc = 0;
long amount = 0;
struct sock *sk = sock->sk;
void __user *argp = (void __user *)arg;
lock_sock(sk);
switch (cmd) {
case TIOCOUTQ:
amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
if (amount < 0)
amount = 0;
rc = put_user(amount, (int __user *)argp);
break;
case TIOCINQ: {
struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
/* These two are safe on a single CPU system as only
* user tasks fiddle here */
if (skb)
amount = skb->len - sizeof(struct ipxhdr);
rc = put_user(amount, (int __user *)argp);
break;
}
case SIOCADDRT:
case SIOCDELRT:
rc = -EPERM;
if (capable(CAP_NET_ADMIN))
rc = ipxrtr_ioctl(cmd, argp);
break;
case SIOCSIFADDR:
case SIOCAIPXITFCRT:
case SIOCAIPXPRISLT:
rc = -EPERM;
if (!capable(CAP_NET_ADMIN))
break;
case SIOCGIFADDR:
rc = ipxitf_ioctl(cmd, argp);
break;
case SIOCIPXCFGDATA:
rc = ipxcfg_get_config_data(argp);
break;
case SIOCIPXNCPCONN:
/*
* This socket wants to take care of the NCP connection
* handed to us in arg.
*/
rc = -EPERM;
if (!capable(CAP_NET_ADMIN))
break;
rc = get_user(ipx_sk(sk)->ipx_ncp_conn,
(const unsigned short __user *)argp);
break;
case SIOCGSTAMP:
rc = sock_get_timestamp(sk, argp);
break;
case SIOCGIFDSTADDR:
case SIOCSIFDSTADDR:
case SIOCGIFBRDADDR:
case SIOCSIFBRDADDR:
case SIOCGIFNETMASK:
case SIOCSIFNETMASK:
rc = -EINVAL;
break;
default:
rc = -ENOIOCTLCMD;
break;
}
release_sock(sk);
return rc;
}
#ifdef CONFIG_COMPAT
static int ipx_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
/*
* These 4 commands use same structure on 32bit and 64bit. Rest of IPX
* commands is handled by generic ioctl code. As these commands are
* SIOCPROTOPRIVATE..SIOCPROTOPRIVATE+3, they cannot be handled by generic
* code.
*/
switch (cmd) {
case SIOCAIPXITFCRT:
case SIOCAIPXPRISLT:
case SIOCIPXCFGDATA:
case SIOCIPXNCPCONN:
return ipx_ioctl(sock, cmd, arg);
default:
return -ENOIOCTLCMD;
}
}
#endif
/*
* Socket family declarations
*/
static const struct net_proto_family ipx_family_ops = {
.family = PF_IPX,
.create = ipx_create,
.owner = THIS_MODULE,
};
static const struct proto_ops ipx_dgram_ops = {
.family = PF_IPX,
.owner = THIS_MODULE,
.release = ipx_release,
.bind = ipx_bind,
.connect = ipx_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = ipx_getname,
.poll = datagram_poll,
.ioctl = ipx_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = ipx_compat_ioctl,
#endif
.listen = sock_no_listen,
.shutdown = sock_no_shutdown, /* FIXME: support shutdown */
.setsockopt = ipx_setsockopt,
.getsockopt = ipx_getsockopt,
.sendmsg = ipx_sendmsg,
.recvmsg = ipx_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static struct packet_type ipx_8023_packet_type __read_mostly = {
.type = cpu_to_be16(ETH_P_802_3),
.func = ipx_rcv,
};
static struct packet_type ipx_dix_packet_type __read_mostly = {
.type = cpu_to_be16(ETH_P_IPX),
.func = ipx_rcv,
};
static struct notifier_block ipx_dev_notifier = {
.notifier_call = ipxitf_device_event,
};
extern struct datalink_proto *make_EII_client(void);
extern void destroy_EII_client(struct datalink_proto *);
static const unsigned char ipx_8022_type = 0xE0;
static const unsigned char ipx_snap_id[5] = { 0x0, 0x0, 0x0, 0x81, 0x37 };
static const char ipx_EII_err_msg[] __initconst =
KERN_CRIT "IPX: Unable to register with Ethernet II\n";
static const char ipx_8023_err_msg[] __initconst =
KERN_CRIT "IPX: Unable to register with 802.3\n";
static const char ipx_llc_err_msg[] __initconst =
KERN_CRIT "IPX: Unable to register with 802.2\n";
static const char ipx_snap_err_msg[] __initconst =
KERN_CRIT "IPX: Unable to register with SNAP\n";
static int __init ipx_init(void)
{
int rc = proto_register(&ipx_proto, 1);
if (rc != 0)
goto out;
sock_register(&ipx_family_ops);
pEII_datalink = make_EII_client();
if (pEII_datalink)
dev_add_pack(&ipx_dix_packet_type);
else
printk(ipx_EII_err_msg);
p8023_datalink = make_8023_client();
if (p8023_datalink)
dev_add_pack(&ipx_8023_packet_type);
else
printk(ipx_8023_err_msg);
p8022_datalink = register_8022_client(ipx_8022_type, ipx_rcv);
if (!p8022_datalink)
printk(ipx_llc_err_msg);
pSNAP_datalink = register_snap_client(ipx_snap_id, ipx_rcv);
if (!pSNAP_datalink)
printk(ipx_snap_err_msg);
register_netdevice_notifier(&ipx_dev_notifier);
ipx_register_sysctl();
ipx_proc_init();
out:
return rc;
}
static void __exit ipx_proto_finito(void)
{
ipx_proc_exit();
ipx_unregister_sysctl();
unregister_netdevice_notifier(&ipx_dev_notifier);
ipxitf_cleanup();
if (pSNAP_datalink) {
unregister_snap_client(pSNAP_datalink);
pSNAP_datalink = NULL;
}
if (p8022_datalink) {
unregister_8022_client(p8022_datalink);
p8022_datalink = NULL;
}
dev_remove_pack(&ipx_8023_packet_type);
if (p8023_datalink) {
destroy_8023_client(p8023_datalink);
p8023_datalink = NULL;
}
dev_remove_pack(&ipx_dix_packet_type);
if (pEII_datalink) {
destroy_EII_client(pEII_datalink);
pEII_datalink = NULL;
}
proto_unregister(&ipx_proto);
sock_unregister(ipx_family_ops.family);
}
module_init(ipx_init);
module_exit(ipx_proto_finito);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_IPX);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_15 |
crossvul-cpp_data_good_5845_8 | /*
BlueZ - Bluetooth protocol stack for Linux
Copyright (C) 2000-2001 Qualcomm Incorporated
Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
/* Bluetooth address family and sockets. */
#include <linux/module.h>
#include <linux/debugfs.h>
#include <asm/ioctls.h>
#include <net/bluetooth/bluetooth.h>
#include <linux/proc_fs.h>
#define VERSION "2.17"
/* Bluetooth sockets */
#define BT_MAX_PROTO 8
static const struct net_proto_family *bt_proto[BT_MAX_PROTO];
static DEFINE_RWLOCK(bt_proto_lock);
static struct lock_class_key bt_lock_key[BT_MAX_PROTO];
static const char *const bt_key_strings[BT_MAX_PROTO] = {
"sk_lock-AF_BLUETOOTH-BTPROTO_L2CAP",
"sk_lock-AF_BLUETOOTH-BTPROTO_HCI",
"sk_lock-AF_BLUETOOTH-BTPROTO_SCO",
"sk_lock-AF_BLUETOOTH-BTPROTO_RFCOMM",
"sk_lock-AF_BLUETOOTH-BTPROTO_BNEP",
"sk_lock-AF_BLUETOOTH-BTPROTO_CMTP",
"sk_lock-AF_BLUETOOTH-BTPROTO_HIDP",
"sk_lock-AF_BLUETOOTH-BTPROTO_AVDTP",
};
static struct lock_class_key bt_slock_key[BT_MAX_PROTO];
static const char *const bt_slock_key_strings[BT_MAX_PROTO] = {
"slock-AF_BLUETOOTH-BTPROTO_L2CAP",
"slock-AF_BLUETOOTH-BTPROTO_HCI",
"slock-AF_BLUETOOTH-BTPROTO_SCO",
"slock-AF_BLUETOOTH-BTPROTO_RFCOMM",
"slock-AF_BLUETOOTH-BTPROTO_BNEP",
"slock-AF_BLUETOOTH-BTPROTO_CMTP",
"slock-AF_BLUETOOTH-BTPROTO_HIDP",
"slock-AF_BLUETOOTH-BTPROTO_AVDTP",
};
void bt_sock_reclassify_lock(struct sock *sk, int proto)
{
BUG_ON(!sk);
BUG_ON(sock_owned_by_user(sk));
sock_lock_init_class_and_name(sk,
bt_slock_key_strings[proto], &bt_slock_key[proto],
bt_key_strings[proto], &bt_lock_key[proto]);
}
EXPORT_SYMBOL(bt_sock_reclassify_lock);
int bt_sock_register(int proto, const struct net_proto_family *ops)
{
int err = 0;
if (proto < 0 || proto >= BT_MAX_PROTO)
return -EINVAL;
write_lock(&bt_proto_lock);
if (bt_proto[proto])
err = -EEXIST;
else
bt_proto[proto] = ops;
write_unlock(&bt_proto_lock);
return err;
}
EXPORT_SYMBOL(bt_sock_register);
void bt_sock_unregister(int proto)
{
if (proto < 0 || proto >= BT_MAX_PROTO)
return;
write_lock(&bt_proto_lock);
bt_proto[proto] = NULL;
write_unlock(&bt_proto_lock);
}
EXPORT_SYMBOL(bt_sock_unregister);
static int bt_sock_create(struct net *net, struct socket *sock, int proto,
int kern)
{
int err;
if (net != &init_net)
return -EAFNOSUPPORT;
if (proto < 0 || proto >= BT_MAX_PROTO)
return -EINVAL;
if (!bt_proto[proto])
request_module("bt-proto-%d", proto);
err = -EPROTONOSUPPORT;
read_lock(&bt_proto_lock);
if (bt_proto[proto] && try_module_get(bt_proto[proto]->owner)) {
err = bt_proto[proto]->create(net, sock, proto, kern);
if (!err)
bt_sock_reclassify_lock(sock->sk, proto);
module_put(bt_proto[proto]->owner);
}
read_unlock(&bt_proto_lock);
return err;
}
void bt_sock_link(struct bt_sock_list *l, struct sock *sk)
{
write_lock(&l->lock);
sk_add_node(sk, &l->head);
write_unlock(&l->lock);
}
EXPORT_SYMBOL(bt_sock_link);
void bt_sock_unlink(struct bt_sock_list *l, struct sock *sk)
{
write_lock(&l->lock);
sk_del_node_init(sk);
write_unlock(&l->lock);
}
EXPORT_SYMBOL(bt_sock_unlink);
void bt_accept_enqueue(struct sock *parent, struct sock *sk)
{
BT_DBG("parent %p, sk %p", parent, sk);
sock_hold(sk);
list_add_tail(&bt_sk(sk)->accept_q, &bt_sk(parent)->accept_q);
bt_sk(sk)->parent = parent;
parent->sk_ack_backlog++;
}
EXPORT_SYMBOL(bt_accept_enqueue);
void bt_accept_unlink(struct sock *sk)
{
BT_DBG("sk %p state %d", sk, sk->sk_state);
list_del_init(&bt_sk(sk)->accept_q);
bt_sk(sk)->parent->sk_ack_backlog--;
bt_sk(sk)->parent = NULL;
sock_put(sk);
}
EXPORT_SYMBOL(bt_accept_unlink);
struct sock *bt_accept_dequeue(struct sock *parent, struct socket *newsock)
{
struct list_head *p, *n;
struct sock *sk;
BT_DBG("parent %p", parent);
list_for_each_safe(p, n, &bt_sk(parent)->accept_q) {
sk = (struct sock *) list_entry(p, struct bt_sock, accept_q);
lock_sock(sk);
/* FIXME: Is this check still needed */
if (sk->sk_state == BT_CLOSED) {
release_sock(sk);
bt_accept_unlink(sk);
continue;
}
if (sk->sk_state == BT_CONNECTED || !newsock ||
test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags)) {
bt_accept_unlink(sk);
if (newsock)
sock_graft(sk, newsock);
release_sock(sk);
return sk;
}
release_sock(sk);
}
return NULL;
}
EXPORT_SYMBOL(bt_accept_dequeue);
int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
int noblock = flags & MSG_DONTWAIT;
struct sock *sk = sock->sk;
struct sk_buff *skb;
size_t copied;
int err;
BT_DBG("sock %p sk %p len %zu", sock, sk, len);
if (flags & (MSG_OOB))
return -EOPNOTSUPP;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb) {
if (sk->sk_shutdown & RCV_SHUTDOWN)
return 0;
return err;
}
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
skb_reset_transport_header(skb);
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err == 0) {
sock_recv_ts_and_drops(msg, sk, skb);
if (bt_sk(sk)->skb_msg_name)
bt_sk(sk)->skb_msg_name(skb, msg->msg_name,
&msg->msg_namelen);
}
skb_free_datagram(sk, skb);
return err ? : copied;
}
EXPORT_SYMBOL(bt_sock_recvmsg);
static long bt_sock_data_wait(struct sock *sk, long timeo)
{
DECLARE_WAITQUEUE(wait, current);
add_wait_queue(sk_sleep(sk), &wait);
for (;;) {
set_current_state(TASK_INTERRUPTIBLE);
if (!skb_queue_empty(&sk->sk_receive_queue))
break;
if (sk->sk_err || (sk->sk_shutdown & RCV_SHUTDOWN))
break;
if (signal_pending(current) || !timeo)
break;
set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
release_sock(sk);
timeo = schedule_timeout(timeo);
lock_sock(sk);
clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(sk_sleep(sk), &wait);
return timeo;
}
int bt_sock_stream_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
int err = 0;
size_t target, copied = 0;
long timeo;
if (flags & MSG_OOB)
return -EOPNOTSUPP;
BT_DBG("sk %p size %zu", sk, size);
lock_sock(sk);
target = sock_rcvlowat(sk, flags & MSG_WAITALL, size);
timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
do {
struct sk_buff *skb;
int chunk;
skb = skb_dequeue(&sk->sk_receive_queue);
if (!skb) {
if (copied >= target)
break;
err = sock_error(sk);
if (err)
break;
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
err = -EAGAIN;
if (!timeo)
break;
timeo = bt_sock_data_wait(sk, timeo);
if (signal_pending(current)) {
err = sock_intr_errno(timeo);
goto out;
}
continue;
}
chunk = min_t(unsigned int, skb->len, size);
if (skb_copy_datagram_iovec(skb, 0, msg->msg_iov, chunk)) {
skb_queue_head(&sk->sk_receive_queue, skb);
if (!copied)
copied = -EFAULT;
break;
}
copied += chunk;
size -= chunk;
sock_recv_ts_and_drops(msg, sk, skb);
if (!(flags & MSG_PEEK)) {
int skb_len = skb_headlen(skb);
if (chunk <= skb_len) {
__skb_pull(skb, chunk);
} else {
struct sk_buff *frag;
__skb_pull(skb, skb_len);
chunk -= skb_len;
skb_walk_frags(skb, frag) {
if (chunk <= frag->len) {
/* Pulling partial data */
skb->len -= chunk;
skb->data_len -= chunk;
__skb_pull(frag, chunk);
break;
} else if (frag->len) {
/* Pulling all frag data */
chunk -= frag->len;
skb->len -= frag->len;
skb->data_len -= frag->len;
__skb_pull(frag, frag->len);
}
}
}
if (skb->len) {
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
kfree_skb(skb);
} else {
/* put message back and return */
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
} while (size);
out:
release_sock(sk);
return copied ? : err;
}
EXPORT_SYMBOL(bt_sock_stream_recvmsg);
static inline unsigned int bt_accept_poll(struct sock *parent)
{
struct list_head *p, *n;
struct sock *sk;
list_for_each_safe(p, n, &bt_sk(parent)->accept_q) {
sk = (struct sock *) list_entry(p, struct bt_sock, accept_q);
if (sk->sk_state == BT_CONNECTED ||
(test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags) &&
sk->sk_state == BT_CONNECT2))
return POLLIN | POLLRDNORM;
}
return 0;
}
unsigned int bt_sock_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
unsigned int mask = 0;
BT_DBG("sock %p, sk %p", sock, sk);
poll_wait(file, sk_sleep(sk), wait);
if (sk->sk_state == BT_LISTEN)
return bt_accept_poll(sk);
if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
mask |= POLLERR |
(sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? POLLPRI : 0);
if (sk->sk_shutdown & RCV_SHUTDOWN)
mask |= POLLRDHUP | POLLIN | POLLRDNORM;
if (sk->sk_shutdown == SHUTDOWN_MASK)
mask |= POLLHUP;
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
if (sk->sk_state == BT_CLOSED)
mask |= POLLHUP;
if (sk->sk_state == BT_CONNECT ||
sk->sk_state == BT_CONNECT2 ||
sk->sk_state == BT_CONFIG)
return mask;
if (!test_bit(BT_SK_SUSPEND, &bt_sk(sk)->flags) && sock_writeable(sk))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
else
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
return mask;
}
EXPORT_SYMBOL(bt_sock_poll);
int bt_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk = sock->sk;
struct sk_buff *skb;
long amount;
int err;
BT_DBG("sk %p cmd %x arg %lx", sk, cmd, arg);
switch (cmd) {
case TIOCOUTQ:
if (sk->sk_state == BT_LISTEN)
return -EINVAL;
amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
if (amount < 0)
amount = 0;
err = put_user(amount, (int __user *) arg);
break;
case TIOCINQ:
if (sk->sk_state == BT_LISTEN)
return -EINVAL;
lock_sock(sk);
skb = skb_peek(&sk->sk_receive_queue);
amount = skb ? skb->len : 0;
release_sock(sk);
err = put_user(amount, (int __user *) arg);
break;
case SIOCGSTAMP:
err = sock_get_timestamp(sk, (struct timeval __user *) arg);
break;
case SIOCGSTAMPNS:
err = sock_get_timestampns(sk, (struct timespec __user *) arg);
break;
default:
err = -ENOIOCTLCMD;
break;
}
return err;
}
EXPORT_SYMBOL(bt_sock_ioctl);
/* This function expects the sk lock to be held when called */
int bt_sock_wait_state(struct sock *sk, int state, unsigned long timeo)
{
DECLARE_WAITQUEUE(wait, current);
int err = 0;
BT_DBG("sk %p", sk);
add_wait_queue(sk_sleep(sk), &wait);
set_current_state(TASK_INTERRUPTIBLE);
while (sk->sk_state != state) {
if (!timeo) {
err = -EINPROGRESS;
break;
}
if (signal_pending(current)) {
err = sock_intr_errno(timeo);
break;
}
release_sock(sk);
timeo = schedule_timeout(timeo);
lock_sock(sk);
set_current_state(TASK_INTERRUPTIBLE);
err = sock_error(sk);
if (err)
break;
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(sk_sleep(sk), &wait);
return err;
}
EXPORT_SYMBOL(bt_sock_wait_state);
/* This function expects the sk lock to be held when called */
int bt_sock_wait_ready(struct sock *sk, unsigned long flags)
{
DECLARE_WAITQUEUE(wait, current);
unsigned long timeo;
int err = 0;
BT_DBG("sk %p", sk);
timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
add_wait_queue(sk_sleep(sk), &wait);
set_current_state(TASK_INTERRUPTIBLE);
while (test_bit(BT_SK_SUSPEND, &bt_sk(sk)->flags)) {
if (!timeo) {
err = -EAGAIN;
break;
}
if (signal_pending(current)) {
err = sock_intr_errno(timeo);
break;
}
release_sock(sk);
timeo = schedule_timeout(timeo);
lock_sock(sk);
set_current_state(TASK_INTERRUPTIBLE);
err = sock_error(sk);
if (err)
break;
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(sk_sleep(sk), &wait);
return err;
}
EXPORT_SYMBOL(bt_sock_wait_ready);
#ifdef CONFIG_PROC_FS
struct bt_seq_state {
struct bt_sock_list *l;
};
static void *bt_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(seq->private->l->lock)
{
struct bt_seq_state *s = seq->private;
struct bt_sock_list *l = s->l;
read_lock(&l->lock);
return seq_hlist_start_head(&l->head, *pos);
}
static void *bt_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct bt_seq_state *s = seq->private;
struct bt_sock_list *l = s->l;
return seq_hlist_next(v, &l->head, pos);
}
static void bt_seq_stop(struct seq_file *seq, void *v)
__releases(seq->private->l->lock)
{
struct bt_seq_state *s = seq->private;
struct bt_sock_list *l = s->l;
read_unlock(&l->lock);
}
static int bt_seq_show(struct seq_file *seq, void *v)
{
struct bt_seq_state *s = seq->private;
struct bt_sock_list *l = s->l;
if (v == SEQ_START_TOKEN) {
seq_puts(seq ,"sk RefCnt Rmem Wmem User Inode Parent");
if (l->custom_seq_show) {
seq_putc(seq, ' ');
l->custom_seq_show(seq, v);
}
seq_putc(seq, '\n');
} else {
struct sock *sk = sk_entry(v);
struct bt_sock *bt = bt_sk(sk);
seq_printf(seq,
"%pK %-6d %-6u %-6u %-6u %-6lu %-6lu",
sk,
atomic_read(&sk->sk_refcnt),
sk_rmem_alloc_get(sk),
sk_wmem_alloc_get(sk),
from_kuid(seq_user_ns(seq), sock_i_uid(sk)),
sock_i_ino(sk),
bt->parent? sock_i_ino(bt->parent): 0LU);
if (l->custom_seq_show) {
seq_putc(seq, ' ');
l->custom_seq_show(seq, v);
}
seq_putc(seq, '\n');
}
return 0;
}
static struct seq_operations bt_seq_ops = {
.start = bt_seq_start,
.next = bt_seq_next,
.stop = bt_seq_stop,
.show = bt_seq_show,
};
static int bt_seq_open(struct inode *inode, struct file *file)
{
struct bt_sock_list *sk_list;
struct bt_seq_state *s;
sk_list = PDE_DATA(inode);
s = __seq_open_private(file, &bt_seq_ops,
sizeof(struct bt_seq_state));
if (!s)
return -ENOMEM;
s->l = sk_list;
return 0;
}
static const struct file_operations bt_fops = {
.open = bt_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private
};
int bt_procfs_init(struct net *net, const char *name,
struct bt_sock_list* sk_list,
int (* seq_show)(struct seq_file *, void *))
{
sk_list->custom_seq_show = seq_show;
if (!proc_create_data(name, 0, net->proc_net, &bt_fops, sk_list))
return -ENOMEM;
return 0;
}
void bt_procfs_cleanup(struct net *net, const char *name)
{
remove_proc_entry(name, net->proc_net);
}
#else
int bt_procfs_init(struct net *net, const char *name,
struct bt_sock_list* sk_list,
int (* seq_show)(struct seq_file *, void *))
{
return 0;
}
void bt_procfs_cleanup(struct net *net, const char *name)
{
}
#endif
EXPORT_SYMBOL(bt_procfs_init);
EXPORT_SYMBOL(bt_procfs_cleanup);
static struct net_proto_family bt_sock_family_ops = {
.owner = THIS_MODULE,
.family = PF_BLUETOOTH,
.create = bt_sock_create,
};
struct dentry *bt_debugfs;
EXPORT_SYMBOL_GPL(bt_debugfs);
static int __init bt_init(void)
{
int err;
BT_INFO("Core ver %s", VERSION);
bt_debugfs = debugfs_create_dir("bluetooth", NULL);
err = bt_sysfs_init();
if (err < 0)
return err;
err = sock_register(&bt_sock_family_ops);
if (err < 0) {
bt_sysfs_cleanup();
return err;
}
BT_INFO("HCI device and connection manager initialized");
err = hci_sock_init();
if (err < 0)
goto error;
err = l2cap_init();
if (err < 0)
goto sock_err;
err = sco_init();
if (err < 0) {
l2cap_exit();
goto sock_err;
}
return 0;
sock_err:
hci_sock_cleanup();
error:
sock_unregister(PF_BLUETOOTH);
bt_sysfs_cleanup();
return err;
}
static void __exit bt_exit(void)
{
sco_exit();
l2cap_exit();
hci_sock_cleanup();
sock_unregister(PF_BLUETOOTH);
bt_sysfs_cleanup();
debugfs_remove_recursive(bt_debugfs);
}
subsys_initcall(bt_init);
module_exit(bt_exit);
MODULE_AUTHOR("Marcel Holtmann <marcel@holtmann.org>");
MODULE_DESCRIPTION("Bluetooth Core ver " VERSION);
MODULE_VERSION(VERSION);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_BLUETOOTH);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_8 |
crossvul-cpp_data_bad_3580_0 | /*
* Functions related to io context handling
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/bio.h>
#include <linux/blkdev.h>
#include <linux/bootmem.h> /* for max_pfn/max_low_pfn */
#include "blk.h"
/*
* For io context allocations
*/
static struct kmem_cache *iocontext_cachep;
static void cfq_dtor(struct io_context *ioc)
{
if (!hlist_empty(&ioc->cic_list)) {
struct cfq_io_context *cic;
cic = list_entry(ioc->cic_list.first, struct cfq_io_context,
cic_list);
cic->dtor(ioc);
}
}
/*
* IO Context helper functions. put_io_context() returns 1 if there are no
* more users of this io context, 0 otherwise.
*/
int put_io_context(struct io_context *ioc)
{
if (ioc == NULL)
return 1;
BUG_ON(atomic_long_read(&ioc->refcount) == 0);
if (atomic_long_dec_and_test(&ioc->refcount)) {
rcu_read_lock();
if (ioc->aic && ioc->aic->dtor)
ioc->aic->dtor(ioc->aic);
cfq_dtor(ioc);
rcu_read_unlock();
kmem_cache_free(iocontext_cachep, ioc);
return 1;
}
return 0;
}
EXPORT_SYMBOL(put_io_context);
static void cfq_exit(struct io_context *ioc)
{
rcu_read_lock();
if (!hlist_empty(&ioc->cic_list)) {
struct cfq_io_context *cic;
cic = list_entry(ioc->cic_list.first, struct cfq_io_context,
cic_list);
cic->exit(ioc);
}
rcu_read_unlock();
}
/* Called by the exitting task */
void exit_io_context(void)
{
struct io_context *ioc;
task_lock(current);
ioc = current->io_context;
current->io_context = NULL;
task_unlock(current);
if (atomic_dec_and_test(&ioc->nr_tasks)) {
if (ioc->aic && ioc->aic->exit)
ioc->aic->exit(ioc->aic);
cfq_exit(ioc);
put_io_context(ioc);
}
}
struct io_context *alloc_io_context(gfp_t gfp_flags, int node)
{
struct io_context *ret;
ret = kmem_cache_alloc_node(iocontext_cachep, gfp_flags, node);
if (ret) {
atomic_long_set(&ret->refcount, 1);
atomic_set(&ret->nr_tasks, 1);
spin_lock_init(&ret->lock);
ret->ioprio_changed = 0;
ret->ioprio = 0;
ret->last_waited = jiffies; /* doesn't matter... */
ret->nr_batch_requests = 0; /* because this is 0 */
ret->aic = NULL;
INIT_RADIX_TREE(&ret->radix_root, GFP_ATOMIC | __GFP_HIGH);
INIT_HLIST_HEAD(&ret->cic_list);
ret->ioc_data = NULL;
}
return ret;
}
/*
* If the current task has no IO context then create one and initialise it.
* Otherwise, return its existing IO context.
*
* This returned IO context doesn't have a specifically elevated refcount,
* but since the current task itself holds a reference, the context can be
* used in general code, so long as it stays within `current` context.
*/
struct io_context *current_io_context(gfp_t gfp_flags, int node)
{
struct task_struct *tsk = current;
struct io_context *ret;
ret = tsk->io_context;
if (likely(ret))
return ret;
ret = alloc_io_context(gfp_flags, node);
if (ret) {
/* make sure set_task_ioprio() sees the settings above */
smp_wmb();
tsk->io_context = ret;
}
return ret;
}
/*
* If the current task has no IO context then create one and initialise it.
* If it does have a context, take a ref on it.
*
* This is always called in the context of the task which submitted the I/O.
*/
struct io_context *get_io_context(gfp_t gfp_flags, int node)
{
struct io_context *ret = NULL;
/*
* Check for unlikely race with exiting task. ioc ref count is
* zero when ioc is being detached.
*/
do {
ret = current_io_context(gfp_flags, node);
if (unlikely(!ret))
break;
} while (!atomic_long_inc_not_zero(&ret->refcount));
return ret;
}
EXPORT_SYMBOL(get_io_context);
void copy_io_context(struct io_context **pdst, struct io_context **psrc)
{
struct io_context *src = *psrc;
struct io_context *dst = *pdst;
if (src) {
BUG_ON(atomic_long_read(&src->refcount) == 0);
atomic_long_inc(&src->refcount);
put_io_context(dst);
*pdst = src;
}
}
EXPORT_SYMBOL(copy_io_context);
static int __init blk_ioc_init(void)
{
iocontext_cachep = kmem_cache_create("blkdev_ioc",
sizeof(struct io_context), 0, SLAB_PANIC, NULL);
return 0;
}
subsys_initcall(blk_ioc_init);
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3580_0 |
crossvul-cpp_data_bad_4783_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT IIIII FFFFF FFFFF %
% T I F F %
% T I FFF FFF %
% T I F F %
% T IIIII F F %
% %
% %
% Read/Write TIFF Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
#ifdef __VMS
#define JPEG_SUPPORT 1
#endif
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/profile.h"
#include "MagickCore/resize.h"
#include "MagickCore/resource_.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/static.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread_.h"
#include "MagickCore/token.h"
#include "MagickCore/utility.h"
#if defined(MAGICKCORE_TIFF_DELEGATE)
# if defined(MAGICKCORE_HAVE_TIFFCONF_H)
# include "tiffconf.h"
# endif
# include "tiff.h"
# include "tiffio.h"
# if !defined(COMPRESSION_ADOBE_DEFLATE)
# define COMPRESSION_ADOBE_DEFLATE 8
# endif
# if !defined(PREDICTOR_HORIZONTAL)
# define PREDICTOR_HORIZONTAL 2
# endif
# if !defined(TIFFTAG_COPYRIGHT)
# define TIFFTAG_COPYRIGHT 33432
# endif
# if !defined(TIFFTAG_OPIIMAGEID)
# define TIFFTAG_OPIIMAGEID 32781
# endif
#include "psd-private.h"
/*
Typedef declarations.
*/
typedef enum
{
ReadSingleSampleMethod,
ReadRGBAMethod,
ReadCMYKAMethod,
ReadYCCKMethod,
ReadStripMethod,
ReadTileMethod,
ReadGenericMethod
} TIFFMethodType;
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
typedef struct _ExifInfo
{
unsigned int
tag,
type,
variable_length;
const char
*property;
} ExifInfo;
static const ExifInfo
exif_info[] = {
{ EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" },
{ EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" },
{ EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" },
{ EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" },
{ EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" },
{ EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" },
{ EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" },
{ EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" },
{ EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" },
{ EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" },
{ EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" },
{ EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" },
{ EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" },
{ EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" },
{ EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" },
{ EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" },
{ EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" },
{ EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" },
{ EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" },
{ EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" },
{ EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" },
{ EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" },
{ EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" },
{ EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" },
{ EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" },
{ EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" },
{ EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" },
{ EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" },
{ EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" },
{ EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" },
{ EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" },
{ EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" },
{ EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" },
{ EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" },
{ EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" },
{ EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" },
{ EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" },
{ EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" },
{ EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" },
{ EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" },
{ EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" },
{ EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" },
{ EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" },
{ EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" },
{ EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" },
{ EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" },
{ EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" },
{ EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" },
{ EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" },
{ EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" },
{ EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" },
{ EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" },
{ EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" },
{ EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" },
{ EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" },
{ 0, 0, 0, (char *) NULL }
};
#endif
#endif /* MAGICKCORE_TIFF_DELEGATE */
/*
Global declarations.
*/
static MagickThreadKey
tiff_exception;
static SemaphoreInfo
*tiff_semaphore = (SemaphoreInfo *) NULL;
static TIFFErrorHandler
error_handler,
warning_handler;
static volatile MagickBooleanType
instantiate_key = MagickFalse;
/*
Forward declarations.
*/
#if defined(MAGICKCORE_TIFF_DELEGATE)
static Image *
ReadTIFFImage(const ImageInfo *,ExceptionInfo *);
static MagickBooleanType
WriteGROUP4Image(const ImageInfo *,Image *,ExceptionInfo *),
WritePTIFImage(const ImageInfo *,Image *,ExceptionInfo *),
WriteTIFFImage(const ImageInfo *,Image *,ExceptionInfo *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s T I F F %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsTIFF() returns MagickTrue if the image format type, identified by the
% magick string, is TIFF.
%
% The format of the IsTIFF method is:
%
% MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\115\115\000\052",4) == 0)
return(MagickTrue);
if (memcmp(magick,"\111\111\052\000",4) == 0)
return(MagickTrue);
#if defined(TIFF_VERSION_BIG)
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0)
return(MagickTrue);
if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0)
return(MagickTrue);
#endif
return(MagickFalse);
}
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d G R O U P 4 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadGROUP4Image() reads a raw CCITT Group 4 image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadGROUP4Image method is:
%
% Image *ReadGROUP4Image(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline size_t WriteLSBLong(FILE *file,const size_t value)
{
unsigned char
buffer[4];
buffer[0]=(unsigned char) value;
buffer[1]=(unsigned char) (value >> 8);
buffer[2]=(unsigned char) (value >> 16);
buffer[3]=(unsigned char) (value >> 24);
return(fwrite(buffer,1,4,file));
}
static Image *ReadGROUP4Image(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MagickPathExtent];
FILE
*file;
Image
*image;
ImageInfo
*read_info;
int
c,
unique_file;
MagickBooleanType
status;
size_t
length;
ssize_t
offset,
strip_offset;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Write raw CCITT Group 4 wrapped as a TIFF image file.
*/
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file);
length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file);
length=fwrite("\000\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->columns);
length=fwrite("\001\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->rows);
length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file);
length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file);
length=fwrite("\021\001\003\000\001\000\000\000",1,8,file);
strip_offset=10+(12*14)+4+8;
length=WriteLSBLong(file,(size_t) strip_offset);
length=fwrite("\022\001\003\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) image_info->orientation);
length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
length=fwrite("\026\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->rows);
length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file);
offset=(ssize_t) ftell(file)-4;
length=fwrite("\032\001\005\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) (strip_offset-8));
length=fwrite("\033\001\005\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) (strip_offset-8));
length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file);
length=fwrite("\000\000\000\000",1,4,file);
length=WriteLSBLong(file,(long) image->resolution.x);
length=WriteLSBLong(file,1);
for (length=0; (c=ReadBlobByte(image)) != EOF; length++)
(void) fputc(c,file);
offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET);
length=WriteLSBLong(file,(unsigned int) length);
(void) fclose(file);
(void) CloseBlob(image);
image=DestroyImage(image);
/*
Read TIFF image.
*/
read_info=CloneImageInfo((ImageInfo *) NULL);
(void) FormatLocaleString(read_info->filename,MagickPathExtent,"%s",filename);
image=ReadTIFFImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
{
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick,"GROUP4",MagickPathExtent);
}
(void) RelinquishUniqueFileResource(filename);
return(image);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTIFFImage() reads a Tagged image file and returns it. It allocates the
% memory necessary for the new Image structure and returns a pointer to the
% new image.
%
% The format of the ReadTIFFImage method is:
%
% Image *ReadTIFFImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline unsigned char ClampYCC(double value)
{
value=255.0-value;
if (value < 0.0)
return((unsigned char)0);
if (value > 255.0)
return((unsigned char)255);
return((unsigned char)(value));
}
static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
a,
b;
a=QuantumScale*GetPixela(image,q)+0.5;
if (a > 1.0)
a-=1.0;
b=QuantumScale*GetPixelb(image,q)+0.5;
if (b > 1.0)
b-=1.0;
SetPixela(image,QuantumRange*a,q);
SetPixelb(image,QuantumRange*b,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
static MagickBooleanType ReadProfile(Image *image,const char *name,
const unsigned char *datum,ssize_t length,ExceptionInfo *exception)
{
MagickBooleanType
status;
StringInfo
*profile;
if (length < 4)
return(MagickFalse);
profile=BlobToStringInfo(datum,(size_t) length);
if (profile == (StringInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=SetImageProfile(image,name,profile,exception);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
return(MagickTrue);
}
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int TIFFCloseBlob(thandle_t image)
{
(void) CloseBlob((Image *) image);
return(0);
}
static void TIFFErrors(const char *module,const char *format,va_list error)
{
char
message[MagickPathExtent];
ExceptionInfo
*exception;
#if defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsnprintf(message,MagickPathExtent,format,error);
#else
(void) vsprintf(message,format,error);
#endif
(void) ConcatenateMagickString(message,".",MagickPathExtent);
exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
if (exception != (ExceptionInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,message,
"`%s'",module);
}
static toff_t TIFFGetBlobSize(thandle_t image)
{
return((toff_t) GetBlobSize((Image *) image));
}
static void TIFFGetProfiles(TIFF *tiff,Image *image,MagickBooleanType ping,
ExceptionInfo *exception)
{
uint32
length;
unsigned char
*profile;
length=0;
if (ping == MagickFalse)
{
#if defined(TIFFTAG_ICCPROFILE)
if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"icc",profile,(ssize_t) length,exception);
#endif
#if defined(TIFFTAG_PHOTOSHOP)
if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"8bim",profile,(ssize_t) length,exception);
#endif
#if defined(TIFFTAG_RICHTIFFIPTC)
if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
{
if (TIFFIsByteSwapped(tiff) != 0)
TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length);
(void) ReadProfile(image,"iptc",profile,4L*length,exception);
}
#endif
#if defined(TIFFTAG_XMLPACKET)
if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"xmp",profile,(ssize_t) length,exception);
#endif
if ((TIFFGetField(tiff,34118,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length,
exception);
}
if ((TIFFGetField(tiff,37724,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length,exception);
}
static void TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception)
{
char
message[MagickPathExtent],
*text;
uint32
count,
length,
type;
unsigned long
*tietz;
if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1)
(void) SetImageProperty(image,"tiff:artist",text,exception);
if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1)
(void) SetImageProperty(image,"tiff:copyright",text,exception);
if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1)
(void) SetImageProperty(image,"tiff:timestamp",text,exception);
if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1)
(void) SetImageProperty(image,"tiff:document",text,exception);
if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1)
(void) SetImageProperty(image,"tiff:hostcomputer",text,exception);
if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1)
(void) SetImageProperty(image,"comment",text,exception);
if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1)
(void) SetImageProperty(image,"tiff:make",text,exception);
if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1)
(void) SetImageProperty(image,"tiff:model",text,exception);
if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1)
{
if (count >= MagickPathExtent)
count=MagickPathExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:image-id",message,exception);
}
if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1)
(void) SetImageProperty(image,"label",text,exception);
if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1)
(void) SetImageProperty(image,"tiff:software",text,exception);
if (TIFFGetField(tiff,33423,&count,&text) == 1)
{
if (count >= MagickPathExtent)
count=MagickPathExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:kodak-33423",message,exception);
}
if (TIFFGetField(tiff,36867,&count,&text) == 1)
{
if (count >= MagickPathExtent)
count=MagickPathExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:kodak-36867",message,exception);
}
if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1)
switch (type)
{
case 0x01:
{
(void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE",
exception);
break;
}
case 0x02:
{
(void) SetImageProperty(image,"tiff:subfiletype","PAGE",exception);
break;
}
case 0x04:
{
(void) SetImageProperty(image,"tiff:subfiletype","MASK",exception);
break;
}
default:
break;
}
if (TIFFGetField(tiff,37706,&length,&tietz) == 1)
{
(void) FormatLocaleString(message,MagickPathExtent,"%lu",tietz[0]);
(void) SetImageProperty(image,"tiff:tietz_offset",message,exception);
}
}
static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
ExceptionInfo *exception)
{
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
char
value[MagickPathExtent];
register ssize_t
i;
tdir_t
directory;
#if defined(TIFF_VERSION_BIG)
uint64
#else
uint32
#endif
offset;
void
*sans;
/*
Read EXIF properties.
*/
offset=0;
if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1)
return;
directory=TIFFCurrentDirectory(tiff);
if (TIFFReadEXIFDirectory(tiff,offset) != 1)
{
TIFFSetDirectory(tiff,directory);
return;
}
sans=NULL;
for (i=0; exif_info[i].tag != 0; i++)
{
*value='\0';
switch (exif_info[i].type)
{
case TIFF_ASCII:
{
char
*ascii;
ascii=(char *) NULL;
if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,&sans,&sans) == 1) &&
(ascii != (char *) NULL) && (*ascii != '\0'))
(void) CopyMagickString(value,ascii,MagickPathExtent);
break;
}
case TIFF_SHORT:
{
if (exif_info[i].variable_length == 0)
{
uint16
shorty;
shorty=0;
if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) == 1)
(void) FormatLocaleString(value,MagickPathExtent,"%d",shorty);
}
else
{
int
tiff_status;
uint16
*shorty;
uint16
shorty_num;
tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty,
&sans,&sans);
if (tiff_status == 1)
(void) FormatLocaleString(value,MagickPathExtent,"%d",
shorty_num != 0 ? shorty[0] : 0);
}
break;
}
case TIFF_LONG:
{
uint32
longy;
longy=0;
if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) == 1)
(void) FormatLocaleString(value,MagickPathExtent,"%d",longy);
break;
}
#if defined(TIFF_VERSION_BIG)
case TIFF_LONG8:
{
uint64
long8y;
long8y=0;
if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) == 1)
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
((MagickOffsetType) long8y));
break;
}
#endif
case TIFF_RATIONAL:
case TIFF_SRATIONAL:
case TIFF_FLOAT:
{
float
floaty;
floaty=0.0;
if (TIFFGetField(tiff,exif_info[i].tag,&floaty,&sans,&sans) == 1)
(void) FormatLocaleString(value,MagickPathExtent,"%g",(double)
floaty);
break;
}
case TIFF_DOUBLE:
{
double
doubley;
doubley=0.0;
if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) == 1)
(void) FormatLocaleString(value,MagickPathExtent,"%g",doubley);
break;
}
default:
break;
}
if (*value != '\0')
(void) SetImageProperty(image,exif_info[i].property,value,exception);
}
TIFFSetDirectory(tiff,directory);
#else
(void) tiff;
(void) image;
#endif
}
static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size)
{
*base=(tdata_t *) GetBlobStreamData((Image *) image);
if (*base != (tdata_t *) NULL)
*size=(toff_t) GetBlobSize((Image *) image);
if (*base != (tdata_t *) NULL)
return(1);
return(0);
}
static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size)
{
tsize_t
count;
count=(tsize_t) ReadBlob((Image *) image,(size_t) size,
(unsigned char *) data);
return(count);
}
static int32 TIFFReadPixels(TIFF *tiff,size_t bits_per_sample,
tsample_t sample,ssize_t row,tdata_t scanline)
{
int32
status;
(void) bits_per_sample;
status=TIFFReadScanline(tiff,scanline,(uint32) row,sample);
return(status);
}
static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence)
{
return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence));
}
static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size)
{
(void) image;
(void) base;
(void) size;
}
static void TIFFWarnings(const char *module,const char *format,va_list warning)
{
char
message[MagickPathExtent];
ExceptionInfo
*exception;
#if defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsnprintf(message,MagickPathExtent,format,warning);
#else
(void) vsprintf(message,format,warning);
#endif
(void) ConcatenateMagickString(message,".",MagickPathExtent);
exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
if (exception != (ExceptionInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
message,"`%s'",module);
}
static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size)
{
tsize_t
count;
count=(tsize_t) WriteBlob((Image *) image,(size_t) size,
(unsigned char *) data);
return(count);
}
static TIFFMethodType GetJPEGMethod(Image* image,TIFF *tiff,uint16 photometric,
uint16 bits_per_sample,uint16 samples_per_pixel)
{
#define BUFFER_SIZE 2048
MagickOffsetType
position,
offset;
register size_t
i;
TIFFMethodType
method;
#if defined(TIFF_VERSION_BIG)
uint64
#else
uint32
#endif
**value;
unsigned char
buffer[BUFFER_SIZE+32];
unsigned short
length;
/* only support 8 bit for now */
if ((photometric != PHOTOMETRIC_SEPARATED) || (bits_per_sample != 8) ||
(samples_per_pixel != 4))
return(ReadGenericMethod);
/* Search for Adobe APP14 JPEG Marker */
if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value))
return(ReadRGBAMethod);
position=TellBlob(image);
offset=(MagickOffsetType) (value[0]);
if (SeekBlob(image,offset,SEEK_SET) != offset)
return(ReadRGBAMethod);
method=ReadRGBAMethod;
if (ReadBlob(image,BUFFER_SIZE,buffer) == BUFFER_SIZE)
{
for (i=0; i < BUFFER_SIZE; i++)
{
while (i < BUFFER_SIZE)
{
if (buffer[i++] == 255)
break;
}
while (i < BUFFER_SIZE)
{
if (buffer[++i] != 255)
break;
}
if (buffer[i++] == 216) /* JPEG_MARKER_SOI */
continue;
length=(unsigned short) (((unsigned int) (buffer[i] << 8) |
(unsigned int) buffer[i+1]) & 0xffff);
if (i+(size_t) length >= BUFFER_SIZE)
break;
if (buffer[i-1] == 238) /* JPEG_MARKER_APP0+14 */
{
if (length != 14)
break;
/* 0 == CMYK, 1 == YCbCr, 2 = YCCK */
if (buffer[i+13] == 2)
method=ReadYCCKMethod;
break;
}
i+=(size_t) length;
}
}
(void) SeekBlob(image,position,SEEK_SET);
return(method);
}
static void TIFFReadPhotoshopLayers(Image* image,const ImageInfo *image_info,
ExceptionInfo *exception)
{
const char
*option;
const StringInfo
*layer_info;
Image
*layers;
PSDInfo
info;
register ssize_t
i;
if (GetImageListLength(image) != 1)
return;
if ((image_info->number_scenes == 1) && (image_info->scene == 0))
return;
option=GetImageOption(image_info,"tiff:ignore-layers");
if (option != (const char * ) NULL)
return;
layer_info=GetImageProfile(image,"tiff:37724");
if (layer_info == (const StringInfo *) NULL)
return;
for (i=0; i < (ssize_t) layer_info->length-8; i++)
{
if (LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0)
continue;
i+=4;
if ((LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) ||
(LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) ||
(LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) ||
(LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0))
break;
}
i+=4;
if (i >= (ssize_t) (layer_info->length-8))
return;
layers=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
(void) DeleteImageProfile(layers,"tiff:37724");
AttachBlob(layers->blob,layer_info->datum,layer_info->length);
SeekBlob(layers,(MagickOffsetType) i,SEEK_SET);
info.version=1;
info.columns=layers->columns;
info.rows=layers->rows;
info.channels=(unsigned short) layers->number_channels;
/* Setting the mode to a value that won't change the colorspace */
info.mode=10;
ReadPSDLayers(layers,image_info,&info,MagickFalse,exception);
DeleteImageFromList(&layers);
if (layers != (Image *) NULL)
{
SetImageArtifact(image,"tiff:has-layers","true");
AppendImageToList(&image,layers);
while (layers != (Image *) NULL)
{
SetImageArtifact(layers,"tiff:has-layers","true");
DetachBlob(layers->blob);
layers=GetNextImageInList(layers);
}
}
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static Image *ReadTIFFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
const char
*option;
float
*chromaticity,
x_position,
y_position,
x_resolution,
y_resolution;
Image
*image;
int
tiff_status;
MagickBooleanType
status;
MagickSizeType
number_pixels;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
pad;
ssize_t
y;
TIFF
*tiff;
TIFFMethodType
method;
uint16
compress_tag,
bits_per_sample,
endian,
extra_samples,
interlace,
max_sample_value,
min_sample_value,
orientation,
pages,
photometric,
*sample_info,
sample_format,
samples_per_pixel,
units,
value;
uint32
height,
rows_per_strip,
width;
unsigned char
*pixels;
/*
Open image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) SetMagickThreadValue(tiff_exception,exception);
tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (image_info->number_scenes != 0)
{
/*
Generate blank images for subimage specification (e.g. image.tif[4].
We need to check the number of directores because it is possible that
the subimage(s) are stored in the photoshop profile.
*/
if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff))
{
for (i=0; i < (ssize_t) image_info->scene; i++)
{
status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
if (status == MagickFalse)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
}
}
}
do
{
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
TIFFPrintDirectory(tiff,stdout,MagickFalse);
RestoreMSCWarning
if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||
(TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1))
{
TIFFClose(tiff);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (sample_format == SAMPLEFORMAT_IEEEFP)
(void) SetImageProperty(image,"quantum:format","floating-point",
exception);
switch (photometric)
{
case PHOTOMETRIC_MINISBLACK:
{
(void) SetImageProperty(image,"tiff:photometric","min-is-black",
exception);
break;
}
case PHOTOMETRIC_MINISWHITE:
{
(void) SetImageProperty(image,"tiff:photometric","min-is-white",
exception);
break;
}
case PHOTOMETRIC_PALETTE:
{
(void) SetImageProperty(image,"tiff:photometric","palette",exception);
break;
}
case PHOTOMETRIC_RGB:
{
(void) SetImageProperty(image,"tiff:photometric","RGB",exception);
break;
}
case PHOTOMETRIC_CIELAB:
{
(void) SetImageProperty(image,"tiff:photometric","CIELAB",exception);
break;
}
case PHOTOMETRIC_LOGL:
{
(void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)",
exception);
break;
}
case PHOTOMETRIC_LOGLUV:
{
(void) SetImageProperty(image,"tiff:photometric","LOGLUV",exception);
break;
}
#if defined(PHOTOMETRIC_MASK)
case PHOTOMETRIC_MASK:
{
(void) SetImageProperty(image,"tiff:photometric","MASK",exception);
break;
}
#endif
case PHOTOMETRIC_SEPARATED:
{
(void) SetImageProperty(image,"tiff:photometric","separated",exception);
break;
}
case PHOTOMETRIC_YCBCR:
{
(void) SetImageProperty(image,"tiff:photometric","YCBCR",exception);
break;
}
default:
{
(void) SetImageProperty(image,"tiff:photometric","unknown",exception);
break;
}
}
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u",
(unsigned int) width,(unsigned int) height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u",
interlace);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Bits per sample: %u",bits_per_sample);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Min sample value: %u",min_sample_value);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Max sample value: %u",max_sample_value);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
"interpretation: %s",GetImageProperty(image,"tiff:photometric",
exception));
}
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=(size_t) bits_per_sample;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
(double) image->depth);
image->endian=MSBEndian;
if (endian == FILLORDER_LSB2MSB)
image->endian=LSBEndian;
#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)
if (TIFFIsBigEndian(tiff) == 0)
{
(void) SetImageProperty(image,"tiff:endian","lsb",exception);
image->endian=LSBEndian;
}
else
{
(void) SetImageProperty(image,"tiff:endian","msb",exception);
image->endian=MSBEndian;
}
#endif
if ((photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
SetImageColorspace(image,GRAYColorspace,exception);
if (photometric == PHOTOMETRIC_SEPARATED)
SetImageColorspace(image,CMYKColorspace,exception);
if (photometric == PHOTOMETRIC_CIELAB)
SetImageColorspace(image,LabColorspace,exception);
TIFFGetProfiles(tiff,image,image_info->ping,exception);
TIFFGetProperties(tiff,image,exception);
option=GetImageOption(image_info,"tiff:exif-properties");
if (IsStringFalse(option) == MagickFalse) /* enabled by default */
TIFFGetEXIFProperties(tiff,image,exception);
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
&samples_per_pixel);
if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) &&
(TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1))
{
image->resolution.x=x_resolution;
image->resolution.y=y_resolution;
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1)
{
if (units == RESUNIT_INCH)
image->units=PixelsPerInchResolution;
if (units == RESUNIT_CENTIMETER)
image->units=PixelsPerCentimeterResolution;
}
if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) &&
(TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1))
{
image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5);
image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5);
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1)
image->orientation=(OrientationType) orientation;
if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)
{
if (chromaticity != (float *) NULL)
{
image->chromaticity.white_point.x=chromaticity[0];
image->chromaticity.white_point.y=chromaticity[1];
}
}
if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)
{
if (chromaticity != (float *) NULL)
{
image->chromaticity.red_primary.x=chromaticity[0];
image->chromaticity.red_primary.y=chromaticity[1];
image->chromaticity.green_primary.x=chromaticity[2];
image->chromaticity.green_primary.y=chromaticity[3];
image->chromaticity.blue_primary.x=chromaticity[4];
image->chromaticity.blue_primary.y=chromaticity[5];
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
TIFFClose(tiff);
ThrowReaderException(CoderError,"CompressNotSupported");
}
#endif
switch (compress_tag)
{
case COMPRESSION_NONE: image->compression=NoCompression; break;
case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;
case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;
case COMPRESSION_JPEG:
{
image->compression=JPEGCompression;
#if defined(JPEG_SUPPORT)
{
char
sampling_factor[MagickPathExtent];
int
tiff_status;
uint16
horizontal,
vertical;
tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING,
&horizontal,&vertical);
if (tiff_status == 1)
{
(void) FormatLocaleString(sampling_factor,MagickPathExtent,
"%dx%d",horizontal,vertical);
(void) SetImageProperty(image,"jpeg:sampling-factor",
sampling_factor,exception);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling Factors: %s",sampling_factor);
}
}
#endif
break;
}
case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;
#if defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA: image->compression=LZMACompression; break;
#endif
case COMPRESSION_LZW: image->compression=LZWCompression; break;
case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;
case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;
default: image->compression=RLECompression; break;
}
/*
Allocate memory for the image and pixel buffer.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (sample_format == SAMPLEFORMAT_UINT)
status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);
if (sample_format == SAMPLEFORMAT_INT)
status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);
if (sample_format == SAMPLEFORMAT_IEEEFP)
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
{
TIFFClose(tiff);
quantum_info=DestroyQuantumInfo(quantum_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
status=MagickTrue;
switch (photometric)
{
case PHOTOMETRIC_MINISBLACK:
{
quantum_info->min_is_white=MagickFalse;
break;
}
case PHOTOMETRIC_MINISWHITE:
{
quantum_info->min_is_white=MagickTrue;
break;
}
default:
break;
}
tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,
&sample_info);
if (tiff_status == 1)
{
(void) SetImageProperty(image,"tiff:alpha","unspecified",exception);
if (extra_samples == 0)
{
if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))
image->alpha_trait=BlendPixelTrait;
}
else
for (i=0; i < extra_samples; i++)
{
image->alpha_trait=BlendPixelTrait;
if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)
{
SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);
(void) SetImageProperty(image,"tiff:alpha","associated",
exception);
}
else
if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)
(void) SetImageProperty(image,"tiff:alpha","unassociated",
exception);
}
}
if ((photometric == PHOTOMETRIC_PALETTE) &&
(pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
{
size_t
colors;
colors=(size_t) GetQuantumRange(bits_per_sample)+1;
if (AcquireImageColormap(image,colors,exception) == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
value=(unsigned short) image->scene;
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1)
image->scene=value;
if (image->storage_class == PseudoClass)
{
int
tiff_status;
size_t
range;
uint16
*blue_colormap,
*green_colormap,
*red_colormap;
/*
Initialize colormap.
*/
tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
&green_colormap,&blue_colormap);
if (tiff_status == 1)
{
if ((red_colormap != (uint16 *) NULL) &&
(green_colormap != (uint16 *) NULL) &&
(blue_colormap != (uint16 *) NULL))
{
range=255; /* might be old style 8-bit colormap */
for (i=0; i < (ssize_t) image->colors; i++)
if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||
(blue_colormap[i] >= 256))
{
range=65535;
break;
}
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ClampToQuantum(((double)
QuantumRange*red_colormap[i])/range);
image->colormap[i].green=ClampToQuantum(((double)
QuantumRange*green_colormap[i])/range);
image->colormap[i].blue=ClampToQuantum(((double)
QuantumRange*blue_colormap[i])/range);
}
}
}
if (image->alpha_trait == UndefinedPixelTrait)
image->depth=GetImageDepth(image,exception);
}
if (image_info->ping != MagickFalse)
{
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
{
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
goto next_tiff_frame;
}
method=ReadGenericMethod;
if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)
{
char
value[MagickPathExtent];
method=ReadStripMethod;
(void) FormatLocaleString(value,MagickPathExtent,"%u",
(unsigned int) rows_per_strip);
(void) SetImageProperty(image,"tiff:rows-per-strip",value,exception);
}
if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG))
method=ReadRGBAMethod;
if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE))
method=ReadCMYKAMethod;
if ((photometric != PHOTOMETRIC_RGB) &&
(photometric != PHOTOMETRIC_CIELAB) &&
(photometric != PHOTOMETRIC_SEPARATED))
method=ReadGenericMethod;
if (image->storage_class == PseudoClass)
method=ReadSingleSampleMethod;
if ((photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
method=ReadSingleSampleMethod;
if ((photometric != PHOTOMETRIC_SEPARATED) &&
(interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))
method=ReadGenericMethod;
if (image->compression == JPEGCompression)
method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,
samples_per_pixel);
if (compress_tag == COMPRESSION_JBIG)
method=ReadStripMethod;
if (TIFFIsTiled(tiff) != MagickFalse)
method=ReadTileMethod;
quantum_info->endian=LSBEndian;
quantum_type=RGBQuantum;
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
switch (method)
{
case ReadSingleSampleMethod:
{
/*
Convert TIFF image to PseudoClass MIFF image.
*/
quantum_type=IndexQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
if (image->alpha_trait != UndefinedPixelTrait)
{
if (image->storage_class != PseudoClass)
{
quantum_type=samples_per_pixel == 1 ? AlphaQuantum :
GrayAlphaQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
}
else
{
quantum_type=IndexAlphaQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
}
}
else
if (image->storage_class != PseudoClass)
{
quantum_type=GrayQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
}
status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
if (status == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register Quantum
*magick_restrict q;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadRGBAMethod:
{
/*
Convert TIFF image to DirectClass MIFF image.
*/
pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);
quantum_type=RGBQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
{
quantum_type=RGBAQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
}
if (image->colorspace == CMYKColorspace)
{
pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
quantum_type=CMYKQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
{
quantum_type=CMYKAQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);
}
}
status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
if (status == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register Quantum
*magick_restrict q;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadCMYKAMethod:
{
/*
Convert TIFF image to DirectClass MIFF image.
*/
for (i=0; i < (ssize_t) samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
int
status;
status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)
pixels);
if (status == -1)
break;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
if (image->colorspace != CMYKColorspace)
switch (i)
{
case 0: quantum_type=RedQuantum; break;
case 1: quantum_type=GreenQuantum; break;
case 2: quantum_type=BlueQuantum; break;
case 3: quantum_type=AlphaQuantum; break;
default: quantum_type=UndefinedQuantum; break;
}
else
switch (i)
{
case 0: quantum_type=CyanQuantum; break;
case 1: quantum_type=MagentaQuantum; break;
case 2: quantum_type=YellowQuantum; break;
case 3: quantum_type=BlackQuantum; break;
case 4: quantum_type=AlphaQuantum; break;
default: quantum_type=UndefinedQuantum; break;
}
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadYCCKMethod:
{
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register Quantum
*magick_restrict q;
register ssize_t
x;
unsigned char
*p;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
p=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+
(1.402*(double) *(p+2))-179.456)),q);
SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p-
(0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+
135.45984)),q);
SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+
(1.772*(double) *(p+1))-226.816)),q);
SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q);
q+=GetPixelChannels(image);
p+=4;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadStripMethod:
{
register uint32
*p;
/*
Convert stripped TIFF image to DirectClass MIFF image.
*/
i=0;
p=(uint32 *) NULL;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
if (i == 0)
{
if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0)
break;
i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
image->rows-y);
}
i--;
p=((uint32 *) pixels)+image->columns*i;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
(TIFFGetR(*p))),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
(TIFFGetG(*p))),q);
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
(TIFFGetB(*p))),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
(TIFFGetA(*p))),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadTileMethod:
{
register uint32
*p;
uint32
*tile_pixels,
columns,
rows;
/*
Convert tiled TIFF image to DirectClass MIFF image.
*/
if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||
(TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))
{
TIFFClose(tiff);
ThrowReaderException(CoderError,"ImageIsNotTiled");
}
(void) SetImageStorageClass(image,DirectClass,exception);
number_pixels=(MagickSizeType) columns*rows;
if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t)
(number_pixels*sizeof(uint32))))
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
tile_pixels=(uint32 *) AcquireQuantumMemory(columns,
rows*sizeof(*tile_pixels));
if (tile_pixels == (uint32 *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (y=0; y < (ssize_t) image->rows; y+=rows)
{
register ssize_t
x;
register Quantum
*magick_restrict q,
*magick_restrict tile;
size_t
columns_remaining,
rows_remaining;
rows_remaining=image->rows-y;
if ((ssize_t) (y+rows) < (ssize_t) image->rows)
rows_remaining=rows;
tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,
exception);
if (tile == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x+=columns)
{
size_t
column,
row;
if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)
break;
columns_remaining=image->columns-x;
if ((ssize_t) (x+columns) < (ssize_t) image->columns)
columns_remaining=columns;
p=tile_pixels+(rows-rows_remaining)*columns;
q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+
x);
for (row=rows_remaining; row > 0; row--)
{
if (image->alpha_trait != UndefinedPixelTrait)
for (column=columns_remaining; column > 0; column--)
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)),q);
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)),q);
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
TIFFGetA(*p)),q);
p++;
q+=GetPixelChannels(image);
}
else
for (column=columns_remaining; column > 0; column--)
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)),q);
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)),q);
p++;
q+=GetPixelChannels(image);
}
p+=columns-columns_remaining;
q-=GetPixelChannels(image)*(image->columns+columns_remaining);
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);
break;
}
case ReadGenericMethod:
default:
{
MemoryInfo
*pixel_info;
register uint32
*p;
uint32
*pixels;
/*
Convert TIFF image to DirectClass MIFF image.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t)
(number_pixels*sizeof(uint32))))
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
sizeof(uint32));
if (pixel_info == (MemoryInfo *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);
(void) TIFFReadRGBAImage(tiff,(uint32) image->columns,
(uint32) image->rows,(uint32 *) pixels,0);
/*
Convert image to DirectClass pixel packets.
*/
p=pixels+number_pixels-1;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
q+=GetPixelChannels(image)*(image->columns-1);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)),q);
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
TIFFGetA(*p)),q);
p--;
q-=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
break;
}
}
SetQuantumImageType(image,quantum_type);
next_tiff_frame:
quantum_info=DestroyQuantumInfo(quantum_info);
if (photometric == PHOTOMETRIC_CIELAB)
DecodeLabImage(image,exception);
if ((photometric == PHOTOMETRIC_LOGL) ||
(photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
{
image->type=GrayscaleType;
if (bits_per_sample == 1)
image->type=BilevelType;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
if (status != MagickFalse)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,image->scene-1,
image->scene);
if (status == MagickFalse)
break;
}
} while (status != MagickFalse);
TIFFClose(tiff);
TIFFReadPhotoshopLayers(image,image_info,exception);
if (image_info->number_scenes != 0)
{
if (image_info->scene >= GetImageListLength(image))
{
/* Subimage was not found in the Photoshop layer */
image=DestroyImageList(image);
return((Image *)NULL);
}
}
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterTIFFImage() adds properties for the TIFF image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterTIFFImage method is:
%
% size_t RegisterTIFFImage(void)
%
*/
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
static TIFFExtendProc
tag_extender = (TIFFExtendProc) NULL;
static void TIFFIgnoreTags(TIFF *tiff)
{
char
*q;
const char
*p,
*tags;
Image
*image;
register ssize_t
i;
size_t
count;
TIFFFieldInfo
*ignore;
if (TIFFGetReadProc(tiff) != TIFFReadBlob)
return;
image=(Image *)TIFFClientdata(tiff);
tags=GetImageArtifact(image,"tiff:ignore-tags");
if (tags == (const char *) NULL)
return;
count=0;
p=tags;
while (*p != '\0')
{
while ((isspace((int) ((unsigned char) *p)) != 0))
p++;
(void) strtol(p,&q,10);
if (p == q)
return;
p=q;
count++;
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
p++;
}
if (count == 0)
return;
i=0;
p=tags;
ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore));
/* This also sets field_bit to 0 (FIELD_IGNORE) */
ResetMagickMemory(ignore,0,count*sizeof(*ignore));
while (*p != '\0')
{
while ((isspace((int) ((unsigned char) *p)) != 0))
p++;
ignore[i].field_tag=(ttag_t) strtol(p,&q,10);
p=q;
i++;
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
p++;
}
(void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count);
ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore);
}
static void TIFFTagExtender(TIFF *tiff)
{
static const TIFFFieldInfo
TIFFExtensions[] =
{
{ 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
(char *) "PhotoshopLayerData" },
{ 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
(char *) "Microscope" }
};
TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/
sizeof(*TIFFExtensions));
if (tag_extender != (TIFFExtendProc) NULL)
(*tag_extender)(tiff);
TIFFIgnoreTags(tiff);
}
#endif
ModuleExport size_t RegisterTIFFImage(void)
{
#define TIFFDescription "Tagged Image File Format"
char
version[MagickPathExtent];
MagickInfo
*entry;
if (tiff_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&tiff_semaphore);
LockSemaphoreInfo(tiff_semaphore);
if (instantiate_key == MagickFalse)
{
if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
error_handler=TIFFSetErrorHandler(TIFFErrors);
warning_handler=TIFFSetWarningHandler(TIFFWarnings);
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
if (tag_extender == (TIFFExtendProc) NULL)
tag_extender=TIFFSetTagExtender(TIFFTagExtender);
#endif
instantiate_key=MagickTrue;
}
UnlockSemaphoreInfo(tiff_semaphore);
*version='\0';
#if defined(TIFF_VERSION)
(void) FormatLocaleString(version,MagickPathExtent,"%d",TIFF_VERSION);
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
{
const char
*p;
register ssize_t
i;
p=TIFFGetVersion();
for (i=0; (i < (MagickPathExtent-1)) && (*p != 0) && (*p != '\n'); i++)
version[i]=(*p++);
version[i]='\0';
}
#endif
entry=AcquireMagickInfo("TIFF","GROUP4","Raw CCITT Group4");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadGROUP4Image;
entry->encoder=(EncodeImageHandler *) WriteGROUP4Image;
#endif
entry->flags|=CoderRawSupportFlag;
entry->flags|=CoderEndianSupportFlag;
entry->flags|=CoderSeekableStreamFlag;
entry->flags^=CoderAdjoinFlag;
entry->flags^=CoderUseExtensionFlag;
entry->format_type=ImplicitFormatType;
entry->mime_type=ConstantString("image/tiff");
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("TIFF","PTIF","Pyramid encoded TIFF");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WritePTIFImage;
#endif
entry->flags|=CoderEndianSupportFlag;
entry->flags|=CoderSeekableStreamFlag;
entry->flags^=CoderUseExtensionFlag;
entry->mime_type=ConstantString("image/tiff");
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("TIFF","TIF",TIFFDescription);
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->flags|=CoderEndianSupportFlag;
entry->flags|=CoderSeekableStreamFlag;
entry->flags|=CoderStealthFlag;
entry->flags^=CoderUseExtensionFlag;
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("TIFF","TIFF",TIFFDescription);
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->magick=(IsImageFormatHandler *) IsTIFF;
entry->flags|=CoderEndianSupportFlag;
entry->flags|=CoderSeekableStreamFlag;
entry->flags^=CoderUseExtensionFlag;
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("TIFF","TIFF64","Tagged Image File Format (64-bit)");
#if defined(TIFF_VERSION_BIG)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->flags|=CoderEndianSupportFlag;
entry->flags|=CoderSeekableStreamFlag;
entry->flags^=CoderAdjoinFlag;
entry->flags^=CoderUseExtensionFlag;
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterTIFFImage() removes format registrations made by the TIFF module
% from the list of supported formats.
%
% The format of the UnregisterTIFFImage method is:
%
% UnregisterTIFFImage(void)
%
*/
ModuleExport void UnregisterTIFFImage(void)
{
(void) UnregisterMagickInfo("TIFF64");
(void) UnregisterMagickInfo("TIFF");
(void) UnregisterMagickInfo("TIF");
(void) UnregisterMagickInfo("PTIF");
if (tiff_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&tiff_semaphore);
LockSemaphoreInfo(tiff_semaphore);
if (instantiate_key != MagickFalse)
{
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
if (tag_extender == (TIFFExtendProc) NULL)
(void) TIFFSetTagExtender(tag_extender);
#endif
if (DeleteMagickThreadKey(tiff_exception) == MagickFalse)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) TIFFSetWarningHandler(warning_handler);
(void) TIFFSetErrorHandler(error_handler);
instantiate_key=MagickFalse;
}
UnlockSemaphoreInfo(tiff_semaphore);
RelinquishSemaphoreInfo(&tiff_semaphore);
}
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e G R O U P 4 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format.
%
% The format of the WriteGROUP4Image method is:
%
% MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
% Image *image,ExceptionInfo *)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
char
filename[MagickPathExtent];
FILE
*file;
Image
*huffman_image;
ImageInfo
*write_info;
int
unique_file;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count;
TIFF
*tiff;
toff_t
*byte_count,
strip_size;
unsigned char
*buffer;
/*
Write image as CCITT Group4 TIFF image to a temporary file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
huffman_image=CloneImage(image,0,0,MagickTrue,exception);
if (huffman_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
huffman_image->endian=MSBEndian;
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
filename);
return(MagickFalse);
}
(void) FormatLocaleString(huffman_image->filename,MagickPathExtent,"tiff:%s",
filename);
(void) SetImageType(huffman_image,BilevelType,exception);
write_info=CloneImageInfo((ImageInfo *) NULL);
SetImageInfoFile(write_info,file);
(void) SetImageType(image,BilevelType,exception);
(void) SetImageDepth(image,1,exception);
write_info->compression=Group4Compression;
write_info->type=BilevelType;
(void) SetImageOption(write_info,"quantum:polarity","min-is-white");
status=WriteTIFFImage(write_info,huffman_image,exception);
(void) fflush(file);
write_info=DestroyImageInfo(write_info);
if (status == MagickFalse)
{
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
return(MagickFalse);
}
tiff=TIFFOpen(filename,"rb");
if (tiff == (TIFF *) NULL)
{
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
image_info->filename);
return(MagickFalse);
}
/*
Allocate raw strip buffer.
*/
if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1)
{
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
return(MagickFalse);
}
strip_size=byte_count[0];
for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
if (byte_count[i] > strip_size)
strip_size=byte_count[i];
buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size,
sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
{
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image_info->filename);
}
/*
Compress runlength encoded to 2D Huffman pixels.
*/
for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
{
count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size);
if (WriteBlob(image,(size_t) count,buffer) != count)
status=MagickFalse;
}
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
(void) CloseBlob(image);
return(status);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P T I F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file
% format.
%
% The format of the WritePTIFImage method is:
%
% MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
Image
*images,
*next,
*pyramid_image;
ImageInfo
*write_info;
MagickBooleanType
status;
PointInfo
resolution;
size_t
columns,
rows;
/*
Create pyramid-encoded TIFF image.
*/
images=NewImageList();
for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
{
Image
*clone_image;
clone_image=CloneImage(next,0,0,MagickFalse,exception);
if (clone_image == (Image *) NULL)
break;
clone_image->previous=NewImageList();
clone_image->next=NewImageList();
(void) SetImageProperty(clone_image,"tiff:subfiletype","none",exception);
AppendImageToList(&images,clone_image);
columns=next->columns;
rows=next->rows;
resolution=next->resolution;
while ((columns > 64) && (rows > 64))
{
columns/=2;
rows/=2;
resolution.x/=2;
resolution.y/=2;
pyramid_image=ResizeImage(next,columns,rows,image->filter,exception);
if (pyramid_image == (Image *) NULL)
break;
pyramid_image->resolution=resolution;
(void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE",
exception);
AppendImageToList(&images,pyramid_image);
}
}
images=GetFirstImageInList(images);
/*
Write pyramid-encoded TIFF image.
*/
write_info=CloneImageInfo(image_info);
write_info->adjoin=MagickTrue;
(void) CopyMagickString(write_info->magick,"TIFF",MagickPathExtent);
(void) CopyMagickString(images->magick,"TIFF",MagickPathExtent);
status=WriteTIFFImage(write_info,images,exception);
images=DestroyImageList(images);
write_info=DestroyImageInfo(write_info);
return(status);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% W r i t e T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteTIFFImage() writes an image in the Tagged image file format.
%
% The format of the WriteTIFFImage method is:
%
% MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef struct _TIFFInfo
{
RectangleInfo
tile_geometry;
unsigned char
*scanline,
*scanlines,
*pixels;
} TIFFInfo;
static void DestroyTIFFInfo(TIFFInfo *tiff_info)
{
assert(tiff_info != (TIFFInfo *) NULL);
if (tiff_info->scanlines != (unsigned char *) NULL)
tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory(
tiff_info->scanlines);
if (tiff_info->pixels != (unsigned char *) NULL)
tiff_info->pixels=(unsigned char *) RelinquishMagickMemory(
tiff_info->pixels);
}
static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
a,
b;
a=QuantumScale*GetPixela(image,q)-0.5;
if (a < 0.0)
a+=1.0;
b=QuantumScale*GetPixelb(image,q)-0.5;
if (b < 0.0)
b+=1.0;
SetPixela(image,QuantumRange*a,q);
SetPixelb(image,QuantumRange*b,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,
TIFF *tiff,TIFFInfo *tiff_info)
{
const char
*option;
MagickStatusType
flags;
uint32
tile_columns,
tile_rows;
assert(tiff_info != (TIFFInfo *) NULL);
(void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info));
option=GetImageOption(image_info,"tiff:tile-geometry");
if (option == (const char *) NULL)
return(MagickTrue);
flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry);
if ((flags & HeightValue) == 0)
tiff_info->tile_geometry.height=tiff_info->tile_geometry.width;
tile_columns=(uint32) tiff_info->tile_geometry.width;
tile_rows=(uint32) tiff_info->tile_geometry.height;
TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows);
(void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns);
(void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows);
tiff_info->tile_geometry.width=tile_columns;
tiff_info->tile_geometry.height=tile_rows;
tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t)
tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines));
tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t)
tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines));
if ((tiff_info->scanlines == (unsigned char *) NULL) ||
(tiff_info->pixels == (unsigned char *) NULL))
{
DestroyTIFFInfo(tiff_info);
return(MagickFalse);
}
return(MagickTrue);
}
static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row,
tsample_t sample,Image *image)
{
int32
status;
register ssize_t
i;
register unsigned char
*p,
*q;
size_t
number_tiles,
tile_width;
ssize_t
bytes_per_pixel,
j,
k,
l;
if (TIFFIsTiled(tiff) == 0)
return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample));
/*
Fill scanlines to tile height.
*/
i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff);
(void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline,
(size_t) TIFFScanlineSize(tiff));
if (((size_t) (row % tiff_info->tile_geometry.height) !=
(tiff_info->tile_geometry.height-1)) &&
(row != (ssize_t) (image->rows-1)))
return(0);
/*
Write tile to TIFF image.
*/
status=0;
bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (
tiff_info->tile_geometry.height*tiff_info->tile_geometry.width);
number_tiles=(image->columns+tiff_info->tile_geometry.width)/
tiff_info->tile_geometry.width;
for (i=0; i < (ssize_t) number_tiles; i++)
{
tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i*
tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width;
for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++)
for (k=0; k < (ssize_t) tile_width; k++)
{
if (bytes_per_pixel == 0)
{
p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
tiff_info->tile_geometry.width+k)/8);
q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8);
*q++=(*p++);
continue;
}
p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
tiff_info->tile_geometry.width+k)*bytes_per_pixel);
q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel);
for (l=0; l < bytes_per_pixel; l++)
*q++=(*p++);
}
if ((i*tiff_info->tile_geometry.width) != image->columns)
status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i*
tiff_info->tile_geometry.width),(uint32) ((row/
tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0,
sample);
if (status < 0)
break;
}
return(status);
}
static void TIFFSetProfiles(TIFF *tiff,Image *image)
{
const char
*name;
const StringInfo
*profile;
if (image->profiles == (void *) NULL)
return;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (GetStringInfoLength(profile) == 0)
{
name=GetNextImageProfile(image);
continue;
}
#if defined(TIFFTAG_XMLPACKET)
if (LocaleCompare(name,"xmp") == 0)
(void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength(
profile),GetStringInfoDatum(profile));
#endif
#if defined(TIFFTAG_ICCPROFILE)
if (LocaleCompare(name,"icc") == 0)
(void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength(
profile),GetStringInfoDatum(profile));
#endif
if (LocaleCompare(name,"iptc") == 0)
{
size_t
length;
StringInfo
*iptc_profile;
iptc_profile=CloneStringInfo(profile);
length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) &
0x03);
SetStringInfoLength(iptc_profile,length);
if (TIFFIsByteSwapped(tiff))
TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile),
(unsigned long) (length/4));
(void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32)
GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile));
iptc_profile=DestroyStringInfo(iptc_profile);
}
#if defined(TIFFTAG_PHOTOSHOP)
if (LocaleCompare(name,"8bim") == 0)
(void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32)
GetStringInfoLength(profile),GetStringInfoDatum(profile));
#endif
if (LocaleCompare(name,"tiff:37724") == 0)
(void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile),
GetStringInfoDatum(profile));
if (LocaleCompare(name,"tiff:34118") == 0)
(void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile),
GetStringInfoDatum(profile));
name=GetNextImageProfile(image);
}
}
static void TIFFSetProperties(TIFF *tiff,const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
const char
*value;
value=GetImageArtifact(image,"tiff:document");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value);
value=GetImageArtifact(image,"tiff:hostcomputer");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value);
value=GetImageArtifact(image,"tiff:artist");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_ARTIST,value);
value=GetImageArtifact(image,"tiff:timestamp");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_DATETIME,value);
value=GetImageArtifact(image,"tiff:make");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_MAKE,value);
value=GetImageArtifact(image,"tiff:model");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_MODEL,value);
value=GetImageArtifact(image,"tiff:software");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value);
value=GetImageArtifact(image,"tiff:copyright");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value);
value=GetImageArtifact(image,"kodak-33423");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,33423,value);
value=GetImageArtifact(image,"kodak-36867");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,36867,value);
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value);
value=GetImageProperty(image,"comment",exception);
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value);
value=GetImageArtifact(image,"tiff:subfiletype");
if (value != (const char *) NULL)
{
if (LocaleCompare(value,"REDUCEDIMAGE") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
else
if (LocaleCompare(value,"PAGE") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
else
if (LocaleCompare(value,"MASK") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK);
}
else
{
uint16
page,
pages;
page=(uint16) image->scene;
pages=(uint16) GetImageListLength(image);
if ((image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
}
static void TIFFSetEXIFProperties(TIFF *tiff,Image *image,
ExceptionInfo *exception)
{
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
const char
*value;
register ssize_t
i;
uint32
offset;
/*
Write EXIF properties.
*/
offset=0;
(void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset);
for (i=0; exif_info[i].tag != 0; i++)
{
value=GetImageProperty(image,exif_info[i].property,exception);
if (value == (const char *) NULL)
continue;
switch (exif_info[i].type)
{
case TIFF_ASCII:
{
(void) TIFFSetField(tiff,exif_info[i].tag,value);
break;
}
case TIFF_SHORT:
{
uint16
field;
field=(uint16) StringToLong(value);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
case TIFF_LONG:
{
uint16
field;
field=(uint16) StringToLong(value);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
case TIFF_RATIONAL:
case TIFF_SRATIONAL:
{
float
field;
field=StringToDouble(value,(char **) NULL);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
default:
break;
}
}
/* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */
#else
(void) tiff;
(void) image;
#endif
}
static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
#if !defined(TIFFDefaultStripSize)
#define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff))
#endif
const char
*mode,
*option;
CompressionType
compression;
EndianType
endian_type;
MagickBooleanType
debug,
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
length;
ssize_t
y;
TIFF
*tiff;
TIFFInfo
tiff_info;
uint16
bits_per_sample,
compress_tag,
endian,
photometric;
uint32
rows_per_strip;
unsigned char
*pixels;
/*
Open TIFF file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
(void) SetMagickThreadValue(tiff_exception,exception);
endian_type=UndefinedEndian;
option=GetImageOption(image_info,"tiff:endian");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian_type=MSBEndian;
if (LocaleNCompare(option,"lsb",3) == 0)
endian_type=LSBEndian;;
}
switch (endian_type)
{
case LSBEndian: mode="wl"; break;
case MSBEndian: mode="wb"; break;
default: mode="w"; break;
}
#if defined(TIFF_VERSION_BIG)
if (LocaleCompare(image_info->magick,"TIFF64") == 0)
switch (endian_type)
{
case LSBEndian: mode="wl8"; break;
case MSBEndian: mode="wb8"; break;
default: mode="w8"; break;
}
#endif
tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
return(MagickFalse);
scene=0;
debug=IsEventLogging();
(void) debug;
do
{
/*
Initialize TIFF fields.
*/
if ((image_info->type != UndefinedType) &&
(image_info->type != OptimizeType))
(void) SetImageType(image,image_info->type,exception);
compression=UndefinedCompression;
if (image->compression != JPEGCompression)
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
(void) SetImageType(image,BilevelType,exception);
(void) SetImageDepth(image,1,exception);
break;
}
case JPEGCompression:
{
(void) SetImageStorageClass(image,DirectClass,exception);
(void) SetImageDepth(image,8,exception);
break;
}
default:
break;
}
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
(quantum_info->format == UndefinedQuantumFormat) &&
(IsHighDynamicRangeImage(image,exception) != MagickFalse))
{
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
(GetPreviousImageInList(image) != (Image *) NULL))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
if ((image->columns != (uint32) image->columns) ||
(image->rows != (uint32) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
(void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
(void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
switch (compression)
{
case FaxCompression:
{
compress_tag=COMPRESSION_CCITTFAX3;
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
case Group4Compression:
{
compress_tag=COMPRESSION_CCITTFAX4;
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
#if defined(COMPRESSION_JBIG)
case JBIG1Compression:
{
compress_tag=COMPRESSION_JBIG;
break;
}
#endif
case JPEGCompression:
{
compress_tag=COMPRESSION_JPEG;
break;
}
#if defined(COMPRESSION_LZMA)
case LZMACompression:
{
compress_tag=COMPRESSION_LZMA;
break;
}
#endif
case LZWCompression:
{
compress_tag=COMPRESSION_LZW;
break;
}
case RLECompression:
{
compress_tag=COMPRESSION_PACKBITS;
break;
}
case ZipCompression:
{
compress_tag=COMPRESSION_ADOBE_DEFLATE;
break;
}
case NoCompression:
default:
{
compress_tag=COMPRESSION_NONE;
break;
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
compression=NoCompression;
}
#else
switch (compress_tag)
{
#if defined(CCITT_SUPPORT)
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
#endif
#if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
case COMPRESSION_JPEG:
#endif
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
#endif
#if defined(LZW_SUPPORT)
case COMPRESSION_LZW:
#endif
#if defined(PACKBITS_SUPPORT)
case COMPRESSION_PACKBITS:
#endif
#if defined(ZIP_SUPPORT)
case COMPRESSION_ADOBE_DEFLATE:
#endif
case COMPRESSION_NONE:
break;
default:
{
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
compression=NoCompression;
break;
}
}
#endif
if (image->colorspace == CMYKColorspace)
{
photometric=PHOTOMETRIC_SEPARATED;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
(void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
}
else
{
/*
Full color TIFF raster.
*/
if (image->colorspace == LabColorspace)
{
photometric=PHOTOMETRIC_CIELAB;
EncodeLabImage(image,exception);
}
else
if (image->colorspace == YCbCrColorspace)
{
photometric=PHOTOMETRIC_YCBCR;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
(void) SetImageStorageClass(image,DirectClass,exception);
(void) SetImageDepth(image,8,exception);
}
else
photometric=PHOTOMETRIC_RGB;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
if ((image_info->type != TrueColorType) &&
(image_info->type != TrueColorAlphaType))
{
if ((image_info->type != PaletteType) &&
(SetImageGray(image,exception) != MagickFalse))
{
photometric=(uint16) (quantum_info->min_is_white !=
MagickFalse ? PHOTOMETRIC_MINISWHITE :
PHOTOMETRIC_MINISBLACK);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
if ((image->depth == 1) &&
(image->alpha_trait == UndefinedPixelTrait))
SetImageMonochrome(image,exception);
}
else
if (image->storage_class == PseudoClass)
{
size_t
depth;
/*
Colormapped TIFF raster.
*/
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
photometric=PHOTOMETRIC_PALETTE;
depth=1;
while ((GetQuantumRange(depth)+1) < image->colors)
depth<<=1;
status=SetQuantumDepth(image,quantum_info,depth);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
if ((compress_tag == COMPRESSION_CCITTFAX3) &&
(photometric != PHOTOMETRIC_MINISWHITE))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
else
if ((compress_tag == COMPRESSION_CCITTFAX4) &&
(photometric != PHOTOMETRIC_MINISWHITE))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
option=GetImageOption(image_info,"tiff:fill-order");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian=FILLORDER_MSB2LSB;
if (LocaleNCompare(option,"lsb",3) == 0)
endian=FILLORDER_LSB2MSB;
}
(void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
(void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
(void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
if (image->alpha_trait != UndefinedPixelTrait)
{
uint16
extra_samples,
sample_info[1],
samples_per_pixel;
/*
TIFF has a matte channel.
*/
extra_samples=1;
sample_info[0]=EXTRASAMPLE_UNASSALPHA;
option=GetImageOption(image_info,"tiff:alpha");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"associated") == 0)
sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
else
if (LocaleCompare(option,"unspecified") == 0)
sample_info[0]=EXTRASAMPLE_UNSPECIFIED;
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
&samples_per_pixel);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
(void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
&sample_info);
if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
}
(void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
switch (quantum_info->format)
{
case FloatingPointQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
(void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
(void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
break;
}
case SignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
break;
}
case UnsignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
break;
}
default:
break;
}
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
if (photometric == PHOTOMETRIC_RGB)
if ((image_info->interlace == PlaneInterlace) ||
(image_info->interlace == PartitionInterlace))
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
rows_per_strip=TIFFDefaultStripSize(tiff,0);
option=GetImageOption(image_info,"tiff:rows-per-strip");
if (option != (const char *) NULL)
rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
switch (compress_tag)
{
case COMPRESSION_JPEG:
{
#if defined(JPEG_SUPPORT)
const char
*sampling_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
rows_per_strip+=(16-(rows_per_strip % 16));
if (image_info->quality != UndefinedCompressionQuality)
(void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
{
const char
*value;
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
sampling_factor=(const char *) NULL;
value=GetImageProperty(image,"jpeg:sampling-factor",exception);
if (value != (char *) NULL)
{
sampling_factor=value;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Input sampling-factors=%s",sampling_factor);
}
if (image_info->sampling_factor != (char *) NULL)
sampling_factor=image_info->sampling_factor;
if (sampling_factor != (const char *) NULL)
{
flags=ParseGeometry(sampling_factor,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
if (image->colorspace == YCbCrColorspace)
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
geometry_info.rho,(uint16) geometry_info.sigma);
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (bits_per_sample == 12)
(void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
#endif
break;
}
case COMPRESSION_ADOBE_DEFLATE:
{
rows_per_strip=(uint32) image->rows;
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
(void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
case COMPRESSION_CCITTFAX3:
{
/*
Byte-aligned EOL.
*/
rows_per_strip=(uint32) image->rows;
(void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
break;
}
case COMPRESSION_CCITTFAX4:
{
rows_per_strip=(uint32) image->rows;
break;
}
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
{
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
(void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
#endif
case COMPRESSION_LZW:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
break;
}
default:
break;
}
if (rows_per_strip < 1)
rows_per_strip=1;
if ((image->rows/rows_per_strip) >= (1UL << 15))
rows_per_strip=(uint32) (image->rows >> 15);
(void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0))
{
unsigned short
units;
/*
Set image resolution.
*/
units=RESUNIT_NONE;
if (image->units == PixelsPerInchResolution)
units=RESUNIT_INCH;
if (image->units == PixelsPerCentimeterResolution)
units=RESUNIT_CENTIMETER;
(void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
(void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->resolution.x);
(void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->resolution.y);
if ((image->page.x < 0) || (image->page.y < 0))
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"TIFF: negative image positions unsupported","%s",image->filename);
if ((image->page.x > 0) && (image->resolution.x > 0.0))
{
/*
Set horizontal image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
image->resolution.x);
}
if ((image->page.y > 0) && (image->resolution.y > 0.0))
{
/*
Set vertical image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
image->resolution.y);
}
}
if (image->chromaticity.white_point.x != 0.0)
{
float
chromaticity[6];
/*
Set image chromaticity.
*/
chromaticity[0]=(float) image->chromaticity.red_primary.x;
chromaticity[1]=(float) image->chromaticity.red_primary.y;
chromaticity[2]=(float) image->chromaticity.green_primary.x;
chromaticity[3]=(float) image->chromaticity.green_primary.y;
chromaticity[4]=(float) image->chromaticity.blue_primary.x;
chromaticity[5]=(float) image->chromaticity.blue_primary.y;
(void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
chromaticity[0]=(float) image->chromaticity.white_point.x;
chromaticity[1]=(float) image->chromaticity.white_point.y;
(void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
}
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1))
{
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
if (image->scene != 0)
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
GetImageListLength(image));
}
if (image->orientation != UndefinedOrientation)
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
(void) TIFFSetProfiles(tiff,image);
{
uint16
page,
pages;
page=(uint16) scene;
pages=(uint16) GetImageListLength(image);
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
(void) TIFFSetProperties(tiff,image_info,image,exception);
DisableMSCWarning(4127)
if (0)
RestoreMSCWarning
(void) TIFFSetEXIFProperties(tiff,image,exception);
/*
Write image scanlines.
*/
if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->endian=LSBEndian;
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
tiff_info.scanline=(unsigned char *) GetQuantumPixels(quantum_info);
switch (photometric)
{
case PHOTOMETRIC_CIELAB:
case PHOTOMETRIC_YCBCR:
case PHOTOMETRIC_RGB:
{
/*
RGB TIFF image.
*/
switch (image_info->interlace)
{
case NoInterlace:
default:
{
quantum_type=RGBQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=RGBAQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) length;
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PlaneInterlace:
case PartitionInterlace:
{
/*
Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
RedQuantum,pixels,exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,100,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GreenQuantum,pixels,exception);
if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,200,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
BlueQuantum,pixels,exception);
if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,300,400);
if (status == MagickFalse)
break;
}
if (image->alpha_trait != UndefinedPixelTrait)
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,exception);
if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,400,400);
if (status == MagickFalse)
break;
}
break;
}
}
break;
}
case PHOTOMETRIC_SEPARATED:
{
/*
CMYK TIFF image.
*/
quantum_type=CMYKQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=CMYKAQuantum;
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PHOTOMETRIC_PALETTE:
{
uint16
*blue,
*green,
*red;
/*
Colormapped TIFF image.
*/
red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
(blue == (uint16 *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize TIFF colormap.
*/
(void) ResetMagickMemory(red,0,65536*sizeof(*red));
(void) ResetMagickMemory(green,0,65536*sizeof(*green));
(void) ResetMagickMemory(blue,0,65536*sizeof(*blue));
for (i=0; i < (ssize_t) image->colors; i++)
{
red[i]=ScaleQuantumToShort(image->colormap[i].red);
green[i]=ScaleQuantumToShort(image->colormap[i].green);
blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
}
(void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
red=(uint16 *) RelinquishMagickMemory(red);
green=(uint16 *) RelinquishMagickMemory(green);
blue=(uint16 *) RelinquishMagickMemory(blue);
}
default:
{
/*
Convert PseudoClass packets to contiguous grayscale scanlines.
*/
quantum_type=IndexQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
{
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayAlphaQuantum;
else
quantum_type=IndexAlphaQuantum;
}
else
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (image->colorspace == LabColorspace)
DecodeLabImage(image,exception);
DestroyTIFFInfo(&tiff_info);
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
RestoreMSCWarning
TIFFPrintDirectory(tiff,stdout,MagickFalse);
(void) TIFFWriteDirectory(tiff);
image=SyncNextImageInList(image);
if (image == (Image *) NULL)
break;
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
TIFFClose(tiff);
return(MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_4783_0 |
crossvul-cpp_data_bad_365_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD CCCC M M %
% D D C MM MM %
% D D C M M M %
% D D C M M %
% DDDD CCCC M M %
% %
% %
% Read DICOM Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/resource_.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/module.h"
/*
Dicom medical image declarations.
*/
typedef struct _DicomInfo
{
const unsigned short
group,
element;
const char
*vr,
*description;
} DicomInfo;
static const DicomInfo
dicom_info[] =
{
{ 0x0000, 0x0000, "UL", "Group Length" },
{ 0x0000, 0x0001, "UL", "Command Length to End" },
{ 0x0000, 0x0002, "UI", "Affected SOP Class UID" },
{ 0x0000, 0x0003, "UI", "Requested SOP Class UID" },
{ 0x0000, 0x0010, "LO", "Command Recognition Code" },
{ 0x0000, 0x0100, "US", "Command Field" },
{ 0x0000, 0x0110, "US", "Message ID" },
{ 0x0000, 0x0120, "US", "Message ID Being Responded To" },
{ 0x0000, 0x0200, "AE", "Initiator" },
{ 0x0000, 0x0300, "AE", "Receiver" },
{ 0x0000, 0x0400, "AE", "Find Location" },
{ 0x0000, 0x0600, "AE", "Move Destination" },
{ 0x0000, 0x0700, "US", "Priority" },
{ 0x0000, 0x0800, "US", "Data Set Type" },
{ 0x0000, 0x0850, "US", "Number of Matches" },
{ 0x0000, 0x0860, "US", "Response Sequence Number" },
{ 0x0000, 0x0900, "US", "Status" },
{ 0x0000, 0x0901, "AT", "Offending Element" },
{ 0x0000, 0x0902, "LO", "Exception Comment" },
{ 0x0000, 0x0903, "US", "Exception ID" },
{ 0x0000, 0x1000, "UI", "Affected SOP Instance UID" },
{ 0x0000, 0x1001, "UI", "Requested SOP Instance UID" },
{ 0x0000, 0x1002, "US", "Event Type ID" },
{ 0x0000, 0x1005, "AT", "Attribute Identifier List" },
{ 0x0000, 0x1008, "US", "Action Type ID" },
{ 0x0000, 0x1020, "US", "Number of Remaining Suboperations" },
{ 0x0000, 0x1021, "US", "Number of Completed Suboperations" },
{ 0x0000, 0x1022, "US", "Number of Failed Suboperations" },
{ 0x0000, 0x1023, "US", "Number of Warning Suboperations" },
{ 0x0000, 0x1030, "AE", "Move Originator Application Entity Title" },
{ 0x0000, 0x1031, "US", "Move Originator Message ID" },
{ 0x0000, 0x4000, "LO", "Dialog Receiver" },
{ 0x0000, 0x4010, "LO", "Terminal Type" },
{ 0x0000, 0x5010, "SH", "Message Set ID" },
{ 0x0000, 0x5020, "SH", "End Message Set" },
{ 0x0000, 0x5110, "LO", "Display Format" },
{ 0x0000, 0x5120, "LO", "Page Position ID" },
{ 0x0000, 0x5130, "LO", "Text Format ID" },
{ 0x0000, 0x5140, "LO", "Normal Reverse" },
{ 0x0000, 0x5150, "LO", "Add Gray Scale" },
{ 0x0000, 0x5160, "LO", "Borders" },
{ 0x0000, 0x5170, "IS", "Copies" },
{ 0x0000, 0x5180, "LO", "OldMagnificationType" },
{ 0x0000, 0x5190, "LO", "Erase" },
{ 0x0000, 0x51a0, "LO", "Print" },
{ 0x0000, 0x51b0, "US", "Overlays" },
{ 0x0002, 0x0000, "UL", "Meta Element Group Length" },
{ 0x0002, 0x0001, "OB", "File Meta Information Version" },
{ 0x0002, 0x0002, "UI", "Media Storage SOP Class UID" },
{ 0x0002, 0x0003, "UI", "Media Storage SOP Instance UID" },
{ 0x0002, 0x0010, "UI", "Transfer Syntax UID" },
{ 0x0002, 0x0012, "UI", "Implementation Class UID" },
{ 0x0002, 0x0013, "SH", "Implementation Version Name" },
{ 0x0002, 0x0016, "AE", "Source Application Entity Title" },
{ 0x0002, 0x0100, "UI", "Private Information Creator UID" },
{ 0x0002, 0x0102, "OB", "Private Information" },
{ 0x0003, 0x0000, "US", "?" },
{ 0x0003, 0x0008, "US", "ISI Command Field" },
{ 0x0003, 0x0011, "US", "Attach ID Application Code" },
{ 0x0003, 0x0012, "UL", "Attach ID Message Count" },
{ 0x0003, 0x0013, "DA", "Attach ID Date" },
{ 0x0003, 0x0014, "TM", "Attach ID Time" },
{ 0x0003, 0x0020, "US", "Message Type" },
{ 0x0003, 0x0030, "DA", "Max Waiting Date" },
{ 0x0003, 0x0031, "TM", "Max Waiting Time" },
{ 0x0004, 0x0000, "UL", "File Set Group Length" },
{ 0x0004, 0x1130, "CS", "File Set ID" },
{ 0x0004, 0x1141, "CS", "File Set Descriptor File ID" },
{ 0x0004, 0x1142, "CS", "File Set Descriptor File Specific Character Set" },
{ 0x0004, 0x1200, "UL", "Root Directory Entity First Directory Record Offset" },
{ 0x0004, 0x1202, "UL", "Root Directory Entity Last Directory Record Offset" },
{ 0x0004, 0x1212, "US", "File Set Consistency Flag" },
{ 0x0004, 0x1220, "SQ", "Directory Record Sequence" },
{ 0x0004, 0x1400, "UL", "Next Directory Record Offset" },
{ 0x0004, 0x1410, "US", "Record In Use Flag" },
{ 0x0004, 0x1420, "UL", "Referenced Lower Level Directory Entity Offset" },
{ 0x0004, 0x1430, "CS", "Directory Record Type" },
{ 0x0004, 0x1432, "UI", "Private Record UID" },
{ 0x0004, 0x1500, "CS", "Referenced File ID" },
{ 0x0004, 0x1504, "UL", "MRDR Directory Record Offset" },
{ 0x0004, 0x1510, "UI", "Referenced SOP Class UID In File" },
{ 0x0004, 0x1511, "UI", "Referenced SOP Instance UID In File" },
{ 0x0004, 0x1512, "UI", "Referenced Transfer Syntax UID In File" },
{ 0x0004, 0x1600, "UL", "Number of References" },
{ 0x0005, 0x0000, "US", "?" },
{ 0x0006, 0x0000, "US", "?" },
{ 0x0008, 0x0000, "UL", "Identifying Group Length" },
{ 0x0008, 0x0001, "UL", "Length to End" },
{ 0x0008, 0x0005, "CS", "Specific Character Set" },
{ 0x0008, 0x0008, "CS", "Image Type" },
{ 0x0008, 0x0010, "LO", "Recognition Code" },
{ 0x0008, 0x0012, "DA", "Instance Creation Date" },
{ 0x0008, 0x0013, "TM", "Instance Creation Time" },
{ 0x0008, 0x0014, "UI", "Instance Creator UID" },
{ 0x0008, 0x0016, "UI", "SOP Class UID" },
{ 0x0008, 0x0018, "UI", "SOP Instance UID" },
{ 0x0008, 0x0020, "DA", "Study Date" },
{ 0x0008, 0x0021, "DA", "Series Date" },
{ 0x0008, 0x0022, "DA", "Acquisition Date" },
{ 0x0008, 0x0023, "DA", "Image Date" },
{ 0x0008, 0x0024, "DA", "Overlay Date" },
{ 0x0008, 0x0025, "DA", "Curve Date" },
{ 0x0008, 0x002A, "DT", "Acquisition DateTime" },
{ 0x0008, 0x0030, "TM", "Study Time" },
{ 0x0008, 0x0031, "TM", "Series Time" },
{ 0x0008, 0x0032, "TM", "Acquisition Time" },
{ 0x0008, 0x0033, "TM", "Image Time" },
{ 0x0008, 0x0034, "TM", "Overlay Time" },
{ 0x0008, 0x0035, "TM", "Curve Time" },
{ 0x0008, 0x0040, "xs", "Old Data Set Type" },
{ 0x0008, 0x0041, "xs", "Old Data Set Subtype" },
{ 0x0008, 0x0042, "CS", "Nuclear Medicine Series Type" },
{ 0x0008, 0x0050, "SH", "Accession Number" },
{ 0x0008, 0x0052, "CS", "Query/Retrieve Level" },
{ 0x0008, 0x0054, "AE", "Retrieve AE Title" },
{ 0x0008, 0x0058, "UI", "Failed SOP Instance UID List" },
{ 0x0008, 0x0060, "CS", "Modality" },
{ 0x0008, 0x0062, "SQ", "Modality Subtype" },
{ 0x0008, 0x0064, "CS", "Conversion Type" },
{ 0x0008, 0x0068, "CS", "Presentation Intent Type" },
{ 0x0008, 0x0070, "LO", "Manufacturer" },
{ 0x0008, 0x0080, "LO", "Institution Name" },
{ 0x0008, 0x0081, "ST", "Institution Address" },
{ 0x0008, 0x0082, "SQ", "Institution Code Sequence" },
{ 0x0008, 0x0090, "PN", "Referring Physician's Name" },
{ 0x0008, 0x0092, "ST", "Referring Physician's Address" },
{ 0x0008, 0x0094, "SH", "Referring Physician's Telephone Numbers" },
{ 0x0008, 0x0100, "SH", "Code Value" },
{ 0x0008, 0x0102, "SH", "Coding Scheme Designator" },
{ 0x0008, 0x0103, "SH", "Coding Scheme Version" },
{ 0x0008, 0x0104, "LO", "Code Meaning" },
{ 0x0008, 0x0105, "CS", "Mapping Resource" },
{ 0x0008, 0x0106, "DT", "Context Group Version" },
{ 0x0008, 0x010b, "CS", "Code Set Extension Flag" },
{ 0x0008, 0x010c, "UI", "Private Coding Scheme Creator UID" },
{ 0x0008, 0x010d, "UI", "Code Set Extension Creator UID" },
{ 0x0008, 0x010f, "CS", "Context Identifier" },
{ 0x0008, 0x1000, "LT", "Network ID" },
{ 0x0008, 0x1010, "SH", "Station Name" },
{ 0x0008, 0x1030, "LO", "Study Description" },
{ 0x0008, 0x1032, "SQ", "Procedure Code Sequence" },
{ 0x0008, 0x103e, "LO", "Series Description" },
{ 0x0008, 0x1040, "LO", "Institutional Department Name" },
{ 0x0008, 0x1048, "PN", "Physician of Record" },
{ 0x0008, 0x1050, "PN", "Performing Physician's Name" },
{ 0x0008, 0x1060, "PN", "Name of Physician(s) Reading Study" },
{ 0x0008, 0x1070, "PN", "Operator's Name" },
{ 0x0008, 0x1080, "LO", "Admitting Diagnosis Description" },
{ 0x0008, 0x1084, "SQ", "Admitting Diagnosis Code Sequence" },
{ 0x0008, 0x1090, "LO", "Manufacturer's Model Name" },
{ 0x0008, 0x1100, "SQ", "Referenced Results Sequence" },
{ 0x0008, 0x1110, "SQ", "Referenced Study Sequence" },
{ 0x0008, 0x1111, "SQ", "Referenced Study Component Sequence" },
{ 0x0008, 0x1115, "SQ", "Referenced Series Sequence" },
{ 0x0008, 0x1120, "SQ", "Referenced Patient Sequence" },
{ 0x0008, 0x1125, "SQ", "Referenced Visit Sequence" },
{ 0x0008, 0x1130, "SQ", "Referenced Overlay Sequence" },
{ 0x0008, 0x1140, "SQ", "Referenced Image Sequence" },
{ 0x0008, 0x1145, "SQ", "Referenced Curve Sequence" },
{ 0x0008, 0x1148, "SQ", "Referenced Previous Waveform" },
{ 0x0008, 0x114a, "SQ", "Referenced Simultaneous Waveforms" },
{ 0x0008, 0x114c, "SQ", "Referenced Subsequent Waveform" },
{ 0x0008, 0x1150, "UI", "Referenced SOP Class UID" },
{ 0x0008, 0x1155, "UI", "Referenced SOP Instance UID" },
{ 0x0008, 0x1160, "IS", "Referenced Frame Number" },
{ 0x0008, 0x1195, "UI", "Transaction UID" },
{ 0x0008, 0x1197, "US", "Failure Reason" },
{ 0x0008, 0x1198, "SQ", "Failed SOP Sequence" },
{ 0x0008, 0x1199, "SQ", "Referenced SOP Sequence" },
{ 0x0008, 0x2110, "CS", "Old Lossy Image Compression" },
{ 0x0008, 0x2111, "ST", "Derivation Description" },
{ 0x0008, 0x2112, "SQ", "Source Image Sequence" },
{ 0x0008, 0x2120, "SH", "Stage Name" },
{ 0x0008, 0x2122, "IS", "Stage Number" },
{ 0x0008, 0x2124, "IS", "Number of Stages" },
{ 0x0008, 0x2128, "IS", "View Number" },
{ 0x0008, 0x2129, "IS", "Number of Event Timers" },
{ 0x0008, 0x212a, "IS", "Number of Views in Stage" },
{ 0x0008, 0x2130, "DS", "Event Elapsed Time(s)" },
{ 0x0008, 0x2132, "LO", "Event Timer Name(s)" },
{ 0x0008, 0x2142, "IS", "Start Trim" },
{ 0x0008, 0x2143, "IS", "Stop Trim" },
{ 0x0008, 0x2144, "IS", "Recommended Display Frame Rate" },
{ 0x0008, 0x2200, "CS", "Transducer Position" },
{ 0x0008, 0x2204, "CS", "Transducer Orientation" },
{ 0x0008, 0x2208, "CS", "Anatomic Structure" },
{ 0x0008, 0x2218, "SQ", "Anatomic Region Sequence" },
{ 0x0008, 0x2220, "SQ", "Anatomic Region Modifier Sequence" },
{ 0x0008, 0x2228, "SQ", "Primary Anatomic Structure Sequence" },
{ 0x0008, 0x2230, "SQ", "Primary Anatomic Structure Modifier Sequence" },
{ 0x0008, 0x2240, "SQ", "Transducer Position Sequence" },
{ 0x0008, 0x2242, "SQ", "Transducer Position Modifier Sequence" },
{ 0x0008, 0x2244, "SQ", "Transducer Orientation Sequence" },
{ 0x0008, 0x2246, "SQ", "Transducer Orientation Modifier Sequence" },
{ 0x0008, 0x2251, "SQ", "Anatomic Structure Space Or Region Code Sequence" },
{ 0x0008, 0x2253, "SQ", "Anatomic Portal Of Entrance Code Sequence" },
{ 0x0008, 0x2255, "SQ", "Anatomic Approach Direction Code Sequence" },
{ 0x0008, 0x2256, "ST", "Anatomic Perspective Description" },
{ 0x0008, 0x2257, "SQ", "Anatomic Perspective Code Sequence" },
{ 0x0008, 0x2258, "ST", "Anatomic Location Of Examining Instrument Description" },
{ 0x0008, 0x2259, "SQ", "Anatomic Location Of Examining Instrument Code Sequence" },
{ 0x0008, 0x225a, "SQ", "Anatomic Structure Space Or Region Modifier Code Sequence" },
{ 0x0008, 0x225c, "SQ", "OnAxis Background Anatomic Structure Code Sequence" },
{ 0x0008, 0x4000, "LT", "Identifying Comments" },
{ 0x0009, 0x0000, "xs", "?" },
{ 0x0009, 0x0001, "xs", "?" },
{ 0x0009, 0x0002, "xs", "?" },
{ 0x0009, 0x0003, "xs", "?" },
{ 0x0009, 0x0004, "xs", "?" },
{ 0x0009, 0x0005, "UN", "?" },
{ 0x0009, 0x0006, "UN", "?" },
{ 0x0009, 0x0007, "UN", "?" },
{ 0x0009, 0x0008, "xs", "?" },
{ 0x0009, 0x0009, "LT", "?" },
{ 0x0009, 0x000a, "IS", "?" },
{ 0x0009, 0x000b, "IS", "?" },
{ 0x0009, 0x000c, "IS", "?" },
{ 0x0009, 0x000d, "IS", "?" },
{ 0x0009, 0x000e, "IS", "?" },
{ 0x0009, 0x000f, "UN", "?" },
{ 0x0009, 0x0010, "xs", "?" },
{ 0x0009, 0x0011, "xs", "?" },
{ 0x0009, 0x0012, "xs", "?" },
{ 0x0009, 0x0013, "xs", "?" },
{ 0x0009, 0x0014, "xs", "?" },
{ 0x0009, 0x0015, "xs", "?" },
{ 0x0009, 0x0016, "xs", "?" },
{ 0x0009, 0x0017, "LT", "?" },
{ 0x0009, 0x0018, "LT", "Data Set Identifier" },
{ 0x0009, 0x001a, "US", "?" },
{ 0x0009, 0x001e, "UI", "?" },
{ 0x0009, 0x0020, "xs", "?" },
{ 0x0009, 0x0021, "xs", "?" },
{ 0x0009, 0x0022, "SH", "User Orientation" },
{ 0x0009, 0x0023, "SL", "Initiation Type" },
{ 0x0009, 0x0024, "xs", "?" },
{ 0x0009, 0x0025, "xs", "?" },
{ 0x0009, 0x0026, "xs", "?" },
{ 0x0009, 0x0027, "xs", "?" },
{ 0x0009, 0x0029, "xs", "?" },
{ 0x0009, 0x002a, "SL", "?" },
{ 0x0009, 0x002c, "LO", "Series Comments" },
{ 0x0009, 0x002d, "SL", "Track Beat Average" },
{ 0x0009, 0x002e, "FD", "Distance Prescribed" },
{ 0x0009, 0x002f, "LT", "?" },
{ 0x0009, 0x0030, "xs", "?" },
{ 0x0009, 0x0031, "xs", "?" },
{ 0x0009, 0x0032, "LT", "?" },
{ 0x0009, 0x0034, "xs", "?" },
{ 0x0009, 0x0035, "SL", "Gantry Locus Type" },
{ 0x0009, 0x0037, "SL", "Starting Heart Rate" },
{ 0x0009, 0x0038, "xs", "?" },
{ 0x0009, 0x0039, "SL", "RR Window Offset" },
{ 0x0009, 0x003a, "SL", "Percent Cycle Imaged" },
{ 0x0009, 0x003e, "US", "?" },
{ 0x0009, 0x003f, "US", "?" },
{ 0x0009, 0x0040, "xs", "?" },
{ 0x0009, 0x0041, "xs", "?" },
{ 0x0009, 0x0042, "xs", "?" },
{ 0x0009, 0x0043, "xs", "?" },
{ 0x0009, 0x0050, "LT", "?" },
{ 0x0009, 0x0051, "xs", "?" },
{ 0x0009, 0x0060, "LT", "?" },
{ 0x0009, 0x0061, "LT", "Series Unique Identifier" },
{ 0x0009, 0x0070, "LT", "?" },
{ 0x0009, 0x0080, "LT", "?" },
{ 0x0009, 0x0091, "LT", "?" },
{ 0x0009, 0x00e2, "LT", "?" },
{ 0x0009, 0x00e3, "UI", "Equipment UID" },
{ 0x0009, 0x00e6, "SH", "Genesis Version Now" },
{ 0x0009, 0x00e7, "UL", "Exam Record Checksum" },
{ 0x0009, 0x00e8, "UL", "?" },
{ 0x0009, 0x00e9, "SL", "Actual Series Data Time Stamp" },
{ 0x0009, 0x00f2, "UN", "?" },
{ 0x0009, 0x00f3, "UN", "?" },
{ 0x0009, 0x00f4, "LT", "?" },
{ 0x0009, 0x00f5, "xs", "?" },
{ 0x0009, 0x00f6, "LT", "PDM Data Object Type Extension" },
{ 0x0009, 0x00f8, "US", "?" },
{ 0x0009, 0x00fb, "IS", "?" },
{ 0x0009, 0x1002, "OB", "?" },
{ 0x0009, 0x1003, "OB", "?" },
{ 0x0009, 0x1010, "UN", "?" },
{ 0x0010, 0x0000, "UL", "Patient Group Length" },
{ 0x0010, 0x0010, "PN", "Patient's Name" },
{ 0x0010, 0x0020, "LO", "Patient's ID" },
{ 0x0010, 0x0021, "LO", "Issuer of Patient's ID" },
{ 0x0010, 0x0030, "DA", "Patient's Birth Date" },
{ 0x0010, 0x0032, "TM", "Patient's Birth Time" },
{ 0x0010, 0x0040, "CS", "Patient's Sex" },
{ 0x0010, 0x0050, "SQ", "Patient's Insurance Plan Code Sequence" },
{ 0x0010, 0x1000, "LO", "Other Patient's ID's" },
{ 0x0010, 0x1001, "PN", "Other Patient's Names" },
{ 0x0010, 0x1005, "PN", "Patient's Birth Name" },
{ 0x0010, 0x1010, "AS", "Patient's Age" },
{ 0x0010, 0x1020, "DS", "Patient's Size" },
{ 0x0010, 0x1030, "DS", "Patient's Weight" },
{ 0x0010, 0x1040, "LO", "Patient's Address" },
{ 0x0010, 0x1050, "LT", "Insurance Plan Identification" },
{ 0x0010, 0x1060, "PN", "Patient's Mother's Birth Name" },
{ 0x0010, 0x1080, "LO", "Military Rank" },
{ 0x0010, 0x1081, "LO", "Branch of Service" },
{ 0x0010, 0x1090, "LO", "Medical Record Locator" },
{ 0x0010, 0x2000, "LO", "Medical Alerts" },
{ 0x0010, 0x2110, "LO", "Contrast Allergies" },
{ 0x0010, 0x2150, "LO", "Country of Residence" },
{ 0x0010, 0x2152, "LO", "Region of Residence" },
{ 0x0010, 0x2154, "SH", "Patients Telephone Numbers" },
{ 0x0010, 0x2160, "SH", "Ethnic Group" },
{ 0x0010, 0x2180, "SH", "Occupation" },
{ 0x0010, 0x21a0, "CS", "Smoking Status" },
{ 0x0010, 0x21b0, "LT", "Additional Patient History" },
{ 0x0010, 0x21c0, "US", "Pregnancy Status" },
{ 0x0010, 0x21d0, "DA", "Last Menstrual Date" },
{ 0x0010, 0x21f0, "LO", "Patients Religious Preference" },
{ 0x0010, 0x4000, "LT", "Patient Comments" },
{ 0x0011, 0x0001, "xs", "?" },
{ 0x0011, 0x0002, "US", "?" },
{ 0x0011, 0x0003, "LT", "Patient UID" },
{ 0x0011, 0x0004, "LT", "Patient ID" },
{ 0x0011, 0x000a, "xs", "?" },
{ 0x0011, 0x000b, "SL", "Effective Series Duration" },
{ 0x0011, 0x000c, "SL", "Num Beats" },
{ 0x0011, 0x000d, "LO", "Radio Nuclide Name" },
{ 0x0011, 0x0010, "xs", "?" },
{ 0x0011, 0x0011, "xs", "?" },
{ 0x0011, 0x0012, "LO", "Dataset Name" },
{ 0x0011, 0x0013, "LO", "Dataset Type" },
{ 0x0011, 0x0015, "xs", "?" },
{ 0x0011, 0x0016, "SL", "Energy Number" },
{ 0x0011, 0x0017, "SL", "RR Interval Window Number" },
{ 0x0011, 0x0018, "SL", "MG Bin Number" },
{ 0x0011, 0x0019, "FD", "Radius Of Rotation" },
{ 0x0011, 0x001a, "SL", "Detector Count Zone" },
{ 0x0011, 0x001b, "SL", "Num Energy Windows" },
{ 0x0011, 0x001c, "SL", "Energy Offset" },
{ 0x0011, 0x001d, "SL", "Energy Range" },
{ 0x0011, 0x001f, "SL", "Image Orientation" },
{ 0x0011, 0x0020, "xs", "?" },
{ 0x0011, 0x0021, "xs", "?" },
{ 0x0011, 0x0022, "xs", "?" },
{ 0x0011, 0x0023, "xs", "?" },
{ 0x0011, 0x0024, "SL", "FOV Mask Y Cutoff Angle" },
{ 0x0011, 0x0025, "xs", "?" },
{ 0x0011, 0x0026, "SL", "Table Orientation" },
{ 0x0011, 0x0027, "SL", "ROI Top Left" },
{ 0x0011, 0x0028, "SL", "ROI Bottom Right" },
{ 0x0011, 0x0030, "xs", "?" },
{ 0x0011, 0x0031, "xs", "?" },
{ 0x0011, 0x0032, "UN", "?" },
{ 0x0011, 0x0033, "LO", "Energy Correct Name" },
{ 0x0011, 0x0034, "LO", "Spatial Correct Name" },
{ 0x0011, 0x0035, "xs", "?" },
{ 0x0011, 0x0036, "LO", "Uniformity Correct Name" },
{ 0x0011, 0x0037, "LO", "Acquisition Specific Correct Name" },
{ 0x0011, 0x0038, "SL", "Byte Order" },
{ 0x0011, 0x003a, "SL", "Picture Format" },
{ 0x0011, 0x003b, "FD", "Pixel Scale" },
{ 0x0011, 0x003c, "FD", "Pixel Offset" },
{ 0x0011, 0x003e, "SL", "FOV Shape" },
{ 0x0011, 0x003f, "SL", "Dataset Flags" },
{ 0x0011, 0x0040, "xs", "?" },
{ 0x0011, 0x0041, "LT", "Medical Alerts" },
{ 0x0011, 0x0042, "LT", "Contrast Allergies" },
{ 0x0011, 0x0044, "FD", "Threshold Center" },
{ 0x0011, 0x0045, "FD", "Threshold Width" },
{ 0x0011, 0x0046, "SL", "Interpolation Type" },
{ 0x0011, 0x0055, "FD", "Period" },
{ 0x0011, 0x0056, "FD", "ElapsedTime" },
{ 0x0011, 0x00a1, "DA", "Patient Registration Date" },
{ 0x0011, 0x00a2, "TM", "Patient Registration Time" },
{ 0x0011, 0x00b0, "LT", "Patient Last Name" },
{ 0x0011, 0x00b2, "LT", "Patient First Name" },
{ 0x0011, 0x00b4, "LT", "Patient Hospital Status" },
{ 0x0011, 0x00bc, "TM", "Current Location Time" },
{ 0x0011, 0x00c0, "LT", "Patient Insurance Status" },
{ 0x0011, 0x00d0, "LT", "Patient Billing Type" },
{ 0x0011, 0x00d2, "LT", "Patient Billing Address" },
{ 0x0013, 0x0000, "LT", "Modifying Physician" },
{ 0x0013, 0x0010, "xs", "?" },
{ 0x0013, 0x0011, "SL", "?" },
{ 0x0013, 0x0012, "xs", "?" },
{ 0x0013, 0x0016, "SL", "AutoTrack Peak" },
{ 0x0013, 0x0017, "SL", "AutoTrack Width" },
{ 0x0013, 0x0018, "FD", "Transmission Scan Time" },
{ 0x0013, 0x0019, "FD", "Transmission Mask Width" },
{ 0x0013, 0x001a, "FD", "Copper Attenuator Thickness" },
{ 0x0013, 0x001c, "FD", "?" },
{ 0x0013, 0x001d, "FD", "?" },
{ 0x0013, 0x001e, "FD", "Tomo View Offset" },
{ 0x0013, 0x0020, "LT", "Patient Name" },
{ 0x0013, 0x0022, "LT", "Patient Id" },
{ 0x0013, 0x0026, "LT", "Study Comments" },
{ 0x0013, 0x0030, "DA", "Patient Birthdate" },
{ 0x0013, 0x0031, "DS", "Patient Weight" },
{ 0x0013, 0x0032, "LT", "Patients Maiden Name" },
{ 0x0013, 0x0033, "LT", "Referring Physician" },
{ 0x0013, 0x0034, "LT", "Admitting Diagnosis" },
{ 0x0013, 0x0035, "LT", "Patient Sex" },
{ 0x0013, 0x0040, "LT", "Procedure Description" },
{ 0x0013, 0x0042, "LT", "Patient Rest Direction" },
{ 0x0013, 0x0044, "LT", "Patient Position" },
{ 0x0013, 0x0046, "LT", "View Direction" },
{ 0x0015, 0x0001, "DS", "Stenosis Calibration Ratio" },
{ 0x0015, 0x0002, "DS", "Stenosis Magnification" },
{ 0x0015, 0x0003, "DS", "Cardiac Calibration Ratio" },
{ 0x0018, 0x0000, "UL", "Acquisition Group Length" },
{ 0x0018, 0x0010, "LO", "Contrast/Bolus Agent" },
{ 0x0018, 0x0012, "SQ", "Contrast/Bolus Agent Sequence" },
{ 0x0018, 0x0014, "SQ", "Contrast/Bolus Administration Route Sequence" },
{ 0x0018, 0x0015, "CS", "Body Part Examined" },
{ 0x0018, 0x0020, "CS", "Scanning Sequence" },
{ 0x0018, 0x0021, "CS", "Sequence Variant" },
{ 0x0018, 0x0022, "CS", "Scan Options" },
{ 0x0018, 0x0023, "CS", "MR Acquisition Type" },
{ 0x0018, 0x0024, "SH", "Sequence Name" },
{ 0x0018, 0x0025, "CS", "Angio Flag" },
{ 0x0018, 0x0026, "SQ", "Intervention Drug Information Sequence" },
{ 0x0018, 0x0027, "TM", "Intervention Drug Stop Time" },
{ 0x0018, 0x0028, "DS", "Intervention Drug Dose" },
{ 0x0018, 0x0029, "SQ", "Intervention Drug Code Sequence" },
{ 0x0018, 0x002a, "SQ", "Additional Drug Sequence" },
{ 0x0018, 0x0030, "LO", "Radionuclide" },
{ 0x0018, 0x0031, "LO", "Radiopharmaceutical" },
{ 0x0018, 0x0032, "DS", "Energy Window Centerline" },
{ 0x0018, 0x0033, "DS", "Energy Window Total Width" },
{ 0x0018, 0x0034, "LO", "Intervention Drug Name" },
{ 0x0018, 0x0035, "TM", "Intervention Drug Start Time" },
{ 0x0018, 0x0036, "SQ", "Intervention Therapy Sequence" },
{ 0x0018, 0x0037, "CS", "Therapy Type" },
{ 0x0018, 0x0038, "CS", "Intervention Status" },
{ 0x0018, 0x0039, "CS", "Therapy Description" },
{ 0x0018, 0x0040, "IS", "Cine Rate" },
{ 0x0018, 0x0050, "DS", "Slice Thickness" },
{ 0x0018, 0x0060, "DS", "KVP" },
{ 0x0018, 0x0070, "IS", "Counts Accumulated" },
{ 0x0018, 0x0071, "CS", "Acquisition Termination Condition" },
{ 0x0018, 0x0072, "DS", "Effective Series Duration" },
{ 0x0018, 0x0073, "CS", "Acquisition Start Condition" },
{ 0x0018, 0x0074, "IS", "Acquisition Start Condition Data" },
{ 0x0018, 0x0075, "IS", "Acquisition Termination Condition Data" },
{ 0x0018, 0x0080, "DS", "Repetition Time" },
{ 0x0018, 0x0081, "DS", "Echo Time" },
{ 0x0018, 0x0082, "DS", "Inversion Time" },
{ 0x0018, 0x0083, "DS", "Number of Averages" },
{ 0x0018, 0x0084, "DS", "Imaging Frequency" },
{ 0x0018, 0x0085, "SH", "Imaged Nucleus" },
{ 0x0018, 0x0086, "IS", "Echo Number(s)" },
{ 0x0018, 0x0087, "DS", "Magnetic Field Strength" },
{ 0x0018, 0x0088, "DS", "Spacing Between Slices" },
{ 0x0018, 0x0089, "IS", "Number of Phase Encoding Steps" },
{ 0x0018, 0x0090, "DS", "Data Collection Diameter" },
{ 0x0018, 0x0091, "IS", "Echo Train Length" },
{ 0x0018, 0x0093, "DS", "Percent Sampling" },
{ 0x0018, 0x0094, "DS", "Percent Phase Field of View" },
{ 0x0018, 0x0095, "DS", "Pixel Bandwidth" },
{ 0x0018, 0x1000, "LO", "Device Serial Number" },
{ 0x0018, 0x1004, "LO", "Plate ID" },
{ 0x0018, 0x1010, "LO", "Secondary Capture Device ID" },
{ 0x0018, 0x1012, "DA", "Date of Secondary Capture" },
{ 0x0018, 0x1014, "TM", "Time of Secondary Capture" },
{ 0x0018, 0x1016, "LO", "Secondary Capture Device Manufacturer" },
{ 0x0018, 0x1018, "LO", "Secondary Capture Device Manufacturer Model Name" },
{ 0x0018, 0x1019, "LO", "Secondary Capture Device Software Version(s)" },
{ 0x0018, 0x1020, "LO", "Software Version(s)" },
{ 0x0018, 0x1022, "SH", "Video Image Format Acquired" },
{ 0x0018, 0x1023, "LO", "Digital Image Format Acquired" },
{ 0x0018, 0x1030, "LO", "Protocol Name" },
{ 0x0018, 0x1040, "LO", "Contrast/Bolus Route" },
{ 0x0018, 0x1041, "DS", "Contrast/Bolus Volume" },
{ 0x0018, 0x1042, "TM", "Contrast/Bolus Start Time" },
{ 0x0018, 0x1043, "TM", "Contrast/Bolus Stop Time" },
{ 0x0018, 0x1044, "DS", "Contrast/Bolus Total Dose" },
{ 0x0018, 0x1045, "IS", "Syringe Counts" },
{ 0x0018, 0x1046, "DS", "Contrast Flow Rate" },
{ 0x0018, 0x1047, "DS", "Contrast Flow Duration" },
{ 0x0018, 0x1048, "CS", "Contrast/Bolus Ingredient" },
{ 0x0018, 0x1049, "DS", "Contrast/Bolus Ingredient Concentration" },
{ 0x0018, 0x1050, "DS", "Spatial Resolution" },
{ 0x0018, 0x1060, "DS", "Trigger Time" },
{ 0x0018, 0x1061, "LO", "Trigger Source or Type" },
{ 0x0018, 0x1062, "IS", "Nominal Interval" },
{ 0x0018, 0x1063, "DS", "Frame Time" },
{ 0x0018, 0x1064, "LO", "Framing Type" },
{ 0x0018, 0x1065, "DS", "Frame Time Vector" },
{ 0x0018, 0x1066, "DS", "Frame Delay" },
{ 0x0018, 0x1067, "DS", "Image Trigger Delay" },
{ 0x0018, 0x1068, "DS", "Group Time Offset" },
{ 0x0018, 0x1069, "DS", "Trigger Time Offset" },
{ 0x0018, 0x106a, "CS", "Synchronization Trigger" },
{ 0x0018, 0x106b, "UI", "Synchronization Frame of Reference" },
{ 0x0018, 0x106e, "UL", "Trigger Sample Position" },
{ 0x0018, 0x1070, "LO", "Radiopharmaceutical Route" },
{ 0x0018, 0x1071, "DS", "Radiopharmaceutical Volume" },
{ 0x0018, 0x1072, "TM", "Radiopharmaceutical Start Time" },
{ 0x0018, 0x1073, "TM", "Radiopharmaceutical Stop Time" },
{ 0x0018, 0x1074, "DS", "Radionuclide Total Dose" },
{ 0x0018, 0x1075, "DS", "Radionuclide Half Life" },
{ 0x0018, 0x1076, "DS", "Radionuclide Positron Fraction" },
{ 0x0018, 0x1077, "DS", "Radiopharmaceutical Specific Activity" },
{ 0x0018, 0x1080, "CS", "Beat Rejection Flag" },
{ 0x0018, 0x1081, "IS", "Low R-R Value" },
{ 0x0018, 0x1082, "IS", "High R-R Value" },
{ 0x0018, 0x1083, "IS", "Intervals Acquired" },
{ 0x0018, 0x1084, "IS", "Intervals Rejected" },
{ 0x0018, 0x1085, "LO", "PVC Rejection" },
{ 0x0018, 0x1086, "IS", "Skip Beats" },
{ 0x0018, 0x1088, "IS", "Heart Rate" },
{ 0x0018, 0x1090, "IS", "Cardiac Number of Images" },
{ 0x0018, 0x1094, "IS", "Trigger Window" },
{ 0x0018, 0x1100, "DS", "Reconstruction Diameter" },
{ 0x0018, 0x1110, "DS", "Distance Source to Detector" },
{ 0x0018, 0x1111, "DS", "Distance Source to Patient" },
{ 0x0018, 0x1114, "DS", "Estimated Radiographic Magnification Factor" },
{ 0x0018, 0x1120, "DS", "Gantry/Detector Tilt" },
{ 0x0018, 0x1121, "DS", "Gantry/Detector Slew" },
{ 0x0018, 0x1130, "DS", "Table Height" },
{ 0x0018, 0x1131, "DS", "Table Traverse" },
{ 0x0018, 0x1134, "CS", "Table Motion" },
{ 0x0018, 0x1135, "DS", "Table Vertical Increment" },
{ 0x0018, 0x1136, "DS", "Table Lateral Increment" },
{ 0x0018, 0x1137, "DS", "Table Longitudinal Increment" },
{ 0x0018, 0x1138, "DS", "Table Angle" },
{ 0x0018, 0x113a, "CS", "Table Type" },
{ 0x0018, 0x1140, "CS", "Rotation Direction" },
{ 0x0018, 0x1141, "DS", "Angular Position" },
{ 0x0018, 0x1142, "DS", "Radial Position" },
{ 0x0018, 0x1143, "DS", "Scan Arc" },
{ 0x0018, 0x1144, "DS", "Angular Step" },
{ 0x0018, 0x1145, "DS", "Center of Rotation Offset" },
{ 0x0018, 0x1146, "DS", "Rotation Offset" },
{ 0x0018, 0x1147, "CS", "Field of View Shape" },
{ 0x0018, 0x1149, "IS", "Field of View Dimension(s)" },
{ 0x0018, 0x1150, "IS", "Exposure Time" },
{ 0x0018, 0x1151, "IS", "X-ray Tube Current" },
{ 0x0018, 0x1152, "IS", "Exposure" },
{ 0x0018, 0x1153, "IS", "Exposure in uAs" },
{ 0x0018, 0x1154, "DS", "AveragePulseWidth" },
{ 0x0018, 0x1155, "CS", "RadiationSetting" },
{ 0x0018, 0x1156, "CS", "Rectification Type" },
{ 0x0018, 0x115a, "CS", "RadiationMode" },
{ 0x0018, 0x115e, "DS", "ImageAreaDoseProduct" },
{ 0x0018, 0x1160, "SH", "Filter Type" },
{ 0x0018, 0x1161, "LO", "TypeOfFilters" },
{ 0x0018, 0x1162, "DS", "IntensifierSize" },
{ 0x0018, 0x1164, "DS", "ImagerPixelSpacing" },
{ 0x0018, 0x1166, "CS", "Grid" },
{ 0x0018, 0x1170, "IS", "Generator Power" },
{ 0x0018, 0x1180, "SH", "Collimator/Grid Name" },
{ 0x0018, 0x1181, "CS", "Collimator Type" },
{ 0x0018, 0x1182, "IS", "Focal Distance" },
{ 0x0018, 0x1183, "DS", "X Focus Center" },
{ 0x0018, 0x1184, "DS", "Y Focus Center" },
{ 0x0018, 0x1190, "DS", "Focal Spot(s)" },
{ 0x0018, 0x1191, "CS", "Anode Target Material" },
{ 0x0018, 0x11a0, "DS", "Body Part Thickness" },
{ 0x0018, 0x11a2, "DS", "Compression Force" },
{ 0x0018, 0x1200, "DA", "Date of Last Calibration" },
{ 0x0018, 0x1201, "TM", "Time of Last Calibration" },
{ 0x0018, 0x1210, "SH", "Convolution Kernel" },
{ 0x0018, 0x1240, "IS", "Upper/Lower Pixel Values" },
{ 0x0018, 0x1242, "IS", "Actual Frame Duration" },
{ 0x0018, 0x1243, "IS", "Count Rate" },
{ 0x0018, 0x1244, "US", "Preferred Playback Sequencing" },
{ 0x0018, 0x1250, "SH", "Receiving Coil" },
{ 0x0018, 0x1251, "SH", "Transmitting Coil" },
{ 0x0018, 0x1260, "SH", "Plate Type" },
{ 0x0018, 0x1261, "LO", "Phosphor Type" },
{ 0x0018, 0x1300, "DS", "Scan Velocity" },
{ 0x0018, 0x1301, "CS", "Whole Body Technique" },
{ 0x0018, 0x1302, "IS", "Scan Length" },
{ 0x0018, 0x1310, "US", "Acquisition Matrix" },
{ 0x0018, 0x1312, "CS", "Phase Encoding Direction" },
{ 0x0018, 0x1314, "DS", "Flip Angle" },
{ 0x0018, 0x1315, "CS", "Variable Flip Angle Flag" },
{ 0x0018, 0x1316, "DS", "SAR" },
{ 0x0018, 0x1318, "DS", "dB/dt" },
{ 0x0018, 0x1400, "LO", "Acquisition Device Processing Description" },
{ 0x0018, 0x1401, "LO", "Acquisition Device Processing Code" },
{ 0x0018, 0x1402, "CS", "Cassette Orientation" },
{ 0x0018, 0x1403, "CS", "Cassette Size" },
{ 0x0018, 0x1404, "US", "Exposures on Plate" },
{ 0x0018, 0x1405, "IS", "Relative X-ray Exposure" },
{ 0x0018, 0x1450, "DS", "Column Angulation" },
{ 0x0018, 0x1460, "DS", "Tomo Layer Height" },
{ 0x0018, 0x1470, "DS", "Tomo Angle" },
{ 0x0018, 0x1480, "DS", "Tomo Time" },
{ 0x0018, 0x1490, "CS", "Tomo Type" },
{ 0x0018, 0x1491, "CS", "Tomo Class" },
{ 0x0018, 0x1495, "IS", "Number of Tomosynthesis Source Images" },
{ 0x0018, 0x1500, "CS", "PositionerMotion" },
{ 0x0018, 0x1508, "CS", "Positioner Type" },
{ 0x0018, 0x1510, "DS", "PositionerPrimaryAngle" },
{ 0x0018, 0x1511, "DS", "PositionerSecondaryAngle" },
{ 0x0018, 0x1520, "DS", "PositionerPrimaryAngleIncrement" },
{ 0x0018, 0x1521, "DS", "PositionerSecondaryAngleIncrement" },
{ 0x0018, 0x1530, "DS", "DetectorPrimaryAngle" },
{ 0x0018, 0x1531, "DS", "DetectorSecondaryAngle" },
{ 0x0018, 0x1600, "CS", "Shutter Shape" },
{ 0x0018, 0x1602, "IS", "Shutter Left Vertical Edge" },
{ 0x0018, 0x1604, "IS", "Shutter Right Vertical Edge" },
{ 0x0018, 0x1606, "IS", "Shutter Upper Horizontal Edge" },
{ 0x0018, 0x1608, "IS", "Shutter Lower Horizonta lEdge" },
{ 0x0018, 0x1610, "IS", "Center of Circular Shutter" },
{ 0x0018, 0x1612, "IS", "Radius of Circular Shutter" },
{ 0x0018, 0x1620, "IS", "Vertices of Polygonal Shutter" },
{ 0x0018, 0x1622, "US", "Shutter Presentation Value" },
{ 0x0018, 0x1623, "US", "Shutter Overlay Group" },
{ 0x0018, 0x1700, "CS", "Collimator Shape" },
{ 0x0018, 0x1702, "IS", "Collimator Left Vertical Edge" },
{ 0x0018, 0x1704, "IS", "Collimator Right Vertical Edge" },
{ 0x0018, 0x1706, "IS", "Collimator Upper Horizontal Edge" },
{ 0x0018, 0x1708, "IS", "Collimator Lower Horizontal Edge" },
{ 0x0018, 0x1710, "IS", "Center of Circular Collimator" },
{ 0x0018, 0x1712, "IS", "Radius of Circular Collimator" },
{ 0x0018, 0x1720, "IS", "Vertices of Polygonal Collimator" },
{ 0x0018, 0x1800, "CS", "Acquisition Time Synchronized" },
{ 0x0018, 0x1801, "SH", "Time Source" },
{ 0x0018, 0x1802, "CS", "Time Distribution Protocol" },
{ 0x0018, 0x4000, "LT", "Acquisition Comments" },
{ 0x0018, 0x5000, "SH", "Output Power" },
{ 0x0018, 0x5010, "LO", "Transducer Data" },
{ 0x0018, 0x5012, "DS", "Focus Depth" },
{ 0x0018, 0x5020, "LO", "Processing Function" },
{ 0x0018, 0x5021, "LO", "Postprocessing Function" },
{ 0x0018, 0x5022, "DS", "Mechanical Index" },
{ 0x0018, 0x5024, "DS", "Thermal Index" },
{ 0x0018, 0x5026, "DS", "Cranial Thermal Index" },
{ 0x0018, 0x5027, "DS", "Soft Tissue Thermal Index" },
{ 0x0018, 0x5028, "DS", "Soft Tissue-Focus Thermal Index" },
{ 0x0018, 0x5029, "DS", "Soft Tissue-Surface Thermal Index" },
{ 0x0018, 0x5030, "DS", "Dynamic Range" },
{ 0x0018, 0x5040, "DS", "Total Gain" },
{ 0x0018, 0x5050, "IS", "Depth of Scan Field" },
{ 0x0018, 0x5100, "CS", "Patient Position" },
{ 0x0018, 0x5101, "CS", "View Position" },
{ 0x0018, 0x5104, "SQ", "Projection Eponymous Name Code Sequence" },
{ 0x0018, 0x5210, "DS", "Image Transformation Matrix" },
{ 0x0018, 0x5212, "DS", "Image Translation Vector" },
{ 0x0018, 0x6000, "DS", "Sensitivity" },
{ 0x0018, 0x6011, "IS", "Sequence of Ultrasound Regions" },
{ 0x0018, 0x6012, "US", "Region Spatial Format" },
{ 0x0018, 0x6014, "US", "Region Data Type" },
{ 0x0018, 0x6016, "UL", "Region Flags" },
{ 0x0018, 0x6018, "UL", "Region Location Min X0" },
{ 0x0018, 0x601a, "UL", "Region Location Min Y0" },
{ 0x0018, 0x601c, "UL", "Region Location Max X1" },
{ 0x0018, 0x601e, "UL", "Region Location Max Y1" },
{ 0x0018, 0x6020, "SL", "Reference Pixel X0" },
{ 0x0018, 0x6022, "SL", "Reference Pixel Y0" },
{ 0x0018, 0x6024, "US", "Physical Units X Direction" },
{ 0x0018, 0x6026, "US", "Physical Units Y Direction" },
{ 0x0018, 0x6028, "FD", "Reference Pixel Physical Value X" },
{ 0x0018, 0x602a, "US", "Reference Pixel Physical Value Y" },
{ 0x0018, 0x602c, "US", "Physical Delta X" },
{ 0x0018, 0x602e, "US", "Physical Delta Y" },
{ 0x0018, 0x6030, "UL", "Transducer Frequency" },
{ 0x0018, 0x6031, "CS", "Transducer Type" },
{ 0x0018, 0x6032, "UL", "Pulse Repetition Frequency" },
{ 0x0018, 0x6034, "FD", "Doppler Correction Angle" },
{ 0x0018, 0x6036, "FD", "Steering Angle" },
{ 0x0018, 0x6038, "UL", "Doppler Sample Volume X Position" },
{ 0x0018, 0x603a, "UL", "Doppler Sample Volume Y Position" },
{ 0x0018, 0x603c, "UL", "TM-Line Position X0" },
{ 0x0018, 0x603e, "UL", "TM-Line Position Y0" },
{ 0x0018, 0x6040, "UL", "TM-Line Position X1" },
{ 0x0018, 0x6042, "UL", "TM-Line Position Y1" },
{ 0x0018, 0x6044, "US", "Pixel Component Organization" },
{ 0x0018, 0x6046, "UL", "Pixel Component Mask" },
{ 0x0018, 0x6048, "UL", "Pixel Component Range Start" },
{ 0x0018, 0x604a, "UL", "Pixel Component Range Stop" },
{ 0x0018, 0x604c, "US", "Pixel Component Physical Units" },
{ 0x0018, 0x604e, "US", "Pixel Component Data Type" },
{ 0x0018, 0x6050, "UL", "Number of Table Break Points" },
{ 0x0018, 0x6052, "UL", "Table of X Break Points" },
{ 0x0018, 0x6054, "FD", "Table of Y Break Points" },
{ 0x0018, 0x6056, "UL", "Number of Table Entries" },
{ 0x0018, 0x6058, "UL", "Table of Pixel Values" },
{ 0x0018, 0x605a, "FL", "Table of Parameter Values" },
{ 0x0018, 0x7000, "CS", "Detector Conditions Nominal Flag" },
{ 0x0018, 0x7001, "DS", "Detector Temperature" },
{ 0x0018, 0x7004, "CS", "Detector Type" },
{ 0x0018, 0x7005, "CS", "Detector Configuration" },
{ 0x0018, 0x7006, "LT", "Detector Description" },
{ 0x0018, 0x7008, "LT", "Detector Mode" },
{ 0x0018, 0x700a, "SH", "Detector ID" },
{ 0x0018, 0x700c, "DA", "Date of Last Detector Calibration " },
{ 0x0018, 0x700e, "TM", "Time of Last Detector Calibration" },
{ 0x0018, 0x7010, "IS", "Exposures on Detector Since Last Calibration" },
{ 0x0018, 0x7011, "IS", "Exposures on Detector Since Manufactured" },
{ 0x0018, 0x7012, "DS", "Detector Time Since Last Exposure" },
{ 0x0018, 0x7014, "DS", "Detector Active Time" },
{ 0x0018, 0x7016, "DS", "Detector Activation Offset From Exposure" },
{ 0x0018, 0x701a, "DS", "Detector Binning" },
{ 0x0018, 0x7020, "DS", "Detector Element Physical Size" },
{ 0x0018, 0x7022, "DS", "Detector Element Spacing" },
{ 0x0018, 0x7024, "CS", "Detector Active Shape" },
{ 0x0018, 0x7026, "DS", "Detector Active Dimensions" },
{ 0x0018, 0x7028, "DS", "Detector Active Origin" },
{ 0x0018, 0x7030, "DS", "Field of View Origin" },
{ 0x0018, 0x7032, "DS", "Field of View Rotation" },
{ 0x0018, 0x7034, "CS", "Field of View Horizontal Flip" },
{ 0x0018, 0x7040, "LT", "Grid Absorbing Material" },
{ 0x0018, 0x7041, "LT", "Grid Spacing Material" },
{ 0x0018, 0x7042, "DS", "Grid Thickness" },
{ 0x0018, 0x7044, "DS", "Grid Pitch" },
{ 0x0018, 0x7046, "IS", "Grid Aspect Ratio" },
{ 0x0018, 0x7048, "DS", "Grid Period" },
{ 0x0018, 0x704c, "DS", "Grid Focal Distance" },
{ 0x0018, 0x7050, "LT", "Filter Material" },
{ 0x0018, 0x7052, "DS", "Filter Thickness Minimum" },
{ 0x0018, 0x7054, "DS", "Filter Thickness Maximum" },
{ 0x0018, 0x7060, "CS", "Exposure Control Mode" },
{ 0x0018, 0x7062, "LT", "Exposure Control Mode Description" },
{ 0x0018, 0x7064, "CS", "Exposure Status" },
{ 0x0018, 0x7065, "DS", "Phototimer Setting" },
{ 0x0019, 0x0000, "xs", "?" },
{ 0x0019, 0x0001, "xs", "?" },
{ 0x0019, 0x0002, "xs", "?" },
{ 0x0019, 0x0003, "xs", "?" },
{ 0x0019, 0x0004, "xs", "?" },
{ 0x0019, 0x0005, "xs", "?" },
{ 0x0019, 0x0006, "xs", "?" },
{ 0x0019, 0x0007, "xs", "?" },
{ 0x0019, 0x0008, "xs", "?" },
{ 0x0019, 0x0009, "xs", "?" },
{ 0x0019, 0x000a, "xs", "?" },
{ 0x0019, 0x000b, "DS", "?" },
{ 0x0019, 0x000c, "US", "?" },
{ 0x0019, 0x000d, "TM", "Time" },
{ 0x0019, 0x000e, "xs", "?" },
{ 0x0019, 0x000f, "DS", "Horizontal Frame Of Reference" },
{ 0x0019, 0x0010, "xs", "?" },
{ 0x0019, 0x0011, "xs", "?" },
{ 0x0019, 0x0012, "xs", "?" },
{ 0x0019, 0x0013, "xs", "?" },
{ 0x0019, 0x0014, "xs", "?" },
{ 0x0019, 0x0015, "xs", "?" },
{ 0x0019, 0x0016, "xs", "?" },
{ 0x0019, 0x0017, "xs", "?" },
{ 0x0019, 0x0018, "xs", "?" },
{ 0x0019, 0x0019, "xs", "?" },
{ 0x0019, 0x001a, "xs", "?" },
{ 0x0019, 0x001b, "xs", "?" },
{ 0x0019, 0x001c, "CS", "Dose" },
{ 0x0019, 0x001d, "IS", "Side Mark" },
{ 0x0019, 0x001e, "xs", "?" },
{ 0x0019, 0x001f, "DS", "Exposure Duration" },
{ 0x0019, 0x0020, "xs", "?" },
{ 0x0019, 0x0021, "xs", "?" },
{ 0x0019, 0x0022, "xs", "?" },
{ 0x0019, 0x0023, "xs", "?" },
{ 0x0019, 0x0024, "xs", "?" },
{ 0x0019, 0x0025, "xs", "?" },
{ 0x0019, 0x0026, "xs", "?" },
{ 0x0019, 0x0027, "xs", "?" },
{ 0x0019, 0x0028, "xs", "?" },
{ 0x0019, 0x0029, "IS", "?" },
{ 0x0019, 0x002a, "xs", "?" },
{ 0x0019, 0x002b, "DS", "Xray Off Position" },
{ 0x0019, 0x002c, "xs", "?" },
{ 0x0019, 0x002d, "US", "?" },
{ 0x0019, 0x002e, "xs", "?" },
{ 0x0019, 0x002f, "DS", "Trigger Frequency" },
{ 0x0019, 0x0030, "xs", "?" },
{ 0x0019, 0x0031, "xs", "?" },
{ 0x0019, 0x0032, "xs", "?" },
{ 0x0019, 0x0033, "UN", "ECG 2 Offset 2" },
{ 0x0019, 0x0034, "US", "?" },
{ 0x0019, 0x0036, "US", "?" },
{ 0x0019, 0x0038, "US", "?" },
{ 0x0019, 0x0039, "xs", "?" },
{ 0x0019, 0x003a, "xs", "?" },
{ 0x0019, 0x003b, "LT", "?" },
{ 0x0019, 0x003c, "xs", "?" },
{ 0x0019, 0x003e, "xs", "?" },
{ 0x0019, 0x003f, "UN", "?" },
{ 0x0019, 0x0040, "xs", "?" },
{ 0x0019, 0x0041, "xs", "?" },
{ 0x0019, 0x0042, "xs", "?" },
{ 0x0019, 0x0043, "xs", "?" },
{ 0x0019, 0x0044, "xs", "?" },
{ 0x0019, 0x0045, "xs", "?" },
{ 0x0019, 0x0046, "xs", "?" },
{ 0x0019, 0x0047, "xs", "?" },
{ 0x0019, 0x0048, "xs", "?" },
{ 0x0019, 0x0049, "US", "?" },
{ 0x0019, 0x004a, "xs", "?" },
{ 0x0019, 0x004b, "SL", "Data Size For Scan Data" },
{ 0x0019, 0x004c, "US", "?" },
{ 0x0019, 0x004e, "US", "?" },
{ 0x0019, 0x0050, "xs", "?" },
{ 0x0019, 0x0051, "xs", "?" },
{ 0x0019, 0x0052, "xs", "?" },
{ 0x0019, 0x0053, "LT", "Barcode" },
{ 0x0019, 0x0054, "xs", "?" },
{ 0x0019, 0x0055, "DS", "Receiver Reference Gain" },
{ 0x0019, 0x0056, "xs", "?" },
{ 0x0019, 0x0057, "SS", "CT Water Number" },
{ 0x0019, 0x0058, "xs", "?" },
{ 0x0019, 0x005a, "xs", "?" },
{ 0x0019, 0x005c, "xs", "?" },
{ 0x0019, 0x005d, "US", "?" },
{ 0x0019, 0x005e, "xs", "?" },
{ 0x0019, 0x005f, "SL", "Increment Between Channels" },
{ 0x0019, 0x0060, "xs", "?" },
{ 0x0019, 0x0061, "xs", "?" },
{ 0x0019, 0x0062, "xs", "?" },
{ 0x0019, 0x0063, "xs", "?" },
{ 0x0019, 0x0064, "xs", "?" },
{ 0x0019, 0x0065, "xs", "?" },
{ 0x0019, 0x0066, "xs", "?" },
{ 0x0019, 0x0067, "xs", "?" },
{ 0x0019, 0x0068, "xs", "?" },
{ 0x0019, 0x0069, "UL", "Convolution Mode" },
{ 0x0019, 0x006a, "xs", "?" },
{ 0x0019, 0x006b, "SS", "Field Of View In Detector Cells" },
{ 0x0019, 0x006c, "US", "?" },
{ 0x0019, 0x006e, "US", "?" },
{ 0x0019, 0x0070, "xs", "?" },
{ 0x0019, 0x0071, "xs", "?" },
{ 0x0019, 0x0072, "xs", "?" },
{ 0x0019, 0x0073, "xs", "?" },
{ 0x0019, 0x0074, "xs", "?" },
{ 0x0019, 0x0075, "xs", "?" },
{ 0x0019, 0x0076, "xs", "?" },
{ 0x0019, 0x0077, "US", "?" },
{ 0x0019, 0x0078, "US", "?" },
{ 0x0019, 0x007a, "US", "?" },
{ 0x0019, 0x007c, "US", "?" },
{ 0x0019, 0x007d, "DS", "Second Echo" },
{ 0x0019, 0x007e, "xs", "?" },
{ 0x0019, 0x007f, "DS", "Table Delta" },
{ 0x0019, 0x0080, "xs", "?" },
{ 0x0019, 0x0081, "xs", "?" },
{ 0x0019, 0x0082, "xs", "?" },
{ 0x0019, 0x0083, "xs", "?" },
{ 0x0019, 0x0084, "xs", "?" },
{ 0x0019, 0x0085, "xs", "?" },
{ 0x0019, 0x0086, "xs", "?" },
{ 0x0019, 0x0087, "xs", "?" },
{ 0x0019, 0x0088, "xs", "?" },
{ 0x0019, 0x008a, "xs", "?" },
{ 0x0019, 0x008b, "SS", "Actual Receive Gain Digital" },
{ 0x0019, 0x008c, "US", "?" },
{ 0x0019, 0x008d, "DS", "Delay After Trigger" },
{ 0x0019, 0x008e, "US", "?" },
{ 0x0019, 0x008f, "SS", "Swap Phase Frequency" },
{ 0x0019, 0x0090, "xs", "?" },
{ 0x0019, 0x0091, "xs", "?" },
{ 0x0019, 0x0092, "xs", "?" },
{ 0x0019, 0x0093, "xs", "?" },
{ 0x0019, 0x0094, "xs", "?" },
{ 0x0019, 0x0095, "SS", "Analog Receiver Gain" },
{ 0x0019, 0x0096, "xs", "?" },
{ 0x0019, 0x0097, "xs", "?" },
{ 0x0019, 0x0098, "xs", "?" },
{ 0x0019, 0x0099, "US", "?" },
{ 0x0019, 0x009a, "US", "?" },
{ 0x0019, 0x009b, "SS", "Pulse Sequence Mode" },
{ 0x0019, 0x009c, "xs", "?" },
{ 0x0019, 0x009d, "DT", "Pulse Sequence Date" },
{ 0x0019, 0x009e, "xs", "?" },
{ 0x0019, 0x009f, "xs", "?" },
{ 0x0019, 0x00a0, "xs", "?" },
{ 0x0019, 0x00a1, "xs", "?" },
{ 0x0019, 0x00a2, "xs", "?" },
{ 0x0019, 0x00a3, "xs", "?" },
{ 0x0019, 0x00a4, "xs", "?" },
{ 0x0019, 0x00a5, "xs", "?" },
{ 0x0019, 0x00a6, "xs", "?" },
{ 0x0019, 0x00a7, "xs", "?" },
{ 0x0019, 0x00a8, "xs", "?" },
{ 0x0019, 0x00a9, "xs", "?" },
{ 0x0019, 0x00aa, "xs", "?" },
{ 0x0019, 0x00ab, "xs", "?" },
{ 0x0019, 0x00ac, "xs", "?" },
{ 0x0019, 0x00ad, "xs", "?" },
{ 0x0019, 0x00ae, "xs", "?" },
{ 0x0019, 0x00af, "xs", "?" },
{ 0x0019, 0x00b0, "xs", "?" },
{ 0x0019, 0x00b1, "xs", "?" },
{ 0x0019, 0x00b2, "xs", "?" },
{ 0x0019, 0x00b3, "xs", "?" },
{ 0x0019, 0x00b4, "xs", "?" },
{ 0x0019, 0x00b5, "xs", "?" },
{ 0x0019, 0x00b6, "DS", "User Data" },
{ 0x0019, 0x00b7, "DS", "User Data" },
{ 0x0019, 0x00b8, "DS", "User Data" },
{ 0x0019, 0x00b9, "DS", "User Data" },
{ 0x0019, 0x00ba, "DS", "User Data" },
{ 0x0019, 0x00bb, "DS", "User Data" },
{ 0x0019, 0x00bc, "DS", "User Data" },
{ 0x0019, 0x00bd, "DS", "User Data" },
{ 0x0019, 0x00be, "DS", "Projection Angle" },
{ 0x0019, 0x00c0, "xs", "?" },
{ 0x0019, 0x00c1, "xs", "?" },
{ 0x0019, 0x00c2, "xs", "?" },
{ 0x0019, 0x00c3, "xs", "?" },
{ 0x0019, 0x00c4, "xs", "?" },
{ 0x0019, 0x00c5, "xs", "?" },
{ 0x0019, 0x00c6, "SS", "SAT Location H" },
{ 0x0019, 0x00c7, "SS", "SAT Location F" },
{ 0x0019, 0x00c8, "SS", "SAT Thickness R L" },
{ 0x0019, 0x00c9, "SS", "SAT Thickness A P" },
{ 0x0019, 0x00ca, "SS", "SAT Thickness H F" },
{ 0x0019, 0x00cb, "xs", "?" },
{ 0x0019, 0x00cc, "xs", "?" },
{ 0x0019, 0x00cd, "SS", "Thickness Disclaimer" },
{ 0x0019, 0x00ce, "SS", "Prescan Type" },
{ 0x0019, 0x00cf, "SS", "Prescan Status" },
{ 0x0019, 0x00d0, "SH", "Raw Data Type" },
{ 0x0019, 0x00d1, "DS", "Flow Sensitivity" },
{ 0x0019, 0x00d2, "xs", "?" },
{ 0x0019, 0x00d3, "xs", "?" },
{ 0x0019, 0x00d4, "xs", "?" },
{ 0x0019, 0x00d5, "xs", "?" },
{ 0x0019, 0x00d6, "xs", "?" },
{ 0x0019, 0x00d7, "xs", "?" },
{ 0x0019, 0x00d8, "xs", "?" },
{ 0x0019, 0x00d9, "xs", "?" },
{ 0x0019, 0x00da, "xs", "?" },
{ 0x0019, 0x00db, "DS", "Back Projector Coefficient" },
{ 0x0019, 0x00dc, "SS", "Primary Speed Correction Used" },
{ 0x0019, 0x00dd, "SS", "Overrange Correction Used" },
{ 0x0019, 0x00de, "DS", "Dynamic Z Alpha Value" },
{ 0x0019, 0x00df, "DS", "User Data" },
{ 0x0019, 0x00e0, "DS", "User Data" },
{ 0x0019, 0x00e1, "xs", "?" },
{ 0x0019, 0x00e2, "xs", "?" },
{ 0x0019, 0x00e3, "xs", "?" },
{ 0x0019, 0x00e4, "LT", "?" },
{ 0x0019, 0x00e5, "IS", "?" },
{ 0x0019, 0x00e6, "US", "?" },
{ 0x0019, 0x00e8, "DS", "?" },
{ 0x0019, 0x00e9, "DS", "?" },
{ 0x0019, 0x00eb, "DS", "?" },
{ 0x0019, 0x00ec, "US", "?" },
{ 0x0019, 0x00f0, "xs", "?" },
{ 0x0019, 0x00f1, "xs", "?" },
{ 0x0019, 0x00f2, "xs", "?" },
{ 0x0019, 0x00f3, "xs", "?" },
{ 0x0019, 0x00f4, "LT", "?" },
{ 0x0019, 0x00f9, "DS", "Transmission Gain" },
{ 0x0019, 0x1015, "UN", "?" },
{ 0x0020, 0x0000, "UL", "Relationship Group Length" },
{ 0x0020, 0x000d, "UI", "Study Instance UID" },
{ 0x0020, 0x000e, "UI", "Series Instance UID" },
{ 0x0020, 0x0010, "SH", "Study ID" },
{ 0x0020, 0x0011, "IS", "Series Number" },
{ 0x0020, 0x0012, "IS", "Acquisition Number" },
{ 0x0020, 0x0013, "IS", "Instance (formerly Image) Number" },
{ 0x0020, 0x0014, "IS", "Isotope Number" },
{ 0x0020, 0x0015, "IS", "Phase Number" },
{ 0x0020, 0x0016, "IS", "Interval Number" },
{ 0x0020, 0x0017, "IS", "Time Slot Number" },
{ 0x0020, 0x0018, "IS", "Angle Number" },
{ 0x0020, 0x0020, "CS", "Patient Orientation" },
{ 0x0020, 0x0022, "IS", "Overlay Number" },
{ 0x0020, 0x0024, "IS", "Curve Number" },
{ 0x0020, 0x0026, "IS", "LUT Number" },
{ 0x0020, 0x0030, "DS", "Image Position" },
{ 0x0020, 0x0032, "DS", "Image Position (Patient)" },
{ 0x0020, 0x0035, "DS", "Image Orientation" },
{ 0x0020, 0x0037, "DS", "Image Orientation (Patient)" },
{ 0x0020, 0x0050, "DS", "Location" },
{ 0x0020, 0x0052, "UI", "Frame of Reference UID" },
{ 0x0020, 0x0060, "CS", "Laterality" },
{ 0x0020, 0x0062, "CS", "Image Laterality" },
{ 0x0020, 0x0070, "LT", "Image Geometry Type" },
{ 0x0020, 0x0080, "LO", "Masking Image" },
{ 0x0020, 0x0100, "IS", "Temporal Position Identifier" },
{ 0x0020, 0x0105, "IS", "Number of Temporal Positions" },
{ 0x0020, 0x0110, "DS", "Temporal Resolution" },
{ 0x0020, 0x1000, "IS", "Series in Study" },
{ 0x0020, 0x1001, "DS", "Acquisitions in Series" },
{ 0x0020, 0x1002, "IS", "Images in Acquisition" },
{ 0x0020, 0x1003, "IS", "Images in Series" },
{ 0x0020, 0x1004, "IS", "Acquisitions in Study" },
{ 0x0020, 0x1005, "IS", "Images in Study" },
{ 0x0020, 0x1020, "LO", "Reference" },
{ 0x0020, 0x1040, "LO", "Position Reference Indicator" },
{ 0x0020, 0x1041, "DS", "Slice Location" },
{ 0x0020, 0x1070, "IS", "Other Study Numbers" },
{ 0x0020, 0x1200, "IS", "Number of Patient Related Studies" },
{ 0x0020, 0x1202, "IS", "Number of Patient Related Series" },
{ 0x0020, 0x1204, "IS", "Number of Patient Related Images" },
{ 0x0020, 0x1206, "IS", "Number of Study Related Series" },
{ 0x0020, 0x1208, "IS", "Number of Study Related Series" },
{ 0x0020, 0x3100, "LO", "Source Image IDs" },
{ 0x0020, 0x3401, "LO", "Modifying Device ID" },
{ 0x0020, 0x3402, "LO", "Modified Image ID" },
{ 0x0020, 0x3403, "xs", "Modified Image Date" },
{ 0x0020, 0x3404, "LO", "Modifying Device Manufacturer" },
{ 0x0020, 0x3405, "xs", "Modified Image Time" },
{ 0x0020, 0x3406, "xs", "Modified Image Description" },
{ 0x0020, 0x4000, "LT", "Image Comments" },
{ 0x0020, 0x5000, "AT", "Original Image Identification" },
{ 0x0020, 0x5002, "LO", "Original Image Identification Nomenclature" },
{ 0x0021, 0x0000, "xs", "?" },
{ 0x0021, 0x0001, "xs", "?" },
{ 0x0021, 0x0002, "xs", "?" },
{ 0x0021, 0x0003, "xs", "?" },
{ 0x0021, 0x0004, "DS", "VOI Position" },
{ 0x0021, 0x0005, "xs", "?" },
{ 0x0021, 0x0006, "IS", "CSI Matrix Size Original" },
{ 0x0021, 0x0007, "xs", "?" },
{ 0x0021, 0x0008, "DS", "Spatial Grid Shift" },
{ 0x0021, 0x0009, "DS", "Signal Limits Minimum" },
{ 0x0021, 0x0010, "xs", "?" },
{ 0x0021, 0x0011, "xs", "?" },
{ 0x0021, 0x0012, "xs", "?" },
{ 0x0021, 0x0013, "xs", "?" },
{ 0x0021, 0x0014, "xs", "?" },
{ 0x0021, 0x0015, "xs", "?" },
{ 0x0021, 0x0016, "xs", "?" },
{ 0x0021, 0x0017, "DS", "EPI Operation Mode Flag" },
{ 0x0021, 0x0018, "xs", "?" },
{ 0x0021, 0x0019, "xs", "?" },
{ 0x0021, 0x0020, "xs", "?" },
{ 0x0021, 0x0021, "xs", "?" },
{ 0x0021, 0x0022, "xs", "?" },
{ 0x0021, 0x0024, "xs", "?" },
{ 0x0021, 0x0025, "US", "?" },
{ 0x0021, 0x0026, "IS", "Image Pixel Offset" },
{ 0x0021, 0x0030, "xs", "?" },
{ 0x0021, 0x0031, "xs", "?" },
{ 0x0021, 0x0032, "xs", "?" },
{ 0x0021, 0x0034, "xs", "?" },
{ 0x0021, 0x0035, "SS", "Series From Which Prescribed" },
{ 0x0021, 0x0036, "xs", "?" },
{ 0x0021, 0x0037, "SS", "Screen Format" },
{ 0x0021, 0x0039, "DS", "Slab Thickness" },
{ 0x0021, 0x0040, "xs", "?" },
{ 0x0021, 0x0041, "xs", "?" },
{ 0x0021, 0x0042, "xs", "?" },
{ 0x0021, 0x0043, "xs", "?" },
{ 0x0021, 0x0044, "xs", "?" },
{ 0x0021, 0x0045, "xs", "?" },
{ 0x0021, 0x0046, "xs", "?" },
{ 0x0021, 0x0047, "xs", "?" },
{ 0x0021, 0x0048, "xs", "?" },
{ 0x0021, 0x0049, "xs", "?" },
{ 0x0021, 0x004a, "xs", "?" },
{ 0x0021, 0x004e, "US", "?" },
{ 0x0021, 0x004f, "xs", "?" },
{ 0x0021, 0x0050, "xs", "?" },
{ 0x0021, 0x0051, "xs", "?" },
{ 0x0021, 0x0052, "xs", "?" },
{ 0x0021, 0x0053, "xs", "?" },
{ 0x0021, 0x0054, "xs", "?" },
{ 0x0021, 0x0055, "xs", "?" },
{ 0x0021, 0x0056, "xs", "?" },
{ 0x0021, 0x0057, "xs", "?" },
{ 0x0021, 0x0058, "xs", "?" },
{ 0x0021, 0x0059, "xs", "?" },
{ 0x0021, 0x005a, "SL", "Integer Slop" },
{ 0x0021, 0x005b, "DS", "Float Slop" },
{ 0x0021, 0x005c, "DS", "Float Slop" },
{ 0x0021, 0x005d, "DS", "Float Slop" },
{ 0x0021, 0x005e, "DS", "Float Slop" },
{ 0x0021, 0x005f, "DS", "Float Slop" },
{ 0x0021, 0x0060, "xs", "?" },
{ 0x0021, 0x0061, "DS", "Image Normal" },
{ 0x0021, 0x0062, "IS", "Reference Type Code" },
{ 0x0021, 0x0063, "DS", "Image Distance" },
{ 0x0021, 0x0065, "US", "Image Positioning History Mask" },
{ 0x0021, 0x006a, "DS", "Image Row" },
{ 0x0021, 0x006b, "DS", "Image Column" },
{ 0x0021, 0x0070, "xs", "?" },
{ 0x0021, 0x0071, "xs", "?" },
{ 0x0021, 0x0072, "xs", "?" },
{ 0x0021, 0x0073, "DS", "Second Repetition Time" },
{ 0x0021, 0x0075, "DS", "Light Brightness" },
{ 0x0021, 0x0076, "DS", "Light Contrast" },
{ 0x0021, 0x007a, "IS", "Overlay Threshold" },
{ 0x0021, 0x007b, "IS", "Surface Threshold" },
{ 0x0021, 0x007c, "IS", "Grey Scale Threshold" },
{ 0x0021, 0x0080, "xs", "?" },
{ 0x0021, 0x0081, "DS", "Auto Window Level Alpha" },
{ 0x0021, 0x0082, "xs", "?" },
{ 0x0021, 0x0083, "DS", "Auto Window Level Window" },
{ 0x0021, 0x0084, "DS", "Auto Window Level Level" },
{ 0x0021, 0x0090, "xs", "?" },
{ 0x0021, 0x0091, "xs", "?" },
{ 0x0021, 0x0092, "xs", "?" },
{ 0x0021, 0x0093, "xs", "?" },
{ 0x0021, 0x0094, "DS", "EPI Change Value of X Component" },
{ 0x0021, 0x0095, "DS", "EPI Change Value of Y Component" },
{ 0x0021, 0x0096, "DS", "EPI Change Value of Z Component" },
{ 0x0021, 0x00a0, "xs", "?" },
{ 0x0021, 0x00a1, "DS", "?" },
{ 0x0021, 0x00a2, "xs", "?" },
{ 0x0021, 0x00a3, "LT", "?" },
{ 0x0021, 0x00a4, "LT", "?" },
{ 0x0021, 0x00a7, "LT", "?" },
{ 0x0021, 0x00b0, "IS", "?" },
{ 0x0021, 0x00c0, "IS", "?" },
{ 0x0023, 0x0000, "xs", "?" },
{ 0x0023, 0x0001, "SL", "Number Of Series In Study" },
{ 0x0023, 0x0002, "SL", "Number Of Unarchived Series" },
{ 0x0023, 0x0010, "xs", "?" },
{ 0x0023, 0x0020, "xs", "?" },
{ 0x0023, 0x0030, "xs", "?" },
{ 0x0023, 0x0040, "xs", "?" },
{ 0x0023, 0x0050, "xs", "?" },
{ 0x0023, 0x0060, "xs", "?" },
{ 0x0023, 0x0070, "xs", "?" },
{ 0x0023, 0x0074, "SL", "Number Of Updates To Info" },
{ 0x0023, 0x007d, "SS", "Indicates If Study Has Complete Info" },
{ 0x0023, 0x0080, "xs", "?" },
{ 0x0023, 0x0090, "xs", "?" },
{ 0x0023, 0x00ff, "US", "?" },
{ 0x0025, 0x0000, "UL", "Group Length" },
{ 0x0025, 0x0006, "SS", "Last Pulse Sequence Used" },
{ 0x0025, 0x0007, "SL", "Images In Series" },
{ 0x0025, 0x0010, "SS", "Landmark Counter" },
{ 0x0025, 0x0011, "SS", "Number Of Acquisitions" },
{ 0x0025, 0x0014, "SL", "Indicates Number Of Updates To Info" },
{ 0x0025, 0x0017, "SL", "Series Complete Flag" },
{ 0x0025, 0x0018, "SL", "Number Of Images Archived" },
{ 0x0025, 0x0019, "SL", "Last Image Number Used" },
{ 0x0025, 0x001a, "SH", "Primary Receiver Suite And Host" },
{ 0x0027, 0x0000, "US", "?" },
{ 0x0027, 0x0006, "SL", "Image Archive Flag" },
{ 0x0027, 0x0010, "SS", "Scout Type" },
{ 0x0027, 0x0011, "UN", "?" },
{ 0x0027, 0x0012, "IS", "?" },
{ 0x0027, 0x0013, "IS", "?" },
{ 0x0027, 0x0014, "IS", "?" },
{ 0x0027, 0x0015, "IS", "?" },
{ 0x0027, 0x0016, "LT", "?" },
{ 0x0027, 0x001c, "SL", "Vma Mamp" },
{ 0x0027, 0x001d, "SS", "Vma Phase" },
{ 0x0027, 0x001e, "SL", "Vma Mod" },
{ 0x0027, 0x001f, "SL", "Vma Clip" },
{ 0x0027, 0x0020, "SS", "Smart Scan On Off Flag" },
{ 0x0027, 0x0030, "SH", "Foreign Image Revision" },
{ 0x0027, 0x0031, "SS", "Imaging Mode" },
{ 0x0027, 0x0032, "SS", "Pulse Sequence" },
{ 0x0027, 0x0033, "SL", "Imaging Options" },
{ 0x0027, 0x0035, "SS", "Plane Type" },
{ 0x0027, 0x0036, "SL", "Oblique Plane" },
{ 0x0027, 0x0040, "SH", "RAS Letter Of Image Location" },
{ 0x0027, 0x0041, "FL", "Image Location" },
{ 0x0027, 0x0042, "FL", "Center R Coord Of Plane Image" },
{ 0x0027, 0x0043, "FL", "Center A Coord Of Plane Image" },
{ 0x0027, 0x0044, "FL", "Center S Coord Of Plane Image" },
{ 0x0027, 0x0045, "FL", "Normal R Coord" },
{ 0x0027, 0x0046, "FL", "Normal A Coord" },
{ 0x0027, 0x0047, "FL", "Normal S Coord" },
{ 0x0027, 0x0048, "FL", "R Coord Of Top Right Corner" },
{ 0x0027, 0x0049, "FL", "A Coord Of Top Right Corner" },
{ 0x0027, 0x004a, "FL", "S Coord Of Top Right Corner" },
{ 0x0027, 0x004b, "FL", "R Coord Of Bottom Right Corner" },
{ 0x0027, 0x004c, "FL", "A Coord Of Bottom Right Corner" },
{ 0x0027, 0x004d, "FL", "S Coord Of Bottom Right Corner" },
{ 0x0027, 0x0050, "FL", "Table Start Location" },
{ 0x0027, 0x0051, "FL", "Table End Location" },
{ 0x0027, 0x0052, "SH", "RAS Letter For Side Of Image" },
{ 0x0027, 0x0053, "SH", "RAS Letter For Anterior Posterior" },
{ 0x0027, 0x0054, "SH", "RAS Letter For Scout Start Loc" },
{ 0x0027, 0x0055, "SH", "RAS Letter For Scout End Loc" },
{ 0x0027, 0x0060, "FL", "Image Dimension X" },
{ 0x0027, 0x0061, "FL", "Image Dimension Y" },
{ 0x0027, 0x0062, "FL", "Number Of Excitations" },
{ 0x0028, 0x0000, "UL", "Image Presentation Group Length" },
{ 0x0028, 0x0002, "US", "Samples per Pixel" },
{ 0x0028, 0x0004, "CS", "Photometric Interpretation" },
{ 0x0028, 0x0005, "US", "Image Dimensions" },
{ 0x0028, 0x0006, "US", "Planar Configuration" },
{ 0x0028, 0x0008, "IS", "Number of Frames" },
{ 0x0028, 0x0009, "AT", "Frame Increment Pointer" },
{ 0x0028, 0x0010, "US", "Rows" },
{ 0x0028, 0x0011, "US", "Columns" },
{ 0x0028, 0x0012, "US", "Planes" },
{ 0x0028, 0x0014, "US", "Ultrasound Color Data Present" },
{ 0x0028, 0x0030, "DS", "Pixel Spacing" },
{ 0x0028, 0x0031, "DS", "Zoom Factor" },
{ 0x0028, 0x0032, "DS", "Zoom Center" },
{ 0x0028, 0x0034, "IS", "Pixel Aspect Ratio" },
{ 0x0028, 0x0040, "LO", "Image Format" },
{ 0x0028, 0x0050, "LT", "Manipulated Image" },
{ 0x0028, 0x0051, "CS", "Corrected Image" },
{ 0x0028, 0x005f, "LO", "Compression Recognition Code" },
{ 0x0028, 0x0060, "LO", "Compression Code" },
{ 0x0028, 0x0061, "SH", "Compression Originator" },
{ 0x0028, 0x0062, "SH", "Compression Label" },
{ 0x0028, 0x0063, "SH", "Compression Description" },
{ 0x0028, 0x0065, "LO", "Compression Sequence" },
{ 0x0028, 0x0066, "AT", "Compression Step Pointers" },
{ 0x0028, 0x0068, "US", "Repeat Interval" },
{ 0x0028, 0x0069, "US", "Bits Grouped" },
{ 0x0028, 0x0070, "US", "Perimeter Table" },
{ 0x0028, 0x0071, "xs", "Perimeter Value" },
{ 0x0028, 0x0080, "US", "Predictor Rows" },
{ 0x0028, 0x0081, "US", "Predictor Columns" },
{ 0x0028, 0x0082, "US", "Predictor Constants" },
{ 0x0028, 0x0090, "LO", "Blocked Pixels" },
{ 0x0028, 0x0091, "US", "Block Rows" },
{ 0x0028, 0x0092, "US", "Block Columns" },
{ 0x0028, 0x0093, "US", "Row Overlap" },
{ 0x0028, 0x0094, "US", "Column Overlap" },
{ 0x0028, 0x0100, "US", "Bits Allocated" },
{ 0x0028, 0x0101, "US", "Bits Stored" },
{ 0x0028, 0x0102, "US", "High Bit" },
{ 0x0028, 0x0103, "US", "Pixel Representation" },
{ 0x0028, 0x0104, "xs", "Smallest Valid Pixel Value" },
{ 0x0028, 0x0105, "xs", "Largest Valid Pixel Value" },
{ 0x0028, 0x0106, "xs", "Smallest Image Pixel Value" },
{ 0x0028, 0x0107, "xs", "Largest Image Pixel Value" },
{ 0x0028, 0x0108, "xs", "Smallest Pixel Value in Series" },
{ 0x0028, 0x0109, "xs", "Largest Pixel Value in Series" },
{ 0x0028, 0x0110, "xs", "Smallest Pixel Value in Plane" },
{ 0x0028, 0x0111, "xs", "Largest Pixel Value in Plane" },
{ 0x0028, 0x0120, "xs", "Pixel Padding Value" },
{ 0x0028, 0x0200, "xs", "Image Location" },
{ 0x0028, 0x0300, "CS", "Quality Control Image" },
{ 0x0028, 0x0301, "CS", "Burned In Annotation" },
{ 0x0028, 0x0400, "xs", "?" },
{ 0x0028, 0x0401, "xs", "?" },
{ 0x0028, 0x0402, "xs", "?" },
{ 0x0028, 0x0403, "xs", "?" },
{ 0x0028, 0x0404, "AT", "Details of Coefficients" },
{ 0x0028, 0x0700, "LO", "DCT Label" },
{ 0x0028, 0x0701, "LO", "Data Block Description" },
{ 0x0028, 0x0702, "AT", "Data Block" },
{ 0x0028, 0x0710, "US", "Normalization Factor Format" },
{ 0x0028, 0x0720, "US", "Zonal Map Number Format" },
{ 0x0028, 0x0721, "AT", "Zonal Map Location" },
{ 0x0028, 0x0722, "US", "Zonal Map Format" },
{ 0x0028, 0x0730, "US", "Adaptive Map Format" },
{ 0x0028, 0x0740, "US", "Code Number Format" },
{ 0x0028, 0x0800, "LO", "Code Label" },
{ 0x0028, 0x0802, "US", "Number of Tables" },
{ 0x0028, 0x0803, "AT", "Code Table Location" },
{ 0x0028, 0x0804, "US", "Bits For Code Word" },
{ 0x0028, 0x0808, "AT", "Image Data Location" },
{ 0x0028, 0x1040, "CS", "Pixel Intensity Relationship" },
{ 0x0028, 0x1041, "SS", "Pixel Intensity Relationship Sign" },
{ 0x0028, 0x1050, "DS", "Window Center" },
{ 0x0028, 0x1051, "DS", "Window Width" },
{ 0x0028, 0x1052, "DS", "Rescale Intercept" },
{ 0x0028, 0x1053, "DS", "Rescale Slope" },
{ 0x0028, 0x1054, "LO", "Rescale Type" },
{ 0x0028, 0x1055, "LO", "Window Center & Width Explanation" },
{ 0x0028, 0x1080, "LO", "Gray Scale" },
{ 0x0028, 0x1090, "CS", "Recommended Viewing Mode" },
{ 0x0028, 0x1100, "xs", "Gray Lookup Table Descriptor" },
{ 0x0028, 0x1101, "xs", "Red Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1102, "xs", "Green Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1103, "xs", "Blue Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1111, "OW", "Large Red Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1112, "OW", "Large Green Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1113, "OW", "Large Blue Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1199, "UI", "Palette Color Lookup Table UID" },
{ 0x0028, 0x1200, "xs", "Gray Lookup Table Data" },
{ 0x0028, 0x1201, "OW", "Red Palette Color Lookup Table Data" },
{ 0x0028, 0x1202, "OW", "Green Palette Color Lookup Table Data" },
{ 0x0028, 0x1203, "OW", "Blue Palette Color Lookup Table Data" },
{ 0x0028, 0x1211, "OW", "Large Red Palette Color Lookup Table Data" },
{ 0x0028, 0x1212, "OW", "Large Green Palette Color Lookup Table Data" },
{ 0x0028, 0x1213, "OW", "Large Blue Palette Color Lookup Table Data" },
{ 0x0028, 0x1214, "UI", "Large Palette Color Lookup Table UID" },
{ 0x0028, 0x1221, "OW", "Segmented Red Palette Color Lookup Table Data" },
{ 0x0028, 0x1222, "OW", "Segmented Green Palette Color Lookup Table Data" },
{ 0x0028, 0x1223, "OW", "Segmented Blue Palette Color Lookup Table Data" },
{ 0x0028, 0x1300, "CS", "Implant Present" },
{ 0x0028, 0x2110, "CS", "Lossy Image Compression" },
{ 0x0028, 0x2112, "DS", "Lossy Image Compression Ratio" },
{ 0x0028, 0x3000, "SQ", "Modality LUT Sequence" },
{ 0x0028, 0x3002, "US", "LUT Descriptor" },
{ 0x0028, 0x3003, "LO", "LUT Explanation" },
{ 0x0028, 0x3004, "LO", "Modality LUT Type" },
{ 0x0028, 0x3006, "US", "LUT Data" },
{ 0x0028, 0x3010, "xs", "VOI LUT Sequence" },
{ 0x0028, 0x4000, "LT", "Image Presentation Comments" },
{ 0x0028, 0x5000, "SQ", "Biplane Acquisition Sequence" },
{ 0x0028, 0x6010, "US", "Representative Frame Number" },
{ 0x0028, 0x6020, "US", "Frame Numbers of Interest" },
{ 0x0028, 0x6022, "LO", "Frame of Interest Description" },
{ 0x0028, 0x6030, "US", "Mask Pointer" },
{ 0x0028, 0x6040, "US", "R Wave Pointer" },
{ 0x0028, 0x6100, "SQ", "Mask Subtraction Sequence" },
{ 0x0028, 0x6101, "CS", "Mask Operation" },
{ 0x0028, 0x6102, "US", "Applicable Frame Range" },
{ 0x0028, 0x6110, "US", "Mask Frame Numbers" },
{ 0x0028, 0x6112, "US", "Contrast Frame Averaging" },
{ 0x0028, 0x6114, "FL", "Mask Sub-Pixel Shift" },
{ 0x0028, 0x6120, "SS", "TID Offset" },
{ 0x0028, 0x6190, "ST", "Mask Operation Explanation" },
{ 0x0029, 0x0000, "xs", "?" },
{ 0x0029, 0x0001, "xs", "?" },
{ 0x0029, 0x0002, "xs", "?" },
{ 0x0029, 0x0003, "xs", "?" },
{ 0x0029, 0x0004, "xs", "?" },
{ 0x0029, 0x0005, "xs", "?" },
{ 0x0029, 0x0006, "xs", "?" },
{ 0x0029, 0x0007, "SL", "Lower Range Of Pixels" },
{ 0x0029, 0x0008, "SH", "Lower Range Of Pixels" },
{ 0x0029, 0x0009, "SH", "Lower Range Of Pixels" },
{ 0x0029, 0x000a, "SS", "Lower Range Of Pixels" },
{ 0x0029, 0x000c, "xs", "?" },
{ 0x0029, 0x000e, "CS", "Zoom Enable Status" },
{ 0x0029, 0x000f, "CS", "Zoom Select Status" },
{ 0x0029, 0x0010, "xs", "?" },
{ 0x0029, 0x0011, "xs", "?" },
{ 0x0029, 0x0013, "LT", "?" },
{ 0x0029, 0x0015, "xs", "?" },
{ 0x0029, 0x0016, "SL", "Lower Range Of Pixels" },
{ 0x0029, 0x0017, "SL", "Lower Range Of Pixels" },
{ 0x0029, 0x0018, "SL", "Upper Range Of Pixels" },
{ 0x0029, 0x001a, "SL", "Length Of Total Info In Bytes" },
{ 0x0029, 0x001e, "xs", "?" },
{ 0x0029, 0x001f, "xs", "?" },
{ 0x0029, 0x0020, "xs", "?" },
{ 0x0029, 0x0022, "IS", "Pixel Quality Value" },
{ 0x0029, 0x0025, "LT", "Processed Pixel Data Quality" },
{ 0x0029, 0x0026, "SS", "Version Of Info Structure" },
{ 0x0029, 0x0030, "xs", "?" },
{ 0x0029, 0x0031, "xs", "?" },
{ 0x0029, 0x0032, "xs", "?" },
{ 0x0029, 0x0033, "xs", "?" },
{ 0x0029, 0x0034, "xs", "?" },
{ 0x0029, 0x0035, "SL", "Advantage Comp Underflow" },
{ 0x0029, 0x0038, "US", "?" },
{ 0x0029, 0x0040, "xs", "?" },
{ 0x0029, 0x0041, "DS", "Magnifying Glass Rectangle" },
{ 0x0029, 0x0043, "DS", "Magnifying Glass Factor" },
{ 0x0029, 0x0044, "US", "Magnifying Glass Function" },
{ 0x0029, 0x004e, "CS", "Magnifying Glass Enable Status" },
{ 0x0029, 0x004f, "CS", "Magnifying Glass Select Status" },
{ 0x0029, 0x0050, "xs", "?" },
{ 0x0029, 0x0051, "LT", "Exposure Code" },
{ 0x0029, 0x0052, "LT", "Sort Code" },
{ 0x0029, 0x0053, "LT", "?" },
{ 0x0029, 0x0060, "xs", "?" },
{ 0x0029, 0x0061, "xs", "?" },
{ 0x0029, 0x0067, "LT", "?" },
{ 0x0029, 0x0070, "xs", "?" },
{ 0x0029, 0x0071, "xs", "?" },
{ 0x0029, 0x0072, "xs", "?" },
{ 0x0029, 0x0077, "CS", "Window Select Status" },
{ 0x0029, 0x0078, "LT", "ECG Display Printing ID" },
{ 0x0029, 0x0079, "CS", "ECG Display Printing" },
{ 0x0029, 0x007e, "CS", "ECG Display Printing Enable Status" },
{ 0x0029, 0x007f, "CS", "ECG Display Printing Select Status" },
{ 0x0029, 0x0080, "xs", "?" },
{ 0x0029, 0x0081, "xs", "?" },
{ 0x0029, 0x0082, "IS", "View Zoom" },
{ 0x0029, 0x0083, "IS", "View Transform" },
{ 0x0029, 0x008e, "CS", "Physiological Display Enable Status" },
{ 0x0029, 0x008f, "CS", "Physiological Display Select Status" },
{ 0x0029, 0x0090, "IS", "?" },
{ 0x0029, 0x0099, "LT", "Shutter Type" },
{ 0x0029, 0x00a0, "US", "Rows of Rectangular Shutter" },
{ 0x0029, 0x00a1, "US", "Columns of Rectangular Shutter" },
{ 0x0029, 0x00a2, "US", "Origin of Rectangular Shutter" },
{ 0x0029, 0x00b0, "US", "Radius of Circular Shutter" },
{ 0x0029, 0x00b2, "US", "Origin of Circular Shutter" },
{ 0x0029, 0x00c0, "LT", "Functional Shutter ID" },
{ 0x0029, 0x00c1, "xs", "?" },
{ 0x0029, 0x00c3, "IS", "Scan Resolution" },
{ 0x0029, 0x00c4, "IS", "Field of View" },
{ 0x0029, 0x00c5, "LT", "Field Of Shutter Rectangle" },
{ 0x0029, 0x00ce, "CS", "Shutter Enable Status" },
{ 0x0029, 0x00cf, "CS", "Shutter Select Status" },
{ 0x0029, 0x00d0, "IS", "?" },
{ 0x0029, 0x00d1, "IS", "?" },
{ 0x0029, 0x00d5, "LT", "Slice Thickness" },
{ 0x0031, 0x0010, "LT", "Request UID" },
{ 0x0031, 0x0012, "LT", "Examination Reason" },
{ 0x0031, 0x0030, "DA", "Requested Date" },
{ 0x0031, 0x0032, "TM", "Worklist Request Start Time" },
{ 0x0031, 0x0033, "TM", "Worklist Request End Time" },
{ 0x0031, 0x0045, "LT", "Requesting Physician" },
{ 0x0031, 0x004a, "TM", "Requested Time" },
{ 0x0031, 0x0050, "LT", "Requested Physician" },
{ 0x0031, 0x0080, "LT", "Requested Location" },
{ 0x0032, 0x0000, "UL", "Study Group Length" },
{ 0x0032, 0x000a, "CS", "Study Status ID" },
{ 0x0032, 0x000c, "CS", "Study Priority ID" },
{ 0x0032, 0x0012, "LO", "Study ID Issuer" },
{ 0x0032, 0x0032, "DA", "Study Verified Date" },
{ 0x0032, 0x0033, "TM", "Study Verified Time" },
{ 0x0032, 0x0034, "DA", "Study Read Date" },
{ 0x0032, 0x0035, "TM", "Study Read Time" },
{ 0x0032, 0x1000, "DA", "Scheduled Study Start Date" },
{ 0x0032, 0x1001, "TM", "Scheduled Study Start Time" },
{ 0x0032, 0x1010, "DA", "Scheduled Study Stop Date" },
{ 0x0032, 0x1011, "TM", "Scheduled Study Stop Time" },
{ 0x0032, 0x1020, "LO", "Scheduled Study Location" },
{ 0x0032, 0x1021, "AE", "Scheduled Study Location AE Title(s)" },
{ 0x0032, 0x1030, "LO", "Reason for Study" },
{ 0x0032, 0x1032, "PN", "Requesting Physician" },
{ 0x0032, 0x1033, "LO", "Requesting Service" },
{ 0x0032, 0x1040, "DA", "Study Arrival Date" },
{ 0x0032, 0x1041, "TM", "Study Arrival Time" },
{ 0x0032, 0x1050, "DA", "Study Completion Date" },
{ 0x0032, 0x1051, "TM", "Study Completion Time" },
{ 0x0032, 0x1055, "CS", "Study Component Status ID" },
{ 0x0032, 0x1060, "LO", "Requested Procedure Description" },
{ 0x0032, 0x1064, "SQ", "Requested Procedure Code Sequence" },
{ 0x0032, 0x1070, "LO", "Requested Contrast Agent" },
{ 0x0032, 0x4000, "LT", "Study Comments" },
{ 0x0033, 0x0001, "UN", "?" },
{ 0x0033, 0x0002, "UN", "?" },
{ 0x0033, 0x0005, "UN", "?" },
{ 0x0033, 0x0006, "UN", "?" },
{ 0x0033, 0x0010, "LT", "Patient Study UID" },
{ 0x0037, 0x0010, "LO", "ReferringDepartment" },
{ 0x0037, 0x0020, "US", "ScreenNumber" },
{ 0x0037, 0x0040, "SH", "LeftOrientation" },
{ 0x0037, 0x0042, "SH", "RightOrientation" },
{ 0x0037, 0x0050, "CS", "Inversion" },
{ 0x0037, 0x0060, "US", "DSA" },
{ 0x0038, 0x0000, "UL", "Visit Group Length" },
{ 0x0038, 0x0004, "SQ", "Referenced Patient Alias Sequence" },
{ 0x0038, 0x0008, "CS", "Visit Status ID" },
{ 0x0038, 0x0010, "LO", "Admission ID" },
{ 0x0038, 0x0011, "LO", "Issuer of Admission ID" },
{ 0x0038, 0x0016, "LO", "Route of Admissions" },
{ 0x0038, 0x001a, "DA", "Scheduled Admission Date" },
{ 0x0038, 0x001b, "TM", "Scheduled Admission Time" },
{ 0x0038, 0x001c, "DA", "Scheduled Discharge Date" },
{ 0x0038, 0x001d, "TM", "Scheduled Discharge Time" },
{ 0x0038, 0x001e, "LO", "Scheduled Patient Institution Residence" },
{ 0x0038, 0x0020, "DA", "Admitting Date" },
{ 0x0038, 0x0021, "TM", "Admitting Time" },
{ 0x0038, 0x0030, "DA", "Discharge Date" },
{ 0x0038, 0x0032, "TM", "Discharge Time" },
{ 0x0038, 0x0040, "LO", "Discharge Diagnosis Description" },
{ 0x0038, 0x0044, "SQ", "Discharge Diagnosis Code Sequence" },
{ 0x0038, 0x0050, "LO", "Special Needs" },
{ 0x0038, 0x0300, "LO", "Current Patient Location" },
{ 0x0038, 0x0400, "LO", "Patient's Institution Residence" },
{ 0x0038, 0x0500, "LO", "Patient State" },
{ 0x0038, 0x4000, "LT", "Visit Comments" },
{ 0x0039, 0x0080, "IS", "Private Entity Number" },
{ 0x0039, 0x0085, "DA", "Private Entity Date" },
{ 0x0039, 0x0090, "TM", "Private Entity Time" },
{ 0x0039, 0x0095, "LO", "Private Entity Launch Command" },
{ 0x0039, 0x00aa, "CS", "Private Entity Type" },
{ 0x003a, 0x0002, "SQ", "Waveform Sequence" },
{ 0x003a, 0x0005, "US", "Waveform Number of Channels" },
{ 0x003a, 0x0010, "UL", "Waveform Number of Samples" },
{ 0x003a, 0x001a, "DS", "Sampling Frequency" },
{ 0x003a, 0x0020, "SH", "Group Label" },
{ 0x003a, 0x0103, "CS", "Waveform Sample Value Representation" },
{ 0x003a, 0x0122, "OB", "Waveform Padding Value" },
{ 0x003a, 0x0200, "SQ", "Channel Definition" },
{ 0x003a, 0x0202, "IS", "Waveform Channel Number" },
{ 0x003a, 0x0203, "SH", "Channel Label" },
{ 0x003a, 0x0205, "CS", "Channel Status" },
{ 0x003a, 0x0208, "SQ", "Channel Source" },
{ 0x003a, 0x0209, "SQ", "Channel Source Modifiers" },
{ 0x003a, 0x020a, "SQ", "Differential Channel Source" },
{ 0x003a, 0x020b, "SQ", "Differential Channel Source Modifiers" },
{ 0x003a, 0x0210, "DS", "Channel Sensitivity" },
{ 0x003a, 0x0211, "SQ", "Channel Sensitivity Units" },
{ 0x003a, 0x0212, "DS", "Channel Sensitivity Correction Factor" },
{ 0x003a, 0x0213, "DS", "Channel Baseline" },
{ 0x003a, 0x0214, "DS", "Channel Time Skew" },
{ 0x003a, 0x0215, "DS", "Channel Sample Skew" },
{ 0x003a, 0x0216, "OB", "Channel Minimum Value" },
{ 0x003a, 0x0217, "OB", "Channel Maximum Value" },
{ 0x003a, 0x0218, "DS", "Channel Offset" },
{ 0x003a, 0x021a, "US", "Bits Per Sample" },
{ 0x003a, 0x0220, "DS", "Filter Low Frequency" },
{ 0x003a, 0x0221, "DS", "Filter High Frequency" },
{ 0x003a, 0x0222, "DS", "Notch Filter Frequency" },
{ 0x003a, 0x0223, "DS", "Notch Filter Bandwidth" },
{ 0x003a, 0x1000, "OB", "Waveform Data" },
{ 0x0040, 0x0001, "AE", "Scheduled Station AE Title" },
{ 0x0040, 0x0002, "DA", "Scheduled Procedure Step Start Date" },
{ 0x0040, 0x0003, "TM", "Scheduled Procedure Step Start Time" },
{ 0x0040, 0x0004, "DA", "Scheduled Procedure Step End Date" },
{ 0x0040, 0x0005, "TM", "Scheduled Procedure Step End Time" },
{ 0x0040, 0x0006, "PN", "Scheduled Performing Physician Name" },
{ 0x0040, 0x0007, "LO", "Scheduled Procedure Step Description" },
{ 0x0040, 0x0008, "SQ", "Scheduled Action Item Code Sequence" },
{ 0x0040, 0x0009, "SH", "Scheduled Procedure Step ID" },
{ 0x0040, 0x0010, "SH", "Scheduled Station Name" },
{ 0x0040, 0x0011, "SH", "Scheduled Procedure Step Location" },
{ 0x0040, 0x0012, "LO", "Pre-Medication" },
{ 0x0040, 0x0020, "CS", "Scheduled Procedure Step Status" },
{ 0x0040, 0x0100, "SQ", "Scheduled Procedure Step Sequence" },
{ 0x0040, 0x0302, "US", "Entrance Dose" },
{ 0x0040, 0x0303, "US", "Exposed Area" },
{ 0x0040, 0x0306, "DS", "Distance Source to Entrance" },
{ 0x0040, 0x0307, "DS", "Distance Source to Support" },
{ 0x0040, 0x0310, "ST", "Comments On Radiation Dose" },
{ 0x0040, 0x0312, "DS", "X-Ray Output" },
{ 0x0040, 0x0314, "DS", "Half Value Layer" },
{ 0x0040, 0x0316, "DS", "Organ Dose" },
{ 0x0040, 0x0318, "CS", "Organ Exposed" },
{ 0x0040, 0x0400, "LT", "Comments On Scheduled Procedure Step" },
{ 0x0040, 0x050a, "LO", "Specimen Accession Number" },
{ 0x0040, 0x0550, "SQ", "Specimen Sequence" },
{ 0x0040, 0x0551, "LO", "Specimen Identifier" },
{ 0x0040, 0x0552, "SQ", "Specimen Description Sequence" },
{ 0x0040, 0x0553, "ST", "Specimen Description" },
{ 0x0040, 0x0555, "SQ", "Acquisition Context Sequence" },
{ 0x0040, 0x0556, "ST", "Acquisition Context Description" },
{ 0x0040, 0x059a, "SQ", "Specimen Type Code Sequence" },
{ 0x0040, 0x06fa, "LO", "Slide Identifier" },
{ 0x0040, 0x071a, "SQ", "Image Center Point Coordinates Sequence" },
{ 0x0040, 0x072a, "DS", "X Offset In Slide Coordinate System" },
{ 0x0040, 0x073a, "DS", "Y Offset In Slide Coordinate System" },
{ 0x0040, 0x074a, "DS", "Z Offset In Slide Coordinate System" },
{ 0x0040, 0x08d8, "SQ", "Pixel Spacing Sequence" },
{ 0x0040, 0x08da, "SQ", "Coordinate System Axis Code Sequence" },
{ 0x0040, 0x08ea, "SQ", "Measurement Units Code Sequence" },
{ 0x0040, 0x09f8, "SQ", "Vital Stain Code Sequence" },
{ 0x0040, 0x1001, "SH", "Requested Procedure ID" },
{ 0x0040, 0x1002, "LO", "Reason For Requested Procedure" },
{ 0x0040, 0x1003, "SH", "Requested Procedure Priority" },
{ 0x0040, 0x1004, "LO", "Patient Transport Arrangements" },
{ 0x0040, 0x1005, "LO", "Requested Procedure Location" },
{ 0x0040, 0x1006, "SH", "Placer Order Number of Procedure" },
{ 0x0040, 0x1007, "SH", "Filler Order Number of Procedure" },
{ 0x0040, 0x1008, "LO", "Confidentiality Code" },
{ 0x0040, 0x1009, "SH", "Reporting Priority" },
{ 0x0040, 0x1010, "PN", "Names of Intended Recipients of Results" },
{ 0x0040, 0x1400, "LT", "Requested Procedure Comments" },
{ 0x0040, 0x2001, "LO", "Reason For Imaging Service Request" },
{ 0x0040, 0x2004, "DA", "Issue Date of Imaging Service Request" },
{ 0x0040, 0x2005, "TM", "Issue Time of Imaging Service Request" },
{ 0x0040, 0x2006, "SH", "Placer Order Number of Imaging Service Request" },
{ 0x0040, 0x2007, "SH", "Filler Order Number of Imaging Service Request" },
{ 0x0040, 0x2008, "PN", "Order Entered By" },
{ 0x0040, 0x2009, "SH", "Order Enterer Location" },
{ 0x0040, 0x2010, "SH", "Order Callback Phone Number" },
{ 0x0040, 0x2400, "LT", "Imaging Service Request Comments" },
{ 0x0040, 0x3001, "LO", "Confidentiality Constraint On Patient Data" },
{ 0x0040, 0xa007, "CS", "Findings Flag" },
{ 0x0040, 0xa020, "SQ", "Findings Sequence" },
{ 0x0040, 0xa021, "UI", "Findings Group UID" },
{ 0x0040, 0xa022, "UI", "Referenced Findings Group UID" },
{ 0x0040, 0xa023, "DA", "Findings Group Recording Date" },
{ 0x0040, 0xa024, "TM", "Findings Group Recording Time" },
{ 0x0040, 0xa026, "SQ", "Findings Source Category Code Sequence" },
{ 0x0040, 0xa027, "LO", "Documenting Organization" },
{ 0x0040, 0xa028, "SQ", "Documenting Organization Identifier Code Sequence" },
{ 0x0040, 0xa032, "LO", "History Reliability Qualifier Description" },
{ 0x0040, 0xa043, "SQ", "Concept Name Code Sequence" },
{ 0x0040, 0xa047, "LO", "Measurement Precision Description" },
{ 0x0040, 0xa057, "CS", "Urgency or Priority Alerts" },
{ 0x0040, 0xa060, "LO", "Sequencing Indicator" },
{ 0x0040, 0xa066, "SQ", "Document Identifier Code Sequence" },
{ 0x0040, 0xa067, "PN", "Document Author" },
{ 0x0040, 0xa068, "SQ", "Document Author Identifier Code Sequence" },
{ 0x0040, 0xa070, "SQ", "Identifier Code Sequence" },
{ 0x0040, 0xa073, "LO", "Object String Identifier" },
{ 0x0040, 0xa074, "OB", "Object Binary Identifier" },
{ 0x0040, 0xa075, "PN", "Documenting Observer" },
{ 0x0040, 0xa076, "SQ", "Documenting Observer Identifier Code Sequence" },
{ 0x0040, 0xa078, "SQ", "Observation Subject Identifier Code Sequence" },
{ 0x0040, 0xa080, "SQ", "Person Identifier Code Sequence" },
{ 0x0040, 0xa085, "SQ", "Procedure Identifier Code Sequence" },
{ 0x0040, 0xa088, "LO", "Object Directory String Identifier" },
{ 0x0040, 0xa089, "OB", "Object Directory Binary Identifier" },
{ 0x0040, 0xa090, "CS", "History Reliability Qualifier" },
{ 0x0040, 0xa0a0, "CS", "Referenced Type of Data" },
{ 0x0040, 0xa0b0, "US", "Referenced Waveform Channels" },
{ 0x0040, 0xa110, "DA", "Date of Document or Verbal Transaction" },
{ 0x0040, 0xa112, "TM", "Time of Document Creation or Verbal Transaction" },
{ 0x0040, 0xa121, "DA", "Date" },
{ 0x0040, 0xa122, "TM", "Time" },
{ 0x0040, 0xa123, "PN", "Person Name" },
{ 0x0040, 0xa124, "SQ", "Referenced Person Sequence" },
{ 0x0040, 0xa125, "CS", "Report Status ID" },
{ 0x0040, 0xa130, "CS", "Temporal Range Type" },
{ 0x0040, 0xa132, "UL", "Referenced Sample Offsets" },
{ 0x0040, 0xa136, "US", "Referenced Frame Numbers" },
{ 0x0040, 0xa138, "DS", "Referenced Time Offsets" },
{ 0x0040, 0xa13a, "DT", "Referenced Datetime" },
{ 0x0040, 0xa160, "UT", "Text Value" },
{ 0x0040, 0xa167, "SQ", "Observation Category Code Sequence" },
{ 0x0040, 0xa168, "SQ", "Concept Code Sequence" },
{ 0x0040, 0xa16a, "ST", "Bibliographic Citation" },
{ 0x0040, 0xa170, "CS", "Observation Class" },
{ 0x0040, 0xa171, "UI", "Observation UID" },
{ 0x0040, 0xa172, "UI", "Referenced Observation UID" },
{ 0x0040, 0xa173, "CS", "Referenced Observation Class" },
{ 0x0040, 0xa174, "CS", "Referenced Object Observation Class" },
{ 0x0040, 0xa180, "US", "Annotation Group Number" },
{ 0x0040, 0xa192, "DA", "Observation Date" },
{ 0x0040, 0xa193, "TM", "Observation Time" },
{ 0x0040, 0xa194, "CS", "Measurement Automation" },
{ 0x0040, 0xa195, "SQ", "Concept Name Code Sequence Modifier" },
{ 0x0040, 0xa224, "ST", "Identification Description" },
{ 0x0040, 0xa290, "CS", "Coordinates Set Geometric Type" },
{ 0x0040, 0xa296, "SQ", "Algorithm Code Sequence" },
{ 0x0040, 0xa297, "ST", "Algorithm Description" },
{ 0x0040, 0xa29a, "SL", "Pixel Coordinates Set" },
{ 0x0040, 0xa300, "SQ", "Measured Value Sequence" },
{ 0x0040, 0xa307, "PN", "Current Observer" },
{ 0x0040, 0xa30a, "DS", "Numeric Value" },
{ 0x0040, 0xa313, "SQ", "Referenced Accession Sequence" },
{ 0x0040, 0xa33a, "ST", "Report Status Comment" },
{ 0x0040, 0xa340, "SQ", "Procedure Context Sequence" },
{ 0x0040, 0xa352, "PN", "Verbal Source" },
{ 0x0040, 0xa353, "ST", "Address" },
{ 0x0040, 0xa354, "LO", "Telephone Number" },
{ 0x0040, 0xa358, "SQ", "Verbal Source Identifier Code Sequence" },
{ 0x0040, 0xa380, "SQ", "Report Detail Sequence" },
{ 0x0040, 0xa402, "UI", "Observation Subject UID" },
{ 0x0040, 0xa403, "CS", "Observation Subject Class" },
{ 0x0040, 0xa404, "SQ", "Observation Subject Type Code Sequence" },
{ 0x0040, 0xa600, "CS", "Observation Subject Context Flag" },
{ 0x0040, 0xa601, "CS", "Observer Context Flag" },
{ 0x0040, 0xa603, "CS", "Procedure Context Flag" },
{ 0x0040, 0xa730, "SQ", "Observations Sequence" },
{ 0x0040, 0xa731, "SQ", "Relationship Sequence" },
{ 0x0040, 0xa732, "SQ", "Relationship Type Code Sequence" },
{ 0x0040, 0xa744, "SQ", "Language Code Sequence" },
{ 0x0040, 0xa992, "ST", "Uniform Resource Locator" },
{ 0x0040, 0xb020, "SQ", "Annotation Sequence" },
{ 0x0040, 0xdb73, "SQ", "Relationship Type Code Sequence Modifier" },
{ 0x0041, 0x0000, "LT", "Papyrus Comments" },
{ 0x0041, 0x0010, "xs", "?" },
{ 0x0041, 0x0011, "xs", "?" },
{ 0x0041, 0x0012, "UL", "Pixel Offset" },
{ 0x0041, 0x0013, "SQ", "Image Identifier Sequence" },
{ 0x0041, 0x0014, "SQ", "External File Reference Sequence" },
{ 0x0041, 0x0015, "US", "Number of Images" },
{ 0x0041, 0x0020, "xs", "?" },
{ 0x0041, 0x0021, "UI", "Referenced SOP Class UID" },
{ 0x0041, 0x0022, "UI", "Referenced SOP Instance UID" },
{ 0x0041, 0x0030, "xs", "?" },
{ 0x0041, 0x0031, "xs", "?" },
{ 0x0041, 0x0032, "xs", "?" },
{ 0x0041, 0x0034, "DA", "Modified Date" },
{ 0x0041, 0x0036, "TM", "Modified Time" },
{ 0x0041, 0x0040, "LT", "Owner Name" },
{ 0x0041, 0x0041, "UI", "Referenced Image SOP Class UID" },
{ 0x0041, 0x0042, "UI", "Referenced Image SOP Instance UID" },
{ 0x0041, 0x0050, "xs", "?" },
{ 0x0041, 0x0060, "UL", "Number of Images" },
{ 0x0041, 0x0062, "UL", "Number of Other" },
{ 0x0041, 0x00a0, "LT", "External Folder Element DSID" },
{ 0x0041, 0x00a1, "US", "External Folder Element Data Set Type" },
{ 0x0041, 0x00a2, "LT", "External Folder Element File Location" },
{ 0x0041, 0x00a3, "UL", "External Folder Element Length" },
{ 0x0041, 0x00b0, "LT", "Internal Folder Element DSID" },
{ 0x0041, 0x00b1, "US", "Internal Folder Element Data Set Type" },
{ 0x0041, 0x00b2, "UL", "Internal Offset To Data Set" },
{ 0x0041, 0x00b3, "UL", "Internal Offset To Image" },
{ 0x0043, 0x0001, "SS", "Bitmap Of Prescan Options" },
{ 0x0043, 0x0002, "SS", "Gradient Offset In X" },
{ 0x0043, 0x0003, "SS", "Gradient Offset In Y" },
{ 0x0043, 0x0004, "SS", "Gradient Offset In Z" },
{ 0x0043, 0x0005, "SS", "Image Is Original Or Unoriginal" },
{ 0x0043, 0x0006, "SS", "Number Of EPI Shots" },
{ 0x0043, 0x0007, "SS", "Views Per Segment" },
{ 0x0043, 0x0008, "SS", "Respiratory Rate In BPM" },
{ 0x0043, 0x0009, "SS", "Respiratory Trigger Point" },
{ 0x0043, 0x000a, "SS", "Type Of Receiver Used" },
{ 0x0043, 0x000b, "DS", "Peak Rate Of Change Of Gradient Field" },
{ 0x0043, 0x000c, "DS", "Limits In Units Of Percent" },
{ 0x0043, 0x000d, "DS", "PSD Estimated Limit" },
{ 0x0043, 0x000e, "DS", "PSD Estimated Limit In Tesla Per Second" },
{ 0x0043, 0x000f, "DS", "SAR Avg Head" },
{ 0x0043, 0x0010, "US", "Window Value" },
{ 0x0043, 0x0011, "US", "Total Input Views" },
{ 0x0043, 0x0012, "SS", "Xray Chain" },
{ 0x0043, 0x0013, "SS", "Recon Kernel Parameters" },
{ 0x0043, 0x0014, "SS", "Calibration Parameters" },
{ 0x0043, 0x0015, "SS", "Total Output Views" },
{ 0x0043, 0x0016, "SS", "Number Of Overranges" },
{ 0x0043, 0x0017, "DS", "IBH Image Scale Factors" },
{ 0x0043, 0x0018, "DS", "BBH Coefficients" },
{ 0x0043, 0x0019, "SS", "Number Of BBH Chains To Blend" },
{ 0x0043, 0x001a, "SL", "Starting Channel Number" },
{ 0x0043, 0x001b, "SS", "PPScan Parameters" },
{ 0x0043, 0x001c, "SS", "GE Image Integrity" },
{ 0x0043, 0x001d, "SS", "Level Value" },
{ 0x0043, 0x001e, "xs", "?" },
{ 0x0043, 0x001f, "SL", "Max Overranges In A View" },
{ 0x0043, 0x0020, "DS", "Avg Overranges All Views" },
{ 0x0043, 0x0021, "SS", "Corrected Afterglow Terms" },
{ 0x0043, 0x0025, "SS", "Reference Channels" },
{ 0x0043, 0x0026, "US", "No Views Ref Channels Blocked" },
{ 0x0043, 0x0027, "xs", "?" },
{ 0x0043, 0x0028, "OB", "Unique Image Identifier" },
{ 0x0043, 0x0029, "OB", "Histogram Tables" },
{ 0x0043, 0x002a, "OB", "User Defined Data" },
{ 0x0043, 0x002b, "SS", "Private Scan Options" },
{ 0x0043, 0x002c, "SS", "Effective Echo Spacing" },
{ 0x0043, 0x002d, "SH", "String Slop Field 1" },
{ 0x0043, 0x002e, "SH", "String Slop Field 2" },
{ 0x0043, 0x002f, "SS", "Raw Data Type" },
{ 0x0043, 0x0030, "SS", "Raw Data Type" },
{ 0x0043, 0x0031, "DS", "RA Coord Of Target Recon Centre" },
{ 0x0043, 0x0032, "SS", "Raw Data Type" },
{ 0x0043, 0x0033, "FL", "Neg Scan Spacing" },
{ 0x0043, 0x0034, "IS", "Offset Frequency" },
{ 0x0043, 0x0035, "UL", "User Usage Tag" },
{ 0x0043, 0x0036, "UL", "User Fill Map MSW" },
{ 0x0043, 0x0037, "UL", "User Fill Map LSW" },
{ 0x0043, 0x0038, "FL", "User 25 To User 48" },
{ 0x0043, 0x0039, "IS", "Slop Integer 6 To Slop Integer 9" },
{ 0x0043, 0x0040, "FL", "Trigger On Position" },
{ 0x0043, 0x0041, "FL", "Degree Of Rotation" },
{ 0x0043, 0x0042, "SL", "DAS Trigger Source" },
{ 0x0043, 0x0043, "SL", "DAS Fpa Gain" },
{ 0x0043, 0x0044, "SL", "DAS Output Source" },
{ 0x0043, 0x0045, "SL", "DAS Ad Input" },
{ 0x0043, 0x0046, "SL", "DAS Cal Mode" },
{ 0x0043, 0x0047, "SL", "DAS Cal Frequency" },
{ 0x0043, 0x0048, "SL", "DAS Reg Xm" },
{ 0x0043, 0x0049, "SL", "DAS Auto Zero" },
{ 0x0043, 0x004a, "SS", "Starting Channel Of View" },
{ 0x0043, 0x004b, "SL", "DAS Xm Pattern" },
{ 0x0043, 0x004c, "SS", "TGGC Trigger Mode" },
{ 0x0043, 0x004d, "FL", "Start Scan To Xray On Delay" },
{ 0x0043, 0x004e, "FL", "Duration Of Xray On" },
{ 0x0044, 0x0000, "UI", "?" },
{ 0x0045, 0x0004, "CS", "AES" },
{ 0x0045, 0x0006, "DS", "Angulation" },
{ 0x0045, 0x0009, "DS", "Real Magnification Factor" },
{ 0x0045, 0x000b, "CS", "Senograph Type" },
{ 0x0045, 0x000c, "DS", "Integration Time" },
{ 0x0045, 0x000d, "DS", "ROI Origin X and Y" },
{ 0x0045, 0x0011, "DS", "Receptor Size cm X and Y" },
{ 0x0045, 0x0012, "IS", "Receptor Size Pixels X and Y" },
{ 0x0045, 0x0013, "ST", "Screen" },
{ 0x0045, 0x0014, "DS", "Pixel Pitch Microns" },
{ 0x0045, 0x0015, "IS", "Pixel Depth Bits" },
{ 0x0045, 0x0016, "IS", "Binning Factor X and Y" },
{ 0x0045, 0x001b, "CS", "Clinical View" },
{ 0x0045, 0x001d, "DS", "Mean Of Raw Gray Levels" },
{ 0x0045, 0x001e, "DS", "Mean Of Offset Gray Levels" },
{ 0x0045, 0x001f, "DS", "Mean Of Corrected Gray Levels" },
{ 0x0045, 0x0020, "DS", "Mean Of Region Gray Levels" },
{ 0x0045, 0x0021, "DS", "Mean Of Log Region Gray Levels" },
{ 0x0045, 0x0022, "DS", "Standard Deviation Of Raw Gray Levels" },
{ 0x0045, 0x0023, "DS", "Standard Deviation Of Corrected Gray Levels" },
{ 0x0045, 0x0024, "DS", "Standard Deviation Of Region Gray Levels" },
{ 0x0045, 0x0025, "DS", "Standard Deviation Of Log Region Gray Levels" },
{ 0x0045, 0x0026, "OB", "MAO Buffer" },
{ 0x0045, 0x0027, "IS", "Set Number" },
{ 0x0045, 0x0028, "CS", "WindowingType (LINEAR or GAMMA)" },
{ 0x0045, 0x0029, "DS", "WindowingParameters" },
{ 0x0045, 0x002a, "IS", "Crosshair Cursor X Coordinates" },
{ 0x0045, 0x002b, "IS", "Crosshair Cursor Y Coordinates" },
{ 0x0045, 0x0039, "US", "Vignette Rows" },
{ 0x0045, 0x003a, "US", "Vignette Columns" },
{ 0x0045, 0x003b, "US", "Vignette Bits Allocated" },
{ 0x0045, 0x003c, "US", "Vignette Bits Stored" },
{ 0x0045, 0x003d, "US", "Vignette High Bit" },
{ 0x0045, 0x003e, "US", "Vignette Pixel Representation" },
{ 0x0045, 0x003f, "OB", "Vignette Pixel Data" },
{ 0x0047, 0x0001, "SQ", "Reconstruction Parameters Sequence" },
{ 0x0047, 0x0050, "UL", "Volume Voxel Count" },
{ 0x0047, 0x0051, "UL", "Volume Segment Count" },
{ 0x0047, 0x0053, "US", "Volume Slice Size" },
{ 0x0047, 0x0054, "US", "Volume Slice Count" },
{ 0x0047, 0x0055, "SL", "Volume Threshold Value" },
{ 0x0047, 0x0057, "DS", "Volume Voxel Ratio" },
{ 0x0047, 0x0058, "DS", "Volume Voxel Size" },
{ 0x0047, 0x0059, "US", "Volume Z Position Size" },
{ 0x0047, 0x0060, "DS", "Volume Base Line" },
{ 0x0047, 0x0061, "DS", "Volume Center Point" },
{ 0x0047, 0x0063, "SL", "Volume Skew Base" },
{ 0x0047, 0x0064, "DS", "Volume Registration Transform Rotation Matrix" },
{ 0x0047, 0x0065, "DS", "Volume Registration Transform Translation Vector" },
{ 0x0047, 0x0070, "DS", "KVP List" },
{ 0x0047, 0x0071, "IS", "XRay Tube Current List" },
{ 0x0047, 0x0072, "IS", "Exposure List" },
{ 0x0047, 0x0080, "LO", "Acquisition DLX Identifier" },
{ 0x0047, 0x0085, "SQ", "Acquisition DLX 2D Series Sequence" },
{ 0x0047, 0x0089, "DS", "Contrast Agent Volume List" },
{ 0x0047, 0x008a, "US", "Number Of Injections" },
{ 0x0047, 0x008b, "US", "Frame Count" },
{ 0x0047, 0x0096, "IS", "Used Frames" },
{ 0x0047, 0x0091, "LO", "XA 3D Reconstruction Algorithm Name" },
{ 0x0047, 0x0092, "CS", "XA 3D Reconstruction Algorithm Version" },
{ 0x0047, 0x0093, "DA", "DLX Calibration Date" },
{ 0x0047, 0x0094, "TM", "DLX Calibration Time" },
{ 0x0047, 0x0095, "CS", "DLX Calibration Status" },
{ 0x0047, 0x0098, "US", "Transform Count" },
{ 0x0047, 0x0099, "SQ", "Transform Sequence" },
{ 0x0047, 0x009a, "DS", "Transform Rotation Matrix" },
{ 0x0047, 0x009b, "DS", "Transform Translation Vector" },
{ 0x0047, 0x009c, "LO", "Transform Label" },
{ 0x0047, 0x00b1, "US", "Wireframe Count" },
{ 0x0047, 0x00b2, "US", "Location System" },
{ 0x0047, 0x00b0, "SQ", "Wireframe List" },
{ 0x0047, 0x00b5, "LO", "Wireframe Name" },
{ 0x0047, 0x00b6, "LO", "Wireframe Group Name" },
{ 0x0047, 0x00b7, "LO", "Wireframe Color" },
{ 0x0047, 0x00b8, "SL", "Wireframe Attributes" },
{ 0x0047, 0x00b9, "SL", "Wireframe Point Count" },
{ 0x0047, 0x00ba, "SL", "Wireframe Timestamp" },
{ 0x0047, 0x00bb, "SQ", "Wireframe Point List" },
{ 0x0047, 0x00bc, "DS", "Wireframe Points Coordinates" },
{ 0x0047, 0x00c0, "DS", "Volume Upper Left High Corner RAS" },
{ 0x0047, 0x00c1, "DS", "Volume Slice To RAS Rotation Matrix" },
{ 0x0047, 0x00c2, "DS", "Volume Upper Left High Corner TLOC" },
{ 0x0047, 0x00d1, "OB", "Volume Segment List" },
{ 0x0047, 0x00d2, "OB", "Volume Gradient List" },
{ 0x0047, 0x00d3, "OB", "Volume Density List" },
{ 0x0047, 0x00d4, "OB", "Volume Z Position List" },
{ 0x0047, 0x00d5, "OB", "Volume Original Index List" },
{ 0x0050, 0x0000, "UL", "Calibration Group Length" },
{ 0x0050, 0x0004, "CS", "Calibration Object" },
{ 0x0050, 0x0010, "SQ", "DeviceSequence" },
{ 0x0050, 0x0014, "DS", "DeviceLength" },
{ 0x0050, 0x0016, "DS", "DeviceDiameter" },
{ 0x0050, 0x0017, "CS", "DeviceDiameterUnits" },
{ 0x0050, 0x0018, "DS", "DeviceVolume" },
{ 0x0050, 0x0019, "DS", "InterMarkerDistance" },
{ 0x0050, 0x0020, "LO", "DeviceDescription" },
{ 0x0050, 0x0030, "SQ", "CodedInterventionDeviceSequence" },
{ 0x0051, 0x0010, "xs", "Image Text" },
{ 0x0054, 0x0000, "UL", "Nuclear Acquisition Group Length" },
{ 0x0054, 0x0010, "US", "Energy Window Vector" },
{ 0x0054, 0x0011, "US", "Number of Energy Windows" },
{ 0x0054, 0x0012, "SQ", "Energy Window Information Sequence" },
{ 0x0054, 0x0013, "SQ", "Energy Window Range Sequence" },
{ 0x0054, 0x0014, "DS", "Energy Window Lower Limit" },
{ 0x0054, 0x0015, "DS", "Energy Window Upper Limit" },
{ 0x0054, 0x0016, "SQ", "Radiopharmaceutical Information Sequence" },
{ 0x0054, 0x0017, "IS", "Residual Syringe Counts" },
{ 0x0054, 0x0018, "SH", "Energy Window Name" },
{ 0x0054, 0x0020, "US", "Detector Vector" },
{ 0x0054, 0x0021, "US", "Number of Detectors" },
{ 0x0054, 0x0022, "SQ", "Detector Information Sequence" },
{ 0x0054, 0x0030, "US", "Phase Vector" },
{ 0x0054, 0x0031, "US", "Number of Phases" },
{ 0x0054, 0x0032, "SQ", "Phase Information Sequence" },
{ 0x0054, 0x0033, "US", "Number of Frames In Phase" },
{ 0x0054, 0x0036, "IS", "Phase Delay" },
{ 0x0054, 0x0038, "IS", "Pause Between Frames" },
{ 0x0054, 0x0050, "US", "Rotation Vector" },
{ 0x0054, 0x0051, "US", "Number of Rotations" },
{ 0x0054, 0x0052, "SQ", "Rotation Information Sequence" },
{ 0x0054, 0x0053, "US", "Number of Frames In Rotation" },
{ 0x0054, 0x0060, "US", "R-R Interval Vector" },
{ 0x0054, 0x0061, "US", "Number of R-R Intervals" },
{ 0x0054, 0x0062, "SQ", "Gated Information Sequence" },
{ 0x0054, 0x0063, "SQ", "Data Information Sequence" },
{ 0x0054, 0x0070, "US", "Time Slot Vector" },
{ 0x0054, 0x0071, "US", "Number of Time Slots" },
{ 0x0054, 0x0072, "SQ", "Time Slot Information Sequence" },
{ 0x0054, 0x0073, "DS", "Time Slot Time" },
{ 0x0054, 0x0080, "US", "Slice Vector" },
{ 0x0054, 0x0081, "US", "Number of Slices" },
{ 0x0054, 0x0090, "US", "Angular View Vector" },
{ 0x0054, 0x0100, "US", "Time Slice Vector" },
{ 0x0054, 0x0101, "US", "Number Of Time Slices" },
{ 0x0054, 0x0200, "DS", "Start Angle" },
{ 0x0054, 0x0202, "CS", "Type of Detector Motion" },
{ 0x0054, 0x0210, "IS", "Trigger Vector" },
{ 0x0054, 0x0211, "US", "Number of Triggers in Phase" },
{ 0x0054, 0x0220, "SQ", "View Code Sequence" },
{ 0x0054, 0x0222, "SQ", "View Modifier Code Sequence" },
{ 0x0054, 0x0300, "SQ", "Radionuclide Code Sequence" },
{ 0x0054, 0x0302, "SQ", "Radiopharmaceutical Route Code Sequence" },
{ 0x0054, 0x0304, "SQ", "Radiopharmaceutical Code Sequence" },
{ 0x0054, 0x0306, "SQ", "Calibration Data Sequence" },
{ 0x0054, 0x0308, "US", "Energy Window Number" },
{ 0x0054, 0x0400, "SH", "Image ID" },
{ 0x0054, 0x0410, "SQ", "Patient Orientation Code Sequence" },
{ 0x0054, 0x0412, "SQ", "Patient Orientation Modifier Code Sequence" },
{ 0x0054, 0x0414, "SQ", "Patient Gantry Relationship Code Sequence" },
{ 0x0054, 0x1000, "CS", "Positron Emission Tomography Series Type" },
{ 0x0054, 0x1001, "CS", "Positron Emission Tomography Units" },
{ 0x0054, 0x1002, "CS", "Counts Source" },
{ 0x0054, 0x1004, "CS", "Reprojection Method" },
{ 0x0054, 0x1100, "CS", "Randoms Correction Method" },
{ 0x0054, 0x1101, "LO", "Attenuation Correction Method" },
{ 0x0054, 0x1102, "CS", "Decay Correction" },
{ 0x0054, 0x1103, "LO", "Reconstruction Method" },
{ 0x0054, 0x1104, "LO", "Detector Lines of Response Used" },
{ 0x0054, 0x1105, "LO", "Scatter Correction Method" },
{ 0x0054, 0x1200, "DS", "Axial Acceptance" },
{ 0x0054, 0x1201, "IS", "Axial Mash" },
{ 0x0054, 0x1202, "IS", "Transverse Mash" },
{ 0x0054, 0x1203, "DS", "Detector Element Size" },
{ 0x0054, 0x1210, "DS", "Coincidence Window Width" },
{ 0x0054, 0x1220, "CS", "Secondary Counts Type" },
{ 0x0054, 0x1300, "DS", "Frame Reference Time" },
{ 0x0054, 0x1310, "IS", "Primary Prompts Counts Accumulated" },
{ 0x0054, 0x1311, "IS", "Secondary Counts Accumulated" },
{ 0x0054, 0x1320, "DS", "Slice Sensitivity Factor" },
{ 0x0054, 0x1321, "DS", "Decay Factor" },
{ 0x0054, 0x1322, "DS", "Dose Calibration Factor" },
{ 0x0054, 0x1323, "DS", "Scatter Fraction Factor" },
{ 0x0054, 0x1324, "DS", "Dead Time Factor" },
{ 0x0054, 0x1330, "US", "Image Index" },
{ 0x0054, 0x1400, "CS", "Counts Included" },
{ 0x0054, 0x1401, "CS", "Dead Time Correction Flag" },
{ 0x0055, 0x0046, "LT", "Current Ward" },
{ 0x0058, 0x0000, "SQ", "?" },
{ 0x0060, 0x3000, "SQ", "Histogram Sequence" },
{ 0x0060, 0x3002, "US", "Histogram Number of Bins" },
{ 0x0060, 0x3004, "xs", "Histogram First Bin Value" },
{ 0x0060, 0x3006, "xs", "Histogram Last Bin Value" },
{ 0x0060, 0x3008, "US", "Histogram Bin Width" },
{ 0x0060, 0x3010, "LO", "Histogram Explanation" },
{ 0x0060, 0x3020, "UL", "Histogram Data" },
{ 0x0070, 0x0001, "SQ", "Graphic Annotation Sequence" },
{ 0x0070, 0x0002, "CS", "Graphic Layer" },
{ 0x0070, 0x0003, "CS", "Bounding Box Annotation Units" },
{ 0x0070, 0x0004, "CS", "Anchor Point Annotation Units" },
{ 0x0070, 0x0005, "CS", "Graphic Annotation Units" },
{ 0x0070, 0x0006, "ST", "Unformatted Text Value" },
{ 0x0070, 0x0008, "SQ", "Text Object Sequence" },
{ 0x0070, 0x0009, "SQ", "Graphic Object Sequence" },
{ 0x0070, 0x0010, "FL", "Bounding Box TLHC" },
{ 0x0070, 0x0011, "FL", "Bounding Box BRHC" },
{ 0x0070, 0x0014, "FL", "Anchor Point" },
{ 0x0070, 0x0015, "CS", "Anchor Point Visibility" },
{ 0x0070, 0x0020, "US", "Graphic Dimensions" },
{ 0x0070, 0x0021, "US", "Number Of Graphic Points" },
{ 0x0070, 0x0022, "FL", "Graphic Data" },
{ 0x0070, 0x0023, "CS", "Graphic Type" },
{ 0x0070, 0x0024, "CS", "Graphic Filled" },
{ 0x0070, 0x0040, "IS", "Image Rotation" },
{ 0x0070, 0x0041, "CS", "Image Horizontal Flip" },
{ 0x0070, 0x0050, "US", "Displayed Area TLHC" },
{ 0x0070, 0x0051, "US", "Displayed Area BRHC" },
{ 0x0070, 0x0060, "SQ", "Graphic Layer Sequence" },
{ 0x0070, 0x0062, "IS", "Graphic Layer Order" },
{ 0x0070, 0x0066, "US", "Graphic Layer Recommended Display Value" },
{ 0x0070, 0x0068, "LO", "Graphic Layer Description" },
{ 0x0070, 0x0080, "CS", "Presentation Label" },
{ 0x0070, 0x0081, "LO", "Presentation Description" },
{ 0x0070, 0x0082, "DA", "Presentation Creation Date" },
{ 0x0070, 0x0083, "TM", "Presentation Creation Time" },
{ 0x0070, 0x0084, "PN", "Presentation Creator's Name" },
{ 0x0070, 0x031a, "UI", "Fiducial UID" },
{ 0x0087, 0x0010, "CS", "Media Type" },
{ 0x0087, 0x0020, "CS", "Media Location" },
{ 0x0087, 0x0050, "IS", "Estimated Retrieve Time" },
{ 0x0088, 0x0000, "UL", "Storage Group Length" },
{ 0x0088, 0x0130, "SH", "Storage Media FileSet ID" },
{ 0x0088, 0x0140, "UI", "Storage Media FileSet UID" },
{ 0x0088, 0x0200, "SQ", "Icon Image Sequence" },
{ 0x0088, 0x0904, "LO", "Topic Title" },
{ 0x0088, 0x0906, "ST", "Topic Subject" },
{ 0x0088, 0x0910, "LO", "Topic Author" },
{ 0x0088, 0x0912, "LO", "Topic Key Words" },
{ 0x0095, 0x0001, "LT", "Examination Folder ID" },
{ 0x0095, 0x0004, "UL", "Folder Reported Status" },
{ 0x0095, 0x0005, "LT", "Folder Reporting Radiologist" },
{ 0x0095, 0x0007, "LT", "SIENET ISA PLA" },
{ 0x0099, 0x0002, "UL", "Data Object Attributes" },
{ 0x00e1, 0x0001, "US", "Data Dictionary Version" },
{ 0x00e1, 0x0014, "LT", "?" },
{ 0x00e1, 0x0022, "DS", "?" },
{ 0x00e1, 0x0023, "DS", "?" },
{ 0x00e1, 0x0024, "LT", "?" },
{ 0x00e1, 0x0025, "LT", "?" },
{ 0x00e1, 0x0040, "SH", "Offset From CT MR Images" },
{ 0x0193, 0x0002, "DS", "RIS Key" },
{ 0x0307, 0x0001, "UN", "RIS Worklist IMGEF" },
{ 0x0309, 0x0001, "UN", "RIS Report IMGEF" },
{ 0x0601, 0x0000, "SH", "Implementation Version" },
{ 0x0601, 0x0020, "DS", "Relative Table Position" },
{ 0x0601, 0x0021, "DS", "Relative Table Height" },
{ 0x0601, 0x0030, "SH", "Surview Direction" },
{ 0x0601, 0x0031, "DS", "Surview Length" },
{ 0x0601, 0x0050, "SH", "Image View Type" },
{ 0x0601, 0x0070, "DS", "Batch Number" },
{ 0x0601, 0x0071, "DS", "Batch Size" },
{ 0x0601, 0x0072, "DS", "Batch Slice Number" },
{ 0x1000, 0x0000, "xs", "?" },
{ 0x1000, 0x0001, "US", "Run Length Triplet" },
{ 0x1000, 0x0002, "US", "Huffman Table Size" },
{ 0x1000, 0x0003, "US", "Huffman Table Triplet" },
{ 0x1000, 0x0004, "US", "Shift Table Size" },
{ 0x1000, 0x0005, "US", "Shift Table Triplet" },
{ 0x1010, 0x0000, "xs", "?" },
{ 0x1369, 0x0000, "US", "?" },
{ 0x2000, 0x0000, "UL", "Film Session Group Length" },
{ 0x2000, 0x0010, "IS", "Number of Copies" },
{ 0x2000, 0x0020, "CS", "Print Priority" },
{ 0x2000, 0x0030, "CS", "Medium Type" },
{ 0x2000, 0x0040, "CS", "Film Destination" },
{ 0x2000, 0x0050, "LO", "Film Session Label" },
{ 0x2000, 0x0060, "IS", "Memory Allocation" },
{ 0x2000, 0x0500, "SQ", "Referenced Film Box Sequence" },
{ 0x2010, 0x0000, "UL", "Film Box Group Length" },
{ 0x2010, 0x0010, "ST", "Image Display Format" },
{ 0x2010, 0x0030, "CS", "Annotation Display Format ID" },
{ 0x2010, 0x0040, "CS", "Film Orientation" },
{ 0x2010, 0x0050, "CS", "Film Size ID" },
{ 0x2010, 0x0060, "CS", "Magnification Type" },
{ 0x2010, 0x0080, "CS", "Smoothing Type" },
{ 0x2010, 0x0100, "CS", "Border Density" },
{ 0x2010, 0x0110, "CS", "Empty Image Density" },
{ 0x2010, 0x0120, "US", "Min Density" },
{ 0x2010, 0x0130, "US", "Max Density" },
{ 0x2010, 0x0140, "CS", "Trim" },
{ 0x2010, 0x0150, "ST", "Configuration Information" },
{ 0x2010, 0x0500, "SQ", "Referenced Film Session Sequence" },
{ 0x2010, 0x0510, "SQ", "Referenced Image Box Sequence" },
{ 0x2010, 0x0520, "SQ", "Referenced Basic Annotation Box Sequence" },
{ 0x2020, 0x0000, "UL", "Image Box Group Length" },
{ 0x2020, 0x0010, "US", "Image Box Position" },
{ 0x2020, 0x0020, "CS", "Polarity" },
{ 0x2020, 0x0030, "DS", "Requested Image Size" },
{ 0x2020, 0x0110, "SQ", "Preformatted Grayscale Image Sequence" },
{ 0x2020, 0x0111, "SQ", "Preformatted Color Image Sequence" },
{ 0x2020, 0x0130, "SQ", "Referenced Image Overlay Box Sequence" },
{ 0x2020, 0x0140, "SQ", "Referenced VOI LUT Box Sequence" },
{ 0x2030, 0x0000, "UL", "Annotation Group Length" },
{ 0x2030, 0x0010, "US", "Annotation Position" },
{ 0x2030, 0x0020, "LO", "Text String" },
{ 0x2040, 0x0000, "UL", "Overlay Box Group Length" },
{ 0x2040, 0x0010, "SQ", "Referenced Overlay Plane Sequence" },
{ 0x2040, 0x0011, "US", "Referenced Overlay Plane Groups" },
{ 0x2040, 0x0060, "CS", "Overlay Magnification Type" },
{ 0x2040, 0x0070, "CS", "Overlay Smoothing Type" },
{ 0x2040, 0x0080, "CS", "Overlay Foreground Density" },
{ 0x2040, 0x0090, "CS", "Overlay Mode" },
{ 0x2040, 0x0100, "CS", "Threshold Density" },
{ 0x2040, 0x0500, "SQ", "Referenced Overlay Image Box Sequence" },
{ 0x2050, 0x0010, "SQ", "Presentation LUT Sequence" },
{ 0x2050, 0x0020, "CS", "Presentation LUT Shape" },
{ 0x2100, 0x0000, "UL", "Print Job Group Length" },
{ 0x2100, 0x0020, "CS", "Execution Status" },
{ 0x2100, 0x0030, "CS", "Execution Status Info" },
{ 0x2100, 0x0040, "DA", "Creation Date" },
{ 0x2100, 0x0050, "TM", "Creation Time" },
{ 0x2100, 0x0070, "AE", "Originator" },
{ 0x2100, 0x0500, "SQ", "Referenced Print Job Sequence" },
{ 0x2110, 0x0000, "UL", "Printer Group Length" },
{ 0x2110, 0x0010, "CS", "Printer Status" },
{ 0x2110, 0x0020, "CS", "Printer Status Info" },
{ 0x2110, 0x0030, "LO", "Printer Name" },
{ 0x2110, 0x0099, "SH", "Print Queue ID" },
{ 0x3002, 0x0002, "SH", "RT Image Label" },
{ 0x3002, 0x0003, "LO", "RT Image Name" },
{ 0x3002, 0x0004, "ST", "RT Image Description" },
{ 0x3002, 0x000a, "CS", "Reported Values Origin" },
{ 0x3002, 0x000c, "CS", "RT Image Plane" },
{ 0x3002, 0x000e, "DS", "X-Ray Image Receptor Angle" },
{ 0x3002, 0x0010, "DS", "RTImageOrientation" },
{ 0x3002, 0x0011, "DS", "Image Plane Pixel Spacing" },
{ 0x3002, 0x0012, "DS", "RT Image Position" },
{ 0x3002, 0x0020, "SH", "Radiation Machine Name" },
{ 0x3002, 0x0022, "DS", "Radiation Machine SAD" },
{ 0x3002, 0x0024, "DS", "Radiation Machine SSD" },
{ 0x3002, 0x0026, "DS", "RT Image SID" },
{ 0x3002, 0x0028, "DS", "Source to Reference Object Distance" },
{ 0x3002, 0x0029, "IS", "Fraction Number" },
{ 0x3002, 0x0030, "SQ", "Exposure Sequence" },
{ 0x3002, 0x0032, "DS", "Meterset Exposure" },
{ 0x3004, 0x0001, "CS", "DVH Type" },
{ 0x3004, 0x0002, "CS", "Dose Units" },
{ 0x3004, 0x0004, "CS", "Dose Type" },
{ 0x3004, 0x0006, "LO", "Dose Comment" },
{ 0x3004, 0x0008, "DS", "Normalization Point" },
{ 0x3004, 0x000a, "CS", "Dose Summation Type" },
{ 0x3004, 0x000c, "DS", "GridFrame Offset Vector" },
{ 0x3004, 0x000e, "DS", "Dose Grid Scaling" },
{ 0x3004, 0x0010, "SQ", "RT Dose ROI Sequence" },
{ 0x3004, 0x0012, "DS", "Dose Value" },
{ 0x3004, 0x0040, "DS", "DVH Normalization Point" },
{ 0x3004, 0x0042, "DS", "DVH Normalization Dose Value" },
{ 0x3004, 0x0050, "SQ", "DVH Sequence" },
{ 0x3004, 0x0052, "DS", "DVH Dose Scaling" },
{ 0x3004, 0x0054, "CS", "DVH Volume Units" },
{ 0x3004, 0x0056, "IS", "DVH Number of Bins" },
{ 0x3004, 0x0058, "DS", "DVH Data" },
{ 0x3004, 0x0060, "SQ", "DVH Referenced ROI Sequence" },
{ 0x3004, 0x0062, "CS", "DVH ROI Contribution Type" },
{ 0x3004, 0x0070, "DS", "DVH Minimum Dose" },
{ 0x3004, 0x0072, "DS", "DVH Maximum Dose" },
{ 0x3004, 0x0074, "DS", "DVH Mean Dose" },
{ 0x3006, 0x0002, "SH", "Structure Set Label" },
{ 0x3006, 0x0004, "LO", "Structure Set Name" },
{ 0x3006, 0x0006, "ST", "Structure Set Description" },
{ 0x3006, 0x0008, "DA", "Structure Set Date" },
{ 0x3006, 0x0009, "TM", "Structure Set Time" },
{ 0x3006, 0x0010, "SQ", "Referenced Frame of Reference Sequence" },
{ 0x3006, 0x0012, "SQ", "RT Referenced Study Sequence" },
{ 0x3006, 0x0014, "SQ", "RT Referenced Series Sequence" },
{ 0x3006, 0x0016, "SQ", "Contour Image Sequence" },
{ 0x3006, 0x0020, "SQ", "Structure Set ROI Sequence" },
{ 0x3006, 0x0022, "IS", "ROI Number" },
{ 0x3006, 0x0024, "UI", "Referenced Frame of Reference UID" },
{ 0x3006, 0x0026, "LO", "ROI Name" },
{ 0x3006, 0x0028, "ST", "ROI Description" },
{ 0x3006, 0x002a, "IS", "ROI Display Color" },
{ 0x3006, 0x002c, "DS", "ROI Volume" },
{ 0x3006, 0x0030, "SQ", "RT Related ROI Sequence" },
{ 0x3006, 0x0033, "CS", "RT ROI Relationship" },
{ 0x3006, 0x0036, "CS", "ROI Generation Algorithm" },
{ 0x3006, 0x0038, "LO", "ROI Generation Description" },
{ 0x3006, 0x0039, "SQ", "ROI Contour Sequence" },
{ 0x3006, 0x0040, "SQ", "Contour Sequence" },
{ 0x3006, 0x0042, "CS", "Contour Geometric Type" },
{ 0x3006, 0x0044, "DS", "Contour SlabT hickness" },
{ 0x3006, 0x0045, "DS", "Contour Offset Vector" },
{ 0x3006, 0x0046, "IS", "Number of Contour Points" },
{ 0x3006, 0x0050, "DS", "Contour Data" },
{ 0x3006, 0x0080, "SQ", "RT ROI Observations Sequence" },
{ 0x3006, 0x0082, "IS", "Observation Number" },
{ 0x3006, 0x0084, "IS", "Referenced ROI Number" },
{ 0x3006, 0x0085, "SH", "ROI Observation Label" },
{ 0x3006, 0x0086, "SQ", "RT ROI Identification Code Sequence" },
{ 0x3006, 0x0088, "ST", "ROI Observation Description" },
{ 0x3006, 0x00a0, "SQ", "Related RT ROI Observations Sequence" },
{ 0x3006, 0x00a4, "CS", "RT ROI Interpreted Type" },
{ 0x3006, 0x00a6, "PN", "ROI Interpreter" },
{ 0x3006, 0x00b0, "SQ", "ROI Physical Properties Sequence" },
{ 0x3006, 0x00b2, "CS", "ROI Physical Property" },
{ 0x3006, 0x00b4, "DS", "ROI Physical Property Value" },
{ 0x3006, 0x00c0, "SQ", "Frame of Reference Relationship Sequence" },
{ 0x3006, 0x00c2, "UI", "Related Frame of Reference UID" },
{ 0x3006, 0x00c4, "CS", "Frame of Reference Transformation Type" },
{ 0x3006, 0x00c6, "DS", "Frame of Reference Transformation Matrix" },
{ 0x3006, 0x00c8, "LO", "Frame of Reference Transformation Comment" },
{ 0x300a, 0x0002, "SH", "RT Plan Label" },
{ 0x300a, 0x0003, "LO", "RT Plan Name" },
{ 0x300a, 0x0004, "ST", "RT Plan Description" },
{ 0x300a, 0x0006, "DA", "RT Plan Date" },
{ 0x300a, 0x0007, "TM", "RT Plan Time" },
{ 0x300a, 0x0009, "LO", "Treatment Protocols" },
{ 0x300a, 0x000a, "CS", "Treatment Intent" },
{ 0x300a, 0x000b, "LO", "Treatment Sites" },
{ 0x300a, 0x000c, "CS", "RT Plan Geometry" },
{ 0x300a, 0x000e, "ST", "Prescription Description" },
{ 0x300a, 0x0010, "SQ", "Dose ReferenceSequence" },
{ 0x300a, 0x0012, "IS", "Dose ReferenceNumber" },
{ 0x300a, 0x0014, "CS", "Dose Reference Structure Type" },
{ 0x300a, 0x0016, "LO", "Dose ReferenceDescription" },
{ 0x300a, 0x0018, "DS", "Dose Reference Point Coordinates" },
{ 0x300a, 0x001a, "DS", "Nominal Prior Dose" },
{ 0x300a, 0x0020, "CS", "Dose Reference Type" },
{ 0x300a, 0x0021, "DS", "Constraint Weight" },
{ 0x300a, 0x0022, "DS", "Delivery Warning Dose" },
{ 0x300a, 0x0023, "DS", "Delivery Maximum Dose" },
{ 0x300a, 0x0025, "DS", "Target Minimum Dose" },
{ 0x300a, 0x0026, "DS", "Target Prescription Dose" },
{ 0x300a, 0x0027, "DS", "Target Maximum Dose" },
{ 0x300a, 0x0028, "DS", "Target Underdose Volume Fraction" },
{ 0x300a, 0x002a, "DS", "Organ at Risk Full-volume Dose" },
{ 0x300a, 0x002b, "DS", "Organ at Risk Limit Dose" },
{ 0x300a, 0x002c, "DS", "Organ at Risk Maximum Dose" },
{ 0x300a, 0x002d, "DS", "Organ at Risk Overdose Volume Fraction" },
{ 0x300a, 0x0040, "SQ", "Tolerance Table Sequence" },
{ 0x300a, 0x0042, "IS", "Tolerance Table Number" },
{ 0x300a, 0x0043, "SH", "Tolerance Table Label" },
{ 0x300a, 0x0044, "DS", "Gantry Angle Tolerance" },
{ 0x300a, 0x0046, "DS", "Beam Limiting Device Angle Tolerance" },
{ 0x300a, 0x0048, "SQ", "Beam Limiting Device Tolerance Sequence" },
{ 0x300a, 0x004a, "DS", "Beam Limiting Device Position Tolerance" },
{ 0x300a, 0x004c, "DS", "Patient Support Angle Tolerance" },
{ 0x300a, 0x004e, "DS", "Table Top Eccentric Angle Tolerance" },
{ 0x300a, 0x0051, "DS", "Table Top Vertical Position Tolerance" },
{ 0x300a, 0x0052, "DS", "Table Top Longitudinal Position Tolerance" },
{ 0x300a, 0x0053, "DS", "Table Top Lateral Position Tolerance" },
{ 0x300a, 0x0055, "CS", "RT Plan Relationship" },
{ 0x300a, 0x0070, "SQ", "Fraction Group Sequence" },
{ 0x300a, 0x0071, "IS", "Fraction Group Number" },
{ 0x300a, 0x0078, "IS", "Number of Fractions Planned" },
{ 0x300a, 0x0079, "IS", "Number of Fractions Per Day" },
{ 0x300a, 0x007a, "IS", "Repeat Fraction Cycle Length" },
{ 0x300a, 0x007b, "LT", "Fraction Pattern" },
{ 0x300a, 0x0080, "IS", "Number of Beams" },
{ 0x300a, 0x0082, "DS", "Beam Dose Specification Point" },
{ 0x300a, 0x0084, "DS", "Beam Dose" },
{ 0x300a, 0x0086, "DS", "Beam Meterset" },
{ 0x300a, 0x00a0, "IS", "Number of Brachy Application Setups" },
{ 0x300a, 0x00a2, "DS", "Brachy Application Setup Dose Specification Point" },
{ 0x300a, 0x00a4, "DS", "Brachy Application Setup Dose" },
{ 0x300a, 0x00b0, "SQ", "Beam Sequence" },
{ 0x300a, 0x00b2, "SH", "Treatment Machine Name " },
{ 0x300a, 0x00b3, "CS", "Primary Dosimeter Unit" },
{ 0x300a, 0x00b4, "DS", "Source-Axis Distance" },
{ 0x300a, 0x00b6, "SQ", "Beam Limiting Device Sequence" },
{ 0x300a, 0x00b8, "CS", "RT Beam Limiting Device Type" },
{ 0x300a, 0x00ba, "DS", "Source to Beam Limiting Device Distance" },
{ 0x300a, 0x00bc, "IS", "Number of Leaf/Jaw Pairs" },
{ 0x300a, 0x00be, "DS", "Leaf Position Boundaries" },
{ 0x300a, 0x00c0, "IS", "Beam Number" },
{ 0x300a, 0x00c2, "LO", "Beam Name" },
{ 0x300a, 0x00c3, "ST", "Beam Description" },
{ 0x300a, 0x00c4, "CS", "Beam Type" },
{ 0x300a, 0x00c6, "CS", "Radiation Type" },
{ 0x300a, 0x00c8, "IS", "Reference Image Number" },
{ 0x300a, 0x00ca, "SQ", "Planned Verification Image Sequence" },
{ 0x300a, 0x00cc, "LO", "Imaging Device Specific Acquisition Parameters" },
{ 0x300a, 0x00ce, "CS", "Treatment Delivery Type" },
{ 0x300a, 0x00d0, "IS", "Number of Wedges" },
{ 0x300a, 0x00d1, "SQ", "Wedge Sequence" },
{ 0x300a, 0x00d2, "IS", "Wedge Number" },
{ 0x300a, 0x00d3, "CS", "Wedge Type" },
{ 0x300a, 0x00d4, "SH", "Wedge ID" },
{ 0x300a, 0x00d5, "IS", "Wedge Angle" },
{ 0x300a, 0x00d6, "DS", "Wedge Factor" },
{ 0x300a, 0x00d8, "DS", "Wedge Orientation" },
{ 0x300a, 0x00da, "DS", "Source to Wedge Tray Distance" },
{ 0x300a, 0x00e0, "IS", "Number of Compensators" },
{ 0x300a, 0x00e1, "SH", "Material ID" },
{ 0x300a, 0x00e2, "DS", "Total Compensator Tray Factor" },
{ 0x300a, 0x00e3, "SQ", "Compensator Sequence" },
{ 0x300a, 0x00e4, "IS", "Compensator Number" },
{ 0x300a, 0x00e5, "SH", "Compensator ID" },
{ 0x300a, 0x00e6, "DS", "Source to Compensator Tray Distance" },
{ 0x300a, 0x00e7, "IS", "Compensator Rows" },
{ 0x300a, 0x00e8, "IS", "Compensator Columns" },
{ 0x300a, 0x00e9, "DS", "Compensator Pixel Spacing" },
{ 0x300a, 0x00ea, "DS", "Compensator Position" },
{ 0x300a, 0x00eb, "DS", "Compensator Transmission Data" },
{ 0x300a, 0x00ec, "DS", "Compensator Thickness Data" },
{ 0x300a, 0x00ed, "IS", "Number of Boli" },
{ 0x300a, 0x00f0, "IS", "Number of Blocks" },
{ 0x300a, 0x00f2, "DS", "Total Block Tray Factor" },
{ 0x300a, 0x00f4, "SQ", "Block Sequence" },
{ 0x300a, 0x00f5, "SH", "Block Tray ID" },
{ 0x300a, 0x00f6, "DS", "Source to Block Tray Distance" },
{ 0x300a, 0x00f8, "CS", "Block Type" },
{ 0x300a, 0x00fa, "CS", "Block Divergence" },
{ 0x300a, 0x00fc, "IS", "Block Number" },
{ 0x300a, 0x00fe, "LO", "Block Name" },
{ 0x300a, 0x0100, "DS", "Block Thickness" },
{ 0x300a, 0x0102, "DS", "Block Transmission" },
{ 0x300a, 0x0104, "IS", "Block Number of Points" },
{ 0x300a, 0x0106, "DS", "Block Data" },
{ 0x300a, 0x0107, "SQ", "Applicator Sequence" },
{ 0x300a, 0x0108, "SH", "Applicator ID" },
{ 0x300a, 0x0109, "CS", "Applicator Type" },
{ 0x300a, 0x010a, "LO", "Applicator Description" },
{ 0x300a, 0x010c, "DS", "Cumulative Dose Reference Coefficient" },
{ 0x300a, 0x010e, "DS", "Final Cumulative Meterset Weight" },
{ 0x300a, 0x0110, "IS", "Number of Control Points" },
{ 0x300a, 0x0111, "SQ", "Control Point Sequence" },
{ 0x300a, 0x0112, "IS", "Control Point Index" },
{ 0x300a, 0x0114, "DS", "Nominal Beam Energy" },
{ 0x300a, 0x0115, "DS", "Dose Rate Set" },
{ 0x300a, 0x0116, "SQ", "Wedge Position Sequence" },
{ 0x300a, 0x0118, "CS", "Wedge Position" },
{ 0x300a, 0x011a, "SQ", "Beam Limiting Device Position Sequence" },
{ 0x300a, 0x011c, "DS", "Leaf Jaw Positions" },
{ 0x300a, 0x011e, "DS", "Gantry Angle" },
{ 0x300a, 0x011f, "CS", "Gantry Rotation Direction" },
{ 0x300a, 0x0120, "DS", "Beam Limiting Device Angle" },
{ 0x300a, 0x0121, "CS", "Beam Limiting Device Rotation Direction" },
{ 0x300a, 0x0122, "DS", "Patient Support Angle" },
{ 0x300a, 0x0123, "CS", "Patient Support Rotation Direction" },
{ 0x300a, 0x0124, "DS", "Table Top Eccentric Axis Distance" },
{ 0x300a, 0x0125, "DS", "Table Top Eccentric Angle" },
{ 0x300a, 0x0126, "CS", "Table Top Eccentric Rotation Direction" },
{ 0x300a, 0x0128, "DS", "Table Top Vertical Position" },
{ 0x300a, 0x0129, "DS", "Table Top Longitudinal Position" },
{ 0x300a, 0x012a, "DS", "Table Top Lateral Position" },
{ 0x300a, 0x012c, "DS", "Isocenter Position" },
{ 0x300a, 0x012e, "DS", "Surface Entry Point" },
{ 0x300a, 0x0130, "DS", "Source to Surface Distance" },
{ 0x300a, 0x0134, "DS", "Cumulative Meterset Weight" },
{ 0x300a, 0x0180, "SQ", "Patient Setup Sequence" },
{ 0x300a, 0x0182, "IS", "Patient Setup Number" },
{ 0x300a, 0x0184, "LO", "Patient Additional Position" },
{ 0x300a, 0x0190, "SQ", "Fixation Device Sequence" },
{ 0x300a, 0x0192, "CS", "Fixation Device Type" },
{ 0x300a, 0x0194, "SH", "Fixation Device Label" },
{ 0x300a, 0x0196, "ST", "Fixation Device Description" },
{ 0x300a, 0x0198, "SH", "Fixation Device Position" },
{ 0x300a, 0x01a0, "SQ", "Shielding Device Sequence" },
{ 0x300a, 0x01a2, "CS", "Shielding Device Type" },
{ 0x300a, 0x01a4, "SH", "Shielding Device Label" },
{ 0x300a, 0x01a6, "ST", "Shielding Device Description" },
{ 0x300a, 0x01a8, "SH", "Shielding Device Position" },
{ 0x300a, 0x01b0, "CS", "Setup Technique" },
{ 0x300a, 0x01b2, "ST", "Setup TechniqueDescription" },
{ 0x300a, 0x01b4, "SQ", "Setup Device Sequence" },
{ 0x300a, 0x01b6, "CS", "Setup Device Type" },
{ 0x300a, 0x01b8, "SH", "Setup Device Label" },
{ 0x300a, 0x01ba, "ST", "Setup Device Description" },
{ 0x300a, 0x01bc, "DS", "Setup Device Parameter" },
{ 0x300a, 0x01d0, "ST", "Setup ReferenceDescription" },
{ 0x300a, 0x01d2, "DS", "Table Top Vertical Setup Displacement" },
{ 0x300a, 0x01d4, "DS", "Table Top Longitudinal Setup Displacement" },
{ 0x300a, 0x01d6, "DS", "Table Top Lateral Setup Displacement" },
{ 0x300a, 0x0200, "CS", "Brachy Treatment Technique" },
{ 0x300a, 0x0202, "CS", "Brachy Treatment Type" },
{ 0x300a, 0x0206, "SQ", "Treatment Machine Sequence" },
{ 0x300a, 0x0210, "SQ", "Source Sequence" },
{ 0x300a, 0x0212, "IS", "Source Number" },
{ 0x300a, 0x0214, "CS", "Source Type" },
{ 0x300a, 0x0216, "LO", "Source Manufacturer" },
{ 0x300a, 0x0218, "DS", "Active Source Diameter" },
{ 0x300a, 0x021a, "DS", "Active Source Length" },
{ 0x300a, 0x0222, "DS", "Source Encapsulation Nominal Thickness" },
{ 0x300a, 0x0224, "DS", "Source Encapsulation Nominal Transmission" },
{ 0x300a, 0x0226, "LO", "Source IsotopeName" },
{ 0x300a, 0x0228, "DS", "Source Isotope Half Life" },
{ 0x300a, 0x022a, "DS", "Reference Air Kerma Rate" },
{ 0x300a, 0x022c, "DA", "Air Kerma Rate Reference Date" },
{ 0x300a, 0x022e, "TM", "Air Kerma Rate Reference Time" },
{ 0x300a, 0x0230, "SQ", "Application Setup Sequence" },
{ 0x300a, 0x0232, "CS", "Application Setup Type" },
{ 0x300a, 0x0234, "IS", "Application Setup Number" },
{ 0x300a, 0x0236, "LO", "Application Setup Name" },
{ 0x300a, 0x0238, "LO", "Application Setup Manufacturer" },
{ 0x300a, 0x0240, "IS", "Template Number" },
{ 0x300a, 0x0242, "SH", "Template Type" },
{ 0x300a, 0x0244, "LO", "Template Name" },
{ 0x300a, 0x0250, "DS", "Total Reference Air Kerma" },
{ 0x300a, 0x0260, "SQ", "Brachy Accessory Device Sequence" },
{ 0x300a, 0x0262, "IS", "Brachy Accessory Device Number" },
{ 0x300a, 0x0263, "SH", "Brachy Accessory Device ID" },
{ 0x300a, 0x0264, "CS", "Brachy Accessory Device Type" },
{ 0x300a, 0x0266, "LO", "Brachy Accessory Device Name" },
{ 0x300a, 0x026a, "DS", "Brachy Accessory Device Nominal Thickness" },
{ 0x300a, 0x026c, "DS", "Brachy Accessory Device Nominal Transmission" },
{ 0x300a, 0x0280, "SQ", "Channel Sequence" },
{ 0x300a, 0x0282, "IS", "Channel Number" },
{ 0x300a, 0x0284, "DS", "Channel Length" },
{ 0x300a, 0x0286, "DS", "Channel Total Time" },
{ 0x300a, 0x0288, "CS", "Source Movement Type" },
{ 0x300a, 0x028a, "IS", "Number of Pulses" },
{ 0x300a, 0x028c, "DS", "Pulse Repetition Interval" },
{ 0x300a, 0x0290, "IS", "Source Applicator Number" },
{ 0x300a, 0x0291, "SH", "Source Applicator ID" },
{ 0x300a, 0x0292, "CS", "Source Applicator Type" },
{ 0x300a, 0x0294, "LO", "Source Applicator Name" },
{ 0x300a, 0x0296, "DS", "Source Applicator Length" },
{ 0x300a, 0x0298, "LO", "Source Applicator Manufacturer" },
{ 0x300a, 0x029c, "DS", "Source Applicator Wall Nominal Thickness" },
{ 0x300a, 0x029e, "DS", "Source Applicator Wall Nominal Transmission" },
{ 0x300a, 0x02a0, "DS", "Source Applicator Step Size" },
{ 0x300a, 0x02a2, "IS", "Transfer Tube Number" },
{ 0x300a, 0x02a4, "DS", "Transfer Tube Length" },
{ 0x300a, 0x02b0, "SQ", "Channel Shield Sequence" },
{ 0x300a, 0x02b2, "IS", "Channel Shield Number" },
{ 0x300a, 0x02b3, "SH", "Channel Shield ID" },
{ 0x300a, 0x02b4, "LO", "Channel Shield Name" },
{ 0x300a, 0x02b8, "DS", "Channel Shield Nominal Thickness" },
{ 0x300a, 0x02ba, "DS", "Channel Shield Nominal Transmission" },
{ 0x300a, 0x02c8, "DS", "Final Cumulative Time Weight" },
{ 0x300a, 0x02d0, "SQ", "Brachy Control Point Sequence" },
{ 0x300a, 0x02d2, "DS", "Control Point Relative Position" },
{ 0x300a, 0x02d4, "DS", "Control Point 3D Position" },
{ 0x300a, 0x02d6, "DS", "Cumulative Time Weight" },
{ 0x300c, 0x0002, "SQ", "Referenced RT Plan Sequence" },
{ 0x300c, 0x0004, "SQ", "Referenced Beam Sequence" },
{ 0x300c, 0x0006, "IS", "Referenced Beam Number" },
{ 0x300c, 0x0007, "IS", "Referenced Reference Image Number" },
{ 0x300c, 0x0008, "DS", "Start Cumulative Meterset Weight" },
{ 0x300c, 0x0009, "DS", "End Cumulative Meterset Weight" },
{ 0x300c, 0x000a, "SQ", "Referenced Brachy Application Setup Sequence" },
{ 0x300c, 0x000c, "IS", "Referenced Brachy Application Setup Number" },
{ 0x300c, 0x000e, "IS", "Referenced Source Number" },
{ 0x300c, 0x0020, "SQ", "Referenced Fraction Group Sequence" },
{ 0x300c, 0x0022, "IS", "Referenced Fraction Group Number" },
{ 0x300c, 0x0040, "SQ", "Referenced Verification Image Sequence" },
{ 0x300c, 0x0042, "SQ", "Referenced Reference Image Sequence" },
{ 0x300c, 0x0050, "SQ", "Referenced Dose Reference Sequence" },
{ 0x300c, 0x0051, "IS", "Referenced Dose Reference Number" },
{ 0x300c, 0x0055, "SQ", "Brachy Referenced Dose Reference Sequence" },
{ 0x300c, 0x0060, "SQ", "Referenced Structure Set Sequence" },
{ 0x300c, 0x006a, "IS", "Referenced Patient Setup Number" },
{ 0x300c, 0x0080, "SQ", "Referenced Dose Sequence" },
{ 0x300c, 0x00a0, "IS", "Referenced Tolerance Table Number" },
{ 0x300c, 0x00b0, "SQ", "Referenced Bolus Sequence" },
{ 0x300c, 0x00c0, "IS", "Referenced Wedge Number" },
{ 0x300c, 0x00d0, "IS", "Referenced Compensato rNumber" },
{ 0x300c, 0x00e0, "IS", "Referenced Block Number" },
{ 0x300c, 0x00f0, "IS", "Referenced Control Point" },
{ 0x300e, 0x0002, "CS", "Approval Status" },
{ 0x300e, 0x0004, "DA", "Review Date" },
{ 0x300e, 0x0005, "TM", "Review Time" },
{ 0x300e, 0x0008, "PN", "Reviewer Name" },
{ 0x4000, 0x0000, "UL", "Text Group Length" },
{ 0x4000, 0x0010, "LT", "Text Arbitrary" },
{ 0x4000, 0x4000, "LT", "Text Comments" },
{ 0x4008, 0x0000, "UL", "Results Group Length" },
{ 0x4008, 0x0040, "SH", "Results ID" },
{ 0x4008, 0x0042, "LO", "Results ID Issuer" },
{ 0x4008, 0x0050, "SQ", "Referenced Interpretation Sequence" },
{ 0x4008, 0x00ff, "CS", "Report Production Status" },
{ 0x4008, 0x0100, "DA", "Interpretation Recorded Date" },
{ 0x4008, 0x0101, "TM", "Interpretation Recorded Time" },
{ 0x4008, 0x0102, "PN", "Interpretation Recorder" },
{ 0x4008, 0x0103, "LO", "Reference to Recorded Sound" },
{ 0x4008, 0x0108, "DA", "Interpretation Transcription Date" },
{ 0x4008, 0x0109, "TM", "Interpretation Transcription Time" },
{ 0x4008, 0x010a, "PN", "Interpretation Transcriber" },
{ 0x4008, 0x010b, "ST", "Interpretation Text" },
{ 0x4008, 0x010c, "PN", "Interpretation Author" },
{ 0x4008, 0x0111, "SQ", "Interpretation Approver Sequence" },
{ 0x4008, 0x0112, "DA", "Interpretation Approval Date" },
{ 0x4008, 0x0113, "TM", "Interpretation Approval Time" },
{ 0x4008, 0x0114, "PN", "Physician Approving Interpretation" },
{ 0x4008, 0x0115, "LT", "Interpretation Diagnosis Description" },
{ 0x4008, 0x0117, "SQ", "InterpretationDiagnosis Code Sequence" },
{ 0x4008, 0x0118, "SQ", "Results Distribution List Sequence" },
{ 0x4008, 0x0119, "PN", "Distribution Name" },
{ 0x4008, 0x011a, "LO", "Distribution Address" },
{ 0x4008, 0x0200, "SH", "Interpretation ID" },
{ 0x4008, 0x0202, "LO", "Interpretation ID Issuer" },
{ 0x4008, 0x0210, "CS", "Interpretation Type ID" },
{ 0x4008, 0x0212, "CS", "Interpretation Status ID" },
{ 0x4008, 0x0300, "ST", "Impressions" },
{ 0x4008, 0x4000, "ST", "Results Comments" },
{ 0x4009, 0x0001, "LT", "Report ID" },
{ 0x4009, 0x0020, "LT", "Report Status" },
{ 0x4009, 0x0030, "DA", "Report Creation Date" },
{ 0x4009, 0x0070, "LT", "Report Approving Physician" },
{ 0x4009, 0x00e0, "LT", "Report Text" },
{ 0x4009, 0x00e1, "LT", "Report Author" },
{ 0x4009, 0x00e3, "LT", "Reporting Radiologist" },
{ 0x5000, 0x0000, "UL", "Curve Group Length" },
{ 0x5000, 0x0005, "US", "Curve Dimensions" },
{ 0x5000, 0x0010, "US", "Number of Points" },
{ 0x5000, 0x0020, "CS", "Type of Data" },
{ 0x5000, 0x0022, "LO", "Curve Description" },
{ 0x5000, 0x0030, "SH", "Axis Units" },
{ 0x5000, 0x0040, "SH", "Axis Labels" },
{ 0x5000, 0x0103, "US", "Data Value Representation" },
{ 0x5000, 0x0104, "US", "Minimum Coordinate Value" },
{ 0x5000, 0x0105, "US", "Maximum Coordinate Value" },
{ 0x5000, 0x0106, "SH", "Curve Range" },
{ 0x5000, 0x0110, "US", "Curve Data Descriptor" },
{ 0x5000, 0x0112, "US", "Coordinate Start Value" },
{ 0x5000, 0x0114, "US", "Coordinate Step Value" },
{ 0x5000, 0x1001, "CS", "Curve Activation Layer" },
{ 0x5000, 0x2000, "US", "Audio Type" },
{ 0x5000, 0x2002, "US", "Audio Sample Format" },
{ 0x5000, 0x2004, "US", "Number of Channels" },
{ 0x5000, 0x2006, "UL", "Number of Samples" },
{ 0x5000, 0x2008, "UL", "Sample Rate" },
{ 0x5000, 0x200a, "UL", "Total Time" },
{ 0x5000, 0x200c, "xs", "Audio Sample Data" },
{ 0x5000, 0x200e, "LT", "Audio Comments" },
{ 0x5000, 0x2500, "LO", "Curve Label" },
{ 0x5000, 0x2600, "SQ", "CurveReferenced Overlay Sequence" },
{ 0x5000, 0x2610, "US", "CurveReferenced Overlay Group" },
{ 0x5000, 0x3000, "OW", "Curve Data" },
{ 0x6000, 0x0000, "UL", "Overlay Group Length" },
{ 0x6000, 0x0001, "US", "Gray Palette Color Lookup Table Descriptor" },
{ 0x6000, 0x0002, "US", "Gray Palette Color Lookup Table Data" },
{ 0x6000, 0x0010, "US", "Overlay Rows" },
{ 0x6000, 0x0011, "US", "Overlay Columns" },
{ 0x6000, 0x0012, "US", "Overlay Planes" },
{ 0x6000, 0x0015, "IS", "Number of Frames in Overlay" },
{ 0x6000, 0x0022, "LO", "Overlay Description" },
{ 0x6000, 0x0040, "CS", "Overlay Type" },
{ 0x6000, 0x0045, "CS", "Overlay Subtype" },
{ 0x6000, 0x0050, "SS", "Overlay Origin" },
{ 0x6000, 0x0051, "US", "Image Frame Origin" },
{ 0x6000, 0x0052, "US", "Plane Origin" },
{ 0x6000, 0x0060, "LO", "Overlay Compression Code" },
{ 0x6000, 0x0061, "SH", "Overlay Compression Originator" },
{ 0x6000, 0x0062, "SH", "Overlay Compression Label" },
{ 0x6000, 0x0063, "SH", "Overlay Compression Description" },
{ 0x6000, 0x0066, "AT", "Overlay Compression Step Pointers" },
{ 0x6000, 0x0068, "US", "Overlay Repeat Interval" },
{ 0x6000, 0x0069, "US", "Overlay Bits Grouped" },
{ 0x6000, 0x0100, "US", "Overlay Bits Allocated" },
{ 0x6000, 0x0102, "US", "Overlay Bit Position" },
{ 0x6000, 0x0110, "LO", "Overlay Format" },
{ 0x6000, 0x0200, "xs", "Overlay Location" },
{ 0x6000, 0x0800, "LO", "Overlay Code Label" },
{ 0x6000, 0x0802, "US", "Overlay Number of Tables" },
{ 0x6000, 0x0803, "AT", "Overlay Code Table Location" },
{ 0x6000, 0x0804, "US", "Overlay Bits For Code Word" },
{ 0x6000, 0x1001, "CS", "Overlay Activation Layer" },
{ 0x6000, 0x1100, "US", "Overlay Descriptor - Gray" },
{ 0x6000, 0x1101, "US", "Overlay Descriptor - Red" },
{ 0x6000, 0x1102, "US", "Overlay Descriptor - Green" },
{ 0x6000, 0x1103, "US", "Overlay Descriptor - Blue" },
{ 0x6000, 0x1200, "US", "Overlays - Gray" },
{ 0x6000, 0x1201, "US", "Overlays - Red" },
{ 0x6000, 0x1202, "US", "Overlays - Green" },
{ 0x6000, 0x1203, "US", "Overlays - Blue" },
{ 0x6000, 0x1301, "IS", "ROI Area" },
{ 0x6000, 0x1302, "DS", "ROI Mean" },
{ 0x6000, 0x1303, "DS", "ROI Standard Deviation" },
{ 0x6000, 0x1500, "LO", "Overlay Label" },
{ 0x6000, 0x3000, "OW", "Overlay Data" },
{ 0x6000, 0x4000, "LT", "Overlay Comments" },
{ 0x6001, 0x0000, "UN", "?" },
{ 0x6001, 0x0010, "LO", "?" },
{ 0x6001, 0x1010, "xs", "?" },
{ 0x6001, 0x1030, "xs", "?" },
{ 0x6021, 0x0000, "xs", "?" },
{ 0x6021, 0x0010, "xs", "?" },
{ 0x7001, 0x0010, "LT", "Dummy" },
{ 0x7003, 0x0010, "LT", "Info" },
{ 0x7005, 0x0010, "LT", "Dummy" },
{ 0x7000, 0x0004, "ST", "TextAnnotation" },
{ 0x7000, 0x0005, "IS", "Box" },
{ 0x7000, 0x0007, "IS", "ArrowEnd" },
{ 0x7001, 0x0001, "SL", "Private Group Length To End" },
{ 0x7001, 0x0002, "OB", "Unknown" },
{ 0x7001, 0x0011, "SL", "Private Creator" },
{ 0x7001, 0x0021, "SL", "Private Creator" },
{ 0x7001, 0x0022, "SQ", "Private Creator" },
{ 0x7001, 0x0041, "SL", "Private Creator" },
{ 0x7001, 0x0042, "SL", "Private Creator" },
{ 0x7001, 0x0051, "SL", "Private Creator" },
{ 0x7001, 0x0052, "SL", "Private Creator" },
{ 0x7001, 0x0075, "SL", "Private Creator" },
{ 0x7001, 0x0076, "SL", "Private Creator" },
{ 0x7001, 0x0077, "OB", "Private Creator" },
{ 0x7001, 0x0101, "SL", "Unknown" },
{ 0x7001, 0x0121, "SL", "Unknown" },
{ 0x7001, 0x0122, "SQ", "Unknown" },
{ 0x7fe0, 0x0000, "UL", "Pixel Data Group Length" },
{ 0x7fe0, 0x0010, "xs", "Pixel Data" },
{ 0x7fe0, 0x0020, "OW", "Coefficients SDVN" },
{ 0x7fe0, 0x0030, "OW", "Coefficients SDHN" },
{ 0x7fe0, 0x0040, "OW", "Coefficients SDDN" },
{ 0x7fe1, 0x0010, "xs", "Pixel Data" },
{ 0x7f00, 0x0000, "UL", "Variable Pixel Data Group Length" },
{ 0x7f00, 0x0010, "xs", "Variable Pixel Data" },
{ 0x7f00, 0x0011, "US", "Variable Next Data Group" },
{ 0x7f00, 0x0020, "OW", "Variable Coefficients SDVN" },
{ 0x7f00, 0x0030, "OW", "Variable Coefficients SDHN" },
{ 0x7f00, 0x0040, "OW", "Variable Coefficients SDDN" },
{ 0x7fe1, 0x0000, "OB", "Binary Data" },
{ 0x7fe3, 0x0000, "LT", "Image Graphics Format Code" },
{ 0x7fe3, 0x0010, "OB", "Image Graphics" },
{ 0x7fe3, 0x0020, "OB", "Image Graphics Dummy" },
{ 0x7ff1, 0x0001, "US", "?" },
{ 0x7ff1, 0x0002, "US", "?" },
{ 0x7ff1, 0x0003, "xs", "?" },
{ 0x7ff1, 0x0004, "IS", "?" },
{ 0x7ff1, 0x0005, "US", "?" },
{ 0x7ff1, 0x0007, "US", "?" },
{ 0x7ff1, 0x0008, "US", "?" },
{ 0x7ff1, 0x0009, "US", "?" },
{ 0x7ff1, 0x000a, "LT", "?" },
{ 0x7ff1, 0x000b, "US", "?" },
{ 0x7ff1, 0x000c, "US", "?" },
{ 0x7ff1, 0x000d, "US", "?" },
{ 0x7ff1, 0x0010, "US", "?" },
{ 0xfffc, 0xfffc, "OB", "Data Set Trailing Padding" },
{ 0xfffe, 0xe000, "!!", "Item" },
{ 0xfffe, 0xe00d, "!!", "Item Delimitation Item" },
{ 0xfffe, 0xe0dd, "!!", "Sequence Delimitation Item" },
{ 0xffff, 0xffff, "xs", (char *) NULL }
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s D C M %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsDCM() returns MagickTrue if the image format type, identified by the
% magick string, is DCM.
%
% The format of the IsDCM method is:
%
% MagickBooleanType IsDCM(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsDCM(const unsigned char *magick,const size_t length)
{
if (length < 132)
return(MagickFalse);
if (LocaleNCompare((char *) (magick+128),"DICM",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d D C M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadDCMImage() reads a Digital Imaging and Communications in Medicine
% (DICOM) file and returns it. It allocates the memory necessary for the
% new Image structure and returns a pointer to the new image.
%
% The format of the ReadDCMImage method is:
%
% Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef struct _DCMInfo
{
MagickBooleanType
polarity;
Quantum
*scale;
size_t
bits_allocated,
bytes_per_pixel,
depth,
mask,
max_value,
samples_per_pixel,
signed_data,
significant_bits;
MagickBooleanType
rescale;
double
rescale_intercept,
rescale_slope,
window_center,
window_width;
} DCMInfo;
typedef struct _DCMStreamInfo
{
size_t
remaining,
segment_count;
ssize_t
segments[15];
size_t
offset_count;
ssize_t
*offsets;
ssize_t
count;
int
byte;
} DCMStreamInfo;
static int ReadDCMByte(DCMStreamInfo *stream_info,Image *image)
{
if (image->compression != RLECompression)
return(ReadBlobByte(image));
if (stream_info->count == 0)
{
int
byte;
ssize_t
count;
if (stream_info->remaining <= 2)
stream_info->remaining=0;
else
stream_info->remaining-=2;
count=(ssize_t) ReadBlobByte(image);
byte=ReadBlobByte(image);
if (count == 128)
return(0);
else
if (count < 128)
{
/*
Literal bytes.
*/
stream_info->count=count;
stream_info->byte=(-1);
return(byte);
}
else
{
/*
Repeated bytes.
*/
stream_info->count=256-count;
stream_info->byte=byte;
return(byte);
}
}
stream_info->count--;
if (stream_info->byte >= 0)
return(stream_info->byte);
if (stream_info->remaining > 0)
stream_info->remaining--;
return(ReadBlobByte(image));
}
static unsigned short ReadDCMShort(DCMStreamInfo *stream_info,Image *image)
{
int
shift,
byte;
unsigned short
value;
if (image->compression != RLECompression)
return(ReadBlobLSBShort(image));
shift=image->depth < 16 ? 4 : 8;
value=(unsigned short) ReadDCMByte(stream_info,image);
byte=ReadDCMByte(stream_info,image);
if (byte < 0)
return(0);
value|=(unsigned short) (byte << shift);
return(value);
}
static signed short ReadDCMSignedShort(DCMStreamInfo *stream_info,Image *image)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
quantum.unsigned_value=ReadDCMShort(stream_info,image);
return(quantum.signed_value);
}
static MagickBooleanType ReadDCMPixels(Image *image,DCMInfo *info,
DCMStreamInfo *stream_info,MagickBooleanType first_segment,
ExceptionInfo *exception)
{
int
byte,
index;
MagickBooleanType
status;
PixelPacket
pixel;
register ssize_t
i,
x;
register Quantum
*q;
ssize_t
y;
/*
Convert DCM Medical image to pixel packets.
*/
byte=0;
i=0;
status=MagickTrue;
(void) memset(&pixel,0,sizeof(pixel));
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (info->samples_per_pixel == 1)
{
int
pixel_value;
if (info->bytes_per_pixel == 1)
pixel_value=info->polarity != MagickFalse ?
((int) info->max_value-ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((info->bits_allocated != 12) || (info->significant_bits != 12))
{
if (info->signed_data)
pixel_value=ReadDCMSignedShort(stream_info,image);
else
pixel_value=(int) ReadDCMShort(stream_info,image);
if (info->polarity != MagickFalse)
pixel_value=(int)info->max_value-pixel_value;
}
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=ReadDCMSignedShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
if (info->signed_data == 1)
pixel_value-=32767;
index=pixel_value;
if (info->rescale != MagickFalse)
{
double
scaled_value;
scaled_value=pixel_value*info->rescale_slope+
info->rescale_intercept;
index=(int) scaled_value;
if (info->window_width != 0)
{
double
window_max,
window_min;
window_min=ceil(info->window_center-
(info->window_width-1.0)/2.0-0.5);
window_max=floor(info->window_center+
(info->window_width-1.0)/2.0+0.5);
if (scaled_value <= window_min)
index=0;
else
if (scaled_value > window_max)
index=(int) info->max_value;
else
index=(int) (info->max_value*(((scaled_value-
info->window_center-0.5)/(info->window_width-1))+0.5));
}
}
index&=info->mask;
index=(int) ConstrainColormapIndex(image,(ssize_t) index,exception);
if (first_segment)
SetPixelIndex(image,(Quantum) index,q);
else
SetPixelIndex(image,(Quantum) (((size_t) index) |
(((size_t) GetPixelIndex(image,q)) << 8)),q);
pixel.red=(unsigned int) image->colormap[index].red;
pixel.green=(unsigned int) image->colormap[index].green;
pixel.blue=(unsigned int) image->colormap[index].blue;
}
else
{
if (info->bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=info->mask;
pixel.green&=info->mask;
pixel.blue&=info->mask;
if (info->scale != (Quantum *) NULL)
{
if ((MagickSizeType) pixel.red <= GetQuantumRange(info->depth))
pixel.red=info->scale[pixel.red];
if ((MagickSizeType) pixel.green <= GetQuantumRange(info->depth))
pixel.green=info->scale[pixel.green];
if ((MagickSizeType) pixel.blue <= GetQuantumRange(info->depth))
pixel.blue=info->scale[pixel.blue];
}
}
if (first_segment != MagickFalse)
{
SetPixelRed(image,(Quantum) pixel.red,q);
SetPixelGreen(image,(Quantum) pixel.green,q);
SetPixelBlue(image,(Quantum) pixel.blue,q);
}
else
{
SetPixelRed(image,(Quantum) (((size_t) pixel.red) |
(((size_t) GetPixelRed(image,q)) << 8)),q);
SetPixelGreen(image,(Quantum) (((size_t) pixel.green) |
(((size_t) GetPixelGreen(image,q)) << 8)),q);
SetPixelBlue(image,(Quantum) (((size_t) pixel.blue) |
(((size_t) GetPixelBlue(image,q)) << 8)),q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
return(status);
}
static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowDCMException(exception,message) \
{ \
if (info.scale != (Quantum *) NULL) \
info.scale=(Quantum *) RelinquishMagickMemory(info.scale); \
if (data != (unsigned char *) NULL) \
data=(unsigned char *) RelinquishMagickMemory(data); \
if (graymap != (int *) NULL) \
graymap=(int *) RelinquishMagickMemory(graymap); \
if (bluemap != (int *) NULL) \
bluemap=(int *) RelinquishMagickMemory(bluemap); \
if (greenmap != (int *) NULL) \
greenmap=(int *) RelinquishMagickMemory(greenmap); \
if (redmap != (int *) NULL) \
redmap=(int *) RelinquishMagickMemory(redmap); \
if (stream_info->offsets != (ssize_t *) NULL) \
stream_info->offsets=(ssize_t *) RelinquishMagickMemory( \
stream_info->offsets); \
if (stream_info != (DCMStreamInfo *) NULL) \
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); \
ThrowReaderException((exception),(message)); \
}
char
explicit_vr[MagickPathExtent],
implicit_vr[MagickPathExtent],
magick[MagickPathExtent],
photometric[MagickPathExtent];
DCMInfo
info;
DCMStreamInfo
*stream_info;
Image
*image;
int
*bluemap,
datum,
*greenmap,
*graymap,
*redmap;
MagickBooleanType
explicit_file,
explicit_retry,
use_explicit;
MagickOffsetType
offset;
register unsigned char
*p;
register ssize_t
i;
size_t
colors,
height,
length,
number_scenes,
quantum,
status,
width;
ssize_t
count,
scene;
unsigned char
*data;
unsigned short
group,
element;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->depth=8UL;
image->endian=LSBEndian;
/*
Read DCM preamble.
*/
(void) memset(&info,0,sizeof(info));
data=(unsigned char *) NULL;
graymap=(int *) NULL;
redmap=(int *) NULL;
greenmap=(int *) NULL;
bluemap=(int *) NULL;
stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info));
if (stream_info == (DCMStreamInfo *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(stream_info,0,sizeof(*stream_info));
count=ReadBlob(image,128,(unsigned char *) magick);
if (count != 128)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,4,(unsigned char *) magick);
if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0))
{
offset=SeekBlob(image,0L,SEEK_SET);
if (offset < 0)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
}
/*
Read DCM Medical image.
*/
(void) CopyMagickString(photometric,"MONOCHROME1 ",MagickPathExtent);
info.bits_allocated=8;
info.bytes_per_pixel=1;
info.depth=8;
info.mask=0xffff;
info.max_value=255UL;
info.samples_per_pixel=1;
info.signed_data=(~0UL);
info.rescale_slope=1.0;
data=(unsigned char *) NULL;
element=0;
explicit_vr[2]='\0';
explicit_file=MagickFalse;
colors=0;
redmap=(int *) NULL;
greenmap=(int *) NULL;
bluemap=(int *) NULL;
graymap=(int *) NULL;
height=0;
number_scenes=1;
use_explicit=MagickFalse;
explicit_retry = MagickFalse;
width=0;
while (TellBlob(image) < (MagickOffsetType) GetBlobSize(image))
{
for (group=0; (group != 0x7FE0) || (element != 0x0010) ; )
{
/*
Read a group.
*/
image->offset=(ssize_t) TellBlob(image);
group=ReadBlobLSBShort(image);
element=ReadBlobLSBShort(image);
if ((group == 0xfffc) && (element == 0xfffc))
break;
if ((group != 0x0002) && (image->endian == MSBEndian))
{
group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF));
element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF));
}
quantum=0;
/*
Find corresponding VR for this group and element.
*/
for (i=0; dicom_info[i].group < 0xffff; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
(void) CopyMagickString(implicit_vr,dicom_info[i].vr,MagickPathExtent);
count=ReadBlob(image,2,(unsigned char *) explicit_vr);
if (count != 2)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
/*
Check for "explicitness", but meta-file headers always explicit.
*/
if ((explicit_file == MagickFalse) && (group != 0x0002))
explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) &&
(isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ?
MagickTrue : MagickFalse;
use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) ||
(explicit_file != MagickFalse) ? MagickTrue : MagickFalse;
if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,"xs",2) == 0))
(void) CopyMagickString(implicit_vr,explicit_vr,MagickPathExtent);
if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,"!!",2) == 0))
{
offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR);
if (offset < 0)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
quantum=4;
}
else
{
/*
Assume explicit type.
*/
quantum=2;
if ((strncmp(explicit_vr,"OB",2) == 0) ||
(strncmp(explicit_vr,"UN",2) == 0) ||
(strncmp(explicit_vr,"OW",2) == 0) ||
(strncmp(explicit_vr,"SQ",2) == 0))
{
(void) ReadBlobLSBShort(image);
quantum=4;
}
}
datum=0;
if (quantum == 4)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if (quantum == 2)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
quantum=0;
length=1;
if (datum != 0)
{
if ((strncmp(implicit_vr,"OW",2) == 0) ||
(strncmp(implicit_vr,"SS",2) == 0) ||
(strncmp(implicit_vr,"US",2) == 0))
quantum=2;
else
if ((strncmp(implicit_vr,"FL",2) == 0) ||
(strncmp(implicit_vr,"OF",2) == 0) ||
(strncmp(implicit_vr,"SL",2) == 0) ||
(strncmp(implicit_vr,"UL",2) == 0))
quantum=4;
else
if (strncmp(implicit_vr,"FD",2) == 0)
quantum=8;
else
quantum=1;
if (datum != ~0)
length=(size_t) datum/quantum;
else
{
/*
Sequence and item of undefined length.
*/
quantum=0;
length=0;
}
}
if (image_info->verbose != MagickFalse)
{
/*
Display Dicom info.
*/
if (use_explicit == MagickFalse)
explicit_vr[0]='\0';
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
(void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)",
(unsigned long) image->offset,(long) length,implicit_vr,explicit_vr,
(unsigned long) group,(unsigned long) element);
if (dicom_info[i].description != (char *) NULL)
(void) FormatLocaleFile(stdout," %s",dicom_info[i].description);
(void) FormatLocaleFile(stdout,": ");
}
if ((group == 0x7FE0) && (element == 0x0010))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"\n");
break;
}
/*
Allocate space and read an array.
*/
data=(unsigned char *) NULL;
if ((length == 1) && (quantum == 1))
datum=ReadBlobByte(image);
else
if ((length == 1) && (quantum == 2))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
else
if ((length == 1) && (quantum == 4))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if ((quantum != 0) && (length != 0))
{
if (length > (size_t) GetBlobSize(image))
ThrowDCMException(CorruptImageError,
"InsufficientImageDataInFile");
if (~length >= 1)
data=(unsigned char *) AcquireQuantumMemory(length+1,quantum*
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowDCMException(ResourceLimitError,
"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) quantum*length,data);
if (count != (ssize_t) (quantum*length))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"count=%d quantum=%d "
"length=%d group=%d\n",(int) count,(int) quantum,(int)
length,(int) group);
ThrowDCMException(CorruptImageError,
"InsufficientImageDataInFile");
}
data[length*quantum]='\0';
}
if ((((unsigned int) group << 16) | element) == 0xFFFEE0DD)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
continue;
}
switch (group)
{
case 0x0002:
{
switch (element)
{
case 0x0010:
{
char
transfer_syntax[MagickPathExtent];
/*
Transfer Syntax.
*/
if ((datum == 0) && (explicit_retry == MagickFalse))
{
explicit_retry=MagickTrue;
(void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET);
group=0;
element=0;
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,
"Corrupted image - trying explicit format\n");
break;
}
*transfer_syntax='\0';
if (data != (unsigned char *) NULL)
(void) CopyMagickString(transfer_syntax,(char *) data,
MagickPathExtent);
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"transfer_syntax=%s\n",
(const char *) transfer_syntax);
if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0)
{
int
subtype,
type;
type=1;
subtype=0;
if (strlen(transfer_syntax) > 17)
{
count=(ssize_t) sscanf(transfer_syntax+17,".%d.%d",&type,
&subtype);
if (count < 1)
ThrowDCMException(CorruptImageError,
"ImproperImageHeader");
}
switch (type)
{
case 1:
{
image->endian=LSBEndian;
break;
}
case 2:
{
image->endian=MSBEndian;
break;
}
case 4:
{
if ((subtype >= 80) && (subtype <= 81))
image->compression=JPEGCompression;
else
if ((subtype >= 90) && (subtype <= 93))
image->compression=JPEG2000Compression;
else
image->compression=JPEGCompression;
break;
}
case 5:
{
image->compression=RLECompression;
break;
}
}
}
break;
}
default:
break;
}
break;
}
case 0x0028:
{
switch (element)
{
case 0x0002:
{
/*
Samples per pixel.
*/
info.samples_per_pixel=(size_t) datum;
if ((info.samples_per_pixel == 0) || (info.samples_per_pixel > 4))
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
break;
}
case 0x0004:
{
/*
Photometric interpretation.
*/
if (data == (unsigned char *) NULL)
break;
for (i=0; i < (ssize_t) MagickMin(length,MagickPathExtent-1); i++)
photometric[i]=(char) data[i];
photometric[i]='\0';
info.polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ?
MagickTrue : MagickFalse;
break;
}
case 0x0006:
{
/*
Planar configuration.
*/
if (datum == 1)
image->interlace=PlaneInterlace;
break;
}
case 0x0008:
{
/*
Number of frames.
*/
if (data == (unsigned char *) NULL)
break;
number_scenes=StringToUnsignedLong((char *) data);
break;
}
case 0x0010:
{
/*
Image rows.
*/
height=(size_t) datum;
break;
}
case 0x0011:
{
/*
Image columns.
*/
width=(size_t) datum;
break;
}
case 0x0100:
{
/*
Bits allocated.
*/
info.bits_allocated=(size_t) datum;
info.bytes_per_pixel=1;
if (datum > 8)
info.bytes_per_pixel=2;
info.depth=info.bits_allocated;
if ((info.depth == 0) || (info.depth > 32))
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
info.max_value=(1UL << info.bits_allocated)-1;
image->depth=info.depth;
break;
}
case 0x0101:
{
/*
Bits stored.
*/
info.significant_bits=(size_t) datum;
info.bytes_per_pixel=1;
if (info.significant_bits > 8)
info.bytes_per_pixel=2;
info.depth=info.significant_bits;
if ((info.depth == 0) || (info.depth > 16))
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
info.max_value=(1UL << info.significant_bits)-1;
info.mask=(size_t) GetQuantumRange(info.significant_bits);
image->depth=info.depth;
break;
}
case 0x0102:
{
/*
High bit.
*/
break;
}
case 0x0103:
{
/*
Pixel representation.
*/
info.signed_data=(size_t) datum;
break;
}
case 0x1050:
{
/*
Visible pixel range: center.
*/
if (data != (unsigned char *) NULL)
info.window_center=StringToDouble((char *) data,(char **) NULL);
break;
}
case 0x1051:
{
/*
Visible pixel range: width.
*/
if (data != (unsigned char *) NULL)
info.window_width=StringToDouble((char *) data,(char **) NULL);
break;
}
case 0x1052:
{
/*
Rescale intercept
*/
if (data != (unsigned char *) NULL)
info.rescale_intercept=StringToDouble((char *) data,
(char **) NULL);
break;
}
case 0x1053:
{
/*
Rescale slope
*/
if (data != (unsigned char *) NULL)
info.rescale_slope=StringToDouble((char *) data,(char **) NULL);
break;
}
case 0x1200:
case 0x3006:
{
/*
Populate graymap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/info.bytes_per_pixel);
datum=(int) colors;
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
graymap=(int *) AcquireQuantumMemory(MagickMax(colors,65536),
sizeof(*graymap));
if (graymap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(graymap,0,MagickMax(colors,65536)*
sizeof(*graymap));
for (i=0; i < (ssize_t) colors; i++)
if (info.bytes_per_pixel == 1)
graymap[i]=(int) data[i];
else
graymap[i]=(int) ((short *) data)[i];
break;
}
case 0x1201:
{
unsigned short
index;
/*
Populate redmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
redmap=(int *) AcquireQuantumMemory(MagickMax(colors,65536),
sizeof(*redmap));
if (redmap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(redmap,0,MagickMax(colors,65536)*
sizeof(*redmap));
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
redmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1202:
{
unsigned short
index;
/*
Populate greenmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
greenmap=(int *) AcquireQuantumMemory(MagickMax(colors,65536),
sizeof(*greenmap));
if (greenmap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(greenmap,0,MagickMax(colors,65536)*
sizeof(*greenmap));
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
greenmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1203:
{
unsigned short
index;
/*
Populate bluemap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
bluemap=(int *) AcquireQuantumMemory(MagickMax(colors,65536),
sizeof(*bluemap));
if (bluemap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(bluemap,0,MagickMax(colors,65536)*
sizeof(*bluemap));
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
bluemap[i]=(int) index;
p+=2;
}
break;
}
default:
break;
}
break;
}
case 0x2050:
{
switch (element)
{
case 0x0020:
{
if ((data != (unsigned char *) NULL) &&
(strncmp((char *) data,"INVERSE",7) == 0))
info.polarity=MagickTrue;
break;
}
default:
break;
}
break;
}
default:
break;
}
if (data != (unsigned char *) NULL)
{
char
*attribute;
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
if (dicom_info[i].description != (char *) NULL)
{
attribute=AcquireString("dcm:");
(void) ConcatenateString(&attribute,dicom_info[i].description);
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i == (ssize_t) length) || (length > 4))
{
(void) SubstituteString(&attribute," ","");
(void) SetImageProperty(image,attribute,(char *) data,
exception);
}
attribute=DestroyString(attribute);
}
}
if (image_info->verbose != MagickFalse)
{
if (data == (unsigned char *) NULL)
(void) FormatLocaleFile(stdout,"%d\n",datum);
else
{
/*
Display group data.
*/
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i != (ssize_t) length) && (length <= 4))
{
ssize_t
j;
datum=0;
for (j=(ssize_t) length-1; j >= 0; j--)
datum=(256*datum+data[j]);
(void) FormatLocaleFile(stdout,"%d",datum);
}
else
for (i=0; i < (ssize_t) length; i++)
if (isprint((int) data[i]) != MagickFalse)
(void) FormatLocaleFile(stdout,"%c",data[i]);
else
(void) FormatLocaleFile(stdout,"%c",'.');
(void) FormatLocaleFile(stdout,"\n");
}
}
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
}
if ((group == 0xfffc) && (element == 0xfffc))
{
Image
*last;
last=RemoveLastImageFromList(&image);
if (last != (Image *) NULL)
last=DestroyImage(last);
break;
}
if ((width == 0) || (height == 0))
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
image->columns=(size_t) width;
image->rows=(size_t) height;
if (info.signed_data == 0xffff)
info.signed_data=(size_t) (info.significant_bits == 16 ? 1 : 0);
if ((image->compression == JPEGCompression) ||
(image->compression == JPEG2000Compression))
{
Image
*images;
ImageInfo
*read_info;
int
c;
/*
Read offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
if (ReadBlobByte(image) == EOF)
break;
(void) (((ssize_t) ReadBlobLSBShort(image) << 16) |
ReadBlobLSBShort(image));
length=(size_t) ReadBlobLSBLong(image);
if (length > (size_t) GetBlobSize(image))
ThrowDCMException(CorruptImageError,"InsufficientImageDataInFile");
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *) RelinquishMagickMemory(
stream_info->offsets);
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
/*
Handle non-native image formats.
*/
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
images=NewImageList();
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
char
filename[MagickPathExtent];
const char
*property;
FILE
*file;
Image
*jpeg_image;
int
unique_file;
unsigned int
tag;
tag=((unsigned int) ReadBlobLSBShort(image) << 16) |
ReadBlobLSBShort(image);
length=(size_t) ReadBlobLSBLong(image);
if (tag == 0xFFFEE0DD)
break; /* sequence delimiter tag */
if (tag != 0xFFFEE000)
{
read_info=DestroyImageInfo(read_info);
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
}
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if (file == (FILE *) NULL)
{
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(exception,FileOpenError,
"UnableToCreateTemporaryFile",filename);
break;
}
for (c=EOF; length != 0; length--)
{
c=ReadBlobByte(image);
if (c == EOF)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
if (fputc(c,file) != c)
break;
}
(void) fclose(file);
if (c == EOF)
break;
(void) FormatLocaleString(read_info->filename,MagickPathExtent,
"jpeg:%s",filename);
if (image->compression == JPEG2000Compression)
(void) FormatLocaleString(read_info->filename,MagickPathExtent,
"j2k:%s",filename);
jpeg_image=ReadImage(read_info,exception);
if (jpeg_image != (Image *) NULL)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
(void) SetImageProperty(jpeg_image,property,
GetImageProperty(image,property,exception),exception);
property=GetNextImageProperty(image);
}
AppendImageToList(&images,jpeg_image);
}
(void) RelinquishUniqueFileResource(filename);
}
read_info=DestroyImageInfo(read_info);
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info);
if (info.scale != (Quantum *) NULL)
info.scale=(Quantum *) RelinquishMagickMemory(info.scale);
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
image=DestroyImageList(image);
return(GetFirstImageInList(images));
}
if (info.depth != (1UL*MAGICKCORE_QUANTUM_DEPTH))
{
QuantumAny
range;
/*
Compute pixel scaling table.
*/
length=(size_t) (GetQuantumRange(info.depth)+1);
if (length > (size_t) GetBlobSize(image))
ThrowDCMException(CorruptImageError,"InsufficientImageDataInFile");
if (info.scale != (Quantum *) NULL)
info.scale=(Quantum *) RelinquishMagickMemory(info.scale);
info.scale=(Quantum *) AcquireQuantumMemory(MagickMax(length,256),
sizeof(*info.scale));
if (info.scale == (Quantum *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(info.scale,0,MagickMax(length,256)*
sizeof(*info.scale));
range=GetQuantumRange(info.depth);
for (i=0; i <= (ssize_t) GetQuantumRange(info.depth); i++)
info.scale[i]=ScaleAnyToQuantum((size_t) i,range);
}
if (image->compression == RLECompression)
{
unsigned int
tag;
/*
Read RLE offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
}
tag=((unsigned int) ReadBlobLSBShort(image) << 16) |
ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
if (length > (size_t) GetBlobSize(image))
ThrowDCMException(CorruptImageError,"InsufficientImageDataInFile");
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
{
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
if (EOFBlob(image) != MagickFalse)
break;
}
offset=TellBlob(image)+8;
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
}
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=info.depth;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
image->colorspace=RGBColorspace;
(void) SetImageBackgroundColor(image,exception);
if ((image->colormap == (PixelInfo *) NULL) &&
(info.samples_per_pixel == 1))
{
int
index;
size_t
one;
one=1;
if (colors == 0)
colors=one << info.depth;
if (AcquireImageColormap(image,colors,exception) == MagickFalse)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
if (redmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=redmap[i];
if ((info.scale != (Quantum *) NULL) && (index >= 0) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].red=(MagickRealType) index;
}
if (greenmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=greenmap[i];
if ((info.scale != (Quantum *) NULL) && (index >= 0) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].green=(MagickRealType) index;
}
if (bluemap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=bluemap[i];
if ((info.scale != (Quantum *) NULL) && (index >= 0) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].blue=(MagickRealType) index;
}
if (graymap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=graymap[i];
if ((info.scale != (Quantum *) NULL) && (index >= 0) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].red=(MagickRealType) index;
image->colormap[i].green=(MagickRealType) index;
image->colormap[i].blue=(MagickRealType) index;
}
}
if (image->compression == RLECompression)
{
unsigned int
tag;
/*
Read RLE segment table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
}
tag=((unsigned int) ReadBlobLSBShort(image) << 16) |
ReadBlobLSBShort(image);
stream_info->remaining=(size_t) ReadBlobLSBLong(image);
if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) ||
(EOFBlob(image) != MagickFalse))
{
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
}
stream_info->count=0;
stream_info->segment_count=ReadBlobLSBLong(image);
for (i=0; i < 15; i++)
stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image);
stream_info->remaining-=64;
if (stream_info->segment_count > 1)
{
info.bytes_per_pixel=1;
info.depth=8;
if (stream_info->offset_count > 0)
(void) SeekBlob(image,(MagickOffsetType)
stream_info->offsets[0]+stream_info->segments[0],SEEK_SET);
}
}
if ((info.samples_per_pixel > 1) && (image->interlace == PlaneInterlace))
{
register ssize_t
x;
register Quantum
*q;
ssize_t
y;
/*
Convert Planar RGB DCM Medical image to pixel packets.
*/
for (i=0; i < (ssize_t) info.samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
switch ((int) i)
{
case 0:
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 1:
{
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 2:
{
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 3:
{
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
default:
break;
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
}
else
{
const char
*option;
/*
Convert DCM Medical image to pixel packets.
*/
option=GetImageOption(image_info,"dcm:display-range");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"reset") == 0)
info.window_width=0;
}
option=GetImageOption(image_info,"dcm:window");
if (option != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(option,&geometry_info);
if (flags & RhoValue)
info.window_center=geometry_info.rho;
if (flags & SigmaValue)
info.window_width=geometry_info.sigma;
info.rescale=MagickTrue;
}
option=GetImageOption(image_info,"dcm:rescale");
if (option != (char *) NULL)
info.rescale=IsStringTrue(option);
if ((info.window_center != 0) && (info.window_width == 0))
info.window_width=info.window_center;
status=ReadDCMPixels(image,&info,stream_info,MagickTrue,exception);
if ((status != MagickFalse) && (stream_info->segment_count > 1))
{
if (stream_info->offset_count > 0)
(void) SeekBlob(image,(MagickOffsetType)
stream_info->offsets[0]+stream_info->segments[1],SEEK_SET);
(void) ReadDCMPixels(image,&info,stream_info,MagickFalse,
exception);
}
}
if (SetImageGray(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace,exception);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (scene < (ssize_t) (number_scenes-1))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
if (TellBlob(image) < (MagickOffsetType) GetBlobSize(image))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
/*
Free resources.
*/
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info);
if (info.scale != (Quantum *) NULL)
info.scale=(Quantum *) RelinquishMagickMemory(info.scale);
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
if (image == (Image *) NULL)
return(image);
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r D C M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterDCMImage() adds attributes for the DCM image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterDCMImage method is:
%
% size_t RegisterDCMImage(void)
%
*/
ModuleExport size_t RegisterDCMImage(void)
{
MagickInfo
*entry;
static const char
*DCMNote=
{
"DICOM is used by the medical community for images like X-rays. The\n"
"specification, \"Digital Imaging and Communications in Medicine\n"
"(DICOM)\", is available at http://medical.nema.org/. In particular,\n"
"see part 5 which describes the image encoding (RLE, JPEG, JPEG-LS),\n"
"and supplement 61 which adds JPEG-2000 encoding."
};
entry=AcquireMagickInfo("DCM","DCM",
"Digital Imaging and Communications in Medicine image");
entry->decoder=(DecodeImageHandler *) ReadDCMImage;
entry->magick=(IsImageFormatHandler *) IsDCM;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
entry->note=ConstantString(DCMNote);
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r D C M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterDCMImage() removes format registrations made by the
% DCM module from the list of supported formats.
%
% The format of the UnregisterDCMImage method is:
%
% UnregisterDCMImage(void)
%
*/
ModuleExport void UnregisterDCMImage(void)
{
(void) UnregisterMagickInfo("DCM");
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_365_0 |
crossvul-cpp_data_good_2162_3 | /*
* Kernel-based Virtual Machine driver for Linux
*
* This module enables machines with Intel VT-x extensions to run virtual
* machines without emulation or binary translation.
*
* Copyright (C) 2006 Qumranet, Inc.
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Authors:
* Avi Kivity <avi@qumranet.com>
* Yaniv Kamay <yaniv@qumranet.com>
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
*/
#include "irq.h"
#include "mmu.h"
#include "cpuid.h"
#include <linux/kvm_host.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/highmem.h>
#include <linux/sched.h>
#include <linux/moduleparam.h>
#include <linux/mod_devicetable.h>
#include <linux/ftrace_event.h>
#include <linux/slab.h>
#include <linux/tboot.h>
#include "kvm_cache_regs.h"
#include "x86.h"
#include <asm/io.h>
#include <asm/desc.h>
#include <asm/vmx.h>
#include <asm/virtext.h>
#include <asm/mce.h>
#include <asm/i387.h>
#include <asm/xcr.h>
#include <asm/perf_event.h>
#include <asm/kexec.h>
#include "trace.h"
#define __ex(x) __kvm_handle_fault_on_reboot(x)
#define __ex_clear(x, reg) \
____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
MODULE_AUTHOR("Qumranet");
MODULE_LICENSE("GPL");
static const struct x86_cpu_id vmx_cpu_id[] = {
X86_FEATURE_MATCH(X86_FEATURE_VMX),
{}
};
MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
static bool __read_mostly enable_vpid = 1;
module_param_named(vpid, enable_vpid, bool, 0444);
static bool __read_mostly flexpriority_enabled = 1;
module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
static bool __read_mostly enable_ept = 1;
module_param_named(ept, enable_ept, bool, S_IRUGO);
static bool __read_mostly enable_unrestricted_guest = 1;
module_param_named(unrestricted_guest,
enable_unrestricted_guest, bool, S_IRUGO);
static bool __read_mostly enable_ept_ad_bits = 1;
module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
static bool __read_mostly emulate_invalid_guest_state = true;
module_param(emulate_invalid_guest_state, bool, S_IRUGO);
static bool __read_mostly vmm_exclusive = 1;
module_param(vmm_exclusive, bool, S_IRUGO);
static bool __read_mostly fasteoi = 1;
module_param(fasteoi, bool, S_IRUGO);
static bool __read_mostly enable_apicv = 1;
module_param(enable_apicv, bool, S_IRUGO);
static bool __read_mostly enable_shadow_vmcs = 1;
module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
/*
* If nested=1, nested virtualization is supported, i.e., guests may use
* VMX and be a hypervisor for its own guests. If nested=0, guests may not
* use VMX instructions.
*/
static bool __read_mostly nested = 0;
module_param(nested, bool, S_IRUGO);
#define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
#define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST (X86_CR0_WP | X86_CR0_NE)
#define KVM_VM_CR0_ALWAYS_ON \
(KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
#define KVM_CR4_GUEST_OWNED_BITS \
(X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
| X86_CR4_OSXMMEXCPT)
#define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
#define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
#define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
/*
* These 2 parameters are used to config the controls for Pause-Loop Exiting:
* ple_gap: upper bound on the amount of time between two successive
* executions of PAUSE in a loop. Also indicate if ple enabled.
* According to test, this time is usually smaller than 128 cycles.
* ple_window: upper bound on the amount of time a guest is allowed to execute
* in a PAUSE loop. Tests indicate that most spinlocks are held for
* less than 2^12 cycles
* Time is measured based on a counter that runs at the same rate as the TSC,
* refer SDM volume 3b section 21.6.13 & 22.1.3.
*/
#define KVM_VMX_DEFAULT_PLE_GAP 128
#define KVM_VMX_DEFAULT_PLE_WINDOW 4096
static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
module_param(ple_gap, int, S_IRUGO);
static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
module_param(ple_window, int, S_IRUGO);
extern const ulong vmx_return;
#define NR_AUTOLOAD_MSRS 8
#define VMCS02_POOL_SIZE 1
struct vmcs {
u32 revision_id;
u32 abort;
char data[0];
};
/*
* Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
* remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
* loaded on this CPU (so we can clear them if the CPU goes down).
*/
struct loaded_vmcs {
struct vmcs *vmcs;
int cpu;
int launched;
struct list_head loaded_vmcss_on_cpu_link;
};
struct shared_msr_entry {
unsigned index;
u64 data;
u64 mask;
};
/*
* struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
* single nested guest (L2), hence the name vmcs12. Any VMX implementation has
* a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
* stored in guest memory specified by VMPTRLD, but is opaque to the guest,
* which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
* More than one of these structures may exist, if L1 runs multiple L2 guests.
* nested_vmx_run() will use the data here to build a vmcs02: a VMCS for the
* underlying hardware which will be used to run L2.
* This structure is packed to ensure that its layout is identical across
* machines (necessary for live migration).
* If there are changes in this struct, VMCS12_REVISION must be changed.
*/
typedef u64 natural_width;
struct __packed vmcs12 {
/* According to the Intel spec, a VMCS region must start with the
* following two fields. Then follow implementation-specific data.
*/
u32 revision_id;
u32 abort;
u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
u32 padding[7]; /* room for future expansion */
u64 io_bitmap_a;
u64 io_bitmap_b;
u64 msr_bitmap;
u64 vm_exit_msr_store_addr;
u64 vm_exit_msr_load_addr;
u64 vm_entry_msr_load_addr;
u64 tsc_offset;
u64 virtual_apic_page_addr;
u64 apic_access_addr;
u64 ept_pointer;
u64 guest_physical_address;
u64 vmcs_link_pointer;
u64 guest_ia32_debugctl;
u64 guest_ia32_pat;
u64 guest_ia32_efer;
u64 guest_ia32_perf_global_ctrl;
u64 guest_pdptr0;
u64 guest_pdptr1;
u64 guest_pdptr2;
u64 guest_pdptr3;
u64 host_ia32_pat;
u64 host_ia32_efer;
u64 host_ia32_perf_global_ctrl;
u64 padding64[8]; /* room for future expansion */
/*
* To allow migration of L1 (complete with its L2 guests) between
* machines of different natural widths (32 or 64 bit), we cannot have
* unsigned long fields with no explict size. We use u64 (aliased
* natural_width) instead. Luckily, x86 is little-endian.
*/
natural_width cr0_guest_host_mask;
natural_width cr4_guest_host_mask;
natural_width cr0_read_shadow;
natural_width cr4_read_shadow;
natural_width cr3_target_value0;
natural_width cr3_target_value1;
natural_width cr3_target_value2;
natural_width cr3_target_value3;
natural_width exit_qualification;
natural_width guest_linear_address;
natural_width guest_cr0;
natural_width guest_cr3;
natural_width guest_cr4;
natural_width guest_es_base;
natural_width guest_cs_base;
natural_width guest_ss_base;
natural_width guest_ds_base;
natural_width guest_fs_base;
natural_width guest_gs_base;
natural_width guest_ldtr_base;
natural_width guest_tr_base;
natural_width guest_gdtr_base;
natural_width guest_idtr_base;
natural_width guest_dr7;
natural_width guest_rsp;
natural_width guest_rip;
natural_width guest_rflags;
natural_width guest_pending_dbg_exceptions;
natural_width guest_sysenter_esp;
natural_width guest_sysenter_eip;
natural_width host_cr0;
natural_width host_cr3;
natural_width host_cr4;
natural_width host_fs_base;
natural_width host_gs_base;
natural_width host_tr_base;
natural_width host_gdtr_base;
natural_width host_idtr_base;
natural_width host_ia32_sysenter_esp;
natural_width host_ia32_sysenter_eip;
natural_width host_rsp;
natural_width host_rip;
natural_width paddingl[8]; /* room for future expansion */
u32 pin_based_vm_exec_control;
u32 cpu_based_vm_exec_control;
u32 exception_bitmap;
u32 page_fault_error_code_mask;
u32 page_fault_error_code_match;
u32 cr3_target_count;
u32 vm_exit_controls;
u32 vm_exit_msr_store_count;
u32 vm_exit_msr_load_count;
u32 vm_entry_controls;
u32 vm_entry_msr_load_count;
u32 vm_entry_intr_info_field;
u32 vm_entry_exception_error_code;
u32 vm_entry_instruction_len;
u32 tpr_threshold;
u32 secondary_vm_exec_control;
u32 vm_instruction_error;
u32 vm_exit_reason;
u32 vm_exit_intr_info;
u32 vm_exit_intr_error_code;
u32 idt_vectoring_info_field;
u32 idt_vectoring_error_code;
u32 vm_exit_instruction_len;
u32 vmx_instruction_info;
u32 guest_es_limit;
u32 guest_cs_limit;
u32 guest_ss_limit;
u32 guest_ds_limit;
u32 guest_fs_limit;
u32 guest_gs_limit;
u32 guest_ldtr_limit;
u32 guest_tr_limit;
u32 guest_gdtr_limit;
u32 guest_idtr_limit;
u32 guest_es_ar_bytes;
u32 guest_cs_ar_bytes;
u32 guest_ss_ar_bytes;
u32 guest_ds_ar_bytes;
u32 guest_fs_ar_bytes;
u32 guest_gs_ar_bytes;
u32 guest_ldtr_ar_bytes;
u32 guest_tr_ar_bytes;
u32 guest_interruptibility_info;
u32 guest_activity_state;
u32 guest_sysenter_cs;
u32 host_ia32_sysenter_cs;
u32 vmx_preemption_timer_value;
u32 padding32[7]; /* room for future expansion */
u16 virtual_processor_id;
u16 guest_es_selector;
u16 guest_cs_selector;
u16 guest_ss_selector;
u16 guest_ds_selector;
u16 guest_fs_selector;
u16 guest_gs_selector;
u16 guest_ldtr_selector;
u16 guest_tr_selector;
u16 host_es_selector;
u16 host_cs_selector;
u16 host_ss_selector;
u16 host_ds_selector;
u16 host_fs_selector;
u16 host_gs_selector;
u16 host_tr_selector;
};
/*
* VMCS12_REVISION is an arbitrary id that should be changed if the content or
* layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
* VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
*/
#define VMCS12_REVISION 0x11e57ed0
/*
* VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
* and any VMCS region. Although only sizeof(struct vmcs12) are used by the
* current implementation, 4K are reserved to avoid future complications.
*/
#define VMCS12_SIZE 0x1000
/* Used to remember the last vmcs02 used for some recently used vmcs12s */
struct vmcs02_list {
struct list_head list;
gpa_t vmptr;
struct loaded_vmcs vmcs02;
};
/*
* The nested_vmx structure is part of vcpu_vmx, and holds information we need
* for correct emulation of VMX (i.e., nested VMX) on this vcpu.
*/
struct nested_vmx {
/* Has the level1 guest done vmxon? */
bool vmxon;
/* The guest-physical address of the current VMCS L1 keeps for L2 */
gpa_t current_vmptr;
/* The host-usable pointer to the above */
struct page *current_vmcs12_page;
struct vmcs12 *current_vmcs12;
struct vmcs *current_shadow_vmcs;
/*
* Indicates if the shadow vmcs must be updated with the
* data hold by vmcs12
*/
bool sync_shadow_vmcs;
/* vmcs02_list cache of VMCSs recently used to run L2 guests */
struct list_head vmcs02_pool;
int vmcs02_num;
u64 vmcs01_tsc_offset;
/* L2 must run next, and mustn't decide to exit to L1. */
bool nested_run_pending;
/*
* Guest pages referred to in vmcs02 with host-physical pointers, so
* we must keep them pinned while L2 runs.
*/
struct page *apic_access_page;
u64 msr_ia32_feature_control;
};
#define POSTED_INTR_ON 0
/* Posted-Interrupt Descriptor */
struct pi_desc {
u32 pir[8]; /* Posted interrupt requested */
u32 control; /* bit 0 of control is outstanding notification bit */
u32 rsvd[7];
} __aligned(64);
static bool pi_test_and_set_on(struct pi_desc *pi_desc)
{
return test_and_set_bit(POSTED_INTR_ON,
(unsigned long *)&pi_desc->control);
}
static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
{
return test_and_clear_bit(POSTED_INTR_ON,
(unsigned long *)&pi_desc->control);
}
static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
{
return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
}
struct vcpu_vmx {
struct kvm_vcpu vcpu;
unsigned long host_rsp;
u8 fail;
u8 cpl;
bool nmi_known_unmasked;
u32 exit_intr_info;
u32 idt_vectoring_info;
ulong rflags;
struct shared_msr_entry *guest_msrs;
int nmsrs;
int save_nmsrs;
unsigned long host_idt_base;
#ifdef CONFIG_X86_64
u64 msr_host_kernel_gs_base;
u64 msr_guest_kernel_gs_base;
#endif
/*
* loaded_vmcs points to the VMCS currently used in this vcpu. For a
* non-nested (L1) guest, it always points to vmcs01. For a nested
* guest (L2), it points to a different VMCS.
*/
struct loaded_vmcs vmcs01;
struct loaded_vmcs *loaded_vmcs;
bool __launched; /* temporary, used in vmx_vcpu_run */
struct msr_autoload {
unsigned nr;
struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
} msr_autoload;
struct {
int loaded;
u16 fs_sel, gs_sel, ldt_sel;
#ifdef CONFIG_X86_64
u16 ds_sel, es_sel;
#endif
int gs_ldt_reload_needed;
int fs_reload_needed;
} host_state;
struct {
int vm86_active;
ulong save_rflags;
struct kvm_segment segs[8];
} rmode;
struct {
u32 bitmask; /* 4 bits per segment (1 bit per field) */
struct kvm_save_segment {
u16 selector;
unsigned long base;
u32 limit;
u32 ar;
} seg[8];
} segment_cache;
int vpid;
bool emulation_required;
/* Support for vnmi-less CPUs */
int soft_vnmi_blocked;
ktime_t entry_time;
s64 vnmi_blocked_time;
u32 exit_reason;
bool rdtscp_enabled;
/* Posted interrupt descriptor */
struct pi_desc pi_desc;
/* Support for a guest hypervisor (nested VMX) */
struct nested_vmx nested;
};
enum segment_cache_field {
SEG_FIELD_SEL = 0,
SEG_FIELD_BASE = 1,
SEG_FIELD_LIMIT = 2,
SEG_FIELD_AR = 3,
SEG_FIELD_NR = 4
};
static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
{
return container_of(vcpu, struct vcpu_vmx, vcpu);
}
#define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
#define FIELD(number, name) [number] = VMCS12_OFFSET(name)
#define FIELD64(number, name) [number] = VMCS12_OFFSET(name), \
[number##_HIGH] = VMCS12_OFFSET(name)+4
static const unsigned long shadow_read_only_fields[] = {
/*
* We do NOT shadow fields that are modified when L0
* traps and emulates any vmx instruction (e.g. VMPTRLD,
* VMXON...) executed by L1.
* For example, VM_INSTRUCTION_ERROR is read
* by L1 if a vmx instruction fails (part of the error path).
* Note the code assumes this logic. If for some reason
* we start shadowing these fields then we need to
* force a shadow sync when L0 emulates vmx instructions
* (e.g. force a sync if VM_INSTRUCTION_ERROR is modified
* by nested_vmx_failValid)
*/
VM_EXIT_REASON,
VM_EXIT_INTR_INFO,
VM_EXIT_INSTRUCTION_LEN,
IDT_VECTORING_INFO_FIELD,
IDT_VECTORING_ERROR_CODE,
VM_EXIT_INTR_ERROR_CODE,
EXIT_QUALIFICATION,
GUEST_LINEAR_ADDRESS,
GUEST_PHYSICAL_ADDRESS
};
static const int max_shadow_read_only_fields =
ARRAY_SIZE(shadow_read_only_fields);
static const unsigned long shadow_read_write_fields[] = {
GUEST_RIP,
GUEST_RSP,
GUEST_CR0,
GUEST_CR3,
GUEST_CR4,
GUEST_INTERRUPTIBILITY_INFO,
GUEST_RFLAGS,
GUEST_CS_SELECTOR,
GUEST_CS_AR_BYTES,
GUEST_CS_LIMIT,
GUEST_CS_BASE,
GUEST_ES_BASE,
CR0_GUEST_HOST_MASK,
CR0_READ_SHADOW,
CR4_READ_SHADOW,
TSC_OFFSET,
EXCEPTION_BITMAP,
CPU_BASED_VM_EXEC_CONTROL,
VM_ENTRY_EXCEPTION_ERROR_CODE,
VM_ENTRY_INTR_INFO_FIELD,
VM_ENTRY_INSTRUCTION_LEN,
VM_ENTRY_EXCEPTION_ERROR_CODE,
HOST_FS_BASE,
HOST_GS_BASE,
HOST_FS_SELECTOR,
HOST_GS_SELECTOR
};
static const int max_shadow_read_write_fields =
ARRAY_SIZE(shadow_read_write_fields);
static const unsigned short vmcs_field_to_offset_table[] = {
FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
FIELD(GUEST_ES_SELECTOR, guest_es_selector),
FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
FIELD(HOST_ES_SELECTOR, host_es_selector),
FIELD(HOST_CS_SELECTOR, host_cs_selector),
FIELD(HOST_SS_SELECTOR, host_ss_selector),
FIELD(HOST_DS_SELECTOR, host_ds_selector),
FIELD(HOST_FS_SELECTOR, host_fs_selector),
FIELD(HOST_GS_SELECTOR, host_gs_selector),
FIELD(HOST_TR_SELECTOR, host_tr_selector),
FIELD64(IO_BITMAP_A, io_bitmap_a),
FIELD64(IO_BITMAP_B, io_bitmap_b),
FIELD64(MSR_BITMAP, msr_bitmap),
FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
FIELD64(TSC_OFFSET, tsc_offset),
FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
FIELD64(EPT_POINTER, ept_pointer),
FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
FIELD64(GUEST_PDPTR0, guest_pdptr0),
FIELD64(GUEST_PDPTR1, guest_pdptr1),
FIELD64(GUEST_PDPTR2, guest_pdptr2),
FIELD64(GUEST_PDPTR3, guest_pdptr3),
FIELD64(HOST_IA32_PAT, host_ia32_pat),
FIELD64(HOST_IA32_EFER, host_ia32_efer),
FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
FIELD(EXCEPTION_BITMAP, exception_bitmap),
FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
FIELD(CR3_TARGET_COUNT, cr3_target_count),
FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
FIELD(TPR_THRESHOLD, tpr_threshold),
FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
FIELD(VM_EXIT_REASON, vm_exit_reason),
FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
FIELD(GUEST_ES_LIMIT, guest_es_limit),
FIELD(GUEST_CS_LIMIT, guest_cs_limit),
FIELD(GUEST_SS_LIMIT, guest_ss_limit),
FIELD(GUEST_DS_LIMIT, guest_ds_limit),
FIELD(GUEST_FS_LIMIT, guest_fs_limit),
FIELD(GUEST_GS_LIMIT, guest_gs_limit),
FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
FIELD(GUEST_TR_LIMIT, guest_tr_limit),
FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
FIELD(CR0_READ_SHADOW, cr0_read_shadow),
FIELD(CR4_READ_SHADOW, cr4_read_shadow),
FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
FIELD(EXIT_QUALIFICATION, exit_qualification),
FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
FIELD(GUEST_CR0, guest_cr0),
FIELD(GUEST_CR3, guest_cr3),
FIELD(GUEST_CR4, guest_cr4),
FIELD(GUEST_ES_BASE, guest_es_base),
FIELD(GUEST_CS_BASE, guest_cs_base),
FIELD(GUEST_SS_BASE, guest_ss_base),
FIELD(GUEST_DS_BASE, guest_ds_base),
FIELD(GUEST_FS_BASE, guest_fs_base),
FIELD(GUEST_GS_BASE, guest_gs_base),
FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
FIELD(GUEST_TR_BASE, guest_tr_base),
FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
FIELD(GUEST_IDTR_BASE, guest_idtr_base),
FIELD(GUEST_DR7, guest_dr7),
FIELD(GUEST_RSP, guest_rsp),
FIELD(GUEST_RIP, guest_rip),
FIELD(GUEST_RFLAGS, guest_rflags),
FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
FIELD(HOST_CR0, host_cr0),
FIELD(HOST_CR3, host_cr3),
FIELD(HOST_CR4, host_cr4),
FIELD(HOST_FS_BASE, host_fs_base),
FIELD(HOST_GS_BASE, host_gs_base),
FIELD(HOST_TR_BASE, host_tr_base),
FIELD(HOST_GDTR_BASE, host_gdtr_base),
FIELD(HOST_IDTR_BASE, host_idtr_base),
FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
FIELD(HOST_RSP, host_rsp),
FIELD(HOST_RIP, host_rip),
};
static const int max_vmcs_field = ARRAY_SIZE(vmcs_field_to_offset_table);
static inline short vmcs_field_to_offset(unsigned long field)
{
if (field >= max_vmcs_field || vmcs_field_to_offset_table[field] == 0)
return -1;
return vmcs_field_to_offset_table[field];
}
static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
{
return to_vmx(vcpu)->nested.current_vmcs12;
}
static struct page *nested_get_page(struct kvm_vcpu *vcpu, gpa_t addr)
{
struct page *page = gfn_to_page(vcpu->kvm, addr >> PAGE_SHIFT);
if (is_error_page(page))
return NULL;
return page;
}
static void nested_release_page(struct page *page)
{
kvm_release_page_dirty(page);
}
static void nested_release_page_clean(struct page *page)
{
kvm_release_page_clean(page);
}
static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
static u64 construct_eptp(unsigned long root_hpa);
static void kvm_cpu_vmxon(u64 addr);
static void kvm_cpu_vmxoff(void);
static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3);
static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
static void vmx_set_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg);
static void vmx_get_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg);
static bool guest_state_valid(struct kvm_vcpu *vcpu);
static u32 vmx_segment_access_rights(struct kvm_segment *var);
static void vmx_sync_pir_to_irr_dummy(struct kvm_vcpu *vcpu);
static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx);
static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
static DEFINE_PER_CPU(struct vmcs *, vmxarea);
static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
/*
* We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
* when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
*/
static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
static DEFINE_PER_CPU(struct desc_ptr, host_gdt);
static unsigned long *vmx_io_bitmap_a;
static unsigned long *vmx_io_bitmap_b;
static unsigned long *vmx_msr_bitmap_legacy;
static unsigned long *vmx_msr_bitmap_longmode;
static unsigned long *vmx_msr_bitmap_legacy_x2apic;
static unsigned long *vmx_msr_bitmap_longmode_x2apic;
static unsigned long *vmx_vmread_bitmap;
static unsigned long *vmx_vmwrite_bitmap;
static bool cpu_has_load_ia32_efer;
static bool cpu_has_load_perf_global_ctrl;
static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
static DEFINE_SPINLOCK(vmx_vpid_lock);
static struct vmcs_config {
int size;
int order;
u32 revision_id;
u32 pin_based_exec_ctrl;
u32 cpu_based_exec_ctrl;
u32 cpu_based_2nd_exec_ctrl;
u32 vmexit_ctrl;
u32 vmentry_ctrl;
} vmcs_config;
static struct vmx_capability {
u32 ept;
u32 vpid;
} vmx_capability;
#define VMX_SEGMENT_FIELD(seg) \
[VCPU_SREG_##seg] = { \
.selector = GUEST_##seg##_SELECTOR, \
.base = GUEST_##seg##_BASE, \
.limit = GUEST_##seg##_LIMIT, \
.ar_bytes = GUEST_##seg##_AR_BYTES, \
}
static const struct kvm_vmx_segment_field {
unsigned selector;
unsigned base;
unsigned limit;
unsigned ar_bytes;
} kvm_vmx_segment_fields[] = {
VMX_SEGMENT_FIELD(CS),
VMX_SEGMENT_FIELD(DS),
VMX_SEGMENT_FIELD(ES),
VMX_SEGMENT_FIELD(FS),
VMX_SEGMENT_FIELD(GS),
VMX_SEGMENT_FIELD(SS),
VMX_SEGMENT_FIELD(TR),
VMX_SEGMENT_FIELD(LDTR),
};
static u64 host_efer;
static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
/*
* Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
* away by decrementing the array size.
*/
static const u32 vmx_msr_index[] = {
#ifdef CONFIG_X86_64
MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
#endif
MSR_EFER, MSR_TSC_AUX, MSR_STAR,
};
#define NR_VMX_MSR ARRAY_SIZE(vmx_msr_index)
static inline bool is_page_fault(u32 intr_info)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
INTR_INFO_VALID_MASK)) ==
(INTR_TYPE_HARD_EXCEPTION | PF_VECTOR | INTR_INFO_VALID_MASK);
}
static inline bool is_no_device(u32 intr_info)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
INTR_INFO_VALID_MASK)) ==
(INTR_TYPE_HARD_EXCEPTION | NM_VECTOR | INTR_INFO_VALID_MASK);
}
static inline bool is_invalid_opcode(u32 intr_info)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
INTR_INFO_VALID_MASK)) ==
(INTR_TYPE_HARD_EXCEPTION | UD_VECTOR | INTR_INFO_VALID_MASK);
}
static inline bool is_external_interrupt(u32 intr_info)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
== (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
}
static inline bool is_machine_check(u32 intr_info)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
INTR_INFO_VALID_MASK)) ==
(INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
}
static inline bool cpu_has_vmx_msr_bitmap(void)
{
return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
}
static inline bool cpu_has_vmx_tpr_shadow(void)
{
return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
}
static inline bool vm_need_tpr_shadow(struct kvm *kvm)
{
return (cpu_has_vmx_tpr_shadow()) && (irqchip_in_kernel(kvm));
}
static inline bool cpu_has_secondary_exec_ctrls(void)
{
return vmcs_config.cpu_based_exec_ctrl &
CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
}
static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
}
static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
}
static inline bool cpu_has_vmx_apic_register_virt(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_APIC_REGISTER_VIRT;
}
static inline bool cpu_has_vmx_virtual_intr_delivery(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
}
static inline bool cpu_has_vmx_posted_intr(void)
{
return vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
}
static inline bool cpu_has_vmx_apicv(void)
{
return cpu_has_vmx_apic_register_virt() &&
cpu_has_vmx_virtual_intr_delivery() &&
cpu_has_vmx_posted_intr();
}
static inline bool cpu_has_vmx_flexpriority(void)
{
return cpu_has_vmx_tpr_shadow() &&
cpu_has_vmx_virtualize_apic_accesses();
}
static inline bool cpu_has_vmx_ept_execute_only(void)
{
return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
}
static inline bool cpu_has_vmx_eptp_uncacheable(void)
{
return vmx_capability.ept & VMX_EPTP_UC_BIT;
}
static inline bool cpu_has_vmx_eptp_writeback(void)
{
return vmx_capability.ept & VMX_EPTP_WB_BIT;
}
static inline bool cpu_has_vmx_ept_2m_page(void)
{
return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
}
static inline bool cpu_has_vmx_ept_1g_page(void)
{
return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
}
static inline bool cpu_has_vmx_ept_4levels(void)
{
return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
}
static inline bool cpu_has_vmx_ept_ad_bits(void)
{
return vmx_capability.ept & VMX_EPT_AD_BIT;
}
static inline bool cpu_has_vmx_invept_context(void)
{
return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
}
static inline bool cpu_has_vmx_invept_global(void)
{
return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
}
static inline bool cpu_has_vmx_invvpid_single(void)
{
return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
}
static inline bool cpu_has_vmx_invvpid_global(void)
{
return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
}
static inline bool cpu_has_vmx_ept(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_ENABLE_EPT;
}
static inline bool cpu_has_vmx_unrestricted_guest(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_UNRESTRICTED_GUEST;
}
static inline bool cpu_has_vmx_ple(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_PAUSE_LOOP_EXITING;
}
static inline bool vm_need_virtualize_apic_accesses(struct kvm *kvm)
{
return flexpriority_enabled && irqchip_in_kernel(kvm);
}
static inline bool cpu_has_vmx_vpid(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_ENABLE_VPID;
}
static inline bool cpu_has_vmx_rdtscp(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_RDTSCP;
}
static inline bool cpu_has_vmx_invpcid(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_ENABLE_INVPCID;
}
static inline bool cpu_has_virtual_nmis(void)
{
return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
}
static inline bool cpu_has_vmx_wbinvd_exit(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_WBINVD_EXITING;
}
static inline bool cpu_has_vmx_shadow_vmcs(void)
{
u64 vmx_msr;
rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
/* check if the cpu supports writing r/o exit information fields */
if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
return false;
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_SHADOW_VMCS;
}
static inline bool report_flexpriority(void)
{
return flexpriority_enabled;
}
static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
{
return vmcs12->cpu_based_vm_exec_control & bit;
}
static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
{
return (vmcs12->cpu_based_vm_exec_control &
CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
(vmcs12->secondary_vm_exec_control & bit);
}
static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12,
struct kvm_vcpu *vcpu)
{
return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
}
static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
{
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
}
static inline bool is_exception(u32 intr_info)
{
return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
== (INTR_TYPE_HARD_EXCEPTION | INTR_INFO_VALID_MASK);
}
static void nested_vmx_vmexit(struct kvm_vcpu *vcpu);
static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12,
u32 reason, unsigned long qualification);
static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
{
int i;
for (i = 0; i < vmx->nmsrs; ++i)
if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
return i;
return -1;
}
static inline void __invvpid(int ext, u16 vpid, gva_t gva)
{
struct {
u64 vpid : 16;
u64 rsvd : 48;
u64 gva;
} operand = { vpid, 0, gva };
asm volatile (__ex(ASM_VMX_INVVPID)
/* CF==1 or ZF==1 --> rc = -1 */
"; ja 1f ; ud2 ; 1:"
: : "a"(&operand), "c"(ext) : "cc", "memory");
}
static inline void __invept(int ext, u64 eptp, gpa_t gpa)
{
struct {
u64 eptp, gpa;
} operand = {eptp, gpa};
asm volatile (__ex(ASM_VMX_INVEPT)
/* CF==1 or ZF==1 --> rc = -1 */
"; ja 1f ; ud2 ; 1:\n"
: : "a" (&operand), "c" (ext) : "cc", "memory");
}
static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
{
int i;
i = __find_msr_index(vmx, msr);
if (i >= 0)
return &vmx->guest_msrs[i];
return NULL;
}
static void vmcs_clear(struct vmcs *vmcs)
{
u64 phys_addr = __pa(vmcs);
u8 error;
asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
: "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
: "cc", "memory");
if (error)
printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
vmcs, phys_addr);
}
static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
{
vmcs_clear(loaded_vmcs->vmcs);
loaded_vmcs->cpu = -1;
loaded_vmcs->launched = 0;
}
static void vmcs_load(struct vmcs *vmcs)
{
u64 phys_addr = __pa(vmcs);
u8 error;
asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
: "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
: "cc", "memory");
if (error)
printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
vmcs, phys_addr);
}
#ifdef CONFIG_KEXEC
/*
* This bitmap is used to indicate whether the vmclear
* operation is enabled on all cpus. All disabled by
* default.
*/
static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
static inline void crash_enable_local_vmclear(int cpu)
{
cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
}
static inline void crash_disable_local_vmclear(int cpu)
{
cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
}
static inline int crash_local_vmclear_enabled(int cpu)
{
return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
}
static void crash_vmclear_local_loaded_vmcss(void)
{
int cpu = raw_smp_processor_id();
struct loaded_vmcs *v;
if (!crash_local_vmclear_enabled(cpu))
return;
list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
loaded_vmcss_on_cpu_link)
vmcs_clear(v->vmcs);
}
#else
static inline void crash_enable_local_vmclear(int cpu) { }
static inline void crash_disable_local_vmclear(int cpu) { }
#endif /* CONFIG_KEXEC */
static void __loaded_vmcs_clear(void *arg)
{
struct loaded_vmcs *loaded_vmcs = arg;
int cpu = raw_smp_processor_id();
if (loaded_vmcs->cpu != cpu)
return; /* vcpu migration can race with cpu offline */
if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
per_cpu(current_vmcs, cpu) = NULL;
crash_disable_local_vmclear(cpu);
list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
/*
* we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
* is before setting loaded_vmcs->vcpu to -1 which is done in
* loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
* then adds the vmcs into percpu list before it is deleted.
*/
smp_wmb();
loaded_vmcs_init(loaded_vmcs);
crash_enable_local_vmclear(cpu);
}
static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
{
int cpu = loaded_vmcs->cpu;
if (cpu != -1)
smp_call_function_single(cpu,
__loaded_vmcs_clear, loaded_vmcs, 1);
}
static inline void vpid_sync_vcpu_single(struct vcpu_vmx *vmx)
{
if (vmx->vpid == 0)
return;
if (cpu_has_vmx_invvpid_single())
__invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vmx->vpid, 0);
}
static inline void vpid_sync_vcpu_global(void)
{
if (cpu_has_vmx_invvpid_global())
__invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
}
static inline void vpid_sync_context(struct vcpu_vmx *vmx)
{
if (cpu_has_vmx_invvpid_single())
vpid_sync_vcpu_single(vmx);
else
vpid_sync_vcpu_global();
}
static inline void ept_sync_global(void)
{
if (cpu_has_vmx_invept_global())
__invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
}
static inline void ept_sync_context(u64 eptp)
{
if (enable_ept) {
if (cpu_has_vmx_invept_context())
__invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
else
ept_sync_global();
}
}
static __always_inline unsigned long vmcs_readl(unsigned long field)
{
unsigned long value;
asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
: "=a"(value) : "d"(field) : "cc");
return value;
}
static __always_inline u16 vmcs_read16(unsigned long field)
{
return vmcs_readl(field);
}
static __always_inline u32 vmcs_read32(unsigned long field)
{
return vmcs_readl(field);
}
static __always_inline u64 vmcs_read64(unsigned long field)
{
#ifdef CONFIG_X86_64
return vmcs_readl(field);
#else
return vmcs_readl(field) | ((u64)vmcs_readl(field+1) << 32);
#endif
}
static noinline void vmwrite_error(unsigned long field, unsigned long value)
{
printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
dump_stack();
}
static void vmcs_writel(unsigned long field, unsigned long value)
{
u8 error;
asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
: "=q"(error) : "a"(value), "d"(field) : "cc");
if (unlikely(error))
vmwrite_error(field, value);
}
static void vmcs_write16(unsigned long field, u16 value)
{
vmcs_writel(field, value);
}
static void vmcs_write32(unsigned long field, u32 value)
{
vmcs_writel(field, value);
}
static void vmcs_write64(unsigned long field, u64 value)
{
vmcs_writel(field, value);
#ifndef CONFIG_X86_64
asm volatile ("");
vmcs_writel(field+1, value >> 32);
#endif
}
static void vmcs_clear_bits(unsigned long field, u32 mask)
{
vmcs_writel(field, vmcs_readl(field) & ~mask);
}
static void vmcs_set_bits(unsigned long field, u32 mask)
{
vmcs_writel(field, vmcs_readl(field) | mask);
}
static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
{
vmx->segment_cache.bitmask = 0;
}
static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
unsigned field)
{
bool ret;
u32 mask = 1 << (seg * SEG_FIELD_NR + field);
if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
vmx->segment_cache.bitmask = 0;
}
ret = vmx->segment_cache.bitmask & mask;
vmx->segment_cache.bitmask |= mask;
return ret;
}
static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
{
u16 *p = &vmx->segment_cache.seg[seg].selector;
if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
*p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
return *p;
}
static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
{
ulong *p = &vmx->segment_cache.seg[seg].base;
if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
*p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
return *p;
}
static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
{
u32 *p = &vmx->segment_cache.seg[seg].limit;
if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
*p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
return *p;
}
static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
{
u32 *p = &vmx->segment_cache.seg[seg].ar;
if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
*p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
return *p;
}
static void update_exception_bitmap(struct kvm_vcpu *vcpu)
{
u32 eb;
eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
(1u << NM_VECTOR) | (1u << DB_VECTOR);
if ((vcpu->guest_debug &
(KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
(KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
eb |= 1u << BP_VECTOR;
if (to_vmx(vcpu)->rmode.vm86_active)
eb = ~0;
if (enable_ept)
eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
if (vcpu->fpu_active)
eb &= ~(1u << NM_VECTOR);
/* When we are running a nested L2 guest and L1 specified for it a
* certain exception bitmap, we must trap the same exceptions and pass
* them to L1. When running L2, we will only handle the exceptions
* specified above if L1 did not want them.
*/
if (is_guest_mode(vcpu))
eb |= get_vmcs12(vcpu)->exception_bitmap;
vmcs_write32(EXCEPTION_BITMAP, eb);
}
static void clear_atomic_switch_msr_special(unsigned long entry,
unsigned long exit)
{
vmcs_clear_bits(VM_ENTRY_CONTROLS, entry);
vmcs_clear_bits(VM_EXIT_CONTROLS, exit);
}
static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
{
unsigned i;
struct msr_autoload *m = &vmx->msr_autoload;
switch (msr) {
case MSR_EFER:
if (cpu_has_load_ia32_efer) {
clear_atomic_switch_msr_special(VM_ENTRY_LOAD_IA32_EFER,
VM_EXIT_LOAD_IA32_EFER);
return;
}
break;
case MSR_CORE_PERF_GLOBAL_CTRL:
if (cpu_has_load_perf_global_ctrl) {
clear_atomic_switch_msr_special(
VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
return;
}
break;
}
for (i = 0; i < m->nr; ++i)
if (m->guest[i].index == msr)
break;
if (i == m->nr)
return;
--m->nr;
m->guest[i] = m->guest[m->nr];
m->host[i] = m->host[m->nr];
vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
}
static void add_atomic_switch_msr_special(unsigned long entry,
unsigned long exit, unsigned long guest_val_vmcs,
unsigned long host_val_vmcs, u64 guest_val, u64 host_val)
{
vmcs_write64(guest_val_vmcs, guest_val);
vmcs_write64(host_val_vmcs, host_val);
vmcs_set_bits(VM_ENTRY_CONTROLS, entry);
vmcs_set_bits(VM_EXIT_CONTROLS, exit);
}
static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
u64 guest_val, u64 host_val)
{
unsigned i;
struct msr_autoload *m = &vmx->msr_autoload;
switch (msr) {
case MSR_EFER:
if (cpu_has_load_ia32_efer) {
add_atomic_switch_msr_special(VM_ENTRY_LOAD_IA32_EFER,
VM_EXIT_LOAD_IA32_EFER,
GUEST_IA32_EFER,
HOST_IA32_EFER,
guest_val, host_val);
return;
}
break;
case MSR_CORE_PERF_GLOBAL_CTRL:
if (cpu_has_load_perf_global_ctrl) {
add_atomic_switch_msr_special(
VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
GUEST_IA32_PERF_GLOBAL_CTRL,
HOST_IA32_PERF_GLOBAL_CTRL,
guest_val, host_val);
return;
}
break;
}
for (i = 0; i < m->nr; ++i)
if (m->guest[i].index == msr)
break;
if (i == NR_AUTOLOAD_MSRS) {
printk_once(KERN_WARNING"Not enough mst switch entries. "
"Can't add msr %x\n", msr);
return;
} else if (i == m->nr) {
++m->nr;
vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
}
m->guest[i].index = msr;
m->guest[i].value = guest_val;
m->host[i].index = msr;
m->host[i].value = host_val;
}
static void reload_tss(void)
{
/*
* VT restores TR but not its size. Useless.
*/
struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
struct desc_struct *descs;
descs = (void *)gdt->address;
descs[GDT_ENTRY_TSS].type = 9; /* available TSS */
load_TR_desc();
}
static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
{
u64 guest_efer;
u64 ignore_bits;
guest_efer = vmx->vcpu.arch.efer;
/*
* NX is emulated; LMA and LME handled by hardware; SCE meaningless
* outside long mode
*/
ignore_bits = EFER_NX | EFER_SCE;
#ifdef CONFIG_X86_64
ignore_bits |= EFER_LMA | EFER_LME;
/* SCE is meaningful only in long mode on Intel */
if (guest_efer & EFER_LMA)
ignore_bits &= ~(u64)EFER_SCE;
#endif
guest_efer &= ~ignore_bits;
guest_efer |= host_efer & ignore_bits;
vmx->guest_msrs[efer_offset].data = guest_efer;
vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
clear_atomic_switch_msr(vmx, MSR_EFER);
/* On ept, can't emulate nx, and must switch nx atomically */
if (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX)) {
guest_efer = vmx->vcpu.arch.efer;
if (!(guest_efer & EFER_LMA))
guest_efer &= ~EFER_LME;
add_atomic_switch_msr(vmx, MSR_EFER, guest_efer, host_efer);
return false;
}
return true;
}
static unsigned long segment_base(u16 selector)
{
struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
struct desc_struct *d;
unsigned long table_base;
unsigned long v;
if (!(selector & ~3))
return 0;
table_base = gdt->address;
if (selector & 4) { /* from ldt */
u16 ldt_selector = kvm_read_ldt();
if (!(ldt_selector & ~3))
return 0;
table_base = segment_base(ldt_selector);
}
d = (struct desc_struct *)(table_base + (selector & ~7));
v = get_desc_base(d);
#ifdef CONFIG_X86_64
if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
#endif
return v;
}
static inline unsigned long kvm_read_tr_base(void)
{
u16 tr;
asm("str %0" : "=g"(tr));
return segment_base(tr);
}
static void vmx_save_host_state(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int i;
if (vmx->host_state.loaded)
return;
vmx->host_state.loaded = 1;
/*
* Set host fs and gs selectors. Unfortunately, 22.2.3 does not
* allow segment selectors with cpl > 0 or ti == 1.
*/
vmx->host_state.ldt_sel = kvm_read_ldt();
vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
savesegment(fs, vmx->host_state.fs_sel);
if (!(vmx->host_state.fs_sel & 7)) {
vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
vmx->host_state.fs_reload_needed = 0;
} else {
vmcs_write16(HOST_FS_SELECTOR, 0);
vmx->host_state.fs_reload_needed = 1;
}
savesegment(gs, vmx->host_state.gs_sel);
if (!(vmx->host_state.gs_sel & 7))
vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
else {
vmcs_write16(HOST_GS_SELECTOR, 0);
vmx->host_state.gs_ldt_reload_needed = 1;
}
#ifdef CONFIG_X86_64
savesegment(ds, vmx->host_state.ds_sel);
savesegment(es, vmx->host_state.es_sel);
#endif
#ifdef CONFIG_X86_64
vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
#else
vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
#endif
#ifdef CONFIG_X86_64
rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
if (is_long_mode(&vmx->vcpu))
wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
#endif
for (i = 0; i < vmx->save_nmsrs; ++i)
kvm_set_shared_msr(vmx->guest_msrs[i].index,
vmx->guest_msrs[i].data,
vmx->guest_msrs[i].mask);
}
static void __vmx_load_host_state(struct vcpu_vmx *vmx)
{
if (!vmx->host_state.loaded)
return;
++vmx->vcpu.stat.host_state_reload;
vmx->host_state.loaded = 0;
#ifdef CONFIG_X86_64
if (is_long_mode(&vmx->vcpu))
rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
#endif
if (vmx->host_state.gs_ldt_reload_needed) {
kvm_load_ldt(vmx->host_state.ldt_sel);
#ifdef CONFIG_X86_64
load_gs_index(vmx->host_state.gs_sel);
#else
loadsegment(gs, vmx->host_state.gs_sel);
#endif
}
if (vmx->host_state.fs_reload_needed)
loadsegment(fs, vmx->host_state.fs_sel);
#ifdef CONFIG_X86_64
if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
loadsegment(ds, vmx->host_state.ds_sel);
loadsegment(es, vmx->host_state.es_sel);
}
#endif
reload_tss();
#ifdef CONFIG_X86_64
wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
#endif
/*
* If the FPU is not active (through the host task or
* the guest vcpu), then restore the cr0.TS bit.
*/
if (!user_has_fpu() && !vmx->vcpu.guest_fpu_loaded)
stts();
load_gdt(&__get_cpu_var(host_gdt));
}
static void vmx_load_host_state(struct vcpu_vmx *vmx)
{
preempt_disable();
__vmx_load_host_state(vmx);
preempt_enable();
}
/*
* Switches to specified vcpu, until a matching vcpu_put(), but assumes
* vcpu mutex is already taken.
*/
static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
if (!vmm_exclusive)
kvm_cpu_vmxon(phys_addr);
else if (vmx->loaded_vmcs->cpu != cpu)
loaded_vmcs_clear(vmx->loaded_vmcs);
if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
vmcs_load(vmx->loaded_vmcs->vmcs);
}
if (vmx->loaded_vmcs->cpu != cpu) {
struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
unsigned long sysenter_esp;
kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
local_irq_disable();
crash_disable_local_vmclear(cpu);
/*
* Read loaded_vmcs->cpu should be before fetching
* loaded_vmcs->loaded_vmcss_on_cpu_link.
* See the comments in __loaded_vmcs_clear().
*/
smp_rmb();
list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
&per_cpu(loaded_vmcss_on_cpu, cpu));
crash_enable_local_vmclear(cpu);
local_irq_enable();
/*
* Linux uses per-cpu TSS and GDT, so set these when switching
* processors.
*/
vmcs_writel(HOST_TR_BASE, kvm_read_tr_base()); /* 22.2.4 */
vmcs_writel(HOST_GDTR_BASE, gdt->address); /* 22.2.4 */
rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
vmx->loaded_vmcs->cpu = cpu;
}
}
static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
{
__vmx_load_host_state(to_vmx(vcpu));
if (!vmm_exclusive) {
__loaded_vmcs_clear(to_vmx(vcpu)->loaded_vmcs);
vcpu->cpu = -1;
kvm_cpu_vmxoff();
}
}
static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
{
ulong cr0;
if (vcpu->fpu_active)
return;
vcpu->fpu_active = 1;
cr0 = vmcs_readl(GUEST_CR0);
cr0 &= ~(X86_CR0_TS | X86_CR0_MP);
cr0 |= kvm_read_cr0_bits(vcpu, X86_CR0_TS | X86_CR0_MP);
vmcs_writel(GUEST_CR0, cr0);
update_exception_bitmap(vcpu);
vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
if (is_guest_mode(vcpu))
vcpu->arch.cr0_guest_owned_bits &=
~get_vmcs12(vcpu)->cr0_guest_host_mask;
vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
}
static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
/*
* Return the cr0 value that a nested guest would read. This is a combination
* of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
* its hypervisor (cr0_read_shadow).
*/
static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
{
return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
(fields->cr0_read_shadow & fields->cr0_guest_host_mask);
}
static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
{
return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
(fields->cr4_read_shadow & fields->cr4_guest_host_mask);
}
static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
{
/* Note that there is no vcpu->fpu_active = 0 here. The caller must
* set this *before* calling this function.
*/
vmx_decache_cr0_guest_bits(vcpu);
vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP);
update_exception_bitmap(vcpu);
vcpu->arch.cr0_guest_owned_bits = 0;
vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
if (is_guest_mode(vcpu)) {
/*
* L1's specified read shadow might not contain the TS bit,
* so now that we turned on shadowing of this bit, we need to
* set this bit of the shadow. Like in nested_vmx_run we need
* nested_read_cr0(vmcs12), but vmcs12->guest_cr0 is not yet
* up-to-date here because we just decached cr0.TS (and we'll
* only update vmcs12->guest_cr0 on nested exit).
*/
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
vmcs12->guest_cr0 = (vmcs12->guest_cr0 & ~X86_CR0_TS) |
(vcpu->arch.cr0 & X86_CR0_TS);
vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
} else
vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
}
static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
{
unsigned long rflags, save_rflags;
if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
__set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
rflags = vmcs_readl(GUEST_RFLAGS);
if (to_vmx(vcpu)->rmode.vm86_active) {
rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
save_rflags = to_vmx(vcpu)->rmode.save_rflags;
rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
}
to_vmx(vcpu)->rflags = rflags;
}
return to_vmx(vcpu)->rflags;
}
static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
{
__set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
to_vmx(vcpu)->rflags = rflags;
if (to_vmx(vcpu)->rmode.vm86_active) {
to_vmx(vcpu)->rmode.save_rflags = rflags;
rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
}
vmcs_writel(GUEST_RFLAGS, rflags);
}
static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
{
u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
int ret = 0;
if (interruptibility & GUEST_INTR_STATE_STI)
ret |= KVM_X86_SHADOW_INT_STI;
if (interruptibility & GUEST_INTR_STATE_MOV_SS)
ret |= KVM_X86_SHADOW_INT_MOV_SS;
return ret & mask;
}
static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
{
u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
u32 interruptibility = interruptibility_old;
interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
if (mask & KVM_X86_SHADOW_INT_MOV_SS)
interruptibility |= GUEST_INTR_STATE_MOV_SS;
else if (mask & KVM_X86_SHADOW_INT_STI)
interruptibility |= GUEST_INTR_STATE_STI;
if ((interruptibility != interruptibility_old))
vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
}
static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
{
unsigned long rip;
rip = kvm_rip_read(vcpu);
rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
kvm_rip_write(vcpu, rip);
/* skipping an emulated instruction also counts */
vmx_set_interrupt_shadow(vcpu, 0);
}
/*
* KVM wants to inject page-faults which it got to the guest. This function
* checks whether in a nested guest, we need to inject them to L1 or L2.
* This function assumes it is called with the exit reason in vmcs02 being
* a #PF exception (this is the only case in which KVM injects a #PF when L2
* is running).
*/
static int nested_pf_handled(struct kvm_vcpu *vcpu)
{
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
/* TODO: also check PFEC_MATCH/MASK, not just EB.PF. */
if (!(vmcs12->exception_bitmap & (1u << PF_VECTOR)))
return 0;
nested_vmx_vmexit(vcpu);
return 1;
}
static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
bool has_error_code, u32 error_code,
bool reinject)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 intr_info = nr | INTR_INFO_VALID_MASK;
if (nr == PF_VECTOR && is_guest_mode(vcpu) &&
!vmx->nested.nested_run_pending && nested_pf_handled(vcpu))
return;
if (has_error_code) {
vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
intr_info |= INTR_INFO_DELIVER_CODE_MASK;
}
if (vmx->rmode.vm86_active) {
int inc_eip = 0;
if (kvm_exception_is_soft(nr))
inc_eip = vcpu->arch.event_exit_inst_len;
if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return;
}
if (kvm_exception_is_soft(nr)) {
vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
vmx->vcpu.arch.event_exit_inst_len);
intr_info |= INTR_TYPE_SOFT_EXCEPTION;
} else
intr_info |= INTR_TYPE_HARD_EXCEPTION;
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
}
static bool vmx_rdtscp_supported(void)
{
return cpu_has_vmx_rdtscp();
}
static bool vmx_invpcid_supported(void)
{
return cpu_has_vmx_invpcid() && enable_ept;
}
/*
* Swap MSR entry in host/guest MSR entry array.
*/
static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
{
struct shared_msr_entry tmp;
tmp = vmx->guest_msrs[to];
vmx->guest_msrs[to] = vmx->guest_msrs[from];
vmx->guest_msrs[from] = tmp;
}
static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu)
{
unsigned long *msr_bitmap;
if (irqchip_in_kernel(vcpu->kvm) && apic_x2apic_mode(vcpu->arch.apic)) {
if (is_long_mode(vcpu))
msr_bitmap = vmx_msr_bitmap_longmode_x2apic;
else
msr_bitmap = vmx_msr_bitmap_legacy_x2apic;
} else {
if (is_long_mode(vcpu))
msr_bitmap = vmx_msr_bitmap_longmode;
else
msr_bitmap = vmx_msr_bitmap_legacy;
}
vmcs_write64(MSR_BITMAP, __pa(msr_bitmap));
}
/*
* Set up the vmcs to automatically save and restore system
* msrs. Don't touch the 64-bit msrs if the guest is in legacy
* mode, as fiddling with msrs is very expensive.
*/
static void setup_msrs(struct vcpu_vmx *vmx)
{
int save_nmsrs, index;
save_nmsrs = 0;
#ifdef CONFIG_X86_64
if (is_long_mode(&vmx->vcpu)) {
index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
if (index >= 0)
move_msr_up(vmx, index, save_nmsrs++);
index = __find_msr_index(vmx, MSR_LSTAR);
if (index >= 0)
move_msr_up(vmx, index, save_nmsrs++);
index = __find_msr_index(vmx, MSR_CSTAR);
if (index >= 0)
move_msr_up(vmx, index, save_nmsrs++);
index = __find_msr_index(vmx, MSR_TSC_AUX);
if (index >= 0 && vmx->rdtscp_enabled)
move_msr_up(vmx, index, save_nmsrs++);
/*
* MSR_STAR is only needed on long mode guests, and only
* if efer.sce is enabled.
*/
index = __find_msr_index(vmx, MSR_STAR);
if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
move_msr_up(vmx, index, save_nmsrs++);
}
#endif
index = __find_msr_index(vmx, MSR_EFER);
if (index >= 0 && update_transition_efer(vmx, index))
move_msr_up(vmx, index, save_nmsrs++);
vmx->save_nmsrs = save_nmsrs;
if (cpu_has_vmx_msr_bitmap())
vmx_set_msr_bitmap(&vmx->vcpu);
}
/*
* reads and returns guest's timestamp counter "register"
* guest_tsc = host_tsc + tsc_offset -- 21.3
*/
static u64 guest_read_tsc(void)
{
u64 host_tsc, tsc_offset;
rdtscll(host_tsc);
tsc_offset = vmcs_read64(TSC_OFFSET);
return host_tsc + tsc_offset;
}
/*
* Like guest_read_tsc, but always returns L1's notion of the timestamp
* counter, even if a nested guest (L2) is currently running.
*/
u64 vmx_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
{
u64 tsc_offset;
tsc_offset = is_guest_mode(vcpu) ?
to_vmx(vcpu)->nested.vmcs01_tsc_offset :
vmcs_read64(TSC_OFFSET);
return host_tsc + tsc_offset;
}
/*
* Engage any workarounds for mis-matched TSC rates. Currently limited to
* software catchup for faster rates on slower CPUs.
*/
static void vmx_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
{
if (!scale)
return;
if (user_tsc_khz > tsc_khz) {
vcpu->arch.tsc_catchup = 1;
vcpu->arch.tsc_always_catchup = 1;
} else
WARN(1, "user requested TSC rate below hardware speed\n");
}
static u64 vmx_read_tsc_offset(struct kvm_vcpu *vcpu)
{
return vmcs_read64(TSC_OFFSET);
}
/*
* writes 'offset' into guest's timestamp counter offset register
*/
static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
{
if (is_guest_mode(vcpu)) {
/*
* We're here if L1 chose not to trap WRMSR to TSC. According
* to the spec, this should set L1's TSC; The offset that L1
* set for L2 remains unchanged, and still needs to be added
* to the newly set TSC to get L2's TSC.
*/
struct vmcs12 *vmcs12;
to_vmx(vcpu)->nested.vmcs01_tsc_offset = offset;
/* recalculate vmcs02.TSC_OFFSET: */
vmcs12 = get_vmcs12(vcpu);
vmcs_write64(TSC_OFFSET, offset +
(nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
vmcs12->tsc_offset : 0));
} else {
trace_kvm_write_tsc_offset(vcpu->vcpu_id,
vmcs_read64(TSC_OFFSET), offset);
vmcs_write64(TSC_OFFSET, offset);
}
}
static void vmx_adjust_tsc_offset(struct kvm_vcpu *vcpu, s64 adjustment, bool host)
{
u64 offset = vmcs_read64(TSC_OFFSET);
vmcs_write64(TSC_OFFSET, offset + adjustment);
if (is_guest_mode(vcpu)) {
/* Even when running L2, the adjustment needs to apply to L1 */
to_vmx(vcpu)->nested.vmcs01_tsc_offset += adjustment;
} else
trace_kvm_write_tsc_offset(vcpu->vcpu_id, offset,
offset + adjustment);
}
static u64 vmx_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
{
return target_tsc - native_read_tsc();
}
static bool guest_cpuid_has_vmx(struct kvm_vcpu *vcpu)
{
struct kvm_cpuid_entry2 *best = kvm_find_cpuid_entry(vcpu, 1, 0);
return best && (best->ecx & (1 << (X86_FEATURE_VMX & 31)));
}
/*
* nested_vmx_allowed() checks whether a guest should be allowed to use VMX
* instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
* all guests if the "nested" module option is off, and can also be disabled
* for a single guest by disabling its VMX cpuid bit.
*/
static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
{
return nested && guest_cpuid_has_vmx(vcpu);
}
/*
* nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
* returned for the various VMX controls MSRs when nested VMX is enabled.
* The same values should also be used to verify that vmcs12 control fields are
* valid during nested entry from L1 to L2.
* Each of these control msrs has a low and high 32-bit half: A low bit is on
* if the corresponding bit in the (32-bit) control field *must* be on, and a
* bit in the high half is on if the corresponding bit in the control field
* may be on. See also vmx_control_verify().
* TODO: allow these variables to be modified (downgraded) by module options
* or other means.
*/
static u32 nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high;
static u32 nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high;
static u32 nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high;
static u32 nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high;
static u32 nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high;
static u32 nested_vmx_misc_low, nested_vmx_misc_high;
static u32 nested_vmx_ept_caps;
static __init void nested_vmx_setup_ctls_msrs(void)
{
/*
* Note that as a general rule, the high half of the MSRs (bits in
* the control fields which may be 1) should be initialized by the
* intersection of the underlying hardware's MSR (i.e., features which
* can be supported) and the list of features we want to expose -
* because they are known to be properly supported in our code.
* Also, usually, the low half of the MSRs (bits which must be 1) can
* be set to 0, meaning that L1 may turn off any of these bits. The
* reason is that if one of these bits is necessary, it will appear
* in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
* fields of vmcs01 and vmcs02, will turn these bits off - and
* nested_vmx_exit_handled() will not pass related exits to L1.
* These rules have exceptions below.
*/
/* pin-based controls */
rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high);
/*
* According to the Intel spec, if bit 55 of VMX_BASIC is off (as it is
* in our case), bits 1, 2 and 4 (i.e., 0x16) must be 1 in this MSR.
*/
nested_vmx_pinbased_ctls_low |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
nested_vmx_pinbased_ctls_high &= PIN_BASED_EXT_INTR_MASK |
PIN_BASED_NMI_EXITING | PIN_BASED_VIRTUAL_NMIS |
PIN_BASED_VMX_PREEMPTION_TIMER;
nested_vmx_pinbased_ctls_high |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
/*
* Exit controls
* If bit 55 of VMX_BASIC is off, bits 0-8 and 10, 11, 13, 14, 16 and
* 17 must be 1.
*/
nested_vmx_exit_ctls_low = VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
/* Note that guest use of VM_EXIT_ACK_INTR_ON_EXIT is not supported. */
#ifdef CONFIG_X86_64
nested_vmx_exit_ctls_high = VM_EXIT_HOST_ADDR_SPACE_SIZE;
#else
nested_vmx_exit_ctls_high = 0;
#endif
nested_vmx_exit_ctls_high |= (VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
VM_EXIT_LOAD_IA32_EFER);
/* entry controls */
rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high);
/* If bit 55 of VMX_BASIC is off, bits 0-8 and 12 must be 1. */
nested_vmx_entry_ctls_low = VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
nested_vmx_entry_ctls_high &=
VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_IA32E_MODE;
nested_vmx_entry_ctls_high |= (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR |
VM_ENTRY_LOAD_IA32_EFER);
/* cpu-based controls */
rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high);
nested_vmx_procbased_ctls_low = 0;
nested_vmx_procbased_ctls_high &=
CPU_BASED_VIRTUAL_INTR_PENDING | CPU_BASED_USE_TSC_OFFSETING |
CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_CR3_STORE_EXITING |
#ifdef CONFIG_X86_64
CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
#endif
CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_EXITING |
CPU_BASED_RDPMC_EXITING | CPU_BASED_RDTSC_EXITING |
CPU_BASED_PAUSE_EXITING |
CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
/*
* We can allow some features even when not supported by the
* hardware. For example, L1 can specify an MSR bitmap - and we
* can use it to avoid exits to L1 - even when L0 runs L2
* without MSR bitmaps.
*/
nested_vmx_procbased_ctls_high |= CPU_BASED_USE_MSR_BITMAPS;
/* secondary cpu-based controls */
rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high);
nested_vmx_secondary_ctls_low = 0;
nested_vmx_secondary_ctls_high &=
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
SECONDARY_EXEC_WBINVD_EXITING;
/* miscellaneous data */
rdmsr(MSR_IA32_VMX_MISC, nested_vmx_misc_low, nested_vmx_misc_high);
nested_vmx_misc_low &= VMX_MISC_PREEMPTION_TIMER_RATE_MASK |
VMX_MISC_SAVE_EFER_LMA;
nested_vmx_misc_high = 0;
}
static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
{
/*
* Bits 0 in high must be 0, and bits 1 in low must be 1.
*/
return ((control & high) | low) == control;
}
static inline u64 vmx_control_msr(u32 low, u32 high)
{
return low | ((u64)high << 32);
}
/*
* If we allow our guest to use VMX instructions (i.e., nested VMX), we should
* also let it use VMX-specific MSRs.
* vmx_get_vmx_msr() and vmx_set_vmx_msr() return 1 when we handled a
* VMX-specific MSR, or 0 when we haven't (and the caller should handle it
* like all other MSRs).
*/
static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
{
if (!nested_vmx_allowed(vcpu) && msr_index >= MSR_IA32_VMX_BASIC &&
msr_index <= MSR_IA32_VMX_TRUE_ENTRY_CTLS) {
/*
* According to the spec, processors which do not support VMX
* should throw a #GP(0) when VMX capability MSRs are read.
*/
kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
return 1;
}
switch (msr_index) {
case MSR_IA32_FEATURE_CONTROL:
if (nested_vmx_allowed(vcpu)) {
*pdata = to_vmx(vcpu)->nested.msr_ia32_feature_control;
break;
}
return 0;
case MSR_IA32_VMX_BASIC:
/*
* This MSR reports some information about VMX support. We
* should return information about the VMX we emulate for the
* guest, and the VMCS structure we give it - not about the
* VMX support of the underlying hardware.
*/
*pdata = VMCS12_REVISION |
((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
(VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
break;
case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
case MSR_IA32_VMX_PINBASED_CTLS:
*pdata = vmx_control_msr(nested_vmx_pinbased_ctls_low,
nested_vmx_pinbased_ctls_high);
break;
case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
case MSR_IA32_VMX_PROCBASED_CTLS:
*pdata = vmx_control_msr(nested_vmx_procbased_ctls_low,
nested_vmx_procbased_ctls_high);
break;
case MSR_IA32_VMX_TRUE_EXIT_CTLS:
case MSR_IA32_VMX_EXIT_CTLS:
*pdata = vmx_control_msr(nested_vmx_exit_ctls_low,
nested_vmx_exit_ctls_high);
break;
case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
case MSR_IA32_VMX_ENTRY_CTLS:
*pdata = vmx_control_msr(nested_vmx_entry_ctls_low,
nested_vmx_entry_ctls_high);
break;
case MSR_IA32_VMX_MISC:
*pdata = vmx_control_msr(nested_vmx_misc_low,
nested_vmx_misc_high);
break;
/*
* These MSRs specify bits which the guest must keep fixed (on or off)
* while L1 is in VMXON mode (in L1's root mode, or running an L2).
* We picked the standard core2 setting.
*/
#define VMXON_CR0_ALWAYSON (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
#define VMXON_CR4_ALWAYSON X86_CR4_VMXE
case MSR_IA32_VMX_CR0_FIXED0:
*pdata = VMXON_CR0_ALWAYSON;
break;
case MSR_IA32_VMX_CR0_FIXED1:
*pdata = -1ULL;
break;
case MSR_IA32_VMX_CR4_FIXED0:
*pdata = VMXON_CR4_ALWAYSON;
break;
case MSR_IA32_VMX_CR4_FIXED1:
*pdata = -1ULL;
break;
case MSR_IA32_VMX_VMCS_ENUM:
*pdata = 0x1f;
break;
case MSR_IA32_VMX_PROCBASED_CTLS2:
*pdata = vmx_control_msr(nested_vmx_secondary_ctls_low,
nested_vmx_secondary_ctls_high);
break;
case MSR_IA32_VMX_EPT_VPID_CAP:
/* Currently, no nested ept or nested vpid */
*pdata = 0;
break;
default:
return 0;
}
return 1;
}
static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
u32 msr_index = msr_info->index;
u64 data = msr_info->data;
bool host_initialized = msr_info->host_initiated;
if (!nested_vmx_allowed(vcpu))
return 0;
if (msr_index == MSR_IA32_FEATURE_CONTROL) {
if (!host_initialized &&
to_vmx(vcpu)->nested.msr_ia32_feature_control
& FEATURE_CONTROL_LOCKED)
return 0;
to_vmx(vcpu)->nested.msr_ia32_feature_control = data;
return 1;
}
/*
* No need to treat VMX capability MSRs specially: If we don't handle
* them, handle_wrmsr will #GP(0), which is correct (they are readonly)
*/
return 0;
}
/*
* Reads an msr value (of 'msr_index') into 'pdata'.
* Returns 0 on success, non-0 otherwise.
* Assumes vcpu_load() was already called.
*/
static int vmx_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
{
u64 data;
struct shared_msr_entry *msr;
if (!pdata) {
printk(KERN_ERR "BUG: get_msr called with NULL pdata\n");
return -EINVAL;
}
switch (msr_index) {
#ifdef CONFIG_X86_64
case MSR_FS_BASE:
data = vmcs_readl(GUEST_FS_BASE);
break;
case MSR_GS_BASE:
data = vmcs_readl(GUEST_GS_BASE);
break;
case MSR_KERNEL_GS_BASE:
vmx_load_host_state(to_vmx(vcpu));
data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
break;
#endif
case MSR_EFER:
return kvm_get_msr_common(vcpu, msr_index, pdata);
case MSR_IA32_TSC:
data = guest_read_tsc();
break;
case MSR_IA32_SYSENTER_CS:
data = vmcs_read32(GUEST_SYSENTER_CS);
break;
case MSR_IA32_SYSENTER_EIP:
data = vmcs_readl(GUEST_SYSENTER_EIP);
break;
case MSR_IA32_SYSENTER_ESP:
data = vmcs_readl(GUEST_SYSENTER_ESP);
break;
case MSR_TSC_AUX:
if (!to_vmx(vcpu)->rdtscp_enabled)
return 1;
/* Otherwise falls through */
default:
if (vmx_get_vmx_msr(vcpu, msr_index, pdata))
return 0;
msr = find_msr_entry(to_vmx(vcpu), msr_index);
if (msr) {
data = msr->data;
break;
}
return kvm_get_msr_common(vcpu, msr_index, pdata);
}
*pdata = data;
return 0;
}
/*
* Writes msr value into into the appropriate "register".
* Returns 0 on success, non-0 otherwise.
* Assumes vcpu_load() was already called.
*/
static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct shared_msr_entry *msr;
int ret = 0;
u32 msr_index = msr_info->index;
u64 data = msr_info->data;
switch (msr_index) {
case MSR_EFER:
ret = kvm_set_msr_common(vcpu, msr_info);
break;
#ifdef CONFIG_X86_64
case MSR_FS_BASE:
vmx_segment_cache_clear(vmx);
vmcs_writel(GUEST_FS_BASE, data);
break;
case MSR_GS_BASE:
vmx_segment_cache_clear(vmx);
vmcs_writel(GUEST_GS_BASE, data);
break;
case MSR_KERNEL_GS_BASE:
vmx_load_host_state(vmx);
vmx->msr_guest_kernel_gs_base = data;
break;
#endif
case MSR_IA32_SYSENTER_CS:
vmcs_write32(GUEST_SYSENTER_CS, data);
break;
case MSR_IA32_SYSENTER_EIP:
vmcs_writel(GUEST_SYSENTER_EIP, data);
break;
case MSR_IA32_SYSENTER_ESP:
vmcs_writel(GUEST_SYSENTER_ESP, data);
break;
case MSR_IA32_TSC:
kvm_write_tsc(vcpu, msr_info);
break;
case MSR_IA32_CR_PAT:
if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
vmcs_write64(GUEST_IA32_PAT, data);
vcpu->arch.pat = data;
break;
}
ret = kvm_set_msr_common(vcpu, msr_info);
break;
case MSR_IA32_TSC_ADJUST:
ret = kvm_set_msr_common(vcpu, msr_info);
break;
case MSR_TSC_AUX:
if (!vmx->rdtscp_enabled)
return 1;
/* Check reserved bit, higher 32 bits should be zero */
if ((data >> 32) != 0)
return 1;
/* Otherwise falls through */
default:
if (vmx_set_vmx_msr(vcpu, msr_info))
break;
msr = find_msr_entry(vmx, msr_index);
if (msr) {
msr->data = data;
if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
preempt_disable();
kvm_set_shared_msr(msr->index, msr->data,
msr->mask);
preempt_enable();
}
break;
}
ret = kvm_set_msr_common(vcpu, msr_info);
}
return ret;
}
static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
{
__set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
switch (reg) {
case VCPU_REGS_RSP:
vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
break;
case VCPU_REGS_RIP:
vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
break;
case VCPU_EXREG_PDPTR:
if (enable_ept)
ept_save_pdptrs(vcpu);
break;
default:
break;
}
}
static __init int cpu_has_kvm_support(void)
{
return cpu_has_vmx();
}
static __init int vmx_disabled_by_bios(void)
{
u64 msr;
rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
if (msr & FEATURE_CONTROL_LOCKED) {
/* launched w/ TXT and VMX disabled */
if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
&& tboot_enabled())
return 1;
/* launched w/o TXT and VMX only enabled w/ TXT */
if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
&& (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
&& !tboot_enabled()) {
printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
"activate TXT before enabling KVM\n");
return 1;
}
/* launched w/o TXT and VMX disabled */
if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
&& !tboot_enabled())
return 1;
}
return 0;
}
static void kvm_cpu_vmxon(u64 addr)
{
asm volatile (ASM_VMX_VMXON_RAX
: : "a"(&addr), "m"(addr)
: "memory", "cc");
}
static int hardware_enable(void *garbage)
{
int cpu = raw_smp_processor_id();
u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
u64 old, test_bits;
if (read_cr4() & X86_CR4_VMXE)
return -EBUSY;
INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
/*
* Now we can enable the vmclear operation in kdump
* since the loaded_vmcss_on_cpu list on this cpu
* has been initialized.
*
* Though the cpu is not in VMX operation now, there
* is no problem to enable the vmclear operation
* for the loaded_vmcss_on_cpu list is empty!
*/
crash_enable_local_vmclear(cpu);
rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
test_bits = FEATURE_CONTROL_LOCKED;
test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
if (tboot_enabled())
test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
if ((old & test_bits) != test_bits) {
/* enable and lock */
wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
}
write_cr4(read_cr4() | X86_CR4_VMXE); /* FIXME: not cpu hotplug safe */
if (vmm_exclusive) {
kvm_cpu_vmxon(phys_addr);
ept_sync_global();
}
native_store_gdt(&__get_cpu_var(host_gdt));
return 0;
}
static void vmclear_local_loaded_vmcss(void)
{
int cpu = raw_smp_processor_id();
struct loaded_vmcs *v, *n;
list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
loaded_vmcss_on_cpu_link)
__loaded_vmcs_clear(v);
}
/* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
* tricks.
*/
static void kvm_cpu_vmxoff(void)
{
asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
}
static void hardware_disable(void *garbage)
{
if (vmm_exclusive) {
vmclear_local_loaded_vmcss();
kvm_cpu_vmxoff();
}
write_cr4(read_cr4() & ~X86_CR4_VMXE);
}
static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
u32 msr, u32 *result)
{
u32 vmx_msr_low, vmx_msr_high;
u32 ctl = ctl_min | ctl_opt;
rdmsr(msr, vmx_msr_low, vmx_msr_high);
ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
/* Ensure minimum (required) set of control bits are supported. */
if (ctl_min & ~ctl)
return -EIO;
*result = ctl;
return 0;
}
static __init bool allow_1_setting(u32 msr, u32 ctl)
{
u32 vmx_msr_low, vmx_msr_high;
rdmsr(msr, vmx_msr_low, vmx_msr_high);
return vmx_msr_high & ctl;
}
static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
{
u32 vmx_msr_low, vmx_msr_high;
u32 min, opt, min2, opt2;
u32 _pin_based_exec_control = 0;
u32 _cpu_based_exec_control = 0;
u32 _cpu_based_2nd_exec_control = 0;
u32 _vmexit_control = 0;
u32 _vmentry_control = 0;
min = CPU_BASED_HLT_EXITING |
#ifdef CONFIG_X86_64
CPU_BASED_CR8_LOAD_EXITING |
CPU_BASED_CR8_STORE_EXITING |
#endif
CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_CR3_STORE_EXITING |
CPU_BASED_USE_IO_BITMAPS |
CPU_BASED_MOV_DR_EXITING |
CPU_BASED_USE_TSC_OFFSETING |
CPU_BASED_MWAIT_EXITING |
CPU_BASED_MONITOR_EXITING |
CPU_BASED_INVLPG_EXITING |
CPU_BASED_RDPMC_EXITING;
opt = CPU_BASED_TPR_SHADOW |
CPU_BASED_USE_MSR_BITMAPS |
CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
&_cpu_based_exec_control) < 0)
return -EIO;
#ifdef CONFIG_X86_64
if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
_cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
~CPU_BASED_CR8_STORE_EXITING;
#endif
if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
min2 = 0;
opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
SECONDARY_EXEC_WBINVD_EXITING |
SECONDARY_EXEC_ENABLE_VPID |
SECONDARY_EXEC_ENABLE_EPT |
SECONDARY_EXEC_UNRESTRICTED_GUEST |
SECONDARY_EXEC_PAUSE_LOOP_EXITING |
SECONDARY_EXEC_RDTSCP |
SECONDARY_EXEC_ENABLE_INVPCID |
SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
SECONDARY_EXEC_SHADOW_VMCS;
if (adjust_vmx_controls(min2, opt2,
MSR_IA32_VMX_PROCBASED_CTLS2,
&_cpu_based_2nd_exec_control) < 0)
return -EIO;
}
#ifndef CONFIG_X86_64
if (!(_cpu_based_2nd_exec_control &
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
_cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
#endif
if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
_cpu_based_2nd_exec_control &= ~(
SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
/* CR3 accesses and invlpg don't need to cause VM Exits when EPT
enabled */
_cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_CR3_STORE_EXITING |
CPU_BASED_INVLPG_EXITING);
rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
vmx_capability.ept, vmx_capability.vpid);
}
min = 0;
#ifdef CONFIG_X86_64
min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
#endif
opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
VM_EXIT_ACK_INTR_ON_EXIT;
if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
&_vmexit_control) < 0)
return -EIO;
min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR;
if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
&_pin_based_exec_control) < 0)
return -EIO;
if (!(_cpu_based_2nd_exec_control &
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) ||
!(_vmexit_control & VM_EXIT_ACK_INTR_ON_EXIT))
_pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
min = 0;
opt = VM_ENTRY_LOAD_IA32_PAT;
if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
&_vmentry_control) < 0)
return -EIO;
rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
/* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
return -EIO;
#ifdef CONFIG_X86_64
/* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
if (vmx_msr_high & (1u<<16))
return -EIO;
#endif
/* Require Write-Back (WB) memory type for VMCS accesses. */
if (((vmx_msr_high >> 18) & 15) != 6)
return -EIO;
vmcs_conf->size = vmx_msr_high & 0x1fff;
vmcs_conf->order = get_order(vmcs_config.size);
vmcs_conf->revision_id = vmx_msr_low;
vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
vmcs_conf->vmexit_ctrl = _vmexit_control;
vmcs_conf->vmentry_ctrl = _vmentry_control;
cpu_has_load_ia32_efer =
allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
VM_ENTRY_LOAD_IA32_EFER)
&& allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
VM_EXIT_LOAD_IA32_EFER);
cpu_has_load_perf_global_ctrl =
allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
&& allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
/*
* Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
* but due to arrata below it can't be used. Workaround is to use
* msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
*
* VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
*
* AAK155 (model 26)
* AAP115 (model 30)
* AAT100 (model 37)
* BC86,AAY89,BD102 (model 44)
* BA97 (model 46)
*
*/
if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
switch (boot_cpu_data.x86_model) {
case 26:
case 30:
case 37:
case 44:
case 46:
cpu_has_load_perf_global_ctrl = false;
printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
"does not work properly. Using workaround\n");
break;
default:
break;
}
}
return 0;
}
static struct vmcs *alloc_vmcs_cpu(int cpu)
{
int node = cpu_to_node(cpu);
struct page *pages;
struct vmcs *vmcs;
pages = alloc_pages_exact_node(node, GFP_KERNEL, vmcs_config.order);
if (!pages)
return NULL;
vmcs = page_address(pages);
memset(vmcs, 0, vmcs_config.size);
vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
return vmcs;
}
static struct vmcs *alloc_vmcs(void)
{
return alloc_vmcs_cpu(raw_smp_processor_id());
}
static void free_vmcs(struct vmcs *vmcs)
{
free_pages((unsigned long)vmcs, vmcs_config.order);
}
/*
* Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
*/
static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
{
if (!loaded_vmcs->vmcs)
return;
loaded_vmcs_clear(loaded_vmcs);
free_vmcs(loaded_vmcs->vmcs);
loaded_vmcs->vmcs = NULL;
}
static void free_kvm_area(void)
{
int cpu;
for_each_possible_cpu(cpu) {
free_vmcs(per_cpu(vmxarea, cpu));
per_cpu(vmxarea, cpu) = NULL;
}
}
static __init int alloc_kvm_area(void)
{
int cpu;
for_each_possible_cpu(cpu) {
struct vmcs *vmcs;
vmcs = alloc_vmcs_cpu(cpu);
if (!vmcs) {
free_kvm_area();
return -ENOMEM;
}
per_cpu(vmxarea, cpu) = vmcs;
}
return 0;
}
static __init int hardware_setup(void)
{
if (setup_vmcs_config(&vmcs_config) < 0)
return -EIO;
if (boot_cpu_has(X86_FEATURE_NX))
kvm_enable_efer_bits(EFER_NX);
if (!cpu_has_vmx_vpid())
enable_vpid = 0;
if (!cpu_has_vmx_shadow_vmcs())
enable_shadow_vmcs = 0;
if (!cpu_has_vmx_ept() ||
!cpu_has_vmx_ept_4levels()) {
enable_ept = 0;
enable_unrestricted_guest = 0;
enable_ept_ad_bits = 0;
}
if (!cpu_has_vmx_ept_ad_bits())
enable_ept_ad_bits = 0;
if (!cpu_has_vmx_unrestricted_guest())
enable_unrestricted_guest = 0;
if (!cpu_has_vmx_flexpriority())
flexpriority_enabled = 0;
if (!cpu_has_vmx_tpr_shadow())
kvm_x86_ops->update_cr8_intercept = NULL;
if (enable_ept && !cpu_has_vmx_ept_2m_page())
kvm_disable_largepages();
if (!cpu_has_vmx_ple())
ple_gap = 0;
if (!cpu_has_vmx_apicv())
enable_apicv = 0;
if (enable_apicv)
kvm_x86_ops->update_cr8_intercept = NULL;
else {
kvm_x86_ops->hwapic_irr_update = NULL;
kvm_x86_ops->deliver_posted_interrupt = NULL;
kvm_x86_ops->sync_pir_to_irr = vmx_sync_pir_to_irr_dummy;
}
if (nested)
nested_vmx_setup_ctls_msrs();
return alloc_kvm_area();
}
static __exit void hardware_unsetup(void)
{
free_kvm_area();
}
static bool emulation_required(struct kvm_vcpu *vcpu)
{
return emulate_invalid_guest_state && !guest_state_valid(vcpu);
}
static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
struct kvm_segment *save)
{
if (!emulate_invalid_guest_state) {
/*
* CS and SS RPL should be equal during guest entry according
* to VMX spec, but in reality it is not always so. Since vcpu
* is in the middle of the transition from real mode to
* protected mode it is safe to assume that RPL 0 is a good
* default value.
*/
if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
save->selector &= ~SELECTOR_RPL_MASK;
save->dpl = save->selector & SELECTOR_RPL_MASK;
save->s = 1;
}
vmx_set_segment(vcpu, save, seg);
}
static void enter_pmode(struct kvm_vcpu *vcpu)
{
unsigned long flags;
struct vcpu_vmx *vmx = to_vmx(vcpu);
/*
* Update real mode segment cache. It may be not up-to-date if sement
* register was written while vcpu was in a guest mode.
*/
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
vmx->rmode.vm86_active = 0;
vmx_segment_cache_clear(vmx);
vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
flags = vmcs_readl(GUEST_RFLAGS);
flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
vmcs_writel(GUEST_RFLAGS, flags);
vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
(vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
update_exception_bitmap(vcpu);
fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
/* CPL is always 0 when CPU enters protected mode */
__set_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
vmx->cpl = 0;
}
static void fix_rmode_seg(int seg, struct kvm_segment *save)
{
const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
struct kvm_segment var = *save;
var.dpl = 0x3;
if (seg == VCPU_SREG_CS)
var.type = 0x3;
if (!emulate_invalid_guest_state) {
var.selector = var.base >> 4;
var.base = var.base & 0xffff0;
var.limit = 0xffff;
var.g = 0;
var.db = 0;
var.present = 1;
var.s = 1;
var.l = 0;
var.unusable = 0;
var.type = 0x3;
var.avl = 0;
if (save->base & 0xf)
printk_once(KERN_WARNING "kvm: segment base is not "
"paragraph aligned when entering "
"protected mode (seg=%d)", seg);
}
vmcs_write16(sf->selector, var.selector);
vmcs_write32(sf->base, var.base);
vmcs_write32(sf->limit, var.limit);
vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
}
static void enter_rmode(struct kvm_vcpu *vcpu)
{
unsigned long flags;
struct vcpu_vmx *vmx = to_vmx(vcpu);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
vmx->rmode.vm86_active = 1;
/*
* Very old userspace does not call KVM_SET_TSS_ADDR before entering
* vcpu. Warn the user that an update is overdue.
*/
if (!vcpu->kvm->arch.tss_addr)
printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
"called before entering vcpu\n");
vmx_segment_cache_clear(vmx);
vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr);
vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
flags = vmcs_readl(GUEST_RFLAGS);
vmx->rmode.save_rflags = flags;
flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
vmcs_writel(GUEST_RFLAGS, flags);
vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
update_exception_bitmap(vcpu);
fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
kvm_mmu_reset_context(vcpu);
}
static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
if (!msr)
return;
/*
* Force kernel_gs_base reloading before EFER changes, as control
* of this msr depends on is_long_mode().
*/
vmx_load_host_state(to_vmx(vcpu));
vcpu->arch.efer = efer;
if (efer & EFER_LMA) {
vmcs_write32(VM_ENTRY_CONTROLS,
vmcs_read32(VM_ENTRY_CONTROLS) |
VM_ENTRY_IA32E_MODE);
msr->data = efer;
} else {
vmcs_write32(VM_ENTRY_CONTROLS,
vmcs_read32(VM_ENTRY_CONTROLS) &
~VM_ENTRY_IA32E_MODE);
msr->data = efer & ~EFER_LME;
}
setup_msrs(vmx);
}
#ifdef CONFIG_X86_64
static void enter_lmode(struct kvm_vcpu *vcpu)
{
u32 guest_tr_ar;
vmx_segment_cache_clear(to_vmx(vcpu));
guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
if ((guest_tr_ar & AR_TYPE_MASK) != AR_TYPE_BUSY_64_TSS) {
pr_debug_ratelimited("%s: tss fixup for long mode. \n",
__func__);
vmcs_write32(GUEST_TR_AR_BYTES,
(guest_tr_ar & ~AR_TYPE_MASK)
| AR_TYPE_BUSY_64_TSS);
}
vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
}
static void exit_lmode(struct kvm_vcpu *vcpu)
{
vmcs_write32(VM_ENTRY_CONTROLS,
vmcs_read32(VM_ENTRY_CONTROLS)
& ~VM_ENTRY_IA32E_MODE);
vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
}
#endif
static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
{
vpid_sync_context(to_vmx(vcpu));
if (enable_ept) {
if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
return;
ept_sync_context(construct_eptp(vcpu->arch.mmu.root_hpa));
}
}
static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
{
ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
}
static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
{
if (enable_ept && is_paging(vcpu))
vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
}
static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
{
ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
}
static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
{
if (!test_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_dirty))
return;
if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
vmcs_write64(GUEST_PDPTR0, vcpu->arch.mmu.pdptrs[0]);
vmcs_write64(GUEST_PDPTR1, vcpu->arch.mmu.pdptrs[1]);
vmcs_write64(GUEST_PDPTR2, vcpu->arch.mmu.pdptrs[2]);
vmcs_write64(GUEST_PDPTR3, vcpu->arch.mmu.pdptrs[3]);
}
}
static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
{
if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
vcpu->arch.mmu.pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
vcpu->arch.mmu.pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
vcpu->arch.mmu.pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
vcpu->arch.mmu.pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
}
__set_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_avail);
__set_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_dirty);
}
static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
unsigned long cr0,
struct kvm_vcpu *vcpu)
{
if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
vmx_decache_cr3(vcpu);
if (!(cr0 & X86_CR0_PG)) {
/* From paging/starting to nonpaging */
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
(CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_CR3_STORE_EXITING));
vcpu->arch.cr0 = cr0;
vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
} else if (!is_paging(vcpu)) {
/* From nonpaging to paging */
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
~(CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_CR3_STORE_EXITING));
vcpu->arch.cr0 = cr0;
vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
}
if (!(cr0 & X86_CR0_WP))
*hw_cr0 &= ~X86_CR0_WP;
}
static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
unsigned long hw_cr0;
hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
if (enable_unrestricted_guest)
hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
else {
hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
enter_pmode(vcpu);
if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
enter_rmode(vcpu);
}
#ifdef CONFIG_X86_64
if (vcpu->arch.efer & EFER_LME) {
if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
enter_lmode(vcpu);
if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
exit_lmode(vcpu);
}
#endif
if (enable_ept)
ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
if (!vcpu->fpu_active)
hw_cr0 |= X86_CR0_TS | X86_CR0_MP;
vmcs_writel(CR0_READ_SHADOW, cr0);
vmcs_writel(GUEST_CR0, hw_cr0);
vcpu->arch.cr0 = cr0;
/* depends on vcpu->arch.cr0 to be set to a new value */
vmx->emulation_required = emulation_required(vcpu);
}
static u64 construct_eptp(unsigned long root_hpa)
{
u64 eptp;
/* TODO write the value reading from MSR */
eptp = VMX_EPT_DEFAULT_MT |
VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
if (enable_ept_ad_bits)
eptp |= VMX_EPT_AD_ENABLE_BIT;
eptp |= (root_hpa & PAGE_MASK);
return eptp;
}
static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
{
unsigned long guest_cr3;
u64 eptp;
guest_cr3 = cr3;
if (enable_ept) {
eptp = construct_eptp(cr3);
vmcs_write64(EPT_POINTER, eptp);
guest_cr3 = is_paging(vcpu) ? kvm_read_cr3(vcpu) :
vcpu->kvm->arch.ept_identity_map_addr;
ept_load_pdptrs(vcpu);
}
vmx_flush_tlb(vcpu);
vmcs_writel(GUEST_CR3, guest_cr3);
}
static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
{
unsigned long hw_cr4 = cr4 | (to_vmx(vcpu)->rmode.vm86_active ?
KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
if (cr4 & X86_CR4_VMXE) {
/*
* To use VMXON (and later other VMX instructions), a guest
* must first be able to turn on cr4.VMXE (see handle_vmon()).
* So basically the check on whether to allow nested VMX
* is here.
*/
if (!nested_vmx_allowed(vcpu))
return 1;
}
if (to_vmx(vcpu)->nested.vmxon &&
((cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON))
return 1;
vcpu->arch.cr4 = cr4;
if (enable_ept) {
if (!is_paging(vcpu)) {
hw_cr4 &= ~X86_CR4_PAE;
hw_cr4 |= X86_CR4_PSE;
/*
* SMEP is disabled if CPU is in non-paging mode in
* hardware. However KVM always uses paging mode to
* emulate guest non-paging mode with TDP.
* To emulate this behavior, SMEP needs to be manually
* disabled when guest switches to non-paging mode.
*/
hw_cr4 &= ~X86_CR4_SMEP;
} else if (!(cr4 & X86_CR4_PAE)) {
hw_cr4 &= ~X86_CR4_PAE;
}
}
vmcs_writel(CR4_READ_SHADOW, cr4);
vmcs_writel(GUEST_CR4, hw_cr4);
return 0;
}
static void vmx_get_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 ar;
if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
*var = vmx->rmode.segs[seg];
if (seg == VCPU_SREG_TR
|| var->selector == vmx_read_guest_seg_selector(vmx, seg))
return;
var->base = vmx_read_guest_seg_base(vmx, seg);
var->selector = vmx_read_guest_seg_selector(vmx, seg);
return;
}
var->base = vmx_read_guest_seg_base(vmx, seg);
var->limit = vmx_read_guest_seg_limit(vmx, seg);
var->selector = vmx_read_guest_seg_selector(vmx, seg);
ar = vmx_read_guest_seg_ar(vmx, seg);
var->unusable = (ar >> 16) & 1;
var->type = ar & 15;
var->s = (ar >> 4) & 1;
var->dpl = (ar >> 5) & 3;
/*
* Some userspaces do not preserve unusable property. Since usable
* segment has to be present according to VMX spec we can use present
* property to amend userspace bug by making unusable segment always
* nonpresent. vmx_segment_access_rights() already marks nonpresent
* segment as unusable.
*/
var->present = !var->unusable;
var->avl = (ar >> 12) & 1;
var->l = (ar >> 13) & 1;
var->db = (ar >> 14) & 1;
var->g = (ar >> 15) & 1;
}
static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
{
struct kvm_segment s;
if (to_vmx(vcpu)->rmode.vm86_active) {
vmx_get_segment(vcpu, &s, seg);
return s.base;
}
return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
}
static int vmx_get_cpl(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (!is_protmode(vcpu))
return 0;
if (!is_long_mode(vcpu)
&& (kvm_get_rflags(vcpu) & X86_EFLAGS_VM)) /* if virtual 8086 */
return 3;
if (!test_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail)) {
__set_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
vmx->cpl = vmx_read_guest_seg_selector(vmx, VCPU_SREG_CS) & 3;
}
return vmx->cpl;
}
static u32 vmx_segment_access_rights(struct kvm_segment *var)
{
u32 ar;
if (var->unusable || !var->present)
ar = 1 << 16;
else {
ar = var->type & 15;
ar |= (var->s & 1) << 4;
ar |= (var->dpl & 3) << 5;
ar |= (var->present & 1) << 7;
ar |= (var->avl & 1) << 12;
ar |= (var->l & 1) << 13;
ar |= (var->db & 1) << 14;
ar |= (var->g & 1) << 15;
}
return ar;
}
static void vmx_set_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
vmx_segment_cache_clear(vmx);
if (seg == VCPU_SREG_CS)
__clear_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
vmx->rmode.segs[seg] = *var;
if (seg == VCPU_SREG_TR)
vmcs_write16(sf->selector, var->selector);
else if (var->s)
fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
goto out;
}
vmcs_writel(sf->base, var->base);
vmcs_write32(sf->limit, var->limit);
vmcs_write16(sf->selector, var->selector);
/*
* Fix the "Accessed" bit in AR field of segment registers for older
* qemu binaries.
* IA32 arch specifies that at the time of processor reset the
* "Accessed" bit in the AR field of segment registers is 1. And qemu
* is setting it to 0 in the userland code. This causes invalid guest
* state vmexit when "unrestricted guest" mode is turned on.
* Fix for this setup issue in cpu_reset is being pushed in the qemu
* tree. Newer qemu binaries with that qemu fix would not need this
* kvm hack.
*/
if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
var->type |= 0x1; /* Accessed */
vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
out:
vmx->emulation_required |= emulation_required(vcpu);
}
static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
{
u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
*db = (ar >> 14) & 1;
*l = (ar >> 13) & 1;
}
static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
{
dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
dt->address = vmcs_readl(GUEST_IDTR_BASE);
}
static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
{
vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
vmcs_writel(GUEST_IDTR_BASE, dt->address);
}
static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
{
dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
dt->address = vmcs_readl(GUEST_GDTR_BASE);
}
static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
{
vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
vmcs_writel(GUEST_GDTR_BASE, dt->address);
}
static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
{
struct kvm_segment var;
u32 ar;
vmx_get_segment(vcpu, &var, seg);
var.dpl = 0x3;
if (seg == VCPU_SREG_CS)
var.type = 0x3;
ar = vmx_segment_access_rights(&var);
if (var.base != (var.selector << 4))
return false;
if (var.limit != 0xffff)
return false;
if (ar != 0xf3)
return false;
return true;
}
static bool code_segment_valid(struct kvm_vcpu *vcpu)
{
struct kvm_segment cs;
unsigned int cs_rpl;
vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
cs_rpl = cs.selector & SELECTOR_RPL_MASK;
if (cs.unusable)
return false;
if (~cs.type & (AR_TYPE_CODE_MASK|AR_TYPE_ACCESSES_MASK))
return false;
if (!cs.s)
return false;
if (cs.type & AR_TYPE_WRITEABLE_MASK) {
if (cs.dpl > cs_rpl)
return false;
} else {
if (cs.dpl != cs_rpl)
return false;
}
if (!cs.present)
return false;
/* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
return true;
}
static bool stack_segment_valid(struct kvm_vcpu *vcpu)
{
struct kvm_segment ss;
unsigned int ss_rpl;
vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
ss_rpl = ss.selector & SELECTOR_RPL_MASK;
if (ss.unusable)
return true;
if (ss.type != 3 && ss.type != 7)
return false;
if (!ss.s)
return false;
if (ss.dpl != ss_rpl) /* DPL != RPL */
return false;
if (!ss.present)
return false;
return true;
}
static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
{
struct kvm_segment var;
unsigned int rpl;
vmx_get_segment(vcpu, &var, seg);
rpl = var.selector & SELECTOR_RPL_MASK;
if (var.unusable)
return true;
if (!var.s)
return false;
if (!var.present)
return false;
if (~var.type & (AR_TYPE_CODE_MASK|AR_TYPE_WRITEABLE_MASK)) {
if (var.dpl < rpl) /* DPL < RPL */
return false;
}
/* TODO: Add other members to kvm_segment_field to allow checking for other access
* rights flags
*/
return true;
}
static bool tr_valid(struct kvm_vcpu *vcpu)
{
struct kvm_segment tr;
vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
if (tr.unusable)
return false;
if (tr.selector & SELECTOR_TI_MASK) /* TI = 1 */
return false;
if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
return false;
if (!tr.present)
return false;
return true;
}
static bool ldtr_valid(struct kvm_vcpu *vcpu)
{
struct kvm_segment ldtr;
vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
if (ldtr.unusable)
return true;
if (ldtr.selector & SELECTOR_TI_MASK) /* TI = 1 */
return false;
if (ldtr.type != 2)
return false;
if (!ldtr.present)
return false;
return true;
}
static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
{
struct kvm_segment cs, ss;
vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
return ((cs.selector & SELECTOR_RPL_MASK) ==
(ss.selector & SELECTOR_RPL_MASK));
}
/*
* Check if guest state is valid. Returns true if valid, false if
* not.
* We assume that registers are always usable
*/
static bool guest_state_valid(struct kvm_vcpu *vcpu)
{
if (enable_unrestricted_guest)
return true;
/* real mode guest state checks */
if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
return false;
if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
return false;
if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
return false;
if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
return false;
if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
return false;
if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
return false;
} else {
/* protected mode guest state checks */
if (!cs_ss_rpl_check(vcpu))
return false;
if (!code_segment_valid(vcpu))
return false;
if (!stack_segment_valid(vcpu))
return false;
if (!data_segment_valid(vcpu, VCPU_SREG_DS))
return false;
if (!data_segment_valid(vcpu, VCPU_SREG_ES))
return false;
if (!data_segment_valid(vcpu, VCPU_SREG_FS))
return false;
if (!data_segment_valid(vcpu, VCPU_SREG_GS))
return false;
if (!tr_valid(vcpu))
return false;
if (!ldtr_valid(vcpu))
return false;
}
/* TODO:
* - Add checks on RIP
* - Add checks on RFLAGS
*/
return true;
}
static int init_rmode_tss(struct kvm *kvm)
{
gfn_t fn;
u16 data = 0;
int r, idx, ret = 0;
idx = srcu_read_lock(&kvm->srcu);
fn = kvm->arch.tss_addr >> PAGE_SHIFT;
r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
if (r < 0)
goto out;
data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
r = kvm_write_guest_page(kvm, fn++, &data,
TSS_IOPB_BASE_OFFSET, sizeof(u16));
if (r < 0)
goto out;
r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
if (r < 0)
goto out;
r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
if (r < 0)
goto out;
data = ~0;
r = kvm_write_guest_page(kvm, fn, &data,
RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
sizeof(u8));
if (r < 0)
goto out;
ret = 1;
out:
srcu_read_unlock(&kvm->srcu, idx);
return ret;
}
static int init_rmode_identity_map(struct kvm *kvm)
{
int i, idx, r, ret;
pfn_t identity_map_pfn;
u32 tmp;
if (!enable_ept)
return 1;
if (unlikely(!kvm->arch.ept_identity_pagetable)) {
printk(KERN_ERR "EPT: identity-mapping pagetable "
"haven't been allocated!\n");
return 0;
}
if (likely(kvm->arch.ept_identity_pagetable_done))
return 1;
ret = 0;
identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
idx = srcu_read_lock(&kvm->srcu);
r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
if (r < 0)
goto out;
/* Set up identity-mapping pagetable for EPT in real mode */
for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
_PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
r = kvm_write_guest_page(kvm, identity_map_pfn,
&tmp, i * sizeof(tmp), sizeof(tmp));
if (r < 0)
goto out;
}
kvm->arch.ept_identity_pagetable_done = true;
ret = 1;
out:
srcu_read_unlock(&kvm->srcu, idx);
return ret;
}
static void seg_setup(int seg)
{
const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
unsigned int ar;
vmcs_write16(sf->selector, 0);
vmcs_writel(sf->base, 0);
vmcs_write32(sf->limit, 0xffff);
ar = 0x93;
if (seg == VCPU_SREG_CS)
ar |= 0x08; /* code segment */
vmcs_write32(sf->ar_bytes, ar);
}
static int alloc_apic_access_page(struct kvm *kvm)
{
struct page *page;
struct kvm_userspace_memory_region kvm_userspace_mem;
int r = 0;
mutex_lock(&kvm->slots_lock);
if (kvm->arch.apic_access_page)
goto out;
kvm_userspace_mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
kvm_userspace_mem.flags = 0;
kvm_userspace_mem.guest_phys_addr = 0xfee00000ULL;
kvm_userspace_mem.memory_size = PAGE_SIZE;
r = __kvm_set_memory_region(kvm, &kvm_userspace_mem);
if (r)
goto out;
page = gfn_to_page(kvm, 0xfee00);
if (is_error_page(page)) {
r = -EFAULT;
goto out;
}
kvm->arch.apic_access_page = page;
out:
mutex_unlock(&kvm->slots_lock);
return r;
}
static int alloc_identity_pagetable(struct kvm *kvm)
{
struct page *page;
struct kvm_userspace_memory_region kvm_userspace_mem;
int r = 0;
mutex_lock(&kvm->slots_lock);
if (kvm->arch.ept_identity_pagetable)
goto out;
kvm_userspace_mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
kvm_userspace_mem.flags = 0;
kvm_userspace_mem.guest_phys_addr =
kvm->arch.ept_identity_map_addr;
kvm_userspace_mem.memory_size = PAGE_SIZE;
r = __kvm_set_memory_region(kvm, &kvm_userspace_mem);
if (r)
goto out;
page = gfn_to_page(kvm, kvm->arch.ept_identity_map_addr >> PAGE_SHIFT);
if (is_error_page(page)) {
r = -EFAULT;
goto out;
}
kvm->arch.ept_identity_pagetable = page;
out:
mutex_unlock(&kvm->slots_lock);
return r;
}
static void allocate_vpid(struct vcpu_vmx *vmx)
{
int vpid;
vmx->vpid = 0;
if (!enable_vpid)
return;
spin_lock(&vmx_vpid_lock);
vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
if (vpid < VMX_NR_VPIDS) {
vmx->vpid = vpid;
__set_bit(vpid, vmx_vpid_bitmap);
}
spin_unlock(&vmx_vpid_lock);
}
static void free_vpid(struct vcpu_vmx *vmx)
{
if (!enable_vpid)
return;
spin_lock(&vmx_vpid_lock);
if (vmx->vpid != 0)
__clear_bit(vmx->vpid, vmx_vpid_bitmap);
spin_unlock(&vmx_vpid_lock);
}
#define MSR_TYPE_R 1
#define MSR_TYPE_W 2
static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
u32 msr, int type)
{
int f = sizeof(unsigned long);
if (!cpu_has_vmx_msr_bitmap())
return;
/*
* See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
* have the write-low and read-high bitmap offsets the wrong way round.
* We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
*/
if (msr <= 0x1fff) {
if (type & MSR_TYPE_R)
/* read-low */
__clear_bit(msr, msr_bitmap + 0x000 / f);
if (type & MSR_TYPE_W)
/* write-low */
__clear_bit(msr, msr_bitmap + 0x800 / f);
} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
msr &= 0x1fff;
if (type & MSR_TYPE_R)
/* read-high */
__clear_bit(msr, msr_bitmap + 0x400 / f);
if (type & MSR_TYPE_W)
/* write-high */
__clear_bit(msr, msr_bitmap + 0xc00 / f);
}
}
static void __vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
u32 msr, int type)
{
int f = sizeof(unsigned long);
if (!cpu_has_vmx_msr_bitmap())
return;
/*
* See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
* have the write-low and read-high bitmap offsets the wrong way round.
* We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
*/
if (msr <= 0x1fff) {
if (type & MSR_TYPE_R)
/* read-low */
__set_bit(msr, msr_bitmap + 0x000 / f);
if (type & MSR_TYPE_W)
/* write-low */
__set_bit(msr, msr_bitmap + 0x800 / f);
} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
msr &= 0x1fff;
if (type & MSR_TYPE_R)
/* read-high */
__set_bit(msr, msr_bitmap + 0x400 / f);
if (type & MSR_TYPE_W)
/* write-high */
__set_bit(msr, msr_bitmap + 0xc00 / f);
}
}
static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only)
{
if (!longmode_only)
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy,
msr, MSR_TYPE_R | MSR_TYPE_W);
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode,
msr, MSR_TYPE_R | MSR_TYPE_W);
}
static void vmx_enable_intercept_msr_read_x2apic(u32 msr)
{
__vmx_enable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
msr, MSR_TYPE_R);
__vmx_enable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
msr, MSR_TYPE_R);
}
static void vmx_disable_intercept_msr_read_x2apic(u32 msr)
{
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
msr, MSR_TYPE_R);
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
msr, MSR_TYPE_R);
}
static void vmx_disable_intercept_msr_write_x2apic(u32 msr)
{
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
msr, MSR_TYPE_W);
__vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
msr, MSR_TYPE_W);
}
static int vmx_vm_has_apicv(struct kvm *kvm)
{
return enable_apicv && irqchip_in_kernel(kvm);
}
/*
* Send interrupt to vcpu via posted interrupt way.
* 1. If target vcpu is running(non-root mode), send posted interrupt
* notification to vcpu and hardware will sync PIR to vIRR atomically.
* 2. If target vcpu isn't running(root mode), kick it to pick up the
* interrupt from PIR in next vmentry.
*/
static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int r;
if (pi_test_and_set_pir(vector, &vmx->pi_desc))
return;
r = pi_test_and_set_on(&vmx->pi_desc);
kvm_make_request(KVM_REQ_EVENT, vcpu);
#ifdef CONFIG_SMP
if (!r && (vcpu->mode == IN_GUEST_MODE))
apic->send_IPI_mask(get_cpu_mask(vcpu->cpu),
POSTED_INTR_VECTOR);
else
#endif
kvm_vcpu_kick(vcpu);
}
static void vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (!pi_test_and_clear_on(&vmx->pi_desc))
return;
kvm_apic_update_irr(vcpu, vmx->pi_desc.pir);
}
static void vmx_sync_pir_to_irr_dummy(struct kvm_vcpu *vcpu)
{
return;
}
/*
* Set up the vmcs's constant host-state fields, i.e., host-state fields that
* will not change in the lifetime of the guest.
* Note that host-state that does change is set elsewhere. E.g., host-state
* that is set differently for each CPU is set in vmx_vcpu_load(), not here.
*/
static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
{
u32 low32, high32;
unsigned long tmpl;
struct desc_ptr dt;
vmcs_writel(HOST_CR0, read_cr0() & ~X86_CR0_TS); /* 22.2.3 */
vmcs_writel(HOST_CR4, read_cr4()); /* 22.2.3, 22.2.5 */
vmcs_writel(HOST_CR3, read_cr3()); /* 22.2.3 FIXME: shadow tables */
vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
#ifdef CONFIG_X86_64
/*
* Load null selectors, so we can avoid reloading them in
* __vmx_load_host_state(), in case userspace uses the null selectors
* too (the expected case).
*/
vmcs_write16(HOST_DS_SELECTOR, 0);
vmcs_write16(HOST_ES_SELECTOR, 0);
#else
vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
#endif
vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
native_store_idt(&dt);
vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
vmx->host_idt_base = dt.address;
vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
rdmsr(MSR_IA32_CR_PAT, low32, high32);
vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
}
}
static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
{
vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
if (enable_ept)
vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
if (is_guest_mode(&vmx->vcpu))
vmx->vcpu.arch.cr4_guest_owned_bits &=
~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
}
static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
{
u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
if (!vmx_vm_has_apicv(vmx->vcpu.kvm))
pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
return pin_based_exec_ctrl;
}
static u32 vmx_exec_control(struct vcpu_vmx *vmx)
{
u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
if (!vm_need_tpr_shadow(vmx->vcpu.kvm)) {
exec_control &= ~CPU_BASED_TPR_SHADOW;
#ifdef CONFIG_X86_64
exec_control |= CPU_BASED_CR8_STORE_EXITING |
CPU_BASED_CR8_LOAD_EXITING;
#endif
}
if (!enable_ept)
exec_control |= CPU_BASED_CR3_STORE_EXITING |
CPU_BASED_CR3_LOAD_EXITING |
CPU_BASED_INVLPG_EXITING;
return exec_control;
}
static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
{
u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
if (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
if (vmx->vpid == 0)
exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
if (!enable_ept) {
exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
enable_unrestricted_guest = 0;
/* Enable INVPCID for non-ept guests may cause performance regression. */
exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
}
if (!enable_unrestricted_guest)
exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
if (!ple_gap)
exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
if (!vmx_vm_has_apicv(vmx->vcpu.kvm))
exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
/* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
(handle_vmptrld).
We can NOT enable shadow_vmcs here because we don't have yet
a current VMCS12
*/
exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
return exec_control;
}
static void ept_set_mmio_spte_mask(void)
{
/*
* EPT Misconfigurations can be generated if the value of bits 2:0
* of an EPT paging-structure entry is 110b (write/execute).
* Also, magic bits (0x3ull << 62) is set to quickly identify mmio
* spte.
*/
kvm_mmu_set_mmio_spte_mask((0x3ull << 62) | 0x6ull);
}
/*
* Sets up the vmcs for emulated real mode.
*/
static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
{
#ifdef CONFIG_X86_64
unsigned long a;
#endif
int i;
/* I/O */
vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
if (enable_shadow_vmcs) {
vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
}
if (cpu_has_vmx_msr_bitmap())
vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy));
vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
/* Control */
vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
if (cpu_has_secondary_exec_ctrls()) {
vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
vmx_secondary_exec_control(vmx));
}
if (vmx_vm_has_apicv(vmx->vcpu.kvm)) {
vmcs_write64(EOI_EXIT_BITMAP0, 0);
vmcs_write64(EOI_EXIT_BITMAP1, 0);
vmcs_write64(EOI_EXIT_BITMAP2, 0);
vmcs_write64(EOI_EXIT_BITMAP3, 0);
vmcs_write16(GUEST_INTR_STATUS, 0);
vmcs_write64(POSTED_INTR_NV, POSTED_INTR_VECTOR);
vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
}
if (ple_gap) {
vmcs_write32(PLE_GAP, ple_gap);
vmcs_write32(PLE_WINDOW, ple_window);
}
vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
vmx_set_constant_host_state(vmx);
#ifdef CONFIG_X86_64
rdmsrl(MSR_FS_BASE, a);
vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
rdmsrl(MSR_GS_BASE, a);
vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
#else
vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
#endif
vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
u32 msr_low, msr_high;
u64 host_pat;
rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high);
host_pat = msr_low | ((u64) msr_high << 32);
/* Write the default value follow host pat */
vmcs_write64(GUEST_IA32_PAT, host_pat);
/* Keep arch.pat sync with GUEST_IA32_PAT */
vmx->vcpu.arch.pat = host_pat;
}
for (i = 0; i < NR_VMX_MSR; ++i) {
u32 index = vmx_msr_index[i];
u32 data_low, data_high;
int j = vmx->nmsrs;
if (rdmsr_safe(index, &data_low, &data_high) < 0)
continue;
if (wrmsr_safe(index, data_low, data_high) < 0)
continue;
vmx->guest_msrs[j].index = i;
vmx->guest_msrs[j].data = 0;
vmx->guest_msrs[j].mask = -1ull;
++vmx->nmsrs;
}
vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
/* 22.2.1, 20.8.1 */
vmcs_write32(VM_ENTRY_CONTROLS, vmcs_config.vmentry_ctrl);
vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
set_cr4_guest_host_mask(vmx);
return 0;
}
static void vmx_vcpu_reset(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u64 msr;
vmx->rmode.vm86_active = 0;
vmx->soft_vnmi_blocked = 0;
vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
kvm_set_cr8(&vmx->vcpu, 0);
msr = 0xfee00000 | MSR_IA32_APICBASE_ENABLE;
if (kvm_vcpu_is_bsp(&vmx->vcpu))
msr |= MSR_IA32_APICBASE_BSP;
kvm_set_apic_base(&vmx->vcpu, msr);
vmx_segment_cache_clear(vmx);
seg_setup(VCPU_SREG_CS);
vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
vmcs_write32(GUEST_CS_BASE, 0xffff0000);
seg_setup(VCPU_SREG_DS);
seg_setup(VCPU_SREG_ES);
seg_setup(VCPU_SREG_FS);
seg_setup(VCPU_SREG_GS);
seg_setup(VCPU_SREG_SS);
vmcs_write16(GUEST_TR_SELECTOR, 0);
vmcs_writel(GUEST_TR_BASE, 0);
vmcs_write32(GUEST_TR_LIMIT, 0xffff);
vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
vmcs_write16(GUEST_LDTR_SELECTOR, 0);
vmcs_writel(GUEST_LDTR_BASE, 0);
vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
vmcs_write32(GUEST_SYSENTER_CS, 0);
vmcs_writel(GUEST_SYSENTER_ESP, 0);
vmcs_writel(GUEST_SYSENTER_EIP, 0);
vmcs_writel(GUEST_RFLAGS, 0x02);
kvm_rip_write(vcpu, 0xfff0);
vmcs_writel(GUEST_GDTR_BASE, 0);
vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
vmcs_writel(GUEST_IDTR_BASE, 0);
vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
vmcs_write32(GUEST_PENDING_DBG_EXCEPTIONS, 0);
/* Special registers */
vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
setup_msrs(vmx);
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
if (cpu_has_vmx_tpr_shadow()) {
vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
if (vm_need_tpr_shadow(vmx->vcpu.kvm))
vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
__pa(vmx->vcpu.arch.apic->regs));
vmcs_write32(TPR_THRESHOLD, 0);
}
if (vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
vmcs_write64(APIC_ACCESS_ADDR,
page_to_phys(vmx->vcpu.kvm->arch.apic_access_page));
if (vmx_vm_has_apicv(vcpu->kvm))
memset(&vmx->pi_desc, 0, sizeof(struct pi_desc));
if (vmx->vpid != 0)
vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
vmx->vcpu.arch.cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
vmx_set_cr0(&vmx->vcpu, kvm_read_cr0(vcpu)); /* enter rmode */
vmx_set_cr4(&vmx->vcpu, 0);
vmx_set_efer(&vmx->vcpu, 0);
vmx_fpu_activate(&vmx->vcpu);
update_exception_bitmap(&vmx->vcpu);
vpid_sync_context(vmx);
}
/*
* In nested virtualization, check if L1 asked to exit on external interrupts.
* For most existing hypervisors, this will always return true.
*/
static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
{
return get_vmcs12(vcpu)->pin_based_vm_exec_control &
PIN_BASED_EXT_INTR_MASK;
}
static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
{
return get_vmcs12(vcpu)->pin_based_vm_exec_control &
PIN_BASED_NMI_EXITING;
}
static int enable_irq_window(struct kvm_vcpu *vcpu)
{
u32 cpu_based_vm_exec_control;
if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
/*
* We get here if vmx_interrupt_allowed() said we can't
* inject to L1 now because L2 must run. The caller will have
* to make L2 exit right after entry, so we can inject to L1
* more promptly.
*/
return -EBUSY;
cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
return 0;
}
static int enable_nmi_window(struct kvm_vcpu *vcpu)
{
u32 cpu_based_vm_exec_control;
if (!cpu_has_virtual_nmis())
return enable_irq_window(vcpu);
if (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI)
return enable_irq_window(vcpu);
cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_NMI_PENDING;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
return 0;
}
static void vmx_inject_irq(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
uint32_t intr;
int irq = vcpu->arch.interrupt.nr;
trace_kvm_inj_virq(irq);
++vcpu->stat.irq_injections;
if (vmx->rmode.vm86_active) {
int inc_eip = 0;
if (vcpu->arch.interrupt.soft)
inc_eip = vcpu->arch.event_exit_inst_len;
if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return;
}
intr = irq | INTR_INFO_VALID_MASK;
if (vcpu->arch.interrupt.soft) {
intr |= INTR_TYPE_SOFT_INTR;
vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
vmx->vcpu.arch.event_exit_inst_len);
} else
intr |= INTR_TYPE_EXT_INTR;
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
}
static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (is_guest_mode(vcpu))
return;
if (!cpu_has_virtual_nmis()) {
/*
* Tracking the NMI-blocked state in software is built upon
* finding the next open IRQ window. This, in turn, depends on
* well-behaving guests: They have to keep IRQs disabled at
* least as long as the NMI handler runs. Otherwise we may
* cause NMI nesting, maybe breaking the guest. But as this is
* highly unlikely, we can live with the residual risk.
*/
vmx->soft_vnmi_blocked = 1;
vmx->vnmi_blocked_time = 0;
}
++vcpu->stat.nmi_injections;
vmx->nmi_known_unmasked = false;
if (vmx->rmode.vm86_active) {
if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return;
}
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
}
static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
{
if (!cpu_has_virtual_nmis())
return to_vmx(vcpu)->soft_vnmi_blocked;
if (to_vmx(vcpu)->nmi_known_unmasked)
return false;
return vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
}
static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (!cpu_has_virtual_nmis()) {
if (vmx->soft_vnmi_blocked != masked) {
vmx->soft_vnmi_blocked = masked;
vmx->vnmi_blocked_time = 0;
}
} else {
vmx->nmi_known_unmasked = !masked;
if (masked)
vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
GUEST_INTR_STATE_NMI);
else
vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
GUEST_INTR_STATE_NMI);
}
}
static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
{
if (is_guest_mode(vcpu)) {
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
if (to_vmx(vcpu)->nested.nested_run_pending)
return 0;
if (nested_exit_on_nmi(vcpu)) {
nested_vmx_vmexit(vcpu);
vmcs12->vm_exit_reason = EXIT_REASON_EXCEPTION_NMI;
vmcs12->vm_exit_intr_info = NMI_VECTOR |
INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK;
/*
* The NMI-triggered VM exit counts as injection:
* clear this one and block further NMIs.
*/
vcpu->arch.nmi_pending = 0;
vmx_set_nmi_mask(vcpu, true);
return 0;
}
}
if (!cpu_has_virtual_nmis() && to_vmx(vcpu)->soft_vnmi_blocked)
return 0;
return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
(GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
| GUEST_INTR_STATE_NMI));
}
static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
{
if (is_guest_mode(vcpu)) {
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
if (to_vmx(vcpu)->nested.nested_run_pending)
return 0;
if (nested_exit_on_intr(vcpu)) {
nested_vmx_vmexit(vcpu);
vmcs12->vm_exit_reason =
EXIT_REASON_EXTERNAL_INTERRUPT;
vmcs12->vm_exit_intr_info = 0;
/*
* fall through to normal code, but now in L1, not L2
*/
}
}
return (vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
!(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
}
static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
{
int ret;
struct kvm_userspace_memory_region tss_mem = {
.slot = TSS_PRIVATE_MEMSLOT,
.guest_phys_addr = addr,
.memory_size = PAGE_SIZE * 3,
.flags = 0,
};
ret = kvm_set_memory_region(kvm, &tss_mem);
if (ret)
return ret;
kvm->arch.tss_addr = addr;
if (!init_rmode_tss(kvm))
return -ENOMEM;
return 0;
}
static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
{
switch (vec) {
case BP_VECTOR:
/*
* Update instruction length as we may reinject the exception
* from user space while in guest debugging mode.
*/
to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
return false;
/* fall through */
case DB_VECTOR:
if (vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
return false;
/* fall through */
case DE_VECTOR:
case OF_VECTOR:
case BR_VECTOR:
case UD_VECTOR:
case DF_VECTOR:
case SS_VECTOR:
case GP_VECTOR:
case MF_VECTOR:
return true;
break;
}
return false;
}
static int handle_rmode_exception(struct kvm_vcpu *vcpu,
int vec, u32 err_code)
{
/*
* Instruction with address size override prefix opcode 0x67
* Cause the #SS fault with 0 error code in VM86 mode.
*/
if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
if (vcpu->arch.halt_request) {
vcpu->arch.halt_request = 0;
return kvm_emulate_halt(vcpu);
}
return 1;
}
return 0;
}
/*
* Forward all other exceptions that are valid in real mode.
* FIXME: Breaks guest debugging in real mode, needs to be fixed with
* the required debugging infrastructure rework.
*/
kvm_queue_exception(vcpu, vec);
return 1;
}
/*
* Trigger machine check on the host. We assume all the MSRs are already set up
* by the CPU and that we still run on the same CPU as the MCE occurred on.
* We pass a fake environment to the machine check handler because we want
* the guest to be always treated like user space, no matter what context
* it used internally.
*/
static void kvm_machine_check(void)
{
#if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
struct pt_regs regs = {
.cs = 3, /* Fake ring 3 no matter what the guest ran on */
.flags = X86_EFLAGS_IF,
};
do_machine_check(®s, 0);
#endif
}
static int handle_machine_check(struct kvm_vcpu *vcpu)
{
/* already handled by vcpu_run */
return 1;
}
static int handle_exception(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct kvm_run *kvm_run = vcpu->run;
u32 intr_info, ex_no, error_code;
unsigned long cr2, rip, dr6;
u32 vect_info;
enum emulation_result er;
vect_info = vmx->idt_vectoring_info;
intr_info = vmx->exit_intr_info;
if (is_machine_check(intr_info))
return handle_machine_check(vcpu);
if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR)
return 1; /* already handled by vmx_vcpu_run() */
if (is_no_device(intr_info)) {
vmx_fpu_activate(vcpu);
return 1;
}
if (is_invalid_opcode(intr_info)) {
er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
if (er != EMULATE_DONE)
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
error_code = 0;
if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
/*
* The #PF with PFEC.RSVD = 1 indicates the guest is accessing
* MMIO, it is better to report an internal error.
* See the comments in vmx_handle_exit.
*/
if ((vect_info & VECTORING_INFO_VALID_MASK) &&
!(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
vcpu->run->internal.ndata = 2;
vcpu->run->internal.data[0] = vect_info;
vcpu->run->internal.data[1] = intr_info;
return 0;
}
if (is_page_fault(intr_info)) {
/* EPT won't cause page fault directly */
BUG_ON(enable_ept);
cr2 = vmcs_readl(EXIT_QUALIFICATION);
trace_kvm_page_fault(cr2, error_code);
if (kvm_event_needs_reinjection(vcpu))
kvm_mmu_unprotect_page_virt(vcpu, cr2);
return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
}
ex_no = intr_info & INTR_INFO_VECTOR_MASK;
if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
return handle_rmode_exception(vcpu, ex_no, error_code);
switch (ex_no) {
case DB_VECTOR:
dr6 = vmcs_readl(EXIT_QUALIFICATION);
if (!(vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
vcpu->arch.dr6 = dr6 | DR6_FIXED_1;
kvm_queue_exception(vcpu, DB_VECTOR);
return 1;
}
kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
/* fall through */
case BP_VECTOR:
/*
* Update instruction length as we may reinject #BP from
* user space while in guest debugging mode. Reading it for
* #DB as well causes no harm, it is not used in that case.
*/
vmx->vcpu.arch.event_exit_inst_len =
vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
kvm_run->exit_reason = KVM_EXIT_DEBUG;
rip = kvm_rip_read(vcpu);
kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
kvm_run->debug.arch.exception = ex_no;
break;
default:
kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
kvm_run->ex.exception = ex_no;
kvm_run->ex.error_code = error_code;
break;
}
return 0;
}
static int handle_external_interrupt(struct kvm_vcpu *vcpu)
{
++vcpu->stat.irq_exits;
return 1;
}
static int handle_triple_fault(struct kvm_vcpu *vcpu)
{
vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
return 0;
}
static int handle_io(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification;
int size, in, string;
unsigned port;
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
string = (exit_qualification & 16) != 0;
in = (exit_qualification & 8) != 0;
++vcpu->stat.io_exits;
if (string || in)
return emulate_instruction(vcpu, 0) == EMULATE_DONE;
port = exit_qualification >> 16;
size = (exit_qualification & 7) + 1;
skip_emulated_instruction(vcpu);
return kvm_fast_pio_out(vcpu, size, port);
}
static void
vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
{
/*
* Patch in the VMCALL instruction:
*/
hypercall[0] = 0x0f;
hypercall[1] = 0x01;
hypercall[2] = 0xc1;
}
/* called to set cr0 as appropriate for a mov-to-cr0 exit. */
static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
{
if (is_guest_mode(vcpu)) {
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
unsigned long orig_val = val;
/*
* We get here when L2 changed cr0 in a way that did not change
* any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
* but did change L0 shadowed bits. So we first calculate the
* effective cr0 value that L1 would like to write into the
* hardware. It consists of the L2-owned bits from the new
* value combined with the L1-owned bits from L1's guest_cr0.
*/
val = (val & ~vmcs12->cr0_guest_host_mask) |
(vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
/* TODO: will have to take unrestricted guest mode into
* account */
if ((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON)
return 1;
if (kvm_set_cr0(vcpu, val))
return 1;
vmcs_writel(CR0_READ_SHADOW, orig_val);
return 0;
} else {
if (to_vmx(vcpu)->nested.vmxon &&
((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON))
return 1;
return kvm_set_cr0(vcpu, val);
}
}
static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
{
if (is_guest_mode(vcpu)) {
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
unsigned long orig_val = val;
/* analogously to handle_set_cr0 */
val = (val & ~vmcs12->cr4_guest_host_mask) |
(vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
if (kvm_set_cr4(vcpu, val))
return 1;
vmcs_writel(CR4_READ_SHADOW, orig_val);
return 0;
} else
return kvm_set_cr4(vcpu, val);
}
/* called to set cr0 as approriate for clts instruction exit. */
static void handle_clts(struct kvm_vcpu *vcpu)
{
if (is_guest_mode(vcpu)) {
/*
* We get here when L2 did CLTS, and L1 didn't shadow CR0.TS
* but we did (!fpu_active). We need to keep GUEST_CR0.TS on,
* just pretend it's off (also in arch.cr0 for fpu_activate).
*/
vmcs_writel(CR0_READ_SHADOW,
vmcs_readl(CR0_READ_SHADOW) & ~X86_CR0_TS);
vcpu->arch.cr0 &= ~X86_CR0_TS;
} else
vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
}
static int handle_cr(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification, val;
int cr;
int reg;
int err;
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
cr = exit_qualification & 15;
reg = (exit_qualification >> 8) & 15;
switch ((exit_qualification >> 4) & 3) {
case 0: /* mov to cr */
val = kvm_register_read(vcpu, reg);
trace_kvm_cr_write(cr, val);
switch (cr) {
case 0:
err = handle_set_cr0(vcpu, val);
kvm_complete_insn_gp(vcpu, err);
return 1;
case 3:
err = kvm_set_cr3(vcpu, val);
kvm_complete_insn_gp(vcpu, err);
return 1;
case 4:
err = handle_set_cr4(vcpu, val);
kvm_complete_insn_gp(vcpu, err);
return 1;
case 8: {
u8 cr8_prev = kvm_get_cr8(vcpu);
u8 cr8 = kvm_register_read(vcpu, reg);
err = kvm_set_cr8(vcpu, cr8);
kvm_complete_insn_gp(vcpu, err);
if (irqchip_in_kernel(vcpu->kvm))
return 1;
if (cr8_prev <= cr8)
return 1;
vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
return 0;
}
}
break;
case 2: /* clts */
handle_clts(vcpu);
trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
skip_emulated_instruction(vcpu);
vmx_fpu_activate(vcpu);
return 1;
case 1: /*mov from cr*/
switch (cr) {
case 3:
val = kvm_read_cr3(vcpu);
kvm_register_write(vcpu, reg, val);
trace_kvm_cr_read(cr, val);
skip_emulated_instruction(vcpu);
return 1;
case 8:
val = kvm_get_cr8(vcpu);
kvm_register_write(vcpu, reg, val);
trace_kvm_cr_read(cr, val);
skip_emulated_instruction(vcpu);
return 1;
}
break;
case 3: /* lmsw */
val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
kvm_lmsw(vcpu, val);
skip_emulated_instruction(vcpu);
return 1;
default:
break;
}
vcpu->run->exit_reason = 0;
vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
(int)(exit_qualification >> 4) & 3, cr);
return 0;
}
static int handle_dr(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification;
int dr, reg;
/* Do not handle if the CPL > 0, will trigger GP on re-entry */
if (!kvm_require_cpl(vcpu, 0))
return 1;
dr = vmcs_readl(GUEST_DR7);
if (dr & DR7_GD) {
/*
* As the vm-exit takes precedence over the debug trap, we
* need to emulate the latter, either for the host or the
* guest debugging itself.
*/
if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
vcpu->run->debug.arch.dr7 = dr;
vcpu->run->debug.arch.pc =
vmcs_readl(GUEST_CS_BASE) +
vmcs_readl(GUEST_RIP);
vcpu->run->debug.arch.exception = DB_VECTOR;
vcpu->run->exit_reason = KVM_EXIT_DEBUG;
return 0;
} else {
vcpu->arch.dr7 &= ~DR7_GD;
vcpu->arch.dr6 |= DR6_BD;
vmcs_writel(GUEST_DR7, vcpu->arch.dr7);
kvm_queue_exception(vcpu, DB_VECTOR);
return 1;
}
}
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
reg = DEBUG_REG_ACCESS_REG(exit_qualification);
if (exit_qualification & TYPE_MOV_FROM_DR) {
unsigned long val;
if (!kvm_get_dr(vcpu, dr, &val))
kvm_register_write(vcpu, reg, val);
} else
kvm_set_dr(vcpu, dr, vcpu->arch.regs[reg]);
skip_emulated_instruction(vcpu);
return 1;
}
static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
{
vmcs_writel(GUEST_DR7, val);
}
static int handle_cpuid(struct kvm_vcpu *vcpu)
{
kvm_emulate_cpuid(vcpu);
return 1;
}
static int handle_rdmsr(struct kvm_vcpu *vcpu)
{
u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
u64 data;
if (vmx_get_msr(vcpu, ecx, &data)) {
trace_kvm_msr_read_ex(ecx);
kvm_inject_gp(vcpu, 0);
return 1;
}
trace_kvm_msr_read(ecx, data);
/* FIXME: handling of bits 32:63 of rax, rdx */
vcpu->arch.regs[VCPU_REGS_RAX] = data & -1u;
vcpu->arch.regs[VCPU_REGS_RDX] = (data >> 32) & -1u;
skip_emulated_instruction(vcpu);
return 1;
}
static int handle_wrmsr(struct kvm_vcpu *vcpu)
{
struct msr_data msr;
u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
| ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
msr.data = data;
msr.index = ecx;
msr.host_initiated = false;
if (vmx_set_msr(vcpu, &msr) != 0) {
trace_kvm_msr_write_ex(ecx, data);
kvm_inject_gp(vcpu, 0);
return 1;
}
trace_kvm_msr_write(ecx, data);
skip_emulated_instruction(vcpu);
return 1;
}
static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
{
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 1;
}
static int handle_interrupt_window(struct kvm_vcpu *vcpu)
{
u32 cpu_based_vm_exec_control;
/* clear pending irq */
cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
kvm_make_request(KVM_REQ_EVENT, vcpu);
++vcpu->stat.irq_window_exits;
/*
* If the user space waits to inject interrupts, exit as soon as
* possible
*/
if (!irqchip_in_kernel(vcpu->kvm) &&
vcpu->run->request_interrupt_window &&
!kvm_cpu_has_interrupt(vcpu)) {
vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
return 0;
}
return 1;
}
static int handle_halt(struct kvm_vcpu *vcpu)
{
skip_emulated_instruction(vcpu);
return kvm_emulate_halt(vcpu);
}
static int handle_vmcall(struct kvm_vcpu *vcpu)
{
skip_emulated_instruction(vcpu);
kvm_emulate_hypercall(vcpu);
return 1;
}
static int handle_invd(struct kvm_vcpu *vcpu)
{
return emulate_instruction(vcpu, 0) == EMULATE_DONE;
}
static int handle_invlpg(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
kvm_mmu_invlpg(vcpu, exit_qualification);
skip_emulated_instruction(vcpu);
return 1;
}
static int handle_rdpmc(struct kvm_vcpu *vcpu)
{
int err;
err = kvm_rdpmc(vcpu);
kvm_complete_insn_gp(vcpu, err);
return 1;
}
static int handle_wbinvd(struct kvm_vcpu *vcpu)
{
skip_emulated_instruction(vcpu);
kvm_emulate_wbinvd(vcpu);
return 1;
}
static int handle_xsetbv(struct kvm_vcpu *vcpu)
{
u64 new_bv = kvm_read_edx_eax(vcpu);
u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
if (kvm_set_xcr(vcpu, index, new_bv) == 0)
skip_emulated_instruction(vcpu);
return 1;
}
static int handle_apic_access(struct kvm_vcpu *vcpu)
{
if (likely(fasteoi)) {
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
int access_type, offset;
access_type = exit_qualification & APIC_ACCESS_TYPE;
offset = exit_qualification & APIC_ACCESS_OFFSET;
/*
* Sane guest uses MOV to write EOI, with written value
* not cared. So make a short-circuit here by avoiding
* heavy instruction emulation.
*/
if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
(offset == APIC_EOI)) {
kvm_lapic_set_eoi(vcpu);
skip_emulated_instruction(vcpu);
return 1;
}
}
return emulate_instruction(vcpu, 0) == EMULATE_DONE;
}
static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
int vector = exit_qualification & 0xff;
/* EOI-induced VM exit is trap-like and thus no need to adjust IP */
kvm_apic_set_eoi_accelerated(vcpu, vector);
return 1;
}
static int handle_apic_write(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 offset = exit_qualification & 0xfff;
/* APIC-write VM exit is trap-like and thus no need to adjust IP */
kvm_apic_write_nodecode(vcpu, offset);
return 1;
}
static int handle_task_switch(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
unsigned long exit_qualification;
bool has_error_code = false;
u32 error_code = 0;
u16 tss_selector;
int reason, type, idt_v, idt_index;
idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
reason = (u32)exit_qualification >> 30;
if (reason == TASK_SWITCH_GATE && idt_v) {
switch (type) {
case INTR_TYPE_NMI_INTR:
vcpu->arch.nmi_injected = false;
vmx_set_nmi_mask(vcpu, true);
break;
case INTR_TYPE_EXT_INTR:
case INTR_TYPE_SOFT_INTR:
kvm_clear_interrupt_queue(vcpu);
break;
case INTR_TYPE_HARD_EXCEPTION:
if (vmx->idt_vectoring_info &
VECTORING_INFO_DELIVER_CODE_MASK) {
has_error_code = true;
error_code =
vmcs_read32(IDT_VECTORING_ERROR_CODE);
}
/* fall through */
case INTR_TYPE_SOFT_EXCEPTION:
kvm_clear_exception_queue(vcpu);
break;
default:
break;
}
}
tss_selector = exit_qualification;
if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
type != INTR_TYPE_EXT_INTR &&
type != INTR_TYPE_NMI_INTR))
skip_emulated_instruction(vcpu);
if (kvm_task_switch(vcpu, tss_selector,
type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
has_error_code, error_code) == EMULATE_FAIL) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
vcpu->run->internal.ndata = 0;
return 0;
}
/* clear all local breakpoint enable flags */
vmcs_writel(GUEST_DR7, vmcs_readl(GUEST_DR7) & ~55);
/*
* TODO: What about debug traps on tss switch?
* Are we supposed to inject them and update dr6?
*/
return 1;
}
static int handle_ept_violation(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification;
gpa_t gpa;
u32 error_code;
int gla_validity;
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
gla_validity = (exit_qualification >> 7) & 0x3;
if (gla_validity != 0x3 && gla_validity != 0x1 && gla_validity != 0) {
printk(KERN_ERR "EPT: Handling EPT violation failed!\n");
printk(KERN_ERR "EPT: GPA: 0x%lx, GVA: 0x%lx\n",
(long unsigned int)vmcs_read64(GUEST_PHYSICAL_ADDRESS),
vmcs_readl(GUEST_LINEAR_ADDRESS));
printk(KERN_ERR "EPT: Exit qualification is 0x%lx\n",
(long unsigned int)exit_qualification);
vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_VIOLATION;
return 0;
}
gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
trace_kvm_page_fault(gpa, exit_qualification);
/* It is a write fault? */
error_code = exit_qualification & (1U << 1);
/* It is a fetch fault? */
error_code |= (exit_qualification & (1U << 2)) << 2;
/* ept page table is present? */
error_code |= (exit_qualification >> 3) & 0x1;
vcpu->arch.exit_qualification = exit_qualification;
return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
}
static u64 ept_rsvd_mask(u64 spte, int level)
{
int i;
u64 mask = 0;
for (i = 51; i > boot_cpu_data.x86_phys_bits; i--)
mask |= (1ULL << i);
if (level > 2)
/* bits 7:3 reserved */
mask |= 0xf8;
else if (level == 2) {
if (spte & (1ULL << 7))
/* 2MB ref, bits 20:12 reserved */
mask |= 0x1ff000;
else
/* bits 6:3 reserved */
mask |= 0x78;
}
return mask;
}
static void ept_misconfig_inspect_spte(struct kvm_vcpu *vcpu, u64 spte,
int level)
{
printk(KERN_ERR "%s: spte 0x%llx level %d\n", __func__, spte, level);
/* 010b (write-only) */
WARN_ON((spte & 0x7) == 0x2);
/* 110b (write/execute) */
WARN_ON((spte & 0x7) == 0x6);
/* 100b (execute-only) and value not supported by logical processor */
if (!cpu_has_vmx_ept_execute_only())
WARN_ON((spte & 0x7) == 0x4);
/* not 000b */
if ((spte & 0x7)) {
u64 rsvd_bits = spte & ept_rsvd_mask(spte, level);
if (rsvd_bits != 0) {
printk(KERN_ERR "%s: rsvd_bits = 0x%llx\n",
__func__, rsvd_bits);
WARN_ON(1);
}
if (level == 1 || (level == 2 && (spte & (1ULL << 7)))) {
u64 ept_mem_type = (spte & 0x38) >> 3;
if (ept_mem_type == 2 || ept_mem_type == 3 ||
ept_mem_type == 7) {
printk(KERN_ERR "%s: ept_mem_type=0x%llx\n",
__func__, ept_mem_type);
WARN_ON(1);
}
}
}
}
static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
{
u64 sptes[4];
int nr_sptes, i, ret;
gpa_t gpa;
gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
ret = handle_mmio_page_fault_common(vcpu, gpa, true);
if (likely(ret == RET_MMIO_PF_EMULATE))
return x86_emulate_instruction(vcpu, gpa, 0, NULL, 0) ==
EMULATE_DONE;
if (unlikely(ret == RET_MMIO_PF_INVALID))
return kvm_mmu_page_fault(vcpu, gpa, 0, NULL, 0);
if (unlikely(ret == RET_MMIO_PF_RETRY))
return 1;
/* It is the real ept misconfig */
printk(KERN_ERR "EPT: Misconfiguration.\n");
printk(KERN_ERR "EPT: GPA: 0x%llx\n", gpa);
nr_sptes = kvm_mmu_get_spte_hierarchy(vcpu, gpa, sptes);
for (i = PT64_ROOT_LEVEL; i > PT64_ROOT_LEVEL - nr_sptes; --i)
ept_misconfig_inspect_spte(vcpu, sptes[i-1], i);
vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
return 0;
}
static int handle_nmi_window(struct kvm_vcpu *vcpu)
{
u32 cpu_based_vm_exec_control;
/* clear pending NMI */
cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
++vcpu->stat.nmi_window_exits;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 1;
}
static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
enum emulation_result err = EMULATE_DONE;
int ret = 1;
u32 cpu_exec_ctrl;
bool intr_window_requested;
unsigned count = 130;
cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
while (!guest_state_valid(vcpu) && count-- != 0) {
if (intr_window_requested && vmx_interrupt_allowed(vcpu))
return handle_interrupt_window(&vmx->vcpu);
if (test_bit(KVM_REQ_EVENT, &vcpu->requests))
return 1;
err = emulate_instruction(vcpu, EMULTYPE_NO_REEXECUTE);
if (err == EMULATE_USER_EXIT) {
ret = 0;
goto out;
}
if (err != EMULATE_DONE) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
vcpu->run->internal.ndata = 0;
return 0;
}
if (vcpu->arch.halt_request) {
vcpu->arch.halt_request = 0;
ret = kvm_emulate_halt(vcpu);
goto out;
}
if (signal_pending(current))
goto out;
if (need_resched())
schedule();
}
vmx->emulation_required = emulation_required(vcpu);
out:
return ret;
}
/*
* Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
* exiting, so only get here on cpu with PAUSE-Loop-Exiting.
*/
static int handle_pause(struct kvm_vcpu *vcpu)
{
skip_emulated_instruction(vcpu);
kvm_vcpu_on_spin(vcpu);
return 1;
}
static int handle_invalid_op(struct kvm_vcpu *vcpu)
{
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
/*
* To run an L2 guest, we need a vmcs02 based on the L1-specified vmcs12.
* We could reuse a single VMCS for all the L2 guests, but we also want the
* option to allocate a separate vmcs02 for each separate loaded vmcs12 - this
* allows keeping them loaded on the processor, and in the future will allow
* optimizations where prepare_vmcs02 doesn't need to set all the fields on
* every entry if they never change.
* So we keep, in vmx->nested.vmcs02_pool, a cache of size VMCS02_POOL_SIZE
* (>=0) with a vmcs02 for each recently loaded vmcs12s, most recent first.
*
* The following functions allocate and free a vmcs02 in this pool.
*/
/* Get a VMCS from the pool to use as vmcs02 for the current vmcs12. */
static struct loaded_vmcs *nested_get_current_vmcs02(struct vcpu_vmx *vmx)
{
struct vmcs02_list *item;
list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
if (item->vmptr == vmx->nested.current_vmptr) {
list_move(&item->list, &vmx->nested.vmcs02_pool);
return &item->vmcs02;
}
if (vmx->nested.vmcs02_num >= max(VMCS02_POOL_SIZE, 1)) {
/* Recycle the least recently used VMCS. */
item = list_entry(vmx->nested.vmcs02_pool.prev,
struct vmcs02_list, list);
item->vmptr = vmx->nested.current_vmptr;
list_move(&item->list, &vmx->nested.vmcs02_pool);
return &item->vmcs02;
}
/* Create a new VMCS */
item = kmalloc(sizeof(struct vmcs02_list), GFP_KERNEL);
if (!item)
return NULL;
item->vmcs02.vmcs = alloc_vmcs();
if (!item->vmcs02.vmcs) {
kfree(item);
return NULL;
}
loaded_vmcs_init(&item->vmcs02);
item->vmptr = vmx->nested.current_vmptr;
list_add(&(item->list), &(vmx->nested.vmcs02_pool));
vmx->nested.vmcs02_num++;
return &item->vmcs02;
}
/* Free and remove from pool a vmcs02 saved for a vmcs12 (if there is one) */
static void nested_free_vmcs02(struct vcpu_vmx *vmx, gpa_t vmptr)
{
struct vmcs02_list *item;
list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
if (item->vmptr == vmptr) {
free_loaded_vmcs(&item->vmcs02);
list_del(&item->list);
kfree(item);
vmx->nested.vmcs02_num--;
return;
}
}
/*
* Free all VMCSs saved for this vcpu, except the one pointed by
* vmx->loaded_vmcs. These include the VMCSs in vmcs02_pool (except the one
* currently used, if running L2), and vmcs01 when running L2.
*/
static void nested_free_all_saved_vmcss(struct vcpu_vmx *vmx)
{
struct vmcs02_list *item, *n;
list_for_each_entry_safe(item, n, &vmx->nested.vmcs02_pool, list) {
if (vmx->loaded_vmcs != &item->vmcs02)
free_loaded_vmcs(&item->vmcs02);
list_del(&item->list);
kfree(item);
}
vmx->nested.vmcs02_num = 0;
if (vmx->loaded_vmcs != &vmx->vmcs01)
free_loaded_vmcs(&vmx->vmcs01);
}
/*
* The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
* set the success or error code of an emulated VMX instruction, as specified
* by Vol 2B, VMX Instruction Reference, "Conventions".
*/
static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
{
vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
& ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
}
static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
{
vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
& ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
X86_EFLAGS_SF | X86_EFLAGS_OF))
| X86_EFLAGS_CF);
}
static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
u32 vm_instruction_error)
{
if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
/*
* failValid writes the error number to the current VMCS, which
* can't be done there isn't a current VMCS.
*/
nested_vmx_failInvalid(vcpu);
return;
}
vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
& ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
X86_EFLAGS_SF | X86_EFLAGS_OF))
| X86_EFLAGS_ZF);
get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
/*
* We don't need to force a shadow sync because
* VM_INSTRUCTION_ERROR is not shadowed
*/
}
/*
* Emulate the VMXON instruction.
* Currently, we just remember that VMX is active, and do not save or even
* inspect the argument to VMXON (the so-called "VMXON pointer") because we
* do not currently need to store anything in that guest-allocated memory
* region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
* argument is different from the VMXON pointer (which the spec says they do).
*/
static int handle_vmon(struct kvm_vcpu *vcpu)
{
struct kvm_segment cs;
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct vmcs *shadow_vmcs;
const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
| FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
/* The Intel VMX Instruction Reference lists a bunch of bits that
* are prerequisite to running VMXON, most notably cr4.VMXE must be
* set to 1 (see vmx_set_cr4() for when we allow the guest to set this).
* Otherwise, we should fail with #UD. We test these now:
*/
if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE) ||
!kvm_read_cr0_bits(vcpu, X86_CR0_PE) ||
(vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
if (is_long_mode(vcpu) && !cs.l) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
if (vmx_get_cpl(vcpu)) {
kvm_inject_gp(vcpu, 0);
return 1;
}
if (vmx->nested.vmxon) {
nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
skip_emulated_instruction(vcpu);
return 1;
}
if ((vmx->nested.msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
!= VMXON_NEEDED_FEATURES) {
kvm_inject_gp(vcpu, 0);
return 1;
}
if (enable_shadow_vmcs) {
shadow_vmcs = alloc_vmcs();
if (!shadow_vmcs)
return -ENOMEM;
/* mark vmcs as shadow */
shadow_vmcs->revision_id |= (1u << 31);
/* init shadow vmcs */
vmcs_clear(shadow_vmcs);
vmx->nested.current_shadow_vmcs = shadow_vmcs;
}
INIT_LIST_HEAD(&(vmx->nested.vmcs02_pool));
vmx->nested.vmcs02_num = 0;
vmx->nested.vmxon = true;
skip_emulated_instruction(vcpu);
nested_vmx_succeed(vcpu);
return 1;
}
/*
* Intel's VMX Instruction Reference specifies a common set of prerequisites
* for running VMX instructions (except VMXON, whose prerequisites are
* slightly different). It also specifies what exception to inject otherwise.
*/
static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
{
struct kvm_segment cs;
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (!vmx->nested.vmxon) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 0;
}
vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
if ((vmx_get_rflags(vcpu) & X86_EFLAGS_VM) ||
(is_long_mode(vcpu) && !cs.l)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 0;
}
if (vmx_get_cpl(vcpu)) {
kvm_inject_gp(vcpu, 0);
return 0;
}
return 1;
}
static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
{
u32 exec_control;
if (enable_shadow_vmcs) {
if (vmx->nested.current_vmcs12 != NULL) {
/* copy to memory all shadowed fields in case
they were modified */
copy_shadow_to_vmcs12(vmx);
vmx->nested.sync_shadow_vmcs = false;
exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
vmcs_write64(VMCS_LINK_POINTER, -1ull);
}
}
kunmap(vmx->nested.current_vmcs12_page);
nested_release_page(vmx->nested.current_vmcs12_page);
}
/*
* Free whatever needs to be freed from vmx->nested when L1 goes down, or
* just stops using VMX.
*/
static void free_nested(struct vcpu_vmx *vmx)
{
if (!vmx->nested.vmxon)
return;
vmx->nested.vmxon = false;
if (vmx->nested.current_vmptr != -1ull) {
nested_release_vmcs12(vmx);
vmx->nested.current_vmptr = -1ull;
vmx->nested.current_vmcs12 = NULL;
}
if (enable_shadow_vmcs)
free_vmcs(vmx->nested.current_shadow_vmcs);
/* Unpin physical memory we referred to in current vmcs02 */
if (vmx->nested.apic_access_page) {
nested_release_page(vmx->nested.apic_access_page);
vmx->nested.apic_access_page = 0;
}
nested_free_all_saved_vmcss(vmx);
}
/* Emulate the VMXOFF instruction */
static int handle_vmoff(struct kvm_vcpu *vcpu)
{
if (!nested_vmx_check_permission(vcpu))
return 1;
free_nested(to_vmx(vcpu));
skip_emulated_instruction(vcpu);
nested_vmx_succeed(vcpu);
return 1;
}
/*
* Decode the memory-address operand of a vmx instruction, as recorded on an
* exit caused by such an instruction (run by a guest hypervisor).
* On success, returns 0. When the operand is invalid, returns 1 and throws
* #UD or #GP.
*/
static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
unsigned long exit_qualification,
u32 vmx_instruction_info, gva_t *ret)
{
/*
* According to Vol. 3B, "Information for VM Exits Due to Instruction
* Execution", on an exit, vmx_instruction_info holds most of the
* addressing components of the operand. Only the displacement part
* is put in exit_qualification (see 3B, "Basic VM-Exit Information").
* For how an actual address is calculated from all these components,
* refer to Vol. 1, "Operand Addressing".
*/
int scaling = vmx_instruction_info & 3;
int addr_size = (vmx_instruction_info >> 7) & 7;
bool is_reg = vmx_instruction_info & (1u << 10);
int seg_reg = (vmx_instruction_info >> 15) & 7;
int index_reg = (vmx_instruction_info >> 18) & 0xf;
bool index_is_valid = !(vmx_instruction_info & (1u << 22));
int base_reg = (vmx_instruction_info >> 23) & 0xf;
bool base_is_valid = !(vmx_instruction_info & (1u << 27));
if (is_reg) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
/* Addr = segment_base + offset */
/* offset = base + [index * scale] + displacement */
*ret = vmx_get_segment_base(vcpu, seg_reg);
if (base_is_valid)
*ret += kvm_register_read(vcpu, base_reg);
if (index_is_valid)
*ret += kvm_register_read(vcpu, index_reg)<<scaling;
*ret += exit_qualification; /* holds the displacement */
if (addr_size == 1) /* 32 bit */
*ret &= 0xffffffff;
/*
* TODO: throw #GP (and return 1) in various cases that the VM*
* instructions require it - e.g., offset beyond segment limit,
* unusable or unreadable/unwritable segment, non-canonical 64-bit
* address, and so on. Currently these are not checked.
*/
return 0;
}
/* Emulate the VMCLEAR instruction */
static int handle_vmclear(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
gva_t gva;
gpa_t vmptr;
struct vmcs12 *vmcs12;
struct page *page;
struct x86_exception e;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
vmcs_read32(VMX_INSTRUCTION_INFO), &gva))
return 1;
if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr,
sizeof(vmptr), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
if (!IS_ALIGNED(vmptr, PAGE_SIZE)) {
nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
skip_emulated_instruction(vcpu);
return 1;
}
if (vmptr == vmx->nested.current_vmptr) {
nested_release_vmcs12(vmx);
vmx->nested.current_vmptr = -1ull;
vmx->nested.current_vmcs12 = NULL;
}
page = nested_get_page(vcpu, vmptr);
if (page == NULL) {
/*
* For accurate processor emulation, VMCLEAR beyond available
* physical memory should do nothing at all. However, it is
* possible that a nested vmx bug, not a guest hypervisor bug,
* resulted in this case, so let's shut down before doing any
* more damage:
*/
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return 1;
}
vmcs12 = kmap(page);
vmcs12->launch_state = 0;
kunmap(page);
nested_release_page(page);
nested_free_vmcs02(vmx, vmptr);
skip_emulated_instruction(vcpu);
nested_vmx_succeed(vcpu);
return 1;
}
static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
/* Emulate the VMLAUNCH instruction */
static int handle_vmlaunch(struct kvm_vcpu *vcpu)
{
return nested_vmx_run(vcpu, true);
}
/* Emulate the VMRESUME instruction */
static int handle_vmresume(struct kvm_vcpu *vcpu)
{
return nested_vmx_run(vcpu, false);
}
enum vmcs_field_type {
VMCS_FIELD_TYPE_U16 = 0,
VMCS_FIELD_TYPE_U64 = 1,
VMCS_FIELD_TYPE_U32 = 2,
VMCS_FIELD_TYPE_NATURAL_WIDTH = 3
};
static inline int vmcs_field_type(unsigned long field)
{
if (0x1 & field) /* the *_HIGH fields are all 32 bit */
return VMCS_FIELD_TYPE_U32;
return (field >> 13) & 0x3 ;
}
static inline int vmcs_field_readonly(unsigned long field)
{
return (((field >> 10) & 0x3) == 1);
}
/*
* Read a vmcs12 field. Since these can have varying lengths and we return
* one type, we chose the biggest type (u64) and zero-extend the return value
* to that size. Note that the caller, handle_vmread, might need to use only
* some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
* 64-bit fields are to be returned).
*/
static inline bool vmcs12_read_any(struct kvm_vcpu *vcpu,
unsigned long field, u64 *ret)
{
short offset = vmcs_field_to_offset(field);
char *p;
if (offset < 0)
return 0;
p = ((char *)(get_vmcs12(vcpu))) + offset;
switch (vmcs_field_type(field)) {
case VMCS_FIELD_TYPE_NATURAL_WIDTH:
*ret = *((natural_width *)p);
return 1;
case VMCS_FIELD_TYPE_U16:
*ret = *((u16 *)p);
return 1;
case VMCS_FIELD_TYPE_U32:
*ret = *((u32 *)p);
return 1;
case VMCS_FIELD_TYPE_U64:
*ret = *((u64 *)p);
return 1;
default:
return 0; /* can never happen. */
}
}
static inline bool vmcs12_write_any(struct kvm_vcpu *vcpu,
unsigned long field, u64 field_value){
short offset = vmcs_field_to_offset(field);
char *p = ((char *) get_vmcs12(vcpu)) + offset;
if (offset < 0)
return false;
switch (vmcs_field_type(field)) {
case VMCS_FIELD_TYPE_U16:
*(u16 *)p = field_value;
return true;
case VMCS_FIELD_TYPE_U32:
*(u32 *)p = field_value;
return true;
case VMCS_FIELD_TYPE_U64:
*(u64 *)p = field_value;
return true;
case VMCS_FIELD_TYPE_NATURAL_WIDTH:
*(natural_width *)p = field_value;
return true;
default:
return false; /* can never happen. */
}
}
static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
{
int i;
unsigned long field;
u64 field_value;
struct vmcs *shadow_vmcs = vmx->nested.current_shadow_vmcs;
const unsigned long *fields = shadow_read_write_fields;
const int num_fields = max_shadow_read_write_fields;
vmcs_load(shadow_vmcs);
for (i = 0; i < num_fields; i++) {
field = fields[i];
switch (vmcs_field_type(field)) {
case VMCS_FIELD_TYPE_U16:
field_value = vmcs_read16(field);
break;
case VMCS_FIELD_TYPE_U32:
field_value = vmcs_read32(field);
break;
case VMCS_FIELD_TYPE_U64:
field_value = vmcs_read64(field);
break;
case VMCS_FIELD_TYPE_NATURAL_WIDTH:
field_value = vmcs_readl(field);
break;
}
vmcs12_write_any(&vmx->vcpu, field, field_value);
}
vmcs_clear(shadow_vmcs);
vmcs_load(vmx->loaded_vmcs->vmcs);
}
static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
{
const unsigned long *fields[] = {
shadow_read_write_fields,
shadow_read_only_fields
};
const int max_fields[] = {
max_shadow_read_write_fields,
max_shadow_read_only_fields
};
int i, q;
unsigned long field;
u64 field_value = 0;
struct vmcs *shadow_vmcs = vmx->nested.current_shadow_vmcs;
vmcs_load(shadow_vmcs);
for (q = 0; q < ARRAY_SIZE(fields); q++) {
for (i = 0; i < max_fields[q]; i++) {
field = fields[q][i];
vmcs12_read_any(&vmx->vcpu, field, &field_value);
switch (vmcs_field_type(field)) {
case VMCS_FIELD_TYPE_U16:
vmcs_write16(field, (u16)field_value);
break;
case VMCS_FIELD_TYPE_U32:
vmcs_write32(field, (u32)field_value);
break;
case VMCS_FIELD_TYPE_U64:
vmcs_write64(field, (u64)field_value);
break;
case VMCS_FIELD_TYPE_NATURAL_WIDTH:
vmcs_writel(field, (long)field_value);
break;
}
}
}
vmcs_clear(shadow_vmcs);
vmcs_load(vmx->loaded_vmcs->vmcs);
}
/*
* VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
* used before) all generate the same failure when it is missing.
*/
static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (vmx->nested.current_vmptr == -1ull) {
nested_vmx_failInvalid(vcpu);
skip_emulated_instruction(vcpu);
return 0;
}
return 1;
}
static int handle_vmread(struct kvm_vcpu *vcpu)
{
unsigned long field;
u64 field_value;
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
gva_t gva = 0;
if (!nested_vmx_check_permission(vcpu) ||
!nested_vmx_check_vmcs12(vcpu))
return 1;
/* Decode instruction info and find the field to read */
field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
/* Read the field, zero-extended to a u64 field_value */
if (!vmcs12_read_any(vcpu, field, &field_value)) {
nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
skip_emulated_instruction(vcpu);
return 1;
}
/*
* Now copy part of this value to register or memory, as requested.
* Note that the number of bits actually copied is 32 or 64 depending
* on the guest's mode (32 or 64 bit), not on the given field's length.
*/
if (vmx_instruction_info & (1u << 10)) {
kvm_register_write(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
field_value);
} else {
if (get_vmx_mem_address(vcpu, exit_qualification,
vmx_instruction_info, &gva))
return 1;
/* _system ok, as nested_vmx_check_permission verified cpl=0 */
kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
&field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
}
nested_vmx_succeed(vcpu);
skip_emulated_instruction(vcpu);
return 1;
}
static int handle_vmwrite(struct kvm_vcpu *vcpu)
{
unsigned long field;
gva_t gva;
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
/* The value to write might be 32 or 64 bits, depending on L1's long
* mode, and eventually we need to write that into a field of several
* possible lengths. The code below first zero-extends the value to 64
* bit (field_value), and then copies only the approriate number of
* bits into the vmcs12 field.
*/
u64 field_value = 0;
struct x86_exception e;
if (!nested_vmx_check_permission(vcpu) ||
!nested_vmx_check_vmcs12(vcpu))
return 1;
if (vmx_instruction_info & (1u << 10))
field_value = kvm_register_read(vcpu,
(((vmx_instruction_info) >> 3) & 0xf));
else {
if (get_vmx_mem_address(vcpu, exit_qualification,
vmx_instruction_info, &gva))
return 1;
if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva,
&field_value, (is_long_mode(vcpu) ? 8 : 4), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
}
field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
if (vmcs_field_readonly(field)) {
nested_vmx_failValid(vcpu,
VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
skip_emulated_instruction(vcpu);
return 1;
}
if (!vmcs12_write_any(vcpu, field, field_value)) {
nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
skip_emulated_instruction(vcpu);
return 1;
}
nested_vmx_succeed(vcpu);
skip_emulated_instruction(vcpu);
return 1;
}
/* Emulate the VMPTRLD instruction */
static int handle_vmptrld(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
gva_t gva;
gpa_t vmptr;
struct x86_exception e;
u32 exec_control;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
vmcs_read32(VMX_INSTRUCTION_INFO), &gva))
return 1;
if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr,
sizeof(vmptr), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
if (!IS_ALIGNED(vmptr, PAGE_SIZE)) {
nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
skip_emulated_instruction(vcpu);
return 1;
}
if (vmx->nested.current_vmptr != vmptr) {
struct vmcs12 *new_vmcs12;
struct page *page;
page = nested_get_page(vcpu, vmptr);
if (page == NULL) {
nested_vmx_failInvalid(vcpu);
skip_emulated_instruction(vcpu);
return 1;
}
new_vmcs12 = kmap(page);
if (new_vmcs12->revision_id != VMCS12_REVISION) {
kunmap(page);
nested_release_page_clean(page);
nested_vmx_failValid(vcpu,
VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
skip_emulated_instruction(vcpu);
return 1;
}
if (vmx->nested.current_vmptr != -1ull)
nested_release_vmcs12(vmx);
vmx->nested.current_vmptr = vmptr;
vmx->nested.current_vmcs12 = new_vmcs12;
vmx->nested.current_vmcs12_page = page;
if (enable_shadow_vmcs) {
exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
exec_control |= SECONDARY_EXEC_SHADOW_VMCS;
vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
vmcs_write64(VMCS_LINK_POINTER,
__pa(vmx->nested.current_shadow_vmcs));
vmx->nested.sync_shadow_vmcs = true;
}
}
nested_vmx_succeed(vcpu);
skip_emulated_instruction(vcpu);
return 1;
}
/* Emulate the VMPTRST instruction */
static int handle_vmptrst(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
gva_t vmcs_gva;
struct x86_exception e;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (get_vmx_mem_address(vcpu, exit_qualification,
vmx_instruction_info, &vmcs_gva))
return 1;
/* ok to use *_system, as nested_vmx_check_permission verified cpl=0 */
if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,
(void *)&to_vmx(vcpu)->nested.current_vmptr,
sizeof(u64), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
nested_vmx_succeed(vcpu);
skip_emulated_instruction(vcpu);
return 1;
}
/* Emulate the INVEPT instruction */
static int handle_invept(struct kvm_vcpu *vcpu)
{
u32 vmx_instruction_info, types;
unsigned long type;
gva_t gva;
struct x86_exception e;
struct {
u64 eptp, gpa;
} operand;
u64 eptp_mask = ((1ull << 51) - 1) & PAGE_MASK;
if (!(nested_vmx_secondary_ctls_high & SECONDARY_EXEC_ENABLE_EPT) ||
!(nested_vmx_ept_caps & VMX_EPT_INVEPT_BIT)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
if (!nested_vmx_check_permission(vcpu))
return 1;
if (!kvm_read_cr0_bits(vcpu, X86_CR0_PE)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
type = kvm_register_read(vcpu, (vmx_instruction_info >> 28) & 0xf);
types = (nested_vmx_ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
if (!(types & (1UL << type))) {
nested_vmx_failValid(vcpu,
VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
return 1;
}
/* According to the Intel VMX instruction reference, the memory
* operand is read even if it isn't needed (e.g., for type==global)
*/
if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
vmx_instruction_info, &gva))
return 1;
if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand,
sizeof(operand), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
switch (type) {
case VMX_EPT_EXTENT_CONTEXT:
if ((operand.eptp & eptp_mask) !=
(nested_ept_get_cr3(vcpu) & eptp_mask))
break;
case VMX_EPT_EXTENT_GLOBAL:
kvm_mmu_sync_roots(vcpu);
kvm_mmu_flush_tlb(vcpu);
nested_vmx_succeed(vcpu);
break;
default:
BUG_ON(1);
break;
}
skip_emulated_instruction(vcpu);
return 1;
}
/*
* The exit handlers return 1 if the exit was handled fully and guest execution
* may resume. Otherwise they set the kvm_run parameter to indicate what needs
* to be done to userspace and return 0.
*/
static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
[EXIT_REASON_EXCEPTION_NMI] = handle_exception,
[EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
[EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
[EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
[EXIT_REASON_IO_INSTRUCTION] = handle_io,
[EXIT_REASON_CR_ACCESS] = handle_cr,
[EXIT_REASON_DR_ACCESS] = handle_dr,
[EXIT_REASON_CPUID] = handle_cpuid,
[EXIT_REASON_MSR_READ] = handle_rdmsr,
[EXIT_REASON_MSR_WRITE] = handle_wrmsr,
[EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
[EXIT_REASON_HLT] = handle_halt,
[EXIT_REASON_INVD] = handle_invd,
[EXIT_REASON_INVLPG] = handle_invlpg,
[EXIT_REASON_RDPMC] = handle_rdpmc,
[EXIT_REASON_VMCALL] = handle_vmcall,
[EXIT_REASON_VMCLEAR] = handle_vmclear,
[EXIT_REASON_VMLAUNCH] = handle_vmlaunch,
[EXIT_REASON_VMPTRLD] = handle_vmptrld,
[EXIT_REASON_VMPTRST] = handle_vmptrst,
[EXIT_REASON_VMREAD] = handle_vmread,
[EXIT_REASON_VMRESUME] = handle_vmresume,
[EXIT_REASON_VMWRITE] = handle_vmwrite,
[EXIT_REASON_VMOFF] = handle_vmoff,
[EXIT_REASON_VMON] = handle_vmon,
[EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
[EXIT_REASON_APIC_ACCESS] = handle_apic_access,
[EXIT_REASON_APIC_WRITE] = handle_apic_write,
[EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
[EXIT_REASON_WBINVD] = handle_wbinvd,
[EXIT_REASON_XSETBV] = handle_xsetbv,
[EXIT_REASON_TASK_SWITCH] = handle_task_switch,
[EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
[EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
[EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
[EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
[EXIT_REASON_MWAIT_INSTRUCTION] = handle_invalid_op,
[EXIT_REASON_MONITOR_INSTRUCTION] = handle_invalid_op,
[EXIT_REASON_INVEPT] = handle_invept,
};
static const int kvm_vmx_max_exit_handlers =
ARRAY_SIZE(kvm_vmx_exit_handlers);
static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
unsigned long exit_qualification;
gpa_t bitmap, last_bitmap;
unsigned int port;
int size;
u8 b;
if (nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING))
return 1;
if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
return 0;
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
port = exit_qualification >> 16;
size = (exit_qualification & 7) + 1;
last_bitmap = (gpa_t)-1;
b = -1;
while (size > 0) {
if (port < 0x8000)
bitmap = vmcs12->io_bitmap_a;
else if (port < 0x10000)
bitmap = vmcs12->io_bitmap_b;
else
return 1;
bitmap += (port & 0x7fff) / 8;
if (last_bitmap != bitmap)
if (kvm_read_guest(vcpu->kvm, bitmap, &b, 1))
return 1;
if (b & (1 << (port & 7)))
return 1;
port++;
size--;
last_bitmap = bitmap;
}
return 0;
}
/*
* Return 1 if we should exit from L2 to L1 to handle an MSR access access,
* rather than handle it ourselves in L0. I.e., check whether L1 expressed
* disinterest in the current event (read or write a specific MSR) by using an
* MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
*/
static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12, u32 exit_reason)
{
u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
gpa_t bitmap;
if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
return 1;
/*
* The MSR_BITMAP page is divided into four 1024-byte bitmaps,
* for the four combinations of read/write and low/high MSR numbers.
* First we need to figure out which of the four to use:
*/
bitmap = vmcs12->msr_bitmap;
if (exit_reason == EXIT_REASON_MSR_WRITE)
bitmap += 2048;
if (msr_index >= 0xc0000000) {
msr_index -= 0xc0000000;
bitmap += 1024;
}
/* Then read the msr_index'th bit from this bitmap: */
if (msr_index < 1024*8) {
unsigned char b;
if (kvm_read_guest(vcpu->kvm, bitmap + msr_index/8, &b, 1))
return 1;
return 1 & (b >> (msr_index & 7));
} else
return 1; /* let L1 handle the wrong parameter */
}
/*
* Return 1 if we should exit from L2 to L1 to handle a CR access exit,
* rather than handle it ourselves in L0. I.e., check if L1 wanted to
* intercept (via guest_host_mask etc.) the current event.
*/
static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
int cr = exit_qualification & 15;
int reg = (exit_qualification >> 8) & 15;
unsigned long val = kvm_register_read(vcpu, reg);
switch ((exit_qualification >> 4) & 3) {
case 0: /* mov to cr */
switch (cr) {
case 0:
if (vmcs12->cr0_guest_host_mask &
(val ^ vmcs12->cr0_read_shadow))
return 1;
break;
case 3:
if ((vmcs12->cr3_target_count >= 1 &&
vmcs12->cr3_target_value0 == val) ||
(vmcs12->cr3_target_count >= 2 &&
vmcs12->cr3_target_value1 == val) ||
(vmcs12->cr3_target_count >= 3 &&
vmcs12->cr3_target_value2 == val) ||
(vmcs12->cr3_target_count >= 4 &&
vmcs12->cr3_target_value3 == val))
return 0;
if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
return 1;
break;
case 4:
if (vmcs12->cr4_guest_host_mask &
(vmcs12->cr4_read_shadow ^ val))
return 1;
break;
case 8:
if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
return 1;
break;
}
break;
case 2: /* clts */
if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
(vmcs12->cr0_read_shadow & X86_CR0_TS))
return 1;
break;
case 1: /* mov from cr */
switch (cr) {
case 3:
if (vmcs12->cpu_based_vm_exec_control &
CPU_BASED_CR3_STORE_EXITING)
return 1;
break;
case 8:
if (vmcs12->cpu_based_vm_exec_control &
CPU_BASED_CR8_STORE_EXITING)
return 1;
break;
}
break;
case 3: /* lmsw */
/*
* lmsw can change bits 1..3 of cr0, and only set bit 0 of
* cr0. Other attempted changes are ignored, with no exit.
*/
if (vmcs12->cr0_guest_host_mask & 0xe &
(val ^ vmcs12->cr0_read_shadow))
return 1;
if ((vmcs12->cr0_guest_host_mask & 0x1) &&
!(vmcs12->cr0_read_shadow & 0x1) &&
(val & 0x1))
return 1;
break;
}
return 0;
}
/*
* Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
* should handle it ourselves in L0 (and then continue L2). Only call this
* when in is_guest_mode (L2).
*/
static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu)
{
u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
u32 exit_reason = vmx->exit_reason;
if (vmx->nested.nested_run_pending)
return 0;
if (unlikely(vmx->fail)) {
pr_info_ratelimited("%s failed vm entry %x\n", __func__,
vmcs_read32(VM_INSTRUCTION_ERROR));
return 1;
}
switch (exit_reason) {
case EXIT_REASON_EXCEPTION_NMI:
if (!is_exception(intr_info))
return 0;
else if (is_page_fault(intr_info))
return enable_ept;
return vmcs12->exception_bitmap &
(1u << (intr_info & INTR_INFO_VECTOR_MASK));
case EXIT_REASON_EXTERNAL_INTERRUPT:
return 0;
case EXIT_REASON_TRIPLE_FAULT:
return 1;
case EXIT_REASON_PENDING_INTERRUPT:
return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
case EXIT_REASON_NMI_WINDOW:
return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
case EXIT_REASON_TASK_SWITCH:
return 1;
case EXIT_REASON_CPUID:
return 1;
case EXIT_REASON_HLT:
return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
case EXIT_REASON_INVD:
return 1;
case EXIT_REASON_INVLPG:
return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
case EXIT_REASON_RDPMC:
return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
case EXIT_REASON_RDTSC:
return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
case EXIT_REASON_INVEPT:
/*
* VMX instructions trap unconditionally. This allows L1 to
* emulate them for its L2 guest, i.e., allows 3-level nesting!
*/
return 1;
case EXIT_REASON_CR_ACCESS:
return nested_vmx_exit_handled_cr(vcpu, vmcs12);
case EXIT_REASON_DR_ACCESS:
return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
case EXIT_REASON_IO_INSTRUCTION:
return nested_vmx_exit_handled_io(vcpu, vmcs12);
case EXIT_REASON_MSR_READ:
case EXIT_REASON_MSR_WRITE:
return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
case EXIT_REASON_INVALID_STATE:
return 1;
case EXIT_REASON_MWAIT_INSTRUCTION:
return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
case EXIT_REASON_MONITOR_INSTRUCTION:
return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
case EXIT_REASON_PAUSE_INSTRUCTION:
return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
nested_cpu_has2(vmcs12,
SECONDARY_EXEC_PAUSE_LOOP_EXITING);
case EXIT_REASON_MCE_DURING_VMENTRY:
return 0;
case EXIT_REASON_TPR_BELOW_THRESHOLD:
return 1;
case EXIT_REASON_APIC_ACCESS:
return nested_cpu_has2(vmcs12,
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
case EXIT_REASON_EPT_VIOLATION:
case EXIT_REASON_EPT_MISCONFIG:
return 0;
case EXIT_REASON_PREEMPTION_TIMER:
return vmcs12->pin_based_vm_exec_control &
PIN_BASED_VMX_PREEMPTION_TIMER;
case EXIT_REASON_WBINVD:
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
case EXIT_REASON_XSETBV:
return 1;
default:
return 1;
}
}
static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
{
*info1 = vmcs_readl(EXIT_QUALIFICATION);
*info2 = vmcs_read32(VM_EXIT_INTR_INFO);
}
/*
* The guest has exited. See if we can fix it or if we need userspace
* assistance.
*/
static int vmx_handle_exit(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 exit_reason = vmx->exit_reason;
u32 vectoring_info = vmx->idt_vectoring_info;
/* If guest state is invalid, start emulating */
if (vmx->emulation_required)
return handle_invalid_guest_state(vcpu);
/*
* the KVM_REQ_EVENT optimization bit is only on for one entry, and if
* we did not inject a still-pending event to L1 now because of
* nested_run_pending, we need to re-enable this bit.
*/
if (vmx->nested.nested_run_pending)
kvm_make_request(KVM_REQ_EVENT, vcpu);
if (!is_guest_mode(vcpu) && (exit_reason == EXIT_REASON_VMLAUNCH ||
exit_reason == EXIT_REASON_VMRESUME))
vmx->nested.nested_run_pending = 1;
else
vmx->nested.nested_run_pending = 0;
if (is_guest_mode(vcpu) && nested_vmx_exit_handled(vcpu)) {
nested_vmx_vmexit(vcpu);
return 1;
}
if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
vcpu->run->fail_entry.hardware_entry_failure_reason
= exit_reason;
return 0;
}
if (unlikely(vmx->fail)) {
vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
vcpu->run->fail_entry.hardware_entry_failure_reason
= vmcs_read32(VM_INSTRUCTION_ERROR);
return 0;
}
/*
* Note:
* Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
* delivery event since it indicates guest is accessing MMIO.
* The vm-exit can be triggered again after return to guest that
* will cause infinite loop.
*/
if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
(exit_reason != EXIT_REASON_EXCEPTION_NMI &&
exit_reason != EXIT_REASON_EPT_VIOLATION &&
exit_reason != EXIT_REASON_TASK_SWITCH)) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
vcpu->run->internal.ndata = 2;
vcpu->run->internal.data[0] = vectoring_info;
vcpu->run->internal.data[1] = exit_reason;
return 0;
}
if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked &&
!(is_guest_mode(vcpu) && nested_cpu_has_virtual_nmis(
get_vmcs12(vcpu), vcpu)))) {
if (vmx_interrupt_allowed(vcpu)) {
vmx->soft_vnmi_blocked = 0;
} else if (vmx->vnmi_blocked_time > 1000000000LL &&
vcpu->arch.nmi_pending) {
/*
* This CPU don't support us in finding the end of an
* NMI-blocked window if the guest runs with IRQs
* disabled. So we pull the trigger after 1 s of
* futile waiting, but inform the user about this.
*/
printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
"state on VCPU %d after 1 s timeout\n",
__func__, vcpu->vcpu_id);
vmx->soft_vnmi_blocked = 0;
}
}
if (exit_reason < kvm_vmx_max_exit_handlers
&& kvm_vmx_exit_handlers[exit_reason])
return kvm_vmx_exit_handlers[exit_reason](vcpu);
else {
vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
vcpu->run->hw.hardware_exit_reason = exit_reason;
}
return 0;
}
static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
{
if (irr == -1 || tpr < irr) {
vmcs_write32(TPR_THRESHOLD, 0);
return;
}
vmcs_write32(TPR_THRESHOLD, irr);
}
static void vmx_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
{
u32 sec_exec_control;
/*
* There is not point to enable virtualize x2apic without enable
* apicv
*/
if (!cpu_has_vmx_virtualize_x2apic_mode() ||
!vmx_vm_has_apicv(vcpu->kvm))
return;
if (!vm_need_tpr_shadow(vcpu->kvm))
return;
sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
if (set) {
sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
} else {
sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
}
vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
vmx_set_msr_bitmap(vcpu);
}
static void vmx_hwapic_isr_update(struct kvm *kvm, int isr)
{
u16 status;
u8 old;
if (!vmx_vm_has_apicv(kvm))
return;
if (isr == -1)
isr = 0;
status = vmcs_read16(GUEST_INTR_STATUS);
old = status >> 8;
if (isr != old) {
status &= 0xff;
status |= isr << 8;
vmcs_write16(GUEST_INTR_STATUS, status);
}
}
static void vmx_set_rvi(int vector)
{
u16 status;
u8 old;
status = vmcs_read16(GUEST_INTR_STATUS);
old = (u8)status & 0xff;
if ((u8)vector != old) {
status &= ~0xff;
status |= (u8)vector;
vmcs_write16(GUEST_INTR_STATUS, status);
}
}
static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
{
if (max_irr == -1)
return;
vmx_set_rvi(max_irr);
}
static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
{
if (!vmx_vm_has_apicv(vcpu->kvm))
return;
vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
}
static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
{
u32 exit_intr_info;
if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
|| vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI))
return;
vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
exit_intr_info = vmx->exit_intr_info;
/* Handle machine checks before interrupts are enabled */
if (is_machine_check(exit_intr_info))
kvm_machine_check();
/* We need to handle NMIs before interrupts are enabled */
if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR &&
(exit_intr_info & INTR_INFO_VALID_MASK)) {
kvm_before_handle_nmi(&vmx->vcpu);
asm("int $2");
kvm_after_handle_nmi(&vmx->vcpu);
}
}
static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
{
u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
/*
* If external interrupt exists, IF bit is set in rflags/eflags on the
* interrupt stack frame, and interrupt will be enabled on a return
* from interrupt handler.
*/
if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
== (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
unsigned int vector;
unsigned long entry;
gate_desc *desc;
struct vcpu_vmx *vmx = to_vmx(vcpu);
#ifdef CONFIG_X86_64
unsigned long tmp;
#endif
vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
desc = (gate_desc *)vmx->host_idt_base + vector;
entry = gate_offset(*desc);
asm volatile(
#ifdef CONFIG_X86_64
"mov %%" _ASM_SP ", %[sp]\n\t"
"and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
"push $%c[ss]\n\t"
"push %[sp]\n\t"
#endif
"pushf\n\t"
"orl $0x200, (%%" _ASM_SP ")\n\t"
__ASM_SIZE(push) " $%c[cs]\n\t"
"call *%[entry]\n\t"
:
#ifdef CONFIG_X86_64
[sp]"=&r"(tmp)
#endif
:
[entry]"r"(entry),
[ss]"i"(__KERNEL_DS),
[cs]"i"(__KERNEL_CS)
);
} else
local_irq_enable();
}
static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
{
u32 exit_intr_info;
bool unblock_nmi;
u8 vector;
bool idtv_info_valid;
idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
if (cpu_has_virtual_nmis()) {
if (vmx->nmi_known_unmasked)
return;
/*
* Can't use vmx->exit_intr_info since we're not sure what
* the exit reason is.
*/
exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
/*
* SDM 3: 27.7.1.2 (September 2008)
* Re-set bit "block by NMI" before VM entry if vmexit caused by
* a guest IRET fault.
* SDM 3: 23.2.2 (September 2008)
* Bit 12 is undefined in any of the following cases:
* If the VM exit sets the valid bit in the IDT-vectoring
* information field.
* If the VM exit is due to a double fault.
*/
if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
vector != DF_VECTOR && !idtv_info_valid)
vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
GUEST_INTR_STATE_NMI);
else
vmx->nmi_known_unmasked =
!(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
& GUEST_INTR_STATE_NMI);
} else if (unlikely(vmx->soft_vnmi_blocked))
vmx->vnmi_blocked_time +=
ktime_to_ns(ktime_sub(ktime_get(), vmx->entry_time));
}
static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
u32 idt_vectoring_info,
int instr_len_field,
int error_code_field)
{
u8 vector;
int type;
bool idtv_info_valid;
idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
vcpu->arch.nmi_injected = false;
kvm_clear_exception_queue(vcpu);
kvm_clear_interrupt_queue(vcpu);
if (!idtv_info_valid)
return;
kvm_make_request(KVM_REQ_EVENT, vcpu);
vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
switch (type) {
case INTR_TYPE_NMI_INTR:
vcpu->arch.nmi_injected = true;
/*
* SDM 3: 27.7.1.2 (September 2008)
* Clear bit "block by NMI" before VM entry if a NMI
* delivery faulted.
*/
vmx_set_nmi_mask(vcpu, false);
break;
case INTR_TYPE_SOFT_EXCEPTION:
vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
/* fall through */
case INTR_TYPE_HARD_EXCEPTION:
if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
u32 err = vmcs_read32(error_code_field);
kvm_queue_exception_e(vcpu, vector, err);
} else
kvm_queue_exception(vcpu, vector);
break;
case INTR_TYPE_SOFT_INTR:
vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
/* fall through */
case INTR_TYPE_EXT_INTR:
kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
break;
default:
break;
}
}
static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
{
__vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
VM_EXIT_INSTRUCTION_LEN,
IDT_VECTORING_ERROR_CODE);
}
static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
{
__vmx_complete_interrupts(vcpu,
vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
VM_ENTRY_INSTRUCTION_LEN,
VM_ENTRY_EXCEPTION_ERROR_CODE);
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
}
static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
{
int i, nr_msrs;
struct perf_guest_switch_msr *msrs;
msrs = perf_guest_get_msrs(&nr_msrs);
if (!msrs)
return;
for (i = 0; i < nr_msrs; i++)
if (msrs[i].host == msrs[i].guest)
clear_atomic_switch_msr(vmx, msrs[i].msr);
else
add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
msrs[i].host);
}
static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
unsigned long debugctlmsr;
/* Record the guest's net vcpu time for enforced NMI injections. */
if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked))
vmx->entry_time = ktime_get();
/* Don't enter VMX if guest state is invalid, let the exit handler
start emulation until we arrive back to a valid state */
if (vmx->emulation_required)
return;
if (vmx->nested.sync_shadow_vmcs) {
copy_vmcs12_to_shadow(vmx);
vmx->nested.sync_shadow_vmcs = false;
}
if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
/* When single-stepping over STI and MOV SS, we must clear the
* corresponding interruptibility bits in the guest state. Otherwise
* vmentry fails as it then expects bit 14 (BS) in pending debug
* exceptions being set, but that's not correct for the guest debugging
* case. */
if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
vmx_set_interrupt_shadow(vcpu, 0);
atomic_switch_perf_msrs(vmx);
debugctlmsr = get_debugctlmsr();
vmx->__launched = vmx->loaded_vmcs->launched;
asm(
/* Store host registers */
"push %%" _ASM_DX "; push %%" _ASM_BP ";"
"push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
"push %%" _ASM_CX " \n\t"
"cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
"je 1f \n\t"
"mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
__ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
"1: \n\t"
/* Reload cr2 if changed */
"mov %c[cr2](%0), %%" _ASM_AX " \n\t"
"mov %%cr2, %%" _ASM_DX " \n\t"
"cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
"je 2f \n\t"
"mov %%" _ASM_AX", %%cr2 \n\t"
"2: \n\t"
/* Check if vmlaunch of vmresume is needed */
"cmpl $0, %c[launched](%0) \n\t"
/* Load guest registers. Don't clobber flags. */
"mov %c[rax](%0), %%" _ASM_AX " \n\t"
"mov %c[rbx](%0), %%" _ASM_BX " \n\t"
"mov %c[rdx](%0), %%" _ASM_DX " \n\t"
"mov %c[rsi](%0), %%" _ASM_SI " \n\t"
"mov %c[rdi](%0), %%" _ASM_DI " \n\t"
"mov %c[rbp](%0), %%" _ASM_BP " \n\t"
#ifdef CONFIG_X86_64
"mov %c[r8](%0), %%r8 \n\t"
"mov %c[r9](%0), %%r9 \n\t"
"mov %c[r10](%0), %%r10 \n\t"
"mov %c[r11](%0), %%r11 \n\t"
"mov %c[r12](%0), %%r12 \n\t"
"mov %c[r13](%0), %%r13 \n\t"
"mov %c[r14](%0), %%r14 \n\t"
"mov %c[r15](%0), %%r15 \n\t"
#endif
"mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
/* Enter guest mode */
"jne 1f \n\t"
__ex(ASM_VMX_VMLAUNCH) "\n\t"
"jmp 2f \n\t"
"1: " __ex(ASM_VMX_VMRESUME) "\n\t"
"2: "
/* Save guest registers, load host registers, keep flags */
"mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
"pop %0 \n\t"
"mov %%" _ASM_AX ", %c[rax](%0) \n\t"
"mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
__ASM_SIZE(pop) " %c[rcx](%0) \n\t"
"mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
"mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
"mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
"mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
#ifdef CONFIG_X86_64
"mov %%r8, %c[r8](%0) \n\t"
"mov %%r9, %c[r9](%0) \n\t"
"mov %%r10, %c[r10](%0) \n\t"
"mov %%r11, %c[r11](%0) \n\t"
"mov %%r12, %c[r12](%0) \n\t"
"mov %%r13, %c[r13](%0) \n\t"
"mov %%r14, %c[r14](%0) \n\t"
"mov %%r15, %c[r15](%0) \n\t"
#endif
"mov %%cr2, %%" _ASM_AX " \n\t"
"mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
"pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t"
"setbe %c[fail](%0) \n\t"
".pushsection .rodata \n\t"
".global vmx_return \n\t"
"vmx_return: " _ASM_PTR " 2b \n\t"
".popsection"
: : "c"(vmx), "d"((unsigned long)HOST_RSP),
[launched]"i"(offsetof(struct vcpu_vmx, __launched)),
[fail]"i"(offsetof(struct vcpu_vmx, fail)),
[host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
[rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
[rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
[rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
[rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
[rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
[rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
[rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
#ifdef CONFIG_X86_64
[r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
[r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
[r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
[r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
[r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
[r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
[r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
[r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
#endif
[cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
[wordsize]"i"(sizeof(ulong))
: "cc", "memory"
#ifdef CONFIG_X86_64
, "rax", "rbx", "rdi", "rsi"
, "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
#else
, "eax", "ebx", "edi", "esi"
#endif
);
/* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
if (debugctlmsr)
update_debugctlmsr(debugctlmsr);
#ifndef CONFIG_X86_64
/*
* The sysexit path does not restore ds/es, so we must set them to
* a reasonable value ourselves.
*
* We can't defer this to vmx_load_host_state() since that function
* may be executed in interrupt context, which saves and restore segments
* around it, nullifying its effect.
*/
loadsegment(ds, __USER_DS);
loadsegment(es, __USER_DS);
#endif
vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
| (1 << VCPU_EXREG_RFLAGS)
| (1 << VCPU_EXREG_CPL)
| (1 << VCPU_EXREG_PDPTR)
| (1 << VCPU_EXREG_SEGMENTS)
| (1 << VCPU_EXREG_CR3));
vcpu->arch.regs_dirty = 0;
vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
vmx->loaded_vmcs->launched = 1;
vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX);
vmx_complete_atomic_exit(vmx);
vmx_recover_nmi_blocking(vmx);
vmx_complete_interrupts(vmx);
}
static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
free_vpid(vmx);
free_nested(vmx);
free_loaded_vmcs(vmx->loaded_vmcs);
kfree(vmx->guest_msrs);
kvm_vcpu_uninit(vcpu);
kmem_cache_free(kvm_vcpu_cache, vmx);
}
static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
{
int err;
struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
int cpu;
if (!vmx)
return ERR_PTR(-ENOMEM);
allocate_vpid(vmx);
err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
if (err)
goto free_vcpu;
vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
err = -ENOMEM;
if (!vmx->guest_msrs) {
goto uninit_vcpu;
}
vmx->loaded_vmcs = &vmx->vmcs01;
vmx->loaded_vmcs->vmcs = alloc_vmcs();
if (!vmx->loaded_vmcs->vmcs)
goto free_msrs;
if (!vmm_exclusive)
kvm_cpu_vmxon(__pa(per_cpu(vmxarea, raw_smp_processor_id())));
loaded_vmcs_init(vmx->loaded_vmcs);
if (!vmm_exclusive)
kvm_cpu_vmxoff();
cpu = get_cpu();
vmx_vcpu_load(&vmx->vcpu, cpu);
vmx->vcpu.cpu = cpu;
err = vmx_vcpu_setup(vmx);
vmx_vcpu_put(&vmx->vcpu);
put_cpu();
if (err)
goto free_vmcs;
if (vm_need_virtualize_apic_accesses(kvm)) {
err = alloc_apic_access_page(kvm);
if (err)
goto free_vmcs;
}
if (enable_ept) {
if (!kvm->arch.ept_identity_map_addr)
kvm->arch.ept_identity_map_addr =
VMX_EPT_IDENTITY_PAGETABLE_ADDR;
err = -ENOMEM;
if (alloc_identity_pagetable(kvm) != 0)
goto free_vmcs;
if (!init_rmode_identity_map(kvm))
goto free_vmcs;
}
vmx->nested.current_vmptr = -1ull;
vmx->nested.current_vmcs12 = NULL;
return &vmx->vcpu;
free_vmcs:
free_loaded_vmcs(vmx->loaded_vmcs);
free_msrs:
kfree(vmx->guest_msrs);
uninit_vcpu:
kvm_vcpu_uninit(&vmx->vcpu);
free_vcpu:
free_vpid(vmx);
kmem_cache_free(kvm_vcpu_cache, vmx);
return ERR_PTR(err);
}
static void __init vmx_check_processor_compat(void *rtn)
{
struct vmcs_config vmcs_conf;
*(int *)rtn = 0;
if (setup_vmcs_config(&vmcs_conf) < 0)
*(int *)rtn = -EIO;
if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
smp_processor_id());
*(int *)rtn = -EIO;
}
}
static int get_ept_level(void)
{
return VMX_EPT_DEFAULT_GAW + 1;
}
static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
{
u64 ret;
/* For VT-d and EPT combination
* 1. MMIO: always map as UC
* 2. EPT with VT-d:
* a. VT-d without snooping control feature: can't guarantee the
* result, try to trust guest.
* b. VT-d with snooping control feature: snooping control feature of
* VT-d engine can guarantee the cache correctness. Just set it
* to WB to keep consistent with host. So the same as item 3.
* 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
* consistent with host MTRR
*/
if (is_mmio)
ret = MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
else if (vcpu->kvm->arch.iommu_domain &&
!(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY))
ret = kvm_get_guest_memory_type(vcpu, gfn) <<
VMX_EPT_MT_EPTE_SHIFT;
else
ret = (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT)
| VMX_EPT_IPAT_BIT;
return ret;
}
static int vmx_get_lpage_level(void)
{
if (enable_ept && !cpu_has_vmx_ept_1g_page())
return PT_DIRECTORY_LEVEL;
else
/* For shadow and EPT supported 1GB page */
return PT_PDPE_LEVEL;
}
static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
{
struct kvm_cpuid_entry2 *best;
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 exec_control;
vmx->rdtscp_enabled = false;
if (vmx_rdtscp_supported()) {
exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
if (exec_control & SECONDARY_EXEC_RDTSCP) {
best = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
if (best && (best->edx & bit(X86_FEATURE_RDTSCP)))
vmx->rdtscp_enabled = true;
else {
exec_control &= ~SECONDARY_EXEC_RDTSCP;
vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
exec_control);
}
}
}
/* Exposing INVPCID only when PCID is exposed */
best = kvm_find_cpuid_entry(vcpu, 0x7, 0);
if (vmx_invpcid_supported() &&
best && (best->ebx & bit(X86_FEATURE_INVPCID)) &&
guest_cpuid_has_pcid(vcpu)) {
exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
exec_control |= SECONDARY_EXEC_ENABLE_INVPCID;
vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
exec_control);
} else {
if (cpu_has_secondary_exec_ctrls()) {
exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
exec_control);
}
if (best)
best->ebx &= ~bit(X86_FEATURE_INVPCID);
}
}
static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
{
if (func == 1 && nested)
entry->ecx |= bit(X86_FEATURE_VMX);
}
static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
struct x86_exception *fault)
{
struct vmcs12 *vmcs12;
nested_vmx_vmexit(vcpu);
vmcs12 = get_vmcs12(vcpu);
if (fault->error_code & PFERR_RSVD_MASK)
vmcs12->vm_exit_reason = EXIT_REASON_EPT_MISCONFIG;
else
vmcs12->vm_exit_reason = EXIT_REASON_EPT_VIOLATION;
vmcs12->exit_qualification = vcpu->arch.exit_qualification;
vmcs12->guest_physical_address = fault->address;
}
/* Callbacks for nested_ept_init_mmu_context: */
static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
{
/* return the page table to be shadowed - in our case, EPT12 */
return get_vmcs12(vcpu)->ept_pointer;
}
static int nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
{
int r = kvm_init_shadow_ept_mmu(vcpu, &vcpu->arch.mmu,
nested_vmx_ept_caps & VMX_EPT_EXECUTE_ONLY_BIT);
vcpu->arch.mmu.set_cr3 = vmx_set_cr3;
vcpu->arch.mmu.get_cr3 = nested_ept_get_cr3;
vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
return r;
}
static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
{
vcpu->arch.walk_mmu = &vcpu->arch.mmu;
}
/*
* prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
* L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
* with L0's requirements for its guest (a.k.a. vmsc01), so we can run the L2
* guest in a way that will both be appropriate to L1's requests, and our
* needs. In addition to modifying the active vmcs (which is vmcs02), this
* function also has additional necessary side-effects, like setting various
* vcpu->arch fields.
*/
static void prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 exec_control;
vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
vmcs12->vm_entry_intr_info_field);
vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
vmcs12->vm_entry_exception_error_code);
vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
vmcs12->vm_entry_instruction_len);
vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
vmcs12->guest_interruptibility_info);
vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
vmx_set_rflags(vcpu, vmcs12->guest_rflags);
vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
vmcs12->guest_pending_dbg_exceptions);
vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
vmcs_write64(VMCS_LINK_POINTER, -1ull);
vmcs_write32(PIN_BASED_VM_EXEC_CONTROL,
(vmcs_config.pin_based_exec_ctrl |
vmcs12->pin_based_vm_exec_control));
if (vmcs12->pin_based_vm_exec_control & PIN_BASED_VMX_PREEMPTION_TIMER)
vmcs_write32(VMX_PREEMPTION_TIMER_VALUE,
vmcs12->vmx_preemption_timer_value);
/*
* Whether page-faults are trapped is determined by a combination of
* 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
* If enable_ept, L0 doesn't care about page faults and we should
* set all of these to L1's desires. However, if !enable_ept, L0 does
* care about (at least some) page faults, and because it is not easy
* (if at all possible?) to merge L0 and L1's desires, we simply ask
* to exit on each and every L2 page fault. This is done by setting
* MASK=MATCH=0 and (see below) EB.PF=1.
* Note that below we don't need special code to set EB.PF beyond the
* "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
* vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
* !enable_ept, EB.PF is 1, so the "or" will always be 1.
*
* A problem with this approach (when !enable_ept) is that L1 may be
* injected with more page faults than it asked for. This could have
* caused problems, but in practice existing hypervisors don't care.
* To fix this, we will need to emulate the PFEC checking (on the L1
* page tables), using walk_addr(), when injecting PFs to L1.
*/
vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
enable_ept ? vmcs12->page_fault_error_code_mask : 0);
vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
enable_ept ? vmcs12->page_fault_error_code_match : 0);
if (cpu_has_secondary_exec_ctrls()) {
u32 exec_control = vmx_secondary_exec_control(vmx);
if (!vmx->rdtscp_enabled)
exec_control &= ~SECONDARY_EXEC_RDTSCP;
/* Take the following fields only from vmcs12 */
exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
if (nested_cpu_has(vmcs12,
CPU_BASED_ACTIVATE_SECONDARY_CONTROLS))
exec_control |= vmcs12->secondary_vm_exec_control;
if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) {
/*
* Translate L1 physical address to host physical
* address for vmcs02. Keep the page pinned, so this
* physical address remains valid. We keep a reference
* to it so we can release it later.
*/
if (vmx->nested.apic_access_page) /* shouldn't happen */
nested_release_page(vmx->nested.apic_access_page);
vmx->nested.apic_access_page =
nested_get_page(vcpu, vmcs12->apic_access_addr);
/*
* If translation failed, no matter: This feature asks
* to exit when accessing the given address, and if it
* can never be accessed, this feature won't do
* anything anyway.
*/
if (!vmx->nested.apic_access_page)
exec_control &=
~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
else
vmcs_write64(APIC_ACCESS_ADDR,
page_to_phys(vmx->nested.apic_access_page));
}
vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
}
/*
* Set host-state according to L0's settings (vmcs12 is irrelevant here)
* Some constant fields are set here by vmx_set_constant_host_state().
* Other fields are different per CPU, and will be set later when
* vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
*/
vmx_set_constant_host_state(vmx);
/*
* HOST_RSP is normally set correctly in vmx_vcpu_run() just before
* entry, but only if the current (host) sp changed from the value
* we wrote last (vmx->host_rsp). This cache is no longer relevant
* if we switch vmcs, and rather than hold a separate cache per vmcs,
* here we just force the write to happen on entry.
*/
vmx->host_rsp = 0;
exec_control = vmx_exec_control(vmx); /* L0's desires */
exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
exec_control &= ~CPU_BASED_TPR_SHADOW;
exec_control |= vmcs12->cpu_based_vm_exec_control;
/*
* Merging of IO and MSR bitmaps not currently supported.
* Rather, exit every time.
*/
exec_control &= ~CPU_BASED_USE_MSR_BITMAPS;
exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
exec_control |= CPU_BASED_UNCOND_IO_EXITING;
vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
/* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
* bitwise-or of what L1 wants to trap for L2, and what we want to
* trap. Note that CR0.TS also needs updating - we do this later.
*/
update_exception_bitmap(vcpu);
vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
/* L2->L1 exit controls are emulated - the hardware exit is to L0 so
* we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
* bits are further modified by vmx_set_efer() below.
*/
vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
/* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
* emulated by vmx_set_efer(), below.
*/
vmcs_write32(VM_ENTRY_CONTROLS,
(vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
~VM_ENTRY_IA32E_MODE) |
(vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)
vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
set_cr4_guest_host_mask(vmx);
if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
vmcs_write64(TSC_OFFSET,
vmx->nested.vmcs01_tsc_offset + vmcs12->tsc_offset);
else
vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset);
if (enable_vpid) {
/*
* Trivially support vpid by letting L2s share their parent
* L1's vpid. TODO: move to a more elaborate solution, giving
* each L2 its own vpid and exposing the vpid feature to L1.
*/
vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
vmx_flush_tlb(vcpu);
}
if (nested_cpu_has_ept(vmcs12)) {
kvm_mmu_unload(vcpu);
nested_ept_init_mmu_context(vcpu);
}
if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)
vcpu->arch.efer = vmcs12->guest_ia32_efer;
else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
vcpu->arch.efer |= (EFER_LMA | EFER_LME);
else
vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
/* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
vmx_set_efer(vcpu, vcpu->arch.efer);
/*
* This sets GUEST_CR0 to vmcs12->guest_cr0, with possibly a modified
* TS bit (for lazy fpu) and bits which we consider mandatory enabled.
* The CR0_READ_SHADOW is what L2 should have expected to read given
* the specifications by L1; It's not enough to take
* vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
* have more bits than L1 expected.
*/
vmx_set_cr0(vcpu, vmcs12->guest_cr0);
vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
vmx_set_cr4(vcpu, vmcs12->guest_cr4);
vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
/* shadow page tables on either EPT or shadow page tables */
kvm_set_cr3(vcpu, vmcs12->guest_cr3);
kvm_mmu_reset_context(vcpu);
/*
* L1 may access the L2's PDPTR, so save them to construct vmcs12
*/
if (enable_ept) {
vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
}
kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
}
/*
* nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
* for running an L2 nested guest.
*/
static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
{
struct vmcs12 *vmcs12;
struct vcpu_vmx *vmx = to_vmx(vcpu);
int cpu;
struct loaded_vmcs *vmcs02;
bool ia32e;
if (!nested_vmx_check_permission(vcpu) ||
!nested_vmx_check_vmcs12(vcpu))
return 1;
skip_emulated_instruction(vcpu);
vmcs12 = get_vmcs12(vcpu);
if (enable_shadow_vmcs)
copy_shadow_to_vmcs12(vmx);
/*
* The nested entry process starts with enforcing various prerequisites
* on vmcs12 as required by the Intel SDM, and act appropriately when
* they fail: As the SDM explains, some conditions should cause the
* instruction to fail, while others will cause the instruction to seem
* to succeed, but return an EXIT_REASON_INVALID_STATE.
* To speed up the normal (success) code path, we should avoid checking
* for misconfigurations which will anyway be caught by the processor
* when using the merged vmcs02.
*/
if (vmcs12->launch_state == launch) {
nested_vmx_failValid(vcpu,
launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
: VMXERR_VMRESUME_NONLAUNCHED_VMCS);
return 1;
}
if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE) {
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
return 1;
}
if ((vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_MSR_BITMAPS) &&
!IS_ALIGNED(vmcs12->msr_bitmap, PAGE_SIZE)) {
/*TODO: Also verify bits beyond physical address width are 0*/
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
return 1;
}
if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
!IS_ALIGNED(vmcs12->apic_access_addr, PAGE_SIZE)) {
/*TODO: Also verify bits beyond physical address width are 0*/
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
return 1;
}
if (vmcs12->vm_entry_msr_load_count > 0 ||
vmcs12->vm_exit_msr_load_count > 0 ||
vmcs12->vm_exit_msr_store_count > 0) {
pr_warn_ratelimited("%s: VMCS MSR_{LOAD,STORE} unsupported\n",
__func__);
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
return 1;
}
if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high) ||
!vmx_control_verify(vmcs12->secondary_vm_exec_control,
nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high) ||
!vmx_control_verify(vmcs12->pin_based_vm_exec_control,
nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high) ||
!vmx_control_verify(vmcs12->vm_exit_controls,
nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high) ||
!vmx_control_verify(vmcs12->vm_entry_controls,
nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high))
{
nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
return 1;
}
if (((vmcs12->host_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) ||
((vmcs12->host_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
nested_vmx_failValid(vcpu,
VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
return 1;
}
if (((vmcs12->guest_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) ||
((vmcs12->guest_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
return 1;
}
if (vmcs12->vmcs_link_pointer != -1ull) {
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_INVALID_STATE, ENTRY_FAIL_VMCS_LINK_PTR);
return 1;
}
/*
* If the load IA32_EFER VM-entry control is 1, the following checks
* are performed on the field for the IA32_EFER MSR:
* - Bits reserved in the IA32_EFER MSR must be 0.
* - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
* the IA-32e mode guest VM-exit control. It must also be identical
* to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
* CR0.PG) is 1.
*/
if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER) {
ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
((vmcs12->guest_cr0 & X86_CR0_PG) &&
ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME))) {
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
return 1;
}
}
/*
* If the load IA32_EFER VM-exit control is 1, bits reserved in the
* IA32_EFER MSR must be 0 in the field for that register. In addition,
* the values of the LMA and LME bits in the field must each be that of
* the host address-space size VM-exit control.
*/
if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
ia32e = (vmcs12->vm_exit_controls &
VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
ia32e != !!(vmcs12->host_ia32_efer & EFER_LME)) {
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
return 1;
}
}
/*
* We're finally done with prerequisite checking, and can start with
* the nested entry.
*/
vmcs02 = nested_get_current_vmcs02(vmx);
if (!vmcs02)
return -ENOMEM;
enter_guest_mode(vcpu);
vmx->nested.vmcs01_tsc_offset = vmcs_read64(TSC_OFFSET);
cpu = get_cpu();
vmx->loaded_vmcs = vmcs02;
vmx_vcpu_put(vcpu);
vmx_vcpu_load(vcpu, cpu);
vcpu->cpu = cpu;
put_cpu();
vmx_segment_cache_clear(vmx);
vmcs12->launch_state = 1;
prepare_vmcs02(vcpu, vmcs12);
/*
* Note no nested_vmx_succeed or nested_vmx_fail here. At this point
* we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
* returned as far as L1 is concerned. It will only return (and set
* the success flag) when L2 exits (see nested_vmx_vmexit()).
*/
return 1;
}
/*
* On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
* because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
* This function returns the new value we should put in vmcs12.guest_cr0.
* It's not enough to just return the vmcs02 GUEST_CR0. Rather,
* 1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
* available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
* didn't trap the bit, because if L1 did, so would L0).
* 2. Bits that L1 asked to trap (and therefore L0 also did) could not have
* been modified by L2, and L1 knows it. So just leave the old value of
* the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
* isn't relevant, because if L0 traps this bit it can set it to anything.
* 3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
* changed these bits, and therefore they need to be updated, but L0
* didn't necessarily allow them to be changed in GUEST_CR0 - and rather
* put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
*/
static inline unsigned long
vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
{
return
/*1*/ (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
/*2*/ (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
/*3*/ (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
vcpu->arch.cr0_guest_owned_bits));
}
static inline unsigned long
vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
{
return
/*1*/ (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
/*2*/ (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
/*3*/ (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
vcpu->arch.cr4_guest_owned_bits));
}
static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
u32 idt_vectoring;
unsigned int nr;
if (vcpu->arch.exception.pending) {
nr = vcpu->arch.exception.nr;
idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
if (kvm_exception_is_soft(nr)) {
vmcs12->vm_exit_instruction_len =
vcpu->arch.event_exit_inst_len;
idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
} else
idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
if (vcpu->arch.exception.has_error_code) {
idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
vmcs12->idt_vectoring_error_code =
vcpu->arch.exception.error_code;
}
vmcs12->idt_vectoring_info_field = idt_vectoring;
} else if (vcpu->arch.nmi_pending) {
vmcs12->idt_vectoring_info_field =
INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
} else if (vcpu->arch.interrupt.pending) {
nr = vcpu->arch.interrupt.nr;
idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
if (vcpu->arch.interrupt.soft) {
idt_vectoring |= INTR_TYPE_SOFT_INTR;
vmcs12->vm_entry_instruction_len =
vcpu->arch.event_exit_inst_len;
} else
idt_vectoring |= INTR_TYPE_EXT_INTR;
vmcs12->idt_vectoring_info_field = idt_vectoring;
}
}
/*
* prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
* and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
* and this function updates it to reflect the changes to the guest state while
* L2 was running (and perhaps made some exits which were handled directly by L0
* without going back to L1), and to reflect the exit reason.
* Note that we do not have to copy here all VMCS fields, just those that
* could have changed by the L2 guest or the exit - i.e., the guest-state and
* exit-information fields only. Other fields are modified by L1 with VMWRITE,
* which already writes to vmcs12 directly.
*/
static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
{
/* update guest state fields: */
vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
vmcs12->guest_interruptibility_info =
vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
vmcs12->guest_pending_dbg_exceptions =
vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
/*
* In some cases (usually, nested EPT), L2 is allowed to change its
* own CR3 without exiting. If it has changed it, we must keep it.
* Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
* by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
*
* Additionally, restore L2's PDPTR to vmcs12.
*/
if (enable_ept) {
vmcs12->guest_cr3 = vmcs_read64(GUEST_CR3);
vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
}
vmcs12->vm_entry_controls =
(vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
(vmcs_read32(VM_ENTRY_CONTROLS) & VM_ENTRY_IA32E_MODE);
/* TODO: These cannot have changed unless we have MSR bitmaps and
* the relevant bit asks not to trap the change */
vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
/* update exit information fields: */
vmcs12->vm_exit_reason = to_vmx(vcpu)->exit_reason;
vmcs12->exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
vmcs12->vm_exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
if ((vmcs12->vm_exit_intr_info &
(INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
(INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK))
vmcs12->vm_exit_intr_error_code =
vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
vmcs12->idt_vectoring_info_field = 0;
vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
/* vm_entry_intr_info_field is cleared on exit. Emulate this
* instead of reading the real value. */
vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
/*
* Transfer the event that L0 or L1 may wanted to inject into
* L2 to IDT_VECTORING_INFO_FIELD.
*/
vmcs12_save_pending_event(vcpu, vmcs12);
}
/*
* Drop what we picked up for L2 via vmx_complete_interrupts. It is
* preserved above and would only end up incorrectly in L1.
*/
vcpu->arch.nmi_injected = false;
kvm_clear_exception_queue(vcpu);
kvm_clear_interrupt_queue(vcpu);
}
/*
* A part of what we need to when the nested L2 guest exits and we want to
* run its L1 parent, is to reset L1's guest state to the host state specified
* in vmcs12.
* This function is to be called not only on normal nested exit, but also on
* a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
* Failures During or After Loading Guest State").
* This function should be called when the active VMCS is L1's (vmcs01).
*/
static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
struct kvm_segment seg;
if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
vcpu->arch.efer = vmcs12->host_ia32_efer;
else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
vcpu->arch.efer |= (EFER_LMA | EFER_LME);
else
vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
vmx_set_efer(vcpu, vcpu->arch.efer);
kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
/*
* Note that calling vmx_set_cr0 is important, even if cr0 hasn't
* actually changed, because it depends on the current state of
* fpu_active (which may have changed).
* Note that vmx_set_cr0 refers to efer set above.
*/
kvm_set_cr0(vcpu, vmcs12->host_cr0);
/*
* If we did fpu_activate()/fpu_deactivate() during L2's run, we need
* to apply the same changes to L1's vmcs. We just set cr0 correctly,
* but we also need to update cr0_guest_host_mask and exception_bitmap.
*/
update_exception_bitmap(vcpu);
vcpu->arch.cr0_guest_owned_bits = (vcpu->fpu_active ? X86_CR0_TS : 0);
vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
/*
* Note that CR4_GUEST_HOST_MASK is already set in the original vmcs01
* (KVM doesn't change it)- no reason to call set_cr4_guest_host_mask();
*/
vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
kvm_set_cr4(vcpu, vmcs12->host_cr4);
if (nested_cpu_has_ept(vmcs12))
nested_ept_uninit_mmu_context(vcpu);
kvm_set_cr3(vcpu, vmcs12->host_cr3);
kvm_mmu_reset_context(vcpu);
if (enable_vpid) {
/*
* Trivially support vpid by letting L2s share their parent
* L1's vpid. TODO: move to a more elaborate solution, giving
* each L2 its own vpid and exposing the vpid feature to L1.
*/
vmx_flush_tlb(vcpu);
}
vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT)
vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
vmcs12->host_ia32_perf_global_ctrl);
/* Set L1 segment info according to Intel SDM
27.5.2 Loading Host Segment and Descriptor-Table Registers */
seg = (struct kvm_segment) {
.base = 0,
.limit = 0xFFFFFFFF,
.selector = vmcs12->host_cs_selector,
.type = 11,
.present = 1,
.s = 1,
.g = 1
};
if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
seg.l = 1;
else
seg.db = 1;
vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
seg = (struct kvm_segment) {
.base = 0,
.limit = 0xFFFFFFFF,
.type = 3,
.present = 1,
.s = 1,
.db = 1,
.g = 1
};
seg.selector = vmcs12->host_ds_selector;
vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
seg.selector = vmcs12->host_es_selector;
vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
seg.selector = vmcs12->host_ss_selector;
vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
seg.selector = vmcs12->host_fs_selector;
seg.base = vmcs12->host_fs_base;
vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
seg.selector = vmcs12->host_gs_selector;
seg.base = vmcs12->host_gs_base;
vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
seg = (struct kvm_segment) {
.base = vmcs12->host_tr_base,
.limit = 0x67,
.selector = vmcs12->host_tr_selector,
.type = 11,
.present = 1
};
vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
kvm_set_dr(vcpu, 7, 0x400);
vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
}
/*
* Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
* and modify vmcs12 to make it see what it would expect to see there if
* L2 was its real guest. Must only be called when in L2 (is_guest_mode())
*/
static void nested_vmx_vmexit(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
int cpu;
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
/* trying to cancel vmlaunch/vmresume is a bug */
WARN_ON_ONCE(vmx->nested.nested_run_pending);
leave_guest_mode(vcpu);
prepare_vmcs12(vcpu, vmcs12);
cpu = get_cpu();
vmx->loaded_vmcs = &vmx->vmcs01;
vmx_vcpu_put(vcpu);
vmx_vcpu_load(vcpu, cpu);
vcpu->cpu = cpu;
put_cpu();
vmx_segment_cache_clear(vmx);
/* if no vmcs02 cache requested, remove the one we used */
if (VMCS02_POOL_SIZE == 0)
nested_free_vmcs02(vmx, vmx->nested.current_vmptr);
load_vmcs12_host_state(vcpu, vmcs12);
/* Update TSC_OFFSET if TSC was changed while L2 ran */
vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset);
/* This is needed for same reason as it was needed in prepare_vmcs02 */
vmx->host_rsp = 0;
/* Unpin physical memory we referred to in vmcs02 */
if (vmx->nested.apic_access_page) {
nested_release_page(vmx->nested.apic_access_page);
vmx->nested.apic_access_page = 0;
}
/*
* Exiting from L2 to L1, we're now back to L1 which thinks it just
* finished a VMLAUNCH or VMRESUME instruction, so we need to set the
* success or failure flag accordingly.
*/
if (unlikely(vmx->fail)) {
vmx->fail = 0;
nested_vmx_failValid(vcpu, vmcs_read32(VM_INSTRUCTION_ERROR));
} else
nested_vmx_succeed(vcpu);
if (enable_shadow_vmcs)
vmx->nested.sync_shadow_vmcs = true;
}
/*
* L1's failure to enter L2 is a subset of a normal exit, as explained in
* 23.7 "VM-entry failures during or after loading guest state" (this also
* lists the acceptable exit-reason and exit-qualification parameters).
* It should only be called before L2 actually succeeded to run, and when
* vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
*/
static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12,
u32 reason, unsigned long qualification)
{
load_vmcs12_host_state(vcpu, vmcs12);
vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
vmcs12->exit_qualification = qualification;
nested_vmx_succeed(vcpu);
if (enable_shadow_vmcs)
to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
}
static int vmx_check_intercept(struct kvm_vcpu *vcpu,
struct x86_instruction_info *info,
enum x86_intercept_stage stage)
{
return X86EMUL_CONTINUE;
}
static struct kvm_x86_ops vmx_x86_ops = {
.cpu_has_kvm_support = cpu_has_kvm_support,
.disabled_by_bios = vmx_disabled_by_bios,
.hardware_setup = hardware_setup,
.hardware_unsetup = hardware_unsetup,
.check_processor_compatibility = vmx_check_processor_compat,
.hardware_enable = hardware_enable,
.hardware_disable = hardware_disable,
.cpu_has_accelerated_tpr = report_flexpriority,
.vcpu_create = vmx_create_vcpu,
.vcpu_free = vmx_free_vcpu,
.vcpu_reset = vmx_vcpu_reset,
.prepare_guest_switch = vmx_save_host_state,
.vcpu_load = vmx_vcpu_load,
.vcpu_put = vmx_vcpu_put,
.update_db_bp_intercept = update_exception_bitmap,
.get_msr = vmx_get_msr,
.set_msr = vmx_set_msr,
.get_segment_base = vmx_get_segment_base,
.get_segment = vmx_get_segment,
.set_segment = vmx_set_segment,
.get_cpl = vmx_get_cpl,
.get_cs_db_l_bits = vmx_get_cs_db_l_bits,
.decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
.decache_cr3 = vmx_decache_cr3,
.decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
.set_cr0 = vmx_set_cr0,
.set_cr3 = vmx_set_cr3,
.set_cr4 = vmx_set_cr4,
.set_efer = vmx_set_efer,
.get_idt = vmx_get_idt,
.set_idt = vmx_set_idt,
.get_gdt = vmx_get_gdt,
.set_gdt = vmx_set_gdt,
.set_dr7 = vmx_set_dr7,
.cache_reg = vmx_cache_reg,
.get_rflags = vmx_get_rflags,
.set_rflags = vmx_set_rflags,
.fpu_activate = vmx_fpu_activate,
.fpu_deactivate = vmx_fpu_deactivate,
.tlb_flush = vmx_flush_tlb,
.run = vmx_vcpu_run,
.handle_exit = vmx_handle_exit,
.skip_emulated_instruction = skip_emulated_instruction,
.set_interrupt_shadow = vmx_set_interrupt_shadow,
.get_interrupt_shadow = vmx_get_interrupt_shadow,
.patch_hypercall = vmx_patch_hypercall,
.set_irq = vmx_inject_irq,
.set_nmi = vmx_inject_nmi,
.queue_exception = vmx_queue_exception,
.cancel_injection = vmx_cancel_injection,
.interrupt_allowed = vmx_interrupt_allowed,
.nmi_allowed = vmx_nmi_allowed,
.get_nmi_mask = vmx_get_nmi_mask,
.set_nmi_mask = vmx_set_nmi_mask,
.enable_nmi_window = enable_nmi_window,
.enable_irq_window = enable_irq_window,
.update_cr8_intercept = update_cr8_intercept,
.set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode,
.vm_has_apicv = vmx_vm_has_apicv,
.load_eoi_exitmap = vmx_load_eoi_exitmap,
.hwapic_irr_update = vmx_hwapic_irr_update,
.hwapic_isr_update = vmx_hwapic_isr_update,
.sync_pir_to_irr = vmx_sync_pir_to_irr,
.deliver_posted_interrupt = vmx_deliver_posted_interrupt,
.set_tss_addr = vmx_set_tss_addr,
.get_tdp_level = get_ept_level,
.get_mt_mask = vmx_get_mt_mask,
.get_exit_info = vmx_get_exit_info,
.get_lpage_level = vmx_get_lpage_level,
.cpuid_update = vmx_cpuid_update,
.rdtscp_supported = vmx_rdtscp_supported,
.invpcid_supported = vmx_invpcid_supported,
.set_supported_cpuid = vmx_set_supported_cpuid,
.has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
.set_tsc_khz = vmx_set_tsc_khz,
.read_tsc_offset = vmx_read_tsc_offset,
.write_tsc_offset = vmx_write_tsc_offset,
.adjust_tsc_offset = vmx_adjust_tsc_offset,
.compute_tsc_offset = vmx_compute_tsc_offset,
.read_l1_tsc = vmx_read_l1_tsc,
.set_tdp_cr3 = vmx_set_cr3,
.check_intercept = vmx_check_intercept,
.handle_external_intr = vmx_handle_external_intr,
};
static int __init vmx_init(void)
{
int r, i, msr;
rdmsrl_safe(MSR_EFER, &host_efer);
for (i = 0; i < NR_VMX_MSR; ++i)
kvm_define_shared_msr(i, vmx_msr_index[i]);
vmx_io_bitmap_a = (unsigned long *)__get_free_page(GFP_KERNEL);
if (!vmx_io_bitmap_a)
return -ENOMEM;
r = -ENOMEM;
vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
if (!vmx_io_bitmap_b)
goto out;
vmx_msr_bitmap_legacy = (unsigned long *)__get_free_page(GFP_KERNEL);
if (!vmx_msr_bitmap_legacy)
goto out1;
vmx_msr_bitmap_legacy_x2apic =
(unsigned long *)__get_free_page(GFP_KERNEL);
if (!vmx_msr_bitmap_legacy_x2apic)
goto out2;
vmx_msr_bitmap_longmode = (unsigned long *)__get_free_page(GFP_KERNEL);
if (!vmx_msr_bitmap_longmode)
goto out3;
vmx_msr_bitmap_longmode_x2apic =
(unsigned long *)__get_free_page(GFP_KERNEL);
if (!vmx_msr_bitmap_longmode_x2apic)
goto out4;
vmx_vmread_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
if (!vmx_vmread_bitmap)
goto out5;
vmx_vmwrite_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
if (!vmx_vmwrite_bitmap)
goto out6;
memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
/* shadowed read/write fields */
for (i = 0; i < max_shadow_read_write_fields; i++) {
clear_bit(shadow_read_write_fields[i], vmx_vmwrite_bitmap);
clear_bit(shadow_read_write_fields[i], vmx_vmread_bitmap);
}
/* shadowed read only fields */
for (i = 0; i < max_shadow_read_only_fields; i++)
clear_bit(shadow_read_only_fields[i], vmx_vmread_bitmap);
/*
* Allow direct access to the PC debug port (it is often used for I/O
* delays, but the vmexits simply slow things down).
*/
memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
clear_bit(0x80, vmx_io_bitmap_a);
memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE);
memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE);
set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
__alignof__(struct vcpu_vmx), THIS_MODULE);
if (r)
goto out7;
#ifdef CONFIG_KEXEC
rcu_assign_pointer(crash_vmclear_loaded_vmcss,
crash_vmclear_local_loaded_vmcss);
#endif
vmx_disable_intercept_for_msr(MSR_FS_BASE, false);
vmx_disable_intercept_for_msr(MSR_GS_BASE, false);
vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true);
vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false);
vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false);
vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false);
memcpy(vmx_msr_bitmap_legacy_x2apic,
vmx_msr_bitmap_legacy, PAGE_SIZE);
memcpy(vmx_msr_bitmap_longmode_x2apic,
vmx_msr_bitmap_longmode, PAGE_SIZE);
if (enable_apicv) {
for (msr = 0x800; msr <= 0x8ff; msr++)
vmx_disable_intercept_msr_read_x2apic(msr);
/* According SDM, in x2apic mode, the whole id reg is used.
* But in KVM, it only use the highest eight bits. Need to
* intercept it */
vmx_enable_intercept_msr_read_x2apic(0x802);
/* TMCCT */
vmx_enable_intercept_msr_read_x2apic(0x839);
/* TPR */
vmx_disable_intercept_msr_write_x2apic(0x808);
/* EOI */
vmx_disable_intercept_msr_write_x2apic(0x80b);
/* SELF-IPI */
vmx_disable_intercept_msr_write_x2apic(0x83f);
}
if (enable_ept) {
kvm_mmu_set_mask_ptes(0ull,
(enable_ept_ad_bits) ? VMX_EPT_ACCESS_BIT : 0ull,
(enable_ept_ad_bits) ? VMX_EPT_DIRTY_BIT : 0ull,
0ull, VMX_EPT_EXECUTABLE_MASK);
ept_set_mmio_spte_mask();
kvm_enable_tdp();
} else
kvm_disable_tdp();
return 0;
out7:
free_page((unsigned long)vmx_vmwrite_bitmap);
out6:
free_page((unsigned long)vmx_vmread_bitmap);
out5:
free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic);
out4:
free_page((unsigned long)vmx_msr_bitmap_longmode);
out3:
free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic);
out2:
free_page((unsigned long)vmx_msr_bitmap_legacy);
out1:
free_page((unsigned long)vmx_io_bitmap_b);
out:
free_page((unsigned long)vmx_io_bitmap_a);
return r;
}
static void __exit vmx_exit(void)
{
free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic);
free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic);
free_page((unsigned long)vmx_msr_bitmap_legacy);
free_page((unsigned long)vmx_msr_bitmap_longmode);
free_page((unsigned long)vmx_io_bitmap_b);
free_page((unsigned long)vmx_io_bitmap_a);
free_page((unsigned long)vmx_vmwrite_bitmap);
free_page((unsigned long)vmx_vmread_bitmap);
#ifdef CONFIG_KEXEC
rcu_assign_pointer(crash_vmclear_loaded_vmcss, NULL);
synchronize_rcu();
#endif
kvm_exit();
}
module_init(vmx_init)
module_exit(vmx_exit)
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2162_3 |
crossvul-cpp_data_good_3025_1 | /*
* IPP routines for the CUPS scheduler.
*
* Copyright 2007-2016 by Apple Inc.
* Copyright 1997-2007 by Easy Software Products, all rights reserved.
*
* This file contains Kerberos support code, copyright 2006 by
* Jelmer Vernooij.
*
* These coded instructions, statements, and computer programs are the
* property of Apple Inc. and are protected by Federal copyright
* law. Distribution and use rights are outlined in the file "LICENSE.txt"
* which should have been included with this file. If this file is
* missing or damaged, see the license at "http://www.cups.org/".
*/
/*
* Include necessary headers...
*/
#include "cupsd.h"
#include <cups/ppd-private.h>
#ifdef __APPLE__
/*# include <ApplicationServices/ApplicationServices.h>
extern CFUUIDRef ColorSyncCreateUUIDFromUInt32(unsigned id);
# include <CoreFoundation/CoreFoundation.h>*/
# ifdef HAVE_MEMBERSHIP_H
# include <membership.h>
# endif /* HAVE_MEMBERSHIP_H */
# ifdef HAVE_MEMBERSHIPPRIV_H
# include <membershipPriv.h>
# else
extern int mbr_user_name_to_uuid(const char* name, uuid_t uu);
extern int mbr_group_name_to_uuid(const char* name, uuid_t uu);
extern int mbr_check_membership_by_id(uuid_t user, gid_t group, int* ismember);
# endif /* HAVE_MEMBERSHIPPRIV_H */
#endif /* __APPLE__ */
/*
* Local functions...
*/
static void accept_jobs(cupsd_client_t *con, ipp_attribute_t *uri);
static void add_class(cupsd_client_t *con, ipp_attribute_t *uri);
static int add_file(cupsd_client_t *con, cupsd_job_t *job,
mime_type_t *filetype, int compression);
static cupsd_job_t *add_job(cupsd_client_t *con, cupsd_printer_t *printer,
mime_type_t *filetype);
static void add_job_subscriptions(cupsd_client_t *con, cupsd_job_t *job);
static void add_job_uuid(cupsd_job_t *job);
static void add_printer(cupsd_client_t *con, ipp_attribute_t *uri);
static void add_printer_state_reasons(cupsd_client_t *con,
cupsd_printer_t *p);
static void add_queued_job_count(cupsd_client_t *con, cupsd_printer_t *p);
static void apply_printer_defaults(cupsd_printer_t *printer,
cupsd_job_t *job);
static void authenticate_job(cupsd_client_t *con, ipp_attribute_t *uri);
static void cancel_all_jobs(cupsd_client_t *con, ipp_attribute_t *uri);
static void cancel_job(cupsd_client_t *con, ipp_attribute_t *uri);
static void cancel_subscription(cupsd_client_t *con, int id);
static int check_rss_recipient(const char *recipient);
static int check_quotas(cupsd_client_t *con, cupsd_printer_t *p);
static void close_job(cupsd_client_t *con, ipp_attribute_t *uri);
static void copy_attrs(ipp_t *to, ipp_t *from, cups_array_t *ra,
ipp_tag_t group, int quickcopy,
cups_array_t *exclude);
static int copy_banner(cupsd_client_t *con, cupsd_job_t *job,
const char *name);
static int copy_file(const char *from, const char *to, mode_t mode);
static int copy_model(cupsd_client_t *con, const char *from,
const char *to);
static void copy_job_attrs(cupsd_client_t *con,
cupsd_job_t *job,
cups_array_t *ra, cups_array_t *exclude);
static void copy_printer_attrs(cupsd_client_t *con,
cupsd_printer_t *printer,
cups_array_t *ra);
static void copy_subscription_attrs(cupsd_client_t *con,
cupsd_subscription_t *sub,
cups_array_t *ra,
cups_array_t *exclude);
static void create_job(cupsd_client_t *con, ipp_attribute_t *uri);
static void create_local_printer(cupsd_client_t *con);
static cups_array_t *create_requested_array(ipp_t *request);
static void create_subscriptions(cupsd_client_t *con, ipp_attribute_t *uri);
static void delete_printer(cupsd_client_t *con, ipp_attribute_t *uri);
static void get_default(cupsd_client_t *con);
static void get_devices(cupsd_client_t *con);
static void get_document(cupsd_client_t *con, ipp_attribute_t *uri);
static void get_jobs(cupsd_client_t *con, ipp_attribute_t *uri);
static void get_job_attrs(cupsd_client_t *con, ipp_attribute_t *uri);
static void get_notifications(cupsd_client_t *con);
static void get_ppd(cupsd_client_t *con, ipp_attribute_t *uri);
static void get_ppds(cupsd_client_t *con);
static void get_printers(cupsd_client_t *con, int type);
static void get_printer_attrs(cupsd_client_t *con, ipp_attribute_t *uri);
static void get_printer_supported(cupsd_client_t *con, ipp_attribute_t *uri);
static void get_subscription_attrs(cupsd_client_t *con, int sub_id);
static void get_subscriptions(cupsd_client_t *con, ipp_attribute_t *uri);
static const char *get_username(cupsd_client_t *con);
static void hold_job(cupsd_client_t *con, ipp_attribute_t *uri);
static void hold_new_jobs(cupsd_client_t *con, ipp_attribute_t *uri);
static void move_job(cupsd_client_t *con, ipp_attribute_t *uri);
static int ppd_parse_line(const char *line, char *option, int olen,
char *choice, int clen);
static void print_job(cupsd_client_t *con, ipp_attribute_t *uri);
static void read_job_ticket(cupsd_client_t *con);
static void reject_jobs(cupsd_client_t *con, ipp_attribute_t *uri);
static void release_held_new_jobs(cupsd_client_t *con,
ipp_attribute_t *uri);
static void release_job(cupsd_client_t *con, ipp_attribute_t *uri);
static void renew_subscription(cupsd_client_t *con, int sub_id);
static void restart_job(cupsd_client_t *con, ipp_attribute_t *uri);
static void save_auth_info(cupsd_client_t *con, cupsd_job_t *job,
ipp_attribute_t *auth_info);
static void send_document(cupsd_client_t *con, ipp_attribute_t *uri);
static void send_http_error(cupsd_client_t *con, http_status_t status,
cupsd_printer_t *printer);
static void send_ipp_status(cupsd_client_t *con, ipp_status_t status,
const char *message, ...)
__attribute__((__format__(__printf__, 3, 4)));
static void set_default(cupsd_client_t *con, ipp_attribute_t *uri);
static void set_job_attrs(cupsd_client_t *con, ipp_attribute_t *uri);
static void set_printer_attrs(cupsd_client_t *con, ipp_attribute_t *uri);
static int set_printer_defaults(cupsd_client_t *con, cupsd_printer_t *printer);
static void start_printer(cupsd_client_t *con, ipp_attribute_t *uri);
static void stop_printer(cupsd_client_t *con, ipp_attribute_t *uri);
static void url_encode_attr(ipp_attribute_t *attr, char *buffer, size_t bufsize);
static char *url_encode_string(const char *s, char *buffer, size_t bufsize);
static int user_allowed(cupsd_printer_t *p, const char *username);
static void validate_job(cupsd_client_t *con, ipp_attribute_t *uri);
static int validate_name(const char *name);
static int validate_user(cupsd_job_t *job, cupsd_client_t *con, const char *owner, char *username, size_t userlen);
/*
* 'cupsdProcessIPPRequest()' - Process an incoming IPP request.
*/
int /* O - 1 on success, 0 on failure */
cupsdProcessIPPRequest(
cupsd_client_t *con) /* I - Client connection */
{
ipp_tag_t group; /* Current group tag */
ipp_attribute_t *attr; /* Current attribute */
ipp_attribute_t *charset; /* Character set attribute */
ipp_attribute_t *language; /* Language attribute */
ipp_attribute_t *uri = NULL; /* Printer or job URI attribute */
ipp_attribute_t *username; /* requesting-user-name attr */
int sub_id; /* Subscription ID */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdProcessIPPRequest(%p[%d]): operation_id=%04x(%s)", con, con->number, con->request->request.op.operation_id, ippOpString(con->request->request.op.operation_id));
if (LogLevel >= CUPSD_LOG_DEBUG2)
{
for (group = IPP_TAG_ZERO, attr = ippFirstAttribute(con->request); attr; attr = ippNextAttribute(con->request))
{
const char *name; /* Attribute name */
char value[1024]; /* Attribute value */
if (group != ippGetGroupTag(attr))
{
group = ippGetGroupTag(attr);
if (group != IPP_TAG_ZERO)
cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdProcessIPPRequest: %s", ippTagString(group));
}
if ((name = ippGetName(attr)) == NULL)
continue;
ippAttributeString(attr, value, sizeof(value));
cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdProcessIPPRequest: %s %s%s '%s'", name, ippGetCount(attr) > 1 ? "1setOf " : "", ippTagString(ippGetValueTag(attr)), value);
}
}
/*
* First build an empty response message for this request...
*/
con->response = ippNew();
con->response->request.status.version[0] =
con->request->request.op.version[0];
con->response->request.status.version[1] =
con->request->request.op.version[1];
con->response->request.status.request_id =
con->request->request.op.request_id;
/*
* Then validate the request header and required attributes...
*/
if (con->request->request.any.version[0] != 1 &&
con->request->request.any.version[0] != 2)
{
/*
* Return an error, since we only support IPP 1.x and 2.x.
*/
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s Bad request version number %d.%d",
IPP_VERSION_NOT_SUPPORTED, con->http->hostname,
con->request->request.any.version[0],
con->request->request.any.version[1]);
send_ipp_status(con, IPP_VERSION_NOT_SUPPORTED,
_("Bad request version number %d.%d."),
con->request->request.any.version[0],
con->request->request.any.version[1]);
}
else if (con->request->request.any.request_id < 1)
{
/*
* Return an error, since request IDs must be between 1 and 2^31-1
*/
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s Bad request ID %d",
IPP_BAD_REQUEST, con->http->hostname,
con->request->request.any.request_id);
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad request ID %d."),
con->request->request.any.request_id);
}
else if (!con->request->attrs)
{
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s No attributes in request",
IPP_BAD_REQUEST, con->http->hostname);
send_ipp_status(con, IPP_BAD_REQUEST, _("No attributes in request."));
}
else
{
/*
* Make sure that the attributes are provided in the correct order and
* don't repeat groups...
*/
for (attr = con->request->attrs, group = attr->group_tag;
attr;
attr = attr->next)
if (attr->group_tag < group && attr->group_tag != IPP_TAG_ZERO)
{
/*
* Out of order; return an error...
*/
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s Attribute groups are out of order",
IPP_BAD_REQUEST, con->http->hostname);
send_ipp_status(con, IPP_BAD_REQUEST,
_("Attribute groups are out of order (%x < %x)."),
attr->group_tag, group);
break;
}
else
group = attr->group_tag;
if (!attr)
{
/*
* Then make sure that the first three attributes are:
*
* attributes-charset
* attributes-natural-language
* printer-uri/job-uri
*/
attr = con->request->attrs;
if (attr && attr->name &&
!strcmp(attr->name, "attributes-charset") &&
(attr->value_tag & IPP_TAG_MASK) == IPP_TAG_CHARSET)
charset = attr;
else
charset = NULL;
if (attr)
attr = attr->next;
if (attr && attr->name &&
!strcmp(attr->name, "attributes-natural-language") &&
(attr->value_tag & IPP_TAG_MASK) == IPP_TAG_LANGUAGE)
{
language = attr;
/*
* Reset language for this request if different from Accept-Language.
*/
if (!con->language ||
strcmp(attr->values[0].string.text, con->language->language))
{
cupsLangFree(con->language);
con->language = cupsLangGet(attr->values[0].string.text);
}
}
else
language = NULL;
if ((attr = ippFindAttribute(con->request, "printer-uri",
IPP_TAG_URI)) != NULL)
uri = attr;
else if ((attr = ippFindAttribute(con->request, "job-uri",
IPP_TAG_URI)) != NULL)
uri = attr;
else if (con->request->request.op.operation_id == CUPS_GET_PPD)
uri = ippFindAttribute(con->request, "ppd-name", IPP_TAG_NAME);
else
uri = NULL;
if (charset)
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
"attributes-charset", NULL,
charset->values[0].string.text);
else
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
"attributes-charset", NULL, "utf-8");
if (language)
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
"attributes-natural-language", NULL,
language->values[0].string.text);
else
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
"attributes-natural-language", NULL, DefaultLanguage);
if (charset &&
_cups_strcasecmp(charset->values[0].string.text, "us-ascii") &&
_cups_strcasecmp(charset->values[0].string.text, "utf-8"))
{
/*
* Bad character set...
*/
cupsdLogMessage(CUPSD_LOG_ERROR, "Unsupported character set \"%s\"",
charset->values[0].string.text);
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s Unsupported attributes-charset value \"%s\"",
IPP_CHARSET, con->http->hostname,
charset->values[0].string.text);
send_ipp_status(con, IPP_BAD_REQUEST,
_("Unsupported character set \"%s\"."),
charset->values[0].string.text);
}
else if (!charset || !language ||
(!uri &&
con->request->request.op.operation_id != CUPS_GET_DEFAULT &&
con->request->request.op.operation_id != CUPS_GET_PRINTERS &&
con->request->request.op.operation_id != CUPS_GET_CLASSES &&
con->request->request.op.operation_id != CUPS_GET_DEVICES &&
con->request->request.op.operation_id != CUPS_GET_PPDS))
{
/*
* Return an error, since attributes-charset,
* attributes-natural-language, and printer-uri/job-uri are required
* for all operations.
*/
if (!charset)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Missing attributes-charset attribute");
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s Missing attributes-charset attribute",
IPP_BAD_REQUEST, con->http->hostname);
}
if (!language)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Missing attributes-natural-language attribute");
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s Missing attributes-natural-language attribute",
IPP_BAD_REQUEST, con->http->hostname);
}
if (!uri)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Missing printer-uri, job-uri, or ppd-name "
"attribute");
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s Missing printer-uri, job-uri, or ppd-name "
"attribute", IPP_BAD_REQUEST, con->http->hostname);
}
cupsdLogMessage(CUPSD_LOG_DEBUG, "Request attributes follow...");
for (attr = con->request->attrs; attr; attr = attr->next)
cupsdLogMessage(CUPSD_LOG_DEBUG,
"attr \"%s\": group_tag = %x, value_tag = %x",
attr->name ? attr->name : "(null)", attr->group_tag,
attr->value_tag);
cupsdLogMessage(CUPSD_LOG_DEBUG, "End of attributes...");
send_ipp_status(con, IPP_BAD_REQUEST,
_("Missing required attributes."));
}
else
{
/*
* OK, all the checks pass so far; make sure requesting-user-name is
* not "root" from a remote host...
*/
if ((username = ippFindAttribute(con->request, "requesting-user-name",
IPP_TAG_NAME)) != NULL)
{
/*
* Check for root user...
*/
if (!strcmp(username->values[0].string.text, "root") &&
_cups_strcasecmp(con->http->hostname, "localhost") &&
strcmp(con->username, "root"))
{
/*
* Remote unauthenticated user masquerading as local root...
*/
ippSetString(con->request, &username, 0, RemoteRoot);
}
}
if ((attr = ippFindAttribute(con->request, "notify-subscription-id",
IPP_TAG_INTEGER)) != NULL)
sub_id = attr->values[0].integer;
else
sub_id = 0;
/*
* Then try processing the operation...
*/
if (uri)
cupsdLogMessage(CUPSD_LOG_DEBUG, "%s %s",
ippOpString(con->request->request.op.operation_id),
uri->values[0].string.text);
else
cupsdLogMessage(CUPSD_LOG_DEBUG, "%s",
ippOpString(con->request->request.op.operation_id));
switch (con->request->request.op.operation_id)
{
case IPP_OP_PRINT_JOB :
print_job(con, uri);
break;
case IPP_OP_VALIDATE_JOB :
validate_job(con, uri);
break;
case IPP_OP_CREATE_JOB :
create_job(con, uri);
break;
case IPP_OP_SEND_DOCUMENT :
send_document(con, uri);
break;
case IPP_OP_CANCEL_JOB :
cancel_job(con, uri);
break;
case IPP_OP_GET_JOB_ATTRIBUTES :
get_job_attrs(con, uri);
break;
case IPP_OP_GET_JOBS :
get_jobs(con, uri);
break;
case IPP_OP_GET_PRINTER_ATTRIBUTES :
get_printer_attrs(con, uri);
break;
case IPP_OP_GET_PRINTER_SUPPORTED_VALUES :
get_printer_supported(con, uri);
break;
case IPP_OP_HOLD_JOB :
hold_job(con, uri);
break;
case IPP_OP_RELEASE_JOB :
release_job(con, uri);
break;
case IPP_OP_RESTART_JOB :
restart_job(con, uri);
break;
case IPP_OP_PAUSE_PRINTER :
stop_printer(con, uri);
break;
case IPP_OP_RESUME_PRINTER :
start_printer(con, uri);
break;
case IPP_OP_PURGE_JOBS :
case IPP_OP_CANCEL_JOBS :
case IPP_OP_CANCEL_MY_JOBS :
cancel_all_jobs(con, uri);
break;
case IPP_OP_SET_JOB_ATTRIBUTES :
set_job_attrs(con, uri);
break;
case IPP_OP_SET_PRINTER_ATTRIBUTES :
set_printer_attrs(con, uri);
break;
case IPP_OP_HOLD_NEW_JOBS :
hold_new_jobs(con, uri);
break;
case IPP_OP_RELEASE_HELD_NEW_JOBS :
release_held_new_jobs(con, uri);
break;
case IPP_OP_CLOSE_JOB :
close_job(con, uri);
break;
case IPP_OP_CUPS_GET_DEFAULT :
get_default(con);
break;
case IPP_OP_CUPS_GET_PRINTERS :
get_printers(con, 0);
break;
case IPP_OP_CUPS_GET_CLASSES :
get_printers(con, CUPS_PRINTER_CLASS);
break;
case IPP_OP_CUPS_ADD_MODIFY_PRINTER :
add_printer(con, uri);
break;
case IPP_OP_CUPS_DELETE_PRINTER :
delete_printer(con, uri);
break;
case IPP_OP_CUPS_ADD_MODIFY_CLASS :
add_class(con, uri);
break;
case IPP_OP_CUPS_DELETE_CLASS :
delete_printer(con, uri);
break;
case IPP_OP_CUPS_ACCEPT_JOBS :
case IPP_OP_ENABLE_PRINTER :
accept_jobs(con, uri);
break;
case IPP_OP_CUPS_REJECT_JOBS :
case IPP_OP_DISABLE_PRINTER :
reject_jobs(con, uri);
break;
case IPP_OP_CUPS_SET_DEFAULT :
set_default(con, uri);
break;
case IPP_OP_CUPS_GET_DEVICES :
get_devices(con);
break;
case IPP_OP_CUPS_GET_DOCUMENT :
get_document(con, uri);
break;
case IPP_OP_CUPS_GET_PPD :
get_ppd(con, uri);
break;
case IPP_OP_CUPS_GET_PPDS :
get_ppds(con);
break;
case IPP_OP_CUPS_MOVE_JOB :
move_job(con, uri);
break;
case IPP_OP_CUPS_AUTHENTICATE_JOB :
authenticate_job(con, uri);
break;
case IPP_OP_CREATE_PRINTER_SUBSCRIPTIONS :
case IPP_OP_CREATE_JOB_SUBSCRIPTIONS :
create_subscriptions(con, uri);
break;
case IPP_OP_GET_SUBSCRIPTION_ATTRIBUTES :
get_subscription_attrs(con, sub_id);
break;
case IPP_OP_GET_SUBSCRIPTIONS :
get_subscriptions(con, uri);
break;
case IPP_OP_RENEW_SUBSCRIPTION :
renew_subscription(con, sub_id);
break;
case IPP_OP_CANCEL_SUBSCRIPTION :
cancel_subscription(con, sub_id);
break;
case IPP_OP_GET_NOTIFICATIONS :
get_notifications(con);
break;
case IPP_OP_CUPS_CREATE_LOCAL_PRINTER :
create_local_printer(con);
break;
default :
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s Operation %04X (%s) not supported",
IPP_OPERATION_NOT_SUPPORTED, con->http->hostname,
con->request->request.op.operation_id,
ippOpString(con->request->request.op.operation_id));
send_ipp_status(con, IPP_OPERATION_NOT_SUPPORTED,
_("%s not supported."),
ippOpString(
con->request->request.op.operation_id));
break;
}
}
}
}
if (con->response)
{
/*
* Sending data from the scheduler...
*/
cupsdLogMessage(con->response->request.status.status_code
>= IPP_BAD_REQUEST &&
con->response->request.status.status_code
!= IPP_NOT_FOUND ? CUPSD_LOG_ERROR : CUPSD_LOG_DEBUG,
"[Client %d] Returning IPP %s for %s (%s) from %s",
con->number,
ippErrorString(con->response->request.status.status_code),
ippOpString(con->request->request.op.operation_id),
uri ? uri->values[0].string.text : "no URI",
con->http->hostname);
httpClearFields(con->http);
#ifdef CUPSD_USE_CHUNKING
/*
* Because older versions of CUPS (1.1.17 and older) and some IPP
* clients do not implement chunking properly, we cannot use
* chunking by default. This may become the default in future
* CUPS releases, or we might add a configuration directive for
* it.
*/
if (con->http->version == HTTP_1_1)
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"[Client %d] Transfer-Encoding: chunked",
con->number);
cupsdSetLength(con->http, 0);
}
else
#endif /* CUPSD_USE_CHUNKING */
{
size_t length; /* Length of response */
length = ippLength(con->response);
if (con->file >= 0 && !con->pipe_pid)
{
struct stat fileinfo; /* File information */
if (!fstat(con->file, &fileinfo))
length += (size_t)fileinfo.st_size;
}
cupsdLogMessage(CUPSD_LOG_DEBUG,
"[Client %d] Content-Length: " CUPS_LLFMT,
con->number, CUPS_LLCAST length);
httpSetLength(con->http, length);
}
if (cupsdSendHeader(con, HTTP_OK, "application/ipp", CUPSD_AUTH_NONE))
{
/*
* Tell the caller the response header was sent successfully...
*/
cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient,
(cupsd_selfunc_t)cupsdWriteClient, con);
return (1);
}
else
{
/*
* Tell the caller the response header could not be sent...
*/
return (0);
}
}
else
{
/*
* Sending data from a subprocess like cups-deviced; tell the caller
* everything is A-OK so far...
*/
return (1);
}
}
/*
* 'cupsdTimeoutJob()' - Timeout a job waiting on job files.
*/
int /* O - 0 on success, -1 on error */
cupsdTimeoutJob(cupsd_job_t *job) /* I - Job to timeout */
{
cupsd_printer_t *printer; /* Destination printer or class */
ipp_attribute_t *attr; /* job-sheets attribute */
int kbytes; /* Kilobytes in banner */
job->pending_timeout = 0;
/*
* See if we need to add the ending sheet...
*/
if (!cupsdLoadJob(job))
return (-1);
printer = cupsdFindDest(job->dest);
attr = ippFindAttribute(job->attrs, "job-sheets", IPP_TAG_NAME);
if (printer && !(printer->type & CUPS_PRINTER_REMOTE) &&
attr && attr->num_values > 1)
{
/*
* Yes...
*/
cupsdLogJob(job, CUPSD_LOG_INFO, "Adding end banner page \"%s\".",
attr->values[1].string.text);
if ((kbytes = copy_banner(NULL, job, attr->values[1].string.text)) < 0)
return (-1);
cupsdUpdateQuota(printer, job->username, 0, kbytes);
}
return (0);
}
/*
* 'accept_jobs()' - Accept print jobs to a printer.
*/
static void
accept_jobs(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer or class URI */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer data */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "accept_jobs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Accept jobs sent to the printer...
*/
printer->accepting = 1;
printer->state_message[0] = '\0';
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, printer, NULL,
"Now accepting jobs.");
if (dtype & CUPS_PRINTER_CLASS)
{
cupsdMarkDirty(CUPSD_DIRTY_CLASSES);
cupsdLogMessage(CUPSD_LOG_INFO, "Class \"%s\" now accepting jobs (\"%s\").",
printer->name, get_username(con));
}
else
{
cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
cupsdLogMessage(CUPSD_LOG_INFO,
"Printer \"%s\" now accepting jobs (\"%s\").",
printer->name, get_username(con));
}
/*
* Everything was ok, so return OK status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'add_class()' - Add a class to the system.
*/
static void
add_class(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - URI of class */
{
http_status_t status; /* Policy status */
int i; /* Looping var */
char scheme[HTTP_MAX_URI], /* Method portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
cupsd_printer_t *pclass, /* Class */
*member; /* Member printer/class */
cups_ptype_t dtype; /* Destination type */
ipp_attribute_t *attr; /* Printer attribute */
int modify; /* Non-zero if we just modified */
int need_restart_job; /* Need to restart job? */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "add_class(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Do we have a valid URI?
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/classes/", 9) || strlen(resource) == 9)
{
/*
* No, return an error...
*/
send_ipp_status(con, IPP_BAD_REQUEST,
_("The printer-uri must be of the form "
"\"ipp://HOSTNAME/classes/CLASSNAME\"."));
return;
}
/*
* Do we have a valid printer name?
*/
if (!validate_name(resource + 9))
{
/*
* No, return an error...
*/
send_ipp_status(con, IPP_BAD_REQUEST,
_("The printer-uri \"%s\" contains invalid characters."),
uri->values[0].string.text);
return;
}
/*
* See if the class already exists; if not, create a new class...
*/
if ((pclass = cupsdFindClass(resource + 9)) == NULL)
{
/*
* Class doesn't exist; see if we have a printer of the same name...
*/
if ((pclass = cupsdFindPrinter(resource + 9)) != NULL)
{
/*
* Yes, return an error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("A printer named \"%s\" already exists."),
resource + 9);
return;
}
/*
* No, check the default policy and then add the class...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
pclass = cupsdAddClass(resource + 9);
modify = 0;
}
else if ((status = cupsdCheckPolicy(pclass->op_policy_ptr, con,
NULL)) != HTTP_OK)
{
send_http_error(con, status, pclass);
return;
}
else
modify = 1;
/*
* Look for attributes and copy them over as needed...
*/
need_restart_job = 0;
if ((attr = ippFindAttribute(con->request, "printer-location", IPP_TAG_TEXT)) != NULL)
cupsdSetString(&pclass->location, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-geo-location", IPP_TAG_URI)) != NULL && !strncmp(attr->values[0].string.text, "geo:", 4))
cupsdSetString(&pclass->geo_location, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-organization", IPP_TAG_TEXT)) != NULL)
cupsdSetString(&pclass->organization, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-organizational-unit", IPP_TAG_TEXT)) != NULL)
cupsdSetString(&pclass->organizational_unit, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-info",
IPP_TAG_TEXT)) != NULL)
cupsdSetString(&pclass->info, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-is-accepting-jobs",
IPP_TAG_BOOLEAN)) != NULL &&
attr->values[0].boolean != pclass->accepting)
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Setting %s printer-is-accepting-jobs to %d (was %d.)",
pclass->name, attr->values[0].boolean, pclass->accepting);
pclass->accepting = attr->values[0].boolean;
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, pclass, NULL, "%s accepting jobs.",
pclass->accepting ? "Now" : "No longer");
}
if ((attr = ippFindAttribute(con->request, "printer-is-shared", IPP_TAG_BOOLEAN)) != NULL)
{
if (pclass->type & CUPS_PRINTER_REMOTE)
{
/*
* Cannot re-share remote printers.
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Cannot change printer-is-shared for remote queues."));
if (!modify)
cupsdDeletePrinter(pclass, 0);
return;
}
if (pclass->shared && !ippGetBoolean(attr, 0))
cupsdDeregisterPrinter(pclass, 1);
cupsdLogMessage(CUPSD_LOG_INFO,
"Setting %s printer-is-shared to %d (was %d.)",
pclass->name, attr->values[0].boolean, pclass->shared);
pclass->shared = ippGetBoolean(attr, 0);
}
if ((attr = ippFindAttribute(con->request, "printer-state",
IPP_TAG_ENUM)) != NULL)
{
if (attr->values[0].integer != IPP_PRINTER_IDLE &&
attr->values[0].integer != IPP_PRINTER_STOPPED)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Attempt to set %s printer-state to bad value %d."),
pclass->name, attr->values[0].integer);
if (!modify)
cupsdDeletePrinter(pclass, 0);
return;
}
cupsdLogMessage(CUPSD_LOG_INFO, "Setting %s printer-state to %d (was %d.)",
pclass->name, attr->values[0].integer, pclass->state);
if (attr->values[0].integer == IPP_PRINTER_STOPPED)
cupsdStopPrinter(pclass, 0);
else
{
cupsdSetPrinterState(pclass, (ipp_pstate_t)(attr->values[0].integer), 0);
need_restart_job = 1;
}
}
if ((attr = ippFindAttribute(con->request, "printer-state-message",
IPP_TAG_TEXT)) != NULL)
{
strlcpy(pclass->state_message, attr->values[0].string.text,
sizeof(pclass->state_message));
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, pclass, NULL, "%s",
pclass->state_message);
}
if ((attr = ippFindAttribute(con->request, "member-uris",
IPP_TAG_URI)) != NULL)
{
/*
* Clear the printer array as needed...
*/
need_restart_job = 1;
if (pclass->num_printers > 0)
{
free(pclass->printers);
pclass->num_printers = 0;
}
/*
* Add each printer or class that is listed...
*/
for (i = 0; i < attr->num_values; i ++)
{
/*
* Search for the printer or class URI...
*/
if (!cupsdValidateDest(attr->values[i].string.text, &dtype, &member))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
if (!modify)
cupsdDeletePrinter(pclass, 0);
return;
}
else if (dtype & CUPS_PRINTER_CLASS)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Nested classes are not allowed."));
if (!modify)
cupsdDeletePrinter(pclass, 0);
return;
}
/*
* Add it to the class...
*/
cupsdAddPrinterToClass(pclass, member);
}
}
if (!set_printer_defaults(con, pclass))
{
if (!modify)
cupsdDeletePrinter(pclass, 0);
return;
}
if ((attr = ippFindAttribute(con->request, "auth-info-required",
IPP_TAG_KEYWORD)) != NULL)
cupsdSetAuthInfoRequired(pclass, NULL, attr);
pclass->config_time = time(NULL);
/*
* Update the printer class attributes and return...
*/
cupsdSetPrinterAttrs(pclass);
cupsdMarkDirty(CUPSD_DIRTY_CLASSES);
if (need_restart_job && pclass->job)
{
/*
* Reset the current job to a "pending" status...
*/
cupsdSetJobState(pclass->job, IPP_JOB_PENDING, CUPSD_JOB_FORCE,
"Job restarted because the class was modified.");
}
cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP);
if (modify)
{
cupsdAddEvent(CUPSD_EVENT_PRINTER_MODIFIED,
pclass, NULL, "Class \"%s\" modified by \"%s\".",
pclass->name, get_username(con));
cupsdLogMessage(CUPSD_LOG_INFO, "Class \"%s\" modified by \"%s\".",
pclass->name, get_username(con));
}
else
{
cupsdAddEvent(CUPSD_EVENT_PRINTER_ADDED,
pclass, NULL, "New class \"%s\" added by \"%s\".",
pclass->name, get_username(con));
cupsdLogMessage(CUPSD_LOG_INFO, "New class \"%s\" added by \"%s\".",
pclass->name, get_username(con));
}
con->response->request.status.status_code = IPP_OK;
}
/*
* 'add_file()' - Add a file to a job.
*/
static int /* O - 0 on success, -1 on error */
add_file(cupsd_client_t *con, /* I - Connection to client */
cupsd_job_t *job, /* I - Job to add to */
mime_type_t *filetype, /* I - Type of file */
int compression) /* I - Compression */
{
mime_type_t **filetypes; /* New filetypes array... */
int *compressions; /* New compressions array... */
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"add_file(con=%p[%d], job=%d, filetype=%s/%s, "
"compression=%d)", con, con ? con->number : -1, job->id,
filetype->super, filetype->type, compression);
/*
* Add the file to the job...
*/
if (job->num_files == 0)
{
compressions = (int *)malloc(sizeof(int));
filetypes = (mime_type_t **)malloc(sizeof(mime_type_t *));
}
else
{
compressions = (int *)realloc(job->compressions,
(size_t)(job->num_files + 1) * sizeof(int));
filetypes = (mime_type_t **)realloc(job->filetypes,
(size_t)(job->num_files + 1) *
sizeof(mime_type_t *));
}
if (compressions)
job->compressions = compressions;
if (filetypes)
job->filetypes = filetypes;
if (!compressions || !filetypes)
{
cupsdSetJobState(job, IPP_JOB_ABORTED, CUPSD_JOB_PURGE,
"Job aborted because the scheduler ran out of memory.");
if (con)
send_ipp_status(con, IPP_INTERNAL_ERROR,
_("Unable to allocate memory for file types."));
return (-1);
}
job->compressions[job->num_files] = compression;
job->filetypes[job->num_files] = filetype;
job->num_files ++;
job->dirty = 1;
cupsdMarkDirty(CUPSD_DIRTY_JOBS);
return (0);
}
/*
* 'add_job()' - Add a job to a print queue.
*/
static cupsd_job_t * /* O - Job object */
add_job(cupsd_client_t *con, /* I - Client connection */
cupsd_printer_t *printer, /* I - Destination printer */
mime_type_t *filetype) /* I - First print file type, if any */
{
http_status_t status; /* Policy status */
ipp_attribute_t *attr, /* Current attribute */
*auth_info; /* auth-info attribute */
const char *mandatory; /* Current mandatory job attribute */
const char *val; /* Default option value */
int priority; /* Job priority */
cupsd_job_t *job; /* Current job */
char job_uri[HTTP_MAX_URI]; /* Job URI */
int kbytes; /* Size of print file */
int i; /* Looping var */
int lowerpagerange; /* Page range bound */
int exact; /* Did we have an exact match? */
ipp_attribute_t *media_col, /* media-col attribute */
*media_margin; /* media-*-margin attribute */
ipp_t *unsup_col; /* media-col in unsupported response */
static const char * const readonly[] =/* List of read-only attributes */
{
"date-time-at-completed",
"date-time-at-creation",
"date-time-at-processing",
"job-detailed-status-messages",
"job-document-access-errors",
"job-id",
"job-impressions-completed",
"job-k-octets-completed",
"job-media-sheets-completed",
"job-pages-completed",
"job-printer-up-time",
"job-printer-uri",
"job-state",
"job-state-message",
"job-state-reasons",
"job-uri",
"number-of-documents",
"number-of-intervening-jobs",
"output-device-assigned",
"time-at-completed",
"time-at-creation",
"time-at-processing"
};
cupsdLogMessage(CUPSD_LOG_DEBUG2, "add_job(%p[%d], %p(%s), %p(%s/%s))",
con, con->number, printer, printer->name,
filetype, filetype ? filetype->super : "none",
filetype ? filetype->type : "none");
/*
* Check remote printing to non-shared printer...
*/
if (!printer->shared &&
_cups_strcasecmp(con->http->hostname, "localhost") &&
_cups_strcasecmp(con->http->hostname, ServerName))
{
send_ipp_status(con, IPP_NOT_AUTHORIZED,
_("The printer or class is not shared."));
return (NULL);
}
/*
* Check policy...
*/
auth_info = ippFindAttribute(con->request, "auth-info", IPP_TAG_TEXT);
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return (NULL);
}
else if (printer->num_auth_info_required == 1 &&
!strcmp(printer->auth_info_required[0], "negotiate") &&
!con->username[0])
{
send_http_error(con, HTTP_UNAUTHORIZED, printer);
return (NULL);
}
#ifdef HAVE_SSL
else if (auth_info && !con->http->tls &&
!httpAddrLocalhost(con->http->hostaddr))
{
/*
* Require encryption of auth-info over non-local connections...
*/
send_http_error(con, HTTP_UPGRADE_REQUIRED, printer);
return (NULL);
}
#endif /* HAVE_SSL */
/*
* See if the printer is accepting jobs...
*/
if (!printer->accepting)
{
send_ipp_status(con, IPP_NOT_ACCEPTING,
_("Destination \"%s\" is not accepting jobs."),
printer->name);
return (NULL);
}
/*
* Validate job template attributes; for now just document-format,
* copies, job-sheets, number-up, page-ranges, mandatory attributes, and
* media...
*/
for (i = 0; i < (int)(sizeof(readonly) / sizeof(readonly[0])); i ++)
{
if ((attr = ippFindAttribute(con->request, readonly[i], IPP_TAG_ZERO)) != NULL)
{
ippDeleteAttribute(con->request, attr);
if (StrictConformance)
{
send_ipp_status(con, IPP_BAD_REQUEST, _("The '%s' Job Status attribute cannot be supplied in a job creation request."), readonly[i]);
return (NULL);
}
cupsdLogMessage(CUPSD_LOG_INFO, "Unexpected '%s' Job Status attribute in a job creation request.", readonly[i]);
}
}
if (printer->pc)
{
for (mandatory = (char *)cupsArrayFirst(printer->pc->mandatory);
mandatory;
mandatory = (char *)cupsArrayNext(printer->pc->mandatory))
{
if (!ippFindAttribute(con->request, mandatory, IPP_TAG_ZERO))
{
/*
* Missing a required attribute...
*/
send_ipp_status(con, IPP_CONFLICT,
_("The \"%s\" attribute is required for print jobs."),
mandatory);
return (NULL);
}
}
}
if (filetype && printer->filetypes &&
!cupsArrayFind(printer->filetypes, filetype))
{
char mimetype[MIME_MAX_SUPER + MIME_MAX_TYPE + 2];
/* MIME media type string */
snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super,
filetype->type);
send_ipp_status(con, IPP_DOCUMENT_FORMAT,
_("Unsupported format \"%s\"."), mimetype);
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE,
"document-format", NULL, mimetype);
return (NULL);
}
if ((attr = ippFindAttribute(con->request, "copies",
IPP_TAG_INTEGER)) != NULL)
{
if (attr->values[0].integer < 1 || attr->values[0].integer > MaxCopies)
{
send_ipp_status(con, IPP_ATTRIBUTES, _("Bad copies value %d."),
attr->values[0].integer);
ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER,
"copies", attr->values[0].integer);
return (NULL);
}
}
if ((attr = ippFindAttribute(con->request, "job-sheets",
IPP_TAG_ZERO)) != NULL)
{
if (attr->value_tag != IPP_TAG_KEYWORD &&
attr->value_tag != IPP_TAG_NAME)
{
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-sheets value type."));
return (NULL);
}
if (attr->num_values > 2)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Too many job-sheets values (%d > 2)."),
attr->num_values);
return (NULL);
}
for (i = 0; i < attr->num_values; i ++)
if (strcmp(attr->values[i].string.text, "none") &&
!cupsdFindBanner(attr->values[i].string.text))
{
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-sheets value \"%s\"."),
attr->values[i].string.text);
return (NULL);
}
}
if ((attr = ippFindAttribute(con->request, "number-up",
IPP_TAG_INTEGER)) != NULL)
{
if (attr->values[0].integer != 1 &&
attr->values[0].integer != 2 &&
attr->values[0].integer != 4 &&
attr->values[0].integer != 6 &&
attr->values[0].integer != 9 &&
attr->values[0].integer != 16)
{
send_ipp_status(con, IPP_ATTRIBUTES, _("Bad number-up value %d."),
attr->values[0].integer);
ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER,
"number-up", attr->values[0].integer);
return (NULL);
}
}
if ((attr = ippFindAttribute(con->request, "page-ranges",
IPP_TAG_RANGE)) != NULL)
{
for (i = 0, lowerpagerange = 1; i < attr->num_values; i ++)
{
if (attr->values[i].range.lower < lowerpagerange ||
attr->values[i].range.lower > attr->values[i].range.upper)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Bad page-ranges values %d-%d."),
attr->values[i].range.lower,
attr->values[i].range.upper);
return (NULL);
}
lowerpagerange = attr->values[i].range.upper + 1;
}
}
/*
* Do media selection as needed...
*/
if (!ippFindAttribute(con->request, "PageRegion", IPP_TAG_ZERO) &&
!ippFindAttribute(con->request, "PageSize", IPP_TAG_ZERO) &&
_ppdCacheGetPageSize(printer->pc, con->request, NULL, &exact))
{
if (!exact &&
(media_col = ippFindAttribute(con->request, "media-col",
IPP_TAG_BEGIN_COLLECTION)) != NULL)
{
send_ipp_status(con, IPP_OK_SUBST, _("Unsupported margins."));
unsup_col = ippNew();
if ((media_margin = ippFindAttribute(media_col->values[0].collection,
"media-bottom-margin",
IPP_TAG_INTEGER)) != NULL)
ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
"media-bottom-margin", media_margin->values[0].integer);
if ((media_margin = ippFindAttribute(media_col->values[0].collection,
"media-left-margin",
IPP_TAG_INTEGER)) != NULL)
ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
"media-left-margin", media_margin->values[0].integer);
if ((media_margin = ippFindAttribute(media_col->values[0].collection,
"media-right-margin",
IPP_TAG_INTEGER)) != NULL)
ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
"media-right-margin", media_margin->values[0].integer);
if ((media_margin = ippFindAttribute(media_col->values[0].collection,
"media-top-margin",
IPP_TAG_INTEGER)) != NULL)
ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
"media-top-margin", media_margin->values[0].integer);
ippAddCollection(con->response, IPP_TAG_UNSUPPORTED_GROUP, "media-col",
unsup_col);
ippDelete(unsup_col);
}
}
/*
* Make sure we aren't over our limit...
*/
if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs)
cupsdCleanJobs();
if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs)
{
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Too many active jobs."));
return (NULL);
}
if ((i = check_quotas(con, printer)) < 0)
{
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Quota limit reached."));
return (NULL);
}
else if (i == 0)
{
send_ipp_status(con, IPP_NOT_AUTHORIZED, _("Not allowed to print."));
return (NULL);
}
/*
* Create the job and set things up...
*/
if ((attr = ippFindAttribute(con->request, "job-priority",
IPP_TAG_INTEGER)) != NULL)
priority = attr->values[0].integer;
else
{
if ((val = cupsGetOption("job-priority", printer->num_options,
printer->options)) != NULL)
priority = atoi(val);
else
priority = 50;
ippAddInteger(con->request, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-priority",
priority);
}
if ((attr = ippFindAttribute(con->request, "job-name", IPP_TAG_ZERO)) == NULL)
ippAddString(con->request, IPP_TAG_JOB, IPP_TAG_NAME, "job-name", NULL, "Untitled");
else if ((attr->value_tag != IPP_TAG_NAME &&
attr->value_tag != IPP_TAG_NAMELANG) ||
attr->num_values != 1)
{
send_ipp_status(con, IPP_ATTRIBUTES,
_("Bad job-name value: Wrong type or count."));
if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL)
attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP;
return (NULL);
}
else if (!ippValidateAttribute(attr))
{
send_ipp_status(con, IPP_ATTRIBUTES, _("Bad job-name value: %s"),
cupsLastErrorString());
if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL)
attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP;
return (NULL);
}
attr = ippFindAttribute(con->request, "requesting-user-name", IPP_TAG_NAME);
if (attr && !ippValidateAttribute(attr))
{
send_ipp_status(con, IPP_ATTRIBUTES, _("Bad requesting-user-name value: %s"), cupsLastErrorString());
if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL)
attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP;
return (NULL);
}
if ((job = cupsdAddJob(priority, printer->name)) == NULL)
{
send_ipp_status(con, IPP_INTERNAL_ERROR,
_("Unable to add job for destination \"%s\"."),
printer->name);
return (NULL);
}
job->dtype = printer->type & (CUPS_PRINTER_CLASS | CUPS_PRINTER_REMOTE);
job->attrs = con->request;
job->dirty = 1;
con->request = ippNewRequest(job->attrs->request.op.operation_id);
cupsdMarkDirty(CUPSD_DIRTY_JOBS);
add_job_uuid(job);
apply_printer_defaults(printer, job);
if (con->username[0])
{
cupsdSetString(&job->username, con->username);
if (attr)
ippSetString(job->attrs, &attr, 0, con->username);
}
else if (attr)
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"add_job: requesting-user-name=\"%s\"",
attr->values[0].string.text);
cupsdSetString(&job->username, attr->values[0].string.text);
}
else
cupsdSetString(&job->username, "anonymous");
if (!attr)
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME,
"job-originating-user-name", NULL, job->username);
else
{
ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB);
ippSetName(job->attrs, &attr, "job-originating-user-name");
}
if (con->username[0] || auth_info)
{
save_auth_info(con, job, auth_info);
/*
* Remove the auth-info attribute from the attribute data...
*/
if (auth_info)
ippDeleteAttribute(job->attrs, auth_info);
}
if ((attr = ippFindAttribute(con->request, "job-name", IPP_TAG_NAME)) != NULL)
cupsdSetString(&(job->name), attr->values[0].string.text);
if ((attr = ippFindAttribute(job->attrs, "job-originating-host-name",
IPP_TAG_ZERO)) != NULL)
{
/*
* Request contains a job-originating-host-name attribute; validate it...
*/
if (attr->value_tag != IPP_TAG_NAME ||
attr->num_values != 1 ||
strcmp(con->http->hostname, "localhost"))
{
/*
* Can't override the value if we aren't connected via localhost.
* Also, we can only have 1 value and it must be a name value.
*/
ippDeleteAttribute(job->attrs, attr);
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-originating-host-name", NULL, con->http->hostname);
}
else
ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB);
}
else
{
/*
* No job-originating-host-name attribute, so use the hostname from
* the connection...
*/
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME,
"job-originating-host-name", NULL, con->http->hostname);
}
ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "date-time-at-completed");
ippAddDate(job->attrs, IPP_TAG_JOB, "date-time-at-creation", ippTimeToDate(time(NULL)));
ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "date-time-at-processing");
ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "time-at-completed");
ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "time-at-creation", time(NULL));
ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "time-at-processing");
/*
* Add remaining job attributes...
*/
ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id);
job->state = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_ENUM,
"job-state", IPP_JOB_STOPPED);
job->state_value = (ipp_jstate_t)job->state->values[0].integer;
job->reasons = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD,
"job-state-reasons", NULL, "job-incoming");
job->impressions = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-impressions-completed", 0);
job->sheets = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER,
"job-media-sheets-completed", 0);
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_URI, "job-printer-uri", NULL,
printer->uri);
if ((attr = ippFindAttribute(job->attrs, "job-k-octets", IPP_TAG_INTEGER)) != NULL)
attr->values[0].integer = 0;
else
ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-k-octets", 0);
if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
if (!attr)
{
if ((val = cupsGetOption("job-hold-until", printer->num_options,
printer->options)) == NULL)
val = "no-hold";
attr = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD,
"job-hold-until", NULL, val);
}
if (printer->holding_new_jobs)
{
/*
* Hold all new jobs on this printer...
*/
if (attr && strcmp(attr->values[0].string.text, "no-hold"))
cupsdSetJobHoldUntil(job, ippGetString(attr, 0, NULL), 0);
else
cupsdSetJobHoldUntil(job, "indefinite", 0);
job->state->values[0].integer = IPP_JOB_HELD;
job->state_value = IPP_JOB_HELD;
ippSetString(job->attrs, &job->reasons, 0, "job-held-on-create");
}
else if (attr && strcmp(attr->values[0].string.text, "no-hold"))
{
/*
* Hold job until specified time...
*/
cupsdSetJobHoldUntil(job, attr->values[0].string.text, 0);
job->state->values[0].integer = IPP_JOB_HELD;
job->state_value = IPP_JOB_HELD;
ippSetString(job->attrs, &job->reasons, 0, "job-hold-until-specified");
}
else if (job->attrs->request.op.operation_id == IPP_CREATE_JOB)
{
job->hold_until = time(NULL) + MultipleOperationTimeout;
job->state->values[0].integer = IPP_JOB_HELD;
job->state_value = IPP_JOB_HELD;
}
else
{
job->state->values[0].integer = IPP_JOB_PENDING;
job->state_value = IPP_JOB_PENDING;
ippSetString(job->attrs, &job->reasons, 0, "none");
}
if (!(printer->type & CUPS_PRINTER_REMOTE) || Classification)
{
/*
* Add job sheets options...
*/
if ((attr = ippFindAttribute(job->attrs, "job-sheets",
IPP_TAG_ZERO)) == NULL)
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Adding default job-sheets values \"%s,%s\"...",
printer->job_sheets[0], printer->job_sheets[1]);
attr = ippAddStrings(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-sheets",
2, NULL, NULL);
ippSetString(job->attrs, &attr, 0, printer->job_sheets[0]);
ippSetString(job->attrs, &attr, 1, printer->job_sheets[1]);
}
job->job_sheets = attr;
/*
* Enforce classification level if set...
*/
if (Classification)
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Classification=\"%s\", ClassifyOverride=%d",
Classification ? Classification : "(null)",
ClassifyOverride);
if (ClassifyOverride)
{
if (!strcmp(attr->values[0].string.text, "none") &&
(attr->num_values == 1 ||
!strcmp(attr->values[1].string.text, "none")))
{
/*
* Force the leading banner to have the classification on it...
*/
ippSetString(job->attrs, &attr, 0, Classification);
cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED "
"job-sheets=\"%s,none\", "
"job-originating-user-name=\"%s\"",
Classification, job->username);
}
else if (attr->num_values == 2 &&
strcmp(attr->values[0].string.text,
attr->values[1].string.text) &&
strcmp(attr->values[0].string.text, "none") &&
strcmp(attr->values[1].string.text, "none"))
{
/*
* Can't put two different security markings on the same document!
*/
ippSetString(job->attrs, &attr, 1, attr->values[0].string.text);
cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED "
"job-sheets=\"%s,%s\", "
"job-originating-user-name=\"%s\"",
attr->values[0].string.text,
attr->values[1].string.text, job->username);
}
else if (strcmp(attr->values[0].string.text, Classification) &&
strcmp(attr->values[0].string.text, "none") &&
(attr->num_values == 1 ||
(strcmp(attr->values[1].string.text, Classification) &&
strcmp(attr->values[1].string.text, "none"))))
{
if (attr->num_values == 1)
cupsdLogJob(job, CUPSD_LOG_NOTICE,
"CLASSIFICATION OVERRIDDEN "
"job-sheets=\"%s\", "
"job-originating-user-name=\"%s\"",
attr->values[0].string.text, job->username);
else
cupsdLogJob(job, CUPSD_LOG_NOTICE,
"CLASSIFICATION OVERRIDDEN "
"job-sheets=\"%s,%s\",fffff "
"job-originating-user-name=\"%s\"",
attr->values[0].string.text,
attr->values[1].string.text, job->username);
}
}
else if (strcmp(attr->values[0].string.text, Classification) &&
(attr->num_values == 1 ||
strcmp(attr->values[1].string.text, Classification)))
{
/*
* Force the banner to have the classification on it...
*/
if (attr->num_values > 1 &&
!strcmp(attr->values[0].string.text, attr->values[1].string.text))
{
ippSetString(job->attrs, &attr, 0, Classification);
ippSetString(job->attrs, &attr, 1, Classification);
}
else
{
if (attr->num_values == 1 ||
strcmp(attr->values[0].string.text, "none"))
ippSetString(job->attrs, &attr, 0, Classification);
if (attr->num_values > 1 &&
strcmp(attr->values[1].string.text, "none"))
ippSetString(job->attrs, &attr, 1, Classification);
}
if (attr->num_values > 1)
cupsdLogJob(job, CUPSD_LOG_NOTICE,
"CLASSIFICATION FORCED "
"job-sheets=\"%s,%s\", "
"job-originating-user-name=\"%s\"",
attr->values[0].string.text,
attr->values[1].string.text, job->username);
else
cupsdLogJob(job, CUPSD_LOG_NOTICE,
"CLASSIFICATION FORCED "
"job-sheets=\"%s\", "
"job-originating-user-name=\"%s\"",
Classification, job->username);
}
}
/*
* See if we need to add the starting sheet...
*/
if (!(printer->type & CUPS_PRINTER_REMOTE))
{
cupsdLogJob(job, CUPSD_LOG_INFO, "Adding start banner page \"%s\".",
attr->values[0].string.text);
if ((kbytes = copy_banner(con, job, attr->values[0].string.text)) < 0)
{
cupsdSetJobState(job, IPP_JOB_ABORTED, CUPSD_JOB_PURGE,
"Aborting job because the start banner could not be "
"copied.");
return (NULL);
}
cupsdUpdateQuota(printer, job->username, 0, kbytes);
}
}
else if ((attr = ippFindAttribute(job->attrs, "job-sheets",
IPP_TAG_ZERO)) != NULL)
job->job_sheets = attr;
/*
* Fill in the response info...
*/
httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "ipp", NULL,
con->clientname, con->clientport, "/jobs/%d", job->id);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI, "job-uri", NULL,
job_uri);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_ENUM, "job-state",
job->state_value);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_TEXT, "job-state-message", NULL, "");
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons",
NULL, job->reasons->values[0].string.text);
con->response->request.status.status_code = IPP_OK;
/*
* Add any job subscriptions...
*/
add_job_subscriptions(con, job);
/*
* Set all but the first two attributes to the job attributes group...
*/
for (attr = job->attrs->attrs->next->next; attr; attr = attr->next)
attr->group_tag = IPP_TAG_JOB;
/*
* Fire the "job created" event...
*/
cupsdAddEvent(CUPSD_EVENT_JOB_CREATED, printer, job, "Job created.");
/*
* Return the new job...
*/
return (job);
}
/*
* 'add_job_subscriptions()' - Add any subscriptions for a job.
*/
static void
add_job_subscriptions(
cupsd_client_t *con, /* I - Client connection */
cupsd_job_t *job) /* I - Newly created job */
{
int i; /* Looping var */
ipp_attribute_t *prev, /* Previous attribute */
*next, /* Next attribute */
*attr; /* Current attribute */
cupsd_subscription_t *sub; /* Subscription object */
const char *recipient, /* notify-recipient-uri */
*pullmethod; /* notify-pull-method */
ipp_attribute_t *user_data; /* notify-user-data */
int interval; /* notify-time-interval */
unsigned mask; /* notify-events */
/*
* Find the first subscription group attribute; return if we have
* none...
*/
for (attr = job->attrs->attrs; attr; attr = attr->next)
if (attr->group_tag == IPP_TAG_SUBSCRIPTION)
break;
if (!attr)
return;
/*
* Process the subscription attributes in the request...
*/
while (attr)
{
recipient = NULL;
pullmethod = NULL;
user_data = NULL;
interval = 0;
mask = CUPSD_EVENT_NONE;
while (attr && attr->group_tag != IPP_TAG_ZERO)
{
if (!strcmp(attr->name, "notify-recipient-uri") &&
attr->value_tag == IPP_TAG_URI)
{
/*
* Validate the recipient scheme against the ServerBin/notifier
* directory...
*/
char notifier[1024], /* Notifier filename */
scheme[HTTP_MAX_URI], /* Scheme portion of URI */
userpass[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
recipient = attr->values[0].string.text;
if (httpSeparateURI(HTTP_URI_CODING_ALL, recipient,
scheme, sizeof(scheme), userpass, sizeof(userpass),
host, sizeof(host), &port,
resource, sizeof(resource)) < HTTP_URI_OK)
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Bad notify-recipient-uri \"%s\"."), recipient);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_ENUM,
"notify-status-code", IPP_URI_SCHEME);
return;
}
snprintf(notifier, sizeof(notifier), "%s/notifier/%s", ServerBin,
scheme);
if (access(notifier, X_OK))
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("notify-recipient-uri URI \"%s\" uses unknown "
"scheme."), recipient);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_ENUM,
"notify-status-code", IPP_URI_SCHEME);
return;
}
if (!strcmp(scheme, "rss") && !check_rss_recipient(recipient))
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("notify-recipient-uri URI \"%s\" is already used."),
recipient);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_ENUM,
"notify-status-code", IPP_ATTRIBUTES);
return;
}
}
else if (!strcmp(attr->name, "notify-pull-method") &&
attr->value_tag == IPP_TAG_KEYWORD)
{
pullmethod = attr->values[0].string.text;
if (strcmp(pullmethod, "ippget"))
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Bad notify-pull-method \"%s\"."), pullmethod);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_ENUM,
"notify-status-code", IPP_ATTRIBUTES);
return;
}
}
else if (!strcmp(attr->name, "notify-charset") &&
attr->value_tag == IPP_TAG_CHARSET &&
strcmp(attr->values[0].string.text, "us-ascii") &&
strcmp(attr->values[0].string.text, "utf-8"))
{
send_ipp_status(con, IPP_CHARSET,
_("Character set \"%s\" not supported."),
attr->values[0].string.text);
return;
}
else if (!strcmp(attr->name, "notify-natural-language") &&
(attr->value_tag != IPP_TAG_LANGUAGE ||
strcmp(attr->values[0].string.text, DefaultLanguage)))
{
send_ipp_status(con, IPP_CHARSET,
_("Language \"%s\" not supported."),
attr->values[0].string.text);
return;
}
else if (!strcmp(attr->name, "notify-user-data") &&
attr->value_tag == IPP_TAG_STRING)
{
if (attr->num_values > 1 || attr->values[0].unknown.length > 63)
{
send_ipp_status(con, IPP_REQUEST_VALUE,
_("The notify-user-data value is too large "
"(%d > 63 octets)."),
attr->values[0].unknown.length);
return;
}
user_data = attr;
}
else if (!strcmp(attr->name, "notify-events") &&
attr->value_tag == IPP_TAG_KEYWORD)
{
for (i = 0; i < attr->num_values; i ++)
mask |= cupsdEventValue(attr->values[i].string.text);
}
else if (!strcmp(attr->name, "notify-lease-duration"))
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("The notify-lease-duration attribute cannot be "
"used with job subscriptions."));
return;
}
else if (!strcmp(attr->name, "notify-time-interval") &&
attr->value_tag == IPP_TAG_INTEGER)
interval = attr->values[0].integer;
attr = attr->next;
}
if (!recipient && !pullmethod)
break;
if (mask == CUPSD_EVENT_NONE)
mask = CUPSD_EVENT_JOB_COMPLETED;
if ((sub = cupsdAddSubscription(mask, cupsdFindDest(job->dest), job,
recipient, 0)) != NULL)
{
sub->interval = interval;
cupsdSetString(&sub->owner, job->username);
if (user_data)
{
sub->user_data_len = user_data->values[0].unknown.length;
memcpy(sub->user_data, user_data->values[0].unknown.data,
(size_t)sub->user_data_len);
}
ippAddSeparator(con->response);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER,
"notify-subscription-id", sub->id);
cupsdLogMessage(CUPSD_LOG_DEBUG, "Added subscription %d for job %d",
sub->id, job->id);
}
if (attr)
attr = attr->next;
}
cupsdMarkDirty(CUPSD_DIRTY_SUBSCRIPTIONS);
/*
* Remove all of the subscription attributes from the job request...
*
* TODO: Optimize this since subscription groups have to come at the
* end of the request...
*/
for (attr = job->attrs->attrs, prev = NULL; attr; attr = next)
{
next = attr->next;
if (attr->group_tag == IPP_TAG_SUBSCRIPTION ||
attr->group_tag == IPP_TAG_ZERO)
{
/*
* Free and remove this attribute...
*/
ippDeleteAttribute(NULL, attr);
if (prev)
prev->next = next;
else
job->attrs->attrs = next;
}
else
prev = attr;
}
job->attrs->last = prev;
job->attrs->current = prev;
}
/*
* 'add_job_uuid()' - Add job-uuid attribute to a job.
*
* See RFC 4122 for the definition of UUIDs and the format.
*/
static void
add_job_uuid(cupsd_job_t *job) /* I - Job */
{
char uuid[64]; /* job-uuid string */
/*
* Add a job-uuid attribute if none exists...
*/
if (!ippFindAttribute(job->attrs, "job-uuid", IPP_TAG_URI))
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_URI, "job-uuid", NULL,
httpAssembleUUID(ServerName, RemotePort, job->dest, job->id,
uuid, sizeof(uuid)));
}
/*
* 'add_printer()' - Add a printer to the system.
*/
static void
add_printer(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - URI of printer */
{
http_status_t status; /* Policy status */
int i; /* Looping var */
char scheme[HTTP_MAX_URI], /* Method portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
cupsd_printer_t *printer; /* Printer/class */
ipp_attribute_t *attr; /* Printer attribute */
cups_file_t *fp; /* Script/PPD file */
char line[1024]; /* Line from file... */
char srcfile[1024], /* Source Script/PPD file */
dstfile[1024]; /* Destination Script/PPD file */
int modify; /* Non-zero if we are modifying */
int changed_driver, /* Changed the PPD? */
need_restart_job, /* Need to restart job? */
set_device_uri, /* Did we set the device URI? */
set_port_monitor; /* Did we set the port monitor? */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "add_printer(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Do we have a valid URI?
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/printers/", 10) || strlen(resource) == 10)
{
/*
* No, return an error...
*/
send_ipp_status(con, IPP_BAD_REQUEST,
_("The printer-uri must be of the form "
"\"ipp://HOSTNAME/printers/PRINTERNAME\"."));
return;
}
/*
* Do we have a valid printer name?
*/
if (!validate_name(resource + 10))
{
/*
* No, return an error...
*/
send_ipp_status(con, IPP_BAD_REQUEST,
_("The printer-uri \"%s\" contains invalid characters."),
uri->values[0].string.text);
return;
}
/*
* See if the printer already exists; if not, create a new printer...
*/
if ((printer = cupsdFindPrinter(resource + 10)) == NULL)
{
/*
* Printer doesn't exist; see if we have a class of the same name...
*/
if ((printer = cupsdFindClass(resource + 10)) != NULL)
{
/*
* Yes, return an error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("A class named \"%s\" already exists."),
resource + 10);
return;
}
/*
* No, check the default policy then add the printer...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
printer = cupsdAddPrinter(resource + 10);
modify = 0;
}
else if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con,
NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
else
modify = 1;
/*
* Look for attributes and copy them over as needed...
*/
changed_driver = 0;
need_restart_job = 0;
if ((attr = ippFindAttribute(con->request, "printer-is-temporary", IPP_TAG_BOOLEAN)) != NULL)
printer->temporary = ippGetBoolean(attr, 0);
if ((attr = ippFindAttribute(con->request, "printer-location",
IPP_TAG_TEXT)) != NULL)
cupsdSetString(&printer->location, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-geo-location", IPP_TAG_URI)) != NULL && !strncmp(attr->values[0].string.text, "geo:", 4))
cupsdSetString(&printer->geo_location, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-organization", IPP_TAG_TEXT)) != NULL)
cupsdSetString(&printer->organization, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-organizational-unit", IPP_TAG_TEXT)) != NULL)
cupsdSetString(&printer->organizational_unit, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-info",
IPP_TAG_TEXT)) != NULL)
cupsdSetString(&printer->info, attr->values[0].string.text);
set_device_uri = 0;
if ((attr = ippFindAttribute(con->request, "device-uri",
IPP_TAG_URI)) != NULL)
{
/*
* Do we have a valid device URI?
*/
http_uri_status_t uri_status; /* URI separation status */
char old_device_uri[1024];
/* Old device URI */
need_restart_job = 1;
uri_status = httpSeparateURI(HTTP_URI_CODING_ALL,
attr->values[0].string.text,
scheme, sizeof(scheme),
username, sizeof(username),
host, sizeof(host), &port,
resource, sizeof(resource));
cupsdLogMessage(CUPSD_LOG_DEBUG, "%s device-uri: %s", printer->name, httpURIStatusString(uri_status));
if (uri_status < HTTP_URI_OK)
{
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Bad device-uri \"%s\"."),
attr->values[0].string.text);
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
if (!strcmp(scheme, "file"))
{
/*
* See if the administrator has enabled file devices...
*/
if (!FileDevice && strcmp(resource, "/dev/null"))
{
/*
* File devices are disabled and the URL is not file:/dev/null...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("File device URIs have been disabled. "
"To enable, see the FileDevice directive in "
"\"%s/cups-files.conf\"."),
ServerRoot);
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
}
else
{
/*
* See if the backend exists and is executable...
*/
snprintf(srcfile, sizeof(srcfile), "%s/backend/%s", ServerBin, scheme);
if (access(srcfile, X_OK))
{
/*
* Could not find device in list!
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Bad device-uri scheme \"%s\"."), scheme);
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
}
if (printer->sanitized_device_uri)
strlcpy(old_device_uri, printer->sanitized_device_uri,
sizeof(old_device_uri));
else
old_device_uri[0] = '\0';
cupsdSetDeviceURI(printer, attr->values[0].string.text);
cupsdLogMessage(CUPSD_LOG_INFO,
"Setting %s device-uri to \"%s\" (was \"%s\".)",
printer->name, printer->sanitized_device_uri,
old_device_uri);
set_device_uri = 1;
}
set_port_monitor = 0;
if ((attr = ippFindAttribute(con->request, "port-monitor",
IPP_TAG_NAME)) != NULL)
{
ipp_attribute_t *supported; /* port-monitor-supported attribute */
need_restart_job = 1;
supported = ippFindAttribute(printer->ppd_attrs, "port-monitor-supported",
IPP_TAG_NAME);
if (supported)
{
for (i = 0; i < supported->num_values; i ++)
if (!strcmp(supported->values[i].string.text,
attr->values[0].string.text))
break;
}
if (!supported || i >= supported->num_values)
{
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Bad port-monitor \"%s\"."),
attr->values[0].string.text);
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
cupsdLogMessage(CUPSD_LOG_INFO,
"Setting %s port-monitor to \"%s\" (was \"%s\".)",
printer->name, attr->values[0].string.text,
printer->port_monitor ? printer->port_monitor : "none");
if (strcmp(attr->values[0].string.text, "none"))
cupsdSetString(&printer->port_monitor, attr->values[0].string.text);
else
cupsdClearString(&printer->port_monitor);
set_port_monitor = 1;
}
if ((attr = ippFindAttribute(con->request, "printer-is-accepting-jobs",
IPP_TAG_BOOLEAN)) != NULL &&
attr->values[0].boolean != printer->accepting)
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Setting %s printer-is-accepting-jobs to %d (was %d.)",
printer->name, attr->values[0].boolean, printer->accepting);
printer->accepting = attr->values[0].boolean;
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, printer, NULL,
"%s accepting jobs.",
printer->accepting ? "Now" : "No longer");
}
if ((attr = ippFindAttribute(con->request, "printer-is-shared", IPP_TAG_BOOLEAN)) != NULL)
{
if (ippGetBoolean(attr, 0) &&
printer->num_auth_info_required == 1 &&
!strcmp(printer->auth_info_required[0], "negotiate"))
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Cannot share a remote Kerberized printer."));
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
if (printer->type & CUPS_PRINTER_REMOTE)
{
/*
* Cannot re-share remote printers.
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Cannot change printer-is-shared for remote queues."));
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
if (printer->shared && !ippGetBoolean(attr, 0))
cupsdDeregisterPrinter(printer, 1);
cupsdLogMessage(CUPSD_LOG_INFO,
"Setting %s printer-is-shared to %d (was %d.)",
printer->name, attr->values[0].boolean, printer->shared);
printer->shared = ippGetBoolean(attr, 0);
if (printer->shared && printer->temporary)
printer->temporary = 0;
}
if ((attr = ippFindAttribute(con->request, "printer-state",
IPP_TAG_ENUM)) != NULL)
{
if (attr->values[0].integer != IPP_PRINTER_IDLE &&
attr->values[0].integer != IPP_PRINTER_STOPPED)
{
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad printer-state value %d."),
attr->values[0].integer);
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
cupsdLogMessage(CUPSD_LOG_INFO, "Setting %s printer-state to %d (was %d.)",
printer->name, attr->values[0].integer, printer->state);
if (attr->values[0].integer == IPP_PRINTER_STOPPED)
cupsdStopPrinter(printer, 0);
else
{
need_restart_job = 1;
cupsdSetPrinterState(printer, (ipp_pstate_t)(attr->values[0].integer), 0);
}
}
if ((attr = ippFindAttribute(con->request, "printer-state-message",
IPP_TAG_TEXT)) != NULL)
{
strlcpy(printer->state_message, attr->values[0].string.text,
sizeof(printer->state_message));
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, printer, NULL, "%s",
printer->state_message);
}
if ((attr = ippFindAttribute(con->request, "printer-state-reasons",
IPP_TAG_KEYWORD)) != NULL)
{
if (attr->num_values >
(int)(sizeof(printer->reasons) / sizeof(printer->reasons[0])))
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Too many printer-state-reasons values (%d > %d)."),
attr->num_values,
(int)(sizeof(printer->reasons) /
sizeof(printer->reasons[0])));
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
for (i = 0; i < printer->num_reasons; i ++)
_cupsStrFree(printer->reasons[i]);
printer->num_reasons = 0;
for (i = 0; i < attr->num_values; i ++)
{
if (!strcmp(attr->values[i].string.text, "none"))
continue;
printer->reasons[printer->num_reasons] =
_cupsStrRetain(attr->values[i].string.text);
printer->num_reasons ++;
if (!strcmp(attr->values[i].string.text, "paused") &&
printer->state != IPP_PRINTER_STOPPED)
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Setting %s printer-state to %d (was %d.)",
printer->name, IPP_PRINTER_STOPPED, printer->state);
cupsdStopPrinter(printer, 0);
}
}
if (PrintcapFormat == PRINTCAP_PLIST)
cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP);
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, printer, NULL,
"Printer \"%s\" state changed.", printer->name);
}
if (!set_printer_defaults(con, printer))
{
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
if ((attr = ippFindAttribute(con->request, "auth-info-required",
IPP_TAG_KEYWORD)) != NULL)
cupsdSetAuthInfoRequired(printer, NULL, attr);
/*
* See if we have all required attributes...
*/
if (!printer->device_uri)
cupsdSetString(&printer->device_uri, "file:///dev/null");
/*
* See if we have a PPD file attached to the request...
*/
if (con->filename)
{
need_restart_job = 1;
changed_driver = 1;
strlcpy(srcfile, con->filename, sizeof(srcfile));
if ((fp = cupsFileOpen(srcfile, "rb")))
{
/*
* Yes; get the first line from it...
*/
line[0] = '\0';
cupsFileGets(fp, line, sizeof(line));
cupsFileClose(fp);
/*
* Then see what kind of file it is...
*/
if (strncmp(line, "*PPD-Adobe", 10))
{
send_ipp_status(con, IPP_STATUS_ERROR_DOCUMENT_FORMAT_NOT_SUPPORTED, _("Bad PPD file."));
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
snprintf(dstfile, sizeof(dstfile), "%s/ppd/%s.ppd", ServerRoot,
printer->name);
/*
* The new file is a PPD file, so move the file over to the ppd
* directory...
*/
if (copy_file(srcfile, dstfile, ConfigFilePerm))
{
send_ipp_status(con, IPP_INTERNAL_ERROR, _("Unable to copy PPD file - %s"), strerror(errno));
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
cupsdLogMessage(CUPSD_LOG_DEBUG, "Copied PPD file successfully");
}
}
else if ((attr = ippFindAttribute(con->request, "ppd-name", IPP_TAG_NAME)) != NULL)
{
const char *ppd_name = ippGetString(attr, 0, NULL);
/* ppd-name value */
need_restart_job = 1;
changed_driver = 1;
if (!strcmp(ppd_name, "raw"))
{
/*
* Raw driver, remove any existing PPD file.
*/
snprintf(dstfile, sizeof(dstfile), "%s/ppd/%s.ppd", ServerRoot, printer->name);
unlink(dstfile);
}
else if (strstr(ppd_name, "../"))
{
send_ipp_status(con, IPP_STATUS_ERROR_ATTRIBUTES_OR_VALUES, _("Invalid ppd-name value."));
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
else
{
/*
* PPD model file...
*/
snprintf(dstfile, sizeof(dstfile), "%s/ppd/%s.ppd", ServerRoot, printer->name);
if (copy_model(con, ppd_name, dstfile))
{
send_ipp_status(con, IPP_INTERNAL_ERROR, _("Unable to copy PPD file."));
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
cupsdLogMessage(CUPSD_LOG_DEBUG, "Copied PPD file successfully");
}
}
if (changed_driver)
{
/*
* If we changed the PPD, then remove the printer's cache file and clear the
* printer-state-reasons...
*/
char cache_name[1024]; /* Cache filename for printer attrs */
snprintf(cache_name, sizeof(cache_name), "%s/%s.data", CacheDir, printer->name);
unlink(cache_name);
cupsdSetPrinterReasons(printer, "none");
/*
* (Re)register color profiles...
*/
cupsdRegisterColor(printer);
}
/*
* If we set the device URI but not the port monitor, check which port
* monitor to use by default...
*/
if (set_device_uri && !set_port_monitor)
{
ppd_file_t *ppd; /* PPD file */
ppd_attr_t *ppdattr; /* cupsPortMonitor attribute */
httpSeparateURI(HTTP_URI_CODING_ALL, printer->device_uri, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
snprintf(srcfile, sizeof(srcfile), "%s/ppd/%s.ppd", ServerRoot,
printer->name);
if ((ppd = _ppdOpenFile(srcfile, _PPD_LOCALIZATION_NONE)) != NULL)
{
for (ppdattr = ppdFindAttr(ppd, "cupsPortMonitor", NULL);
ppdattr;
ppdattr = ppdFindNextAttr(ppd, "cupsPortMonitor", NULL))
if (!strcmp(scheme, ppdattr->spec))
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Setting %s port-monitor to \"%s\" (was \"%s\".)",
printer->name, ppdattr->value,
printer->port_monitor ? printer->port_monitor
: "none");
if (strcmp(ppdattr->value, "none"))
cupsdSetString(&printer->port_monitor, ppdattr->value);
else
cupsdClearString(&printer->port_monitor);
break;
}
ppdClose(ppd);
}
}
printer->config_time = time(NULL);
/*
* Update the printer attributes and return...
*/
cupsdSetPrinterAttrs(printer);
if (!printer->temporary)
cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
if (need_restart_job && printer->job)
{
/*
* Restart the current job...
*/
cupsdSetJobState(printer->job, IPP_JOB_PENDING, CUPSD_JOB_FORCE,
"Job restarted because the printer was modified.");
}
cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP);
if (modify)
{
cupsdAddEvent(CUPSD_EVENT_PRINTER_MODIFIED,
printer, NULL, "Printer \"%s\" modified by \"%s\".",
printer->name, get_username(con));
cupsdLogMessage(CUPSD_LOG_INFO, "Printer \"%s\" modified by \"%s\".",
printer->name, get_username(con));
}
else
{
cupsdAddEvent(CUPSD_EVENT_PRINTER_ADDED,
printer, NULL, "New printer \"%s\" added by \"%s\".",
printer->name, get_username(con));
cupsdLogMessage(CUPSD_LOG_INFO, "New printer \"%s\" added by \"%s\".",
printer->name, get_username(con));
}
con->response->request.status.status_code = IPP_OK;
}
/*
* 'add_printer_state_reasons()' - Add the "printer-state-reasons" attribute
* based upon the printer state...
*/
static void
add_printer_state_reasons(
cupsd_client_t *con, /* I - Client connection */
cupsd_printer_t *p) /* I - Printer info */
{
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"add_printer_state_reasons(%p[%d], %p[%s])",
con, con->number, p, p->name);
if (p->num_reasons == 0)
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_KEYWORD,
"printer-state-reasons", NULL, "none");
else
ippAddStrings(con->response, IPP_TAG_PRINTER, IPP_TAG_KEYWORD,
"printer-state-reasons", p->num_reasons, NULL,
(const char * const *)p->reasons);
}
/*
* 'add_queued_job_count()' - Add the "queued-job-count" attribute for
* the specified printer or class.
*/
static void
add_queued_job_count(
cupsd_client_t *con, /* I - Client connection */
cupsd_printer_t *p) /* I - Printer or class */
{
int count; /* Number of jobs on destination */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "add_queued_job_count(%p[%d], %p[%s])",
con, con->number, p, p->name);
count = cupsdGetPrinterJobCount(p->name);
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_INTEGER,
"queued-job-count", count);
}
/*
* 'apply_printer_defaults()' - Apply printer default options to a job.
*/
static void
apply_printer_defaults(
cupsd_printer_t *printer, /* I - Printer */
cupsd_job_t *job) /* I - Job */
{
int i, /* Looping var */
num_options; /* Number of default options */
cups_option_t *options, /* Default options */
*option; /* Current option */
cupsdLogJob(job, CUPSD_LOG_DEBUG, "Applying default options...");
/*
* Collect all of the default options and add the missing ones to the
* job object...
*/
for (i = printer->num_options, num_options = 0, options = NULL,
option = printer->options;
i > 0;
i --, option ++)
if (!ippFindAttribute(job->attrs, option->name, IPP_TAG_ZERO))
{
if (!strcmp(option->name, "print-quality") && ippFindAttribute(job->attrs, "cupsPrintQuality", IPP_TAG_NAME))
continue; /* Don't override cupsPrintQuality */
cupsdLogJob(job, CUPSD_LOG_DEBUG, "Adding default %s=%s", option->name, option->value);
num_options = cupsAddOption(option->name, option->value, num_options, &options);
}
/*
* Encode these options as attributes in the job object...
*/
cupsEncodeOptions2(job->attrs, num_options, options, IPP_TAG_JOB);
cupsFreeOptions(num_options, options);
}
/*
* 'authenticate_job()' - Set job authentication info.
*/
static void
authenticate_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job URI */
{
ipp_attribute_t *attr, /* job-id attribute */
*auth_info; /* auth-info attribute */
int jobid; /* Job ID */
cupsd_job_t *job; /* Current job */
char scheme[HTTP_MAX_URI],
/* Method portion of URI */
username[HTTP_MAX_URI],
/* Username portion of URI */
host[HTTP_MAX_URI],
/* Host portion of URI */
resource[HTTP_MAX_URI];
/* Resource portion of URI */
int port; /* Port portion of URI */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "authenticate_job(%p[%d], %s)",
con, con->number, uri->values[0].string.text);
/*
* Start with "everything is OK" status...
*/
con->response->request.status.status_code = IPP_OK;
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
jobid = attr->values[0].integer;
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
/*
* See if the job has been completed...
*/
if (job->state_value != IPP_JOB_HELD)
{
/*
* Return a "not-possible" error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job #%d is not held for authentication."),
jobid);
return;
}
/*
* See if we have already authenticated...
*/
auth_info = ippFindAttribute(con->request, "auth-info", IPP_TAG_TEXT);
if (!con->username[0] && !auth_info)
{
cupsd_printer_t *printer; /* Job destination */
/*
* No auth data. If we need to authenticate via Kerberos, send a
* HTTP auth challenge, otherwise just return an IPP error...
*/
printer = cupsdFindDest(job->dest);
if (printer && printer->num_auth_info_required > 0 &&
!strcmp(printer->auth_info_required[0], "negotiate"))
send_http_error(con, HTTP_UNAUTHORIZED, printer);
else
send_ipp_status(con, IPP_NOT_AUTHORIZED,
_("No authentication information provided."));
return;
}
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* Save the authentication information for this job...
*/
save_auth_info(con, job, auth_info);
/*
* Reset the job-hold-until value to "no-hold"...
*/
if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
if (attr)
{
ippSetValueTag(job->attrs, &attr, IPP_TAG_KEYWORD);
ippSetString(job->attrs, &attr, 0, "no-hold");
}
/*
* Release the job and return...
*/
cupsdReleaseJob(job);
cupsdAddEvent(CUPSD_EVENT_JOB_STATE, NULL, job, "Job authenticated by user");
cupsdLogJob(job, CUPSD_LOG_INFO, "Authenticated by \"%s\".", con->username);
cupsdCheckJobs();
}
/*
* 'cancel_all_jobs()' - Cancel all or selected print jobs.
*/
static void
cancel_all_jobs(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job or Printer URI */
{
int i; /* Looping var */
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type */
char scheme[HTTP_MAX_URI], /* Scheme portion of URI */
userpass[HTTP_MAX_URI], /* Username portion of URI */
hostname[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
ipp_attribute_t *attr; /* Attribute in request */
const char *username = NULL; /* Username */
cupsd_jobaction_t purge = CUPSD_JOB_DEFAULT;
/* Purge? */
cupsd_printer_t *printer; /* Printer */
ipp_attribute_t *job_ids; /* job-ids attribute */
cupsd_job_t *job; /* Job */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "cancel_all_jobs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Get the jobs to cancel/purge...
*/
switch (con->request->request.op.operation_id)
{
case IPP_PURGE_JOBS :
/*
* Get the username (if any) for the jobs we want to cancel (only if
* "my-jobs" is specified...
*/
if ((attr = ippFindAttribute(con->request, "my-jobs",
IPP_TAG_BOOLEAN)) != NULL &&
attr->values[0].boolean)
{
if ((attr = ippFindAttribute(con->request, "requesting-user-name",
IPP_TAG_NAME)) != NULL)
username = attr->values[0].string.text;
else
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Missing requesting-user-name attribute."));
return;
}
}
/*
* Look for the "purge-jobs" attribute...
*/
if ((attr = ippFindAttribute(con->request, "purge-jobs",
IPP_TAG_BOOLEAN)) != NULL)
purge = attr->values[0].boolean ? CUPSD_JOB_PURGE : CUPSD_JOB_DEFAULT;
else
purge = CUPSD_JOB_PURGE;
break;
case IPP_CANCEL_MY_JOBS :
if (con->username[0])
username = con->username;
else if ((attr = ippFindAttribute(con->request, "requesting-user-name",
IPP_TAG_NAME)) != NULL)
username = attr->values[0].string.text;
else
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Missing requesting-user-name attribute."));
return;
}
default :
break;
}
job_ids = ippFindAttribute(con->request, "job-ids", IPP_TAG_INTEGER);
/*
* See if we have a printer URI...
*/
if (strcmp(uri->name, "printer-uri"))
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("The printer-uri attribute is required."));
return;
}
/*
* And if the destination is valid...
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI?
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text,
scheme, sizeof(scheme), userpass, sizeof(userpass),
hostname, sizeof(hostname), &port,
resource, sizeof(resource));
if ((!strncmp(resource, "/printers/", 10) && resource[10]) ||
(!strncmp(resource, "/classes/", 9) && resource[9]))
{
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
if (job_ids)
{
for (i = 0; i < job_ids->num_values; i ++)
{
if ((job = cupsdFindJob(job_ids->values[i].integer)) == NULL)
break;
if (con->request->request.op.operation_id == IPP_CANCEL_MY_JOBS &&
_cups_strcasecmp(job->username, username))
break;
}
if (i < job_ids->num_values)
{
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."),
job_ids->values[i].integer);
return;
}
for (i = 0; i < job_ids->num_values; i ++)
{
job = cupsdFindJob(job_ids->values[i].integer);
cupsdSetJobState(job, IPP_JOB_CANCELED, purge,
purge == CUPSD_JOB_PURGE ? "Job purged by user." :
"Job canceled by user.");
}
cupsdLogMessage(CUPSD_LOG_INFO, "Selected jobs were %s by \"%s\".",
purge == CUPSD_JOB_PURGE ? "purged" : "canceled",
get_username(con));
}
else
{
/*
* Cancel all jobs on all printers...
*/
cupsdCancelJobs(NULL, username, purge);
cupsdLogMessage(CUPSD_LOG_INFO, "All jobs were %s by \"%s\".",
purge == CUPSD_JOB_PURGE ? "purged" : "canceled",
get_username(con));
}
}
else
{
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con,
NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
if (job_ids)
{
for (i = 0; i < job_ids->num_values; i ++)
{
if ((job = cupsdFindJob(job_ids->values[i].integer)) == NULL ||
_cups_strcasecmp(job->dest, printer->name))
break;
if (con->request->request.op.operation_id == IPP_CANCEL_MY_JOBS &&
_cups_strcasecmp(job->username, username))
break;
}
if (i < job_ids->num_values)
{
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."),
job_ids->values[i].integer);
return;
}
for (i = 0; i < job_ids->num_values; i ++)
{
job = cupsdFindJob(job_ids->values[i].integer);
cupsdSetJobState(job, IPP_JOB_CANCELED, purge,
purge == CUPSD_JOB_PURGE ? "Job purged by user." :
"Job canceled by user.");
}
cupsdLogMessage(CUPSD_LOG_INFO, "Selected jobs were %s by \"%s\".",
purge == CUPSD_JOB_PURGE ? "purged" : "canceled",
get_username(con));
}
else
{
/*
* Cancel all of the jobs on the named printer...
*/
cupsdCancelJobs(printer->name, username, purge);
cupsdLogMessage(CUPSD_LOG_INFO, "All jobs on \"%s\" were %s by \"%s\".",
printer->name,
purge == CUPSD_JOB_PURGE ? "purged" : "canceled",
get_username(con));
}
}
con->response->request.status.status_code = IPP_OK;
cupsdCheckJobs();
}
/*
* 'cancel_job()' - Cancel a print job.
*/
static void
cancel_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job or Printer URI */
{
ipp_attribute_t *attr; /* Current attribute */
int jobid; /* Job ID */
char scheme[HTTP_MAX_URI], /* Scheme portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
cupsd_job_t *job; /* Job information */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer data */
cupsd_jobaction_t purge; /* Purge the job? */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "cancel_job(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
if ((jobid = attr->values[0].integer) == 0)
{
/*
* Find the current job on the specified printer...
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* See if there are any pending jobs...
*/
for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
job;
job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
if (job->state_value <= IPP_JOB_PROCESSING &&
!_cups_strcasecmp(job->dest, printer->name))
break;
if (job)
jobid = job->id;
else
{
/*
* No, try stopped jobs...
*/
for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
job;
job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
if (job->state_value == IPP_JOB_STOPPED &&
!_cups_strcasecmp(job->dest, printer->name))
break;
if (job)
jobid = job->id;
else
{
send_ipp_status(con, IPP_NOT_POSSIBLE, _("No active jobs on %s."),
printer->name);
return;
}
}
}
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* Look for the "purge-job" attribute...
*/
if ((attr = ippFindAttribute(con->request, "purge-job",
IPP_TAG_BOOLEAN)) != NULL)
purge = attr->values[0].boolean ? CUPSD_JOB_PURGE : CUPSD_JOB_DEFAULT;
else
purge = CUPSD_JOB_DEFAULT;
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* See if the job is already completed, canceled, or aborted; if so,
* we can't cancel...
*/
if (job->state_value >= IPP_JOB_CANCELED && purge != CUPSD_JOB_PURGE)
{
switch (job->state_value)
{
case IPP_JOB_CANCELED :
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job #%d is already canceled - can\'t cancel."),
jobid);
break;
case IPP_JOB_ABORTED :
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job #%d is already aborted - can\'t cancel."),
jobid);
break;
default :
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job #%d is already completed - can\'t cancel."),
jobid);
break;
}
return;
}
/*
* Cancel the job and return...
*/
cupsdSetJobState(job, IPP_JOB_CANCELED, purge,
purge == CUPSD_JOB_PURGE ? "Job purged by \"%s\"" :
"Job canceled by \"%s\"",
username);
cupsdCheckJobs();
if (purge == CUPSD_JOB_PURGE)
cupsdLogMessage(CUPSD_LOG_INFO, "[Job %d] Purged by \"%s\".", jobid,
username);
else
cupsdLogMessage(CUPSD_LOG_INFO, "[Job %d] Canceled by \"%s\".", jobid,
username);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'cancel_subscription()' - Cancel a subscription.
*/
static void
cancel_subscription(
cupsd_client_t *con, /* I - Client connection */
int sub_id) /* I - Subscription ID */
{
http_status_t status; /* Policy status */
cupsd_subscription_t *sub; /* Subscription */
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"cancel_subscription(con=%p[%d], sub_id=%d)",
con, con->number, sub_id);
/*
* Is the subscription ID valid?
*/
if ((sub = cupsdFindSubscription(sub_id)) == NULL)
{
/*
* Bad subscription ID...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("Subscription #%d does not exist."), sub_id);
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(sub->dest ? sub->dest->op_policy_ptr :
DefaultPolicyPtr,
con, sub->owner)) != HTTP_OK)
{
send_http_error(con, status, sub->dest);
return;
}
/*
* Cancel the subscription...
*/
cupsdDeleteSubscription(sub, 1);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'check_rss_recipient()' - Check that we do not have a duplicate RSS feed URI.
*/
static int /* O - 1 if OK, 0 if not */
check_rss_recipient(
const char *recipient) /* I - Recipient URI */
{
cupsd_subscription_t *sub; /* Current subscription */
for (sub = (cupsd_subscription_t *)cupsArrayFirst(Subscriptions);
sub;
sub = (cupsd_subscription_t *)cupsArrayNext(Subscriptions))
if (sub->recipient)
{
/*
* Compare the URIs up to the first ?...
*/
const char *r1, *r2;
for (r1 = recipient, r2 = sub->recipient;
*r1 == *r2 && *r1 && *r1 != '?' && *r2 && *r2 != '?';
r1 ++, r2 ++);
if (*r1 == *r2)
return (0);
}
return (1);
}
/*
* 'check_quotas()' - Check quotas for a printer and user.
*/
static int /* O - 1 if OK, 0 if forbidden,
-1 if limit reached */
check_quotas(cupsd_client_t *con, /* I - Client connection */
cupsd_printer_t *p) /* I - Printer or class */
{
char username[33], /* Username */
*name; /* Current user name */
cupsd_quota_t *q; /* Quota data */
#ifdef HAVE_MBR_UID_TO_UUID
/*
* Use Apple membership APIs which require that all names represent
* valid user account or group records accessible by the server.
*/
uuid_t usr_uuid; /* UUID for job requesting user */
uuid_t usr2_uuid; /* UUID for ACL user name entry */
uuid_t grp_uuid; /* UUID for ACL group name entry */
int mbr_err; /* Error from membership function */
int is_member; /* Is this user a member? */
#else
/*
* Use standard POSIX APIs for checking users and groups...
*/
struct passwd *pw; /* User password data */
#endif /* HAVE_MBR_UID_TO_UUID */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "check_quotas(%p[%d], %p[%s])",
con, con->number, p, p->name);
/*
* Figure out who is printing...
*/
strlcpy(username, get_username(con), sizeof(username));
if ((name = strchr(username, '@')) != NULL)
*name = '\0'; /* Strip @REALM */
/*
* Check global active job limits for printers and users...
*/
if (MaxJobsPerPrinter)
{
/*
* Check if there are too many pending jobs on this printer...
*/
if (cupsdGetPrinterJobCount(p->name) >= MaxJobsPerPrinter)
{
cupsdLogMessage(CUPSD_LOG_INFO, "Too many jobs for printer \"%s\"...",
p->name);
return (-1);
}
}
if (MaxJobsPerUser)
{
/*
* Check if there are too many pending jobs for this user...
*/
if (cupsdGetUserJobCount(username) >= MaxJobsPerUser)
{
cupsdLogMessage(CUPSD_LOG_INFO, "Too many jobs for user \"%s\"...",
username);
return (-1);
}
}
/*
* Check against users...
*/
if (cupsArrayCount(p->users) == 0 && p->k_limit == 0 && p->page_limit == 0)
return (1);
if (cupsArrayCount(p->users))
{
#ifdef HAVE_MBR_UID_TO_UUID
/*
* Get UUID for job requesting user...
*/
if (mbr_user_name_to_uuid((char *)username, usr_uuid))
{
/*
* Unknown user...
*/
cupsdLogMessage(CUPSD_LOG_DEBUG,
"check_quotas: UUID lookup failed for user \"%s\"",
username);
cupsdLogMessage(CUPSD_LOG_INFO,
"Denying user \"%s\" access to printer \"%s\" "
"(unknown user)...",
username, p->name);
return (0);
}
#else
/*
* Get UID and GID of requesting user...
*/
pw = getpwnam(username);
endpwent();
#endif /* HAVE_MBR_UID_TO_UUID */
for (name = (char *)cupsArrayFirst(p->users);
name;
name = (char *)cupsArrayNext(p->users))
if (name[0] == '@')
{
/*
* Check group membership...
*/
#ifdef HAVE_MBR_UID_TO_UUID
if (name[1] == '#')
{
if (uuid_parse(name + 2, grp_uuid))
uuid_clear(grp_uuid);
}
else if ((mbr_err = mbr_group_name_to_uuid(name + 1, grp_uuid)) != 0)
{
/*
* Invalid ACL entries are ignored for matching; just record a
* warning in the log...
*/
cupsdLogMessage(CUPSD_LOG_DEBUG,
"check_quotas: UUID lookup failed for ACL entry "
"\"%s\" (err=%d)", name, mbr_err);
cupsdLogMessage(CUPSD_LOG_WARN,
"Access control entry \"%s\" not a valid group name; "
"entry ignored", name);
}
if ((mbr_err = mbr_check_membership(usr_uuid, grp_uuid,
&is_member)) != 0)
{
/*
* At this point, there should be no errors, but check anyways...
*/
cupsdLogMessage(CUPSD_LOG_DEBUG,
"check_quotas: group \"%s\" membership check "
"failed (err=%d)", name + 1, mbr_err);
is_member = 0;
}
/*
* Stop if we found a match...
*/
if (is_member)
break;
#else
if (cupsdCheckGroup(username, pw, name + 1))
break;
#endif /* HAVE_MBR_UID_TO_UUID */
}
#ifdef HAVE_MBR_UID_TO_UUID
else
{
if (name[0] == '#')
{
if (uuid_parse(name + 1, usr2_uuid))
uuid_clear(usr2_uuid);
}
else if ((mbr_err = mbr_user_name_to_uuid(name, usr2_uuid)) != 0)
{
/*
* Invalid ACL entries are ignored for matching; just record a
* warning in the log...
*/
cupsdLogMessage(CUPSD_LOG_DEBUG,
"check_quotas: UUID lookup failed for ACL entry "
"\"%s\" (err=%d)", name, mbr_err);
cupsdLogMessage(CUPSD_LOG_WARN,
"Access control entry \"%s\" not a valid user name; "
"entry ignored", name);
}
if (!uuid_compare(usr_uuid, usr2_uuid))
break;
}
#else
else if (!_cups_strcasecmp(username, name))
break;
#endif /* HAVE_MBR_UID_TO_UUID */
if ((name != NULL) == p->deny_users)
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Denying user \"%s\" access to printer \"%s\"...",
username, p->name);
return (0);
}
}
/*
* Check quotas...
*/
if (p->k_limit || p->page_limit)
{
if ((q = cupsdUpdateQuota(p, username, 0, 0)) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to allocate quota data for user \"%s\"",
username);
return (-1);
}
if ((q->k_count >= p->k_limit && p->k_limit) ||
(q->page_count >= p->page_limit && p->page_limit))
{
cupsdLogMessage(CUPSD_LOG_INFO, "User \"%s\" is over the quota limit...",
username);
return (-1);
}
}
/*
* If we have gotten this far, we're done!
*/
return (1);
}
/*
* 'close_job()' - Close a multi-file job.
*/
static void
close_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
cupsd_job_t *job; /* Job */
ipp_attribute_t *attr; /* Attribute */
char job_uri[HTTP_MAX_URI],
/* Job URI */
username[256]; /* User name */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "close_job(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* See if we have a job URI or a printer URI...
*/
if (strcmp(uri->name, "printer-uri"))
{
/*
* job-uri is not supported by Close-Job!
*/
send_ipp_status(con, IPP_BAD_REQUEST,
_("Close-Job doesn't support the job-uri attribute."));
return;
}
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
if ((job = cupsdFindJob(attr->values[0].integer)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."),
attr->values[0].integer);
return;
}
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* Add any ending sheet...
*/
if (cupsdTimeoutJob(job))
return;
if (job->state_value == IPP_JOB_STOPPED)
{
job->state->values[0].integer = IPP_JOB_PENDING;
job->state_value = IPP_JOB_PENDING;
}
else if (job->state_value == IPP_JOB_HELD)
{
if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
if (!attr || !strcmp(attr->values[0].string.text, "no-hold"))
{
job->state->values[0].integer = IPP_JOB_PENDING;
job->state_value = IPP_JOB_PENDING;
}
}
job->dirty = 1;
cupsdMarkDirty(CUPSD_DIRTY_JOBS);
/*
* Fill in the response info...
*/
httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "ipp", NULL,
con->clientname, con->clientport, "/jobs/%d", job->id);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI, "job-uri", NULL,
job_uri);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_ENUM, "job-state",
job->state_value);
con->response->request.status.status_code = IPP_OK;
/*
* Start the job if necessary...
*/
cupsdCheckJobs();
}
/*
* 'copy_attrs()' - Copy attributes from one request to another.
*/
static void
copy_attrs(ipp_t *to, /* I - Destination request */
ipp_t *from, /* I - Source request */
cups_array_t *ra, /* I - Requested attributes */
ipp_tag_t group, /* I - Group to copy */
int quickcopy, /* I - Do a quick copy? */
cups_array_t *exclude) /* I - Attributes to exclude? */
{
ipp_attribute_t *fromattr; /* Source attribute */
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"copy_attrs(to=%p, from=%p, ra=%p, group=%x, quickcopy=%d)",
to, from, ra, group, quickcopy);
if (!to || !from)
return;
for (fromattr = from->attrs; fromattr; fromattr = fromattr->next)
{
/*
* Filter attributes as needed...
*/
if ((group != IPP_TAG_ZERO && fromattr->group_tag != group &&
fromattr->group_tag != IPP_TAG_ZERO) || !fromattr->name)
continue;
if (!strcmp(fromattr->name, "document-password") ||
!strcmp(fromattr->name, "job-authorization-uri") ||
!strcmp(fromattr->name, "job-password") ||
!strcmp(fromattr->name, "job-password-encryption") ||
!strcmp(fromattr->name, "job-printer-uri"))
continue;
if (exclude &&
(cupsArrayFind(exclude, fromattr->name) ||
cupsArrayFind(exclude, "all")))
{
/*
* We need to exclude this attribute for security reasons; we require the
* job-id attribute regardless of the security settings for IPP
* conformance.
*
* The job-printer-uri attribute is handled by copy_job_attrs().
*
* Subscription attribute security is handled by copy_subscription_attrs().
*/
if (strcmp(fromattr->name, "job-id"))
continue;
}
if (!ra || cupsArrayFind(ra, fromattr->name))
{
/*
* Don't send collection attributes by default to IPP/1.x clients
* since many do not support collections. Also don't send
* media-col-database unless specifically requested by the client.
*/
if (fromattr->value_tag == IPP_TAG_BEGIN_COLLECTION &&
!ra &&
(to->request.status.version[0] == 1 ||
!strcmp(fromattr->name, "media-col-database")))
continue;
ippCopyAttribute(to, fromattr, quickcopy);
}
}
}
/*
* 'copy_banner()' - Copy a banner file to the requests directory for the
* specified job.
*/
static int /* O - Size of banner file in kbytes */
copy_banner(cupsd_client_t *con, /* I - Client connection */
cupsd_job_t *job, /* I - Job information */
const char *name) /* I - Name of banner */
{
int i; /* Looping var */
int kbytes; /* Size of banner file in kbytes */
char filename[1024]; /* Job filename */
cupsd_banner_t *banner; /* Pointer to banner */
cups_file_t *in; /* Input file */
cups_file_t *out; /* Output file */
int ch; /* Character from file */
char attrname[255], /* Name of attribute */
*s; /* Pointer into name */
ipp_attribute_t *attr; /* Attribute */
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"copy_banner(con=%p[%d], job=%p[%d], name=\"%s\")",
con, con ? con->number : -1, job, job->id,
name ? name : "(null)");
/*
* Find the banner; return if not found or "none"...
*/
if (!name || !strcmp(name, "none") ||
(banner = cupsdFindBanner(name)) == NULL)
return (0);
/*
* Open the banner and job files...
*/
if (add_file(con, job, banner->filetype, 0))
return (-1);
snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot, job->id,
job->num_files);
if ((out = cupsFileOpen(filename, "w")) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to create banner job file %s - %s",
filename, strerror(errno));
job->num_files --;
return (0);
}
fchmod(cupsFileNumber(out), 0640);
fchown(cupsFileNumber(out), RunUser, Group);
/*
* Try the localized banner file under the subdirectory...
*/
strlcpy(attrname, job->attrs->attrs->next->values[0].string.text,
sizeof(attrname));
if (strlen(attrname) > 2 && attrname[2] == '-')
{
/*
* Convert ll-cc to ll_CC...
*/
attrname[2] = '_';
attrname[3] = (char)toupper(attrname[3] & 255);
attrname[4] = (char)toupper(attrname[4] & 255);
}
snprintf(filename, sizeof(filename), "%s/banners/%s/%s", DataDir,
attrname, name);
if (access(filename, 0) && strlen(attrname) > 2)
{
/*
* Wasn't able to find "ll_CC" locale file; try the non-national
* localization banner directory.
*/
attrname[2] = '\0';
snprintf(filename, sizeof(filename), "%s/banners/%s/%s", DataDir,
attrname, name);
}
if (access(filename, 0))
{
/*
* Use the non-localized banner file.
*/
snprintf(filename, sizeof(filename), "%s/banners/%s", DataDir, name);
}
if ((in = cupsFileOpen(filename, "r")) == NULL)
{
cupsFileClose(out);
unlink(filename);
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to open banner template file %s - %s",
filename, strerror(errno));
job->num_files --;
return (0);
}
/*
* Parse the file to the end...
*/
while ((ch = cupsFileGetChar(in)) != EOF)
if (ch == '{')
{
/*
* Get an attribute name...
*/
for (s = attrname; (ch = cupsFileGetChar(in)) != EOF;)
if (!isalpha(ch & 255) && ch != '-' && ch != '?')
break;
else if (s < (attrname + sizeof(attrname) - 1))
*s++ = (char)ch;
else
break;
*s = '\0';
if (ch != '}')
{
/*
* Ignore { followed by stuff that is not an attribute name...
*/
cupsFilePrintf(out, "{%s%c", attrname, ch);
continue;
}
/*
* See if it is defined...
*/
if (attrname[0] == '?')
s = attrname + 1;
else
s = attrname;
if (!strcmp(s, "printer-name"))
{
cupsFilePuts(out, job->dest);
continue;
}
else if ((attr = ippFindAttribute(job->attrs, s, IPP_TAG_ZERO)) == NULL)
{
/*
* See if we have a leading question mark...
*/
if (attrname[0] != '?')
{
/*
* Nope, write to file as-is; probably a PostScript procedure...
*/
cupsFilePrintf(out, "{%s}", attrname);
}
continue;
}
/*
* Output value(s)...
*/
for (i = 0; i < attr->num_values; i ++)
{
if (i)
cupsFilePutChar(out, ',');
switch (attr->value_tag)
{
case IPP_TAG_INTEGER :
case IPP_TAG_ENUM :
if (!strncmp(s, "time-at-", 8))
{
struct timeval tv; /* Time value */
tv.tv_sec = attr->values[i].integer;
tv.tv_usec = 0;
cupsFilePuts(out, cupsdGetDateTime(&tv, CUPSD_TIME_STANDARD));
}
else
cupsFilePrintf(out, "%d", attr->values[i].integer);
break;
case IPP_TAG_BOOLEAN :
cupsFilePrintf(out, "%d", attr->values[i].boolean);
break;
case IPP_TAG_NOVALUE :
cupsFilePuts(out, "novalue");
break;
case IPP_TAG_RANGE :
cupsFilePrintf(out, "%d-%d", attr->values[i].range.lower,
attr->values[i].range.upper);
break;
case IPP_TAG_RESOLUTION :
cupsFilePrintf(out, "%dx%d%s", attr->values[i].resolution.xres,
attr->values[i].resolution.yres,
attr->values[i].resolution.units == IPP_RES_PER_INCH ?
"dpi" : "dpcm");
break;
case IPP_TAG_URI :
case IPP_TAG_STRING :
case IPP_TAG_TEXT :
case IPP_TAG_NAME :
case IPP_TAG_KEYWORD :
case IPP_TAG_CHARSET :
case IPP_TAG_LANGUAGE :
if (!_cups_strcasecmp(banner->filetype->type, "postscript"))
{
/*
* Need to quote strings for PS banners...
*/
const char *p;
for (p = attr->values[i].string.text; *p; p ++)
{
if (*p == '(' || *p == ')' || *p == '\\')
{
cupsFilePutChar(out, '\\');
cupsFilePutChar(out, *p);
}
else if (*p < 32 || *p > 126)
cupsFilePrintf(out, "\\%03o", *p & 255);
else
cupsFilePutChar(out, *p);
}
}
else
cupsFilePuts(out, attr->values[i].string.text);
break;
default :
break; /* anti-compiler-warning-code */
}
}
}
else if (ch == '\\') /* Quoted char */
{
ch = cupsFileGetChar(in);
if (ch != '{') /* Only do special handling for \{ */
cupsFilePutChar(out, '\\');
cupsFilePutChar(out, ch);
}
else
cupsFilePutChar(out, ch);
cupsFileClose(in);
kbytes = (cupsFileTell(out) + 1023) / 1024;
job->koctets += kbytes;
if ((attr = ippFindAttribute(job->attrs, "job-k-octets", IPP_TAG_INTEGER)) != NULL)
attr->values[0].integer += kbytes;
cupsFileClose(out);
return (kbytes);
}
/*
* 'copy_file()' - Copy a PPD file...
*/
static int /* O - 0 = success, -1 = error */
copy_file(const char *from, /* I - Source file */
const char *to, /* I - Destination file */
mode_t mode) /* I - Permissions */
{
cups_file_t *src, /* Source file */
*dst; /* Destination file */
int bytes; /* Bytes to read/write */
char buffer[2048]; /* Copy buffer */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "copy_file(\"%s\", \"%s\")", from, to);
/*
* Open the source and destination file for a copy...
*/
if ((src = cupsFileOpen(from, "rb")) == NULL)
return (-1);
if ((dst = cupsdCreateConfFile(to, mode)) == NULL)
{
cupsFileClose(src);
return (-1);
}
/*
* Copy the source file to the destination...
*/
while ((bytes = cupsFileRead(src, buffer, sizeof(buffer))) > 0)
if (cupsFileWrite(dst, buffer, (size_t)bytes) < bytes)
{
cupsFileClose(src);
cupsFileClose(dst);
return (-1);
}
/*
* Close both files and return...
*/
cupsFileClose(src);
return (cupsdCloseCreatedConfFile(dst, to));
}
/*
* 'copy_model()' - Copy a PPD model file, substituting default values
* as needed...
*/
static int /* O - 0 = success, -1 = error */
copy_model(cupsd_client_t *con, /* I - Client connection */
const char *from, /* I - Source file */
const char *to) /* I - Destination file */
{
fd_set input; /* select() input set */
struct timeval timeout; /* select() timeout */
int maxfd; /* Max file descriptor for select() */
char tempfile[1024]; /* Temporary PPD file */
int tempfd; /* Temporary PPD file descriptor */
int temppid; /* Process ID of cups-driverd */
int temppipe[2]; /* Temporary pipes */
char *argv[4], /* Command-line arguments */
*envp[MAX_ENV]; /* Environment */
cups_file_t *src, /* Source file */
*dst; /* Destination file */
ppd_file_t *ppd; /* PPD file */
int bytes, /* Bytes from pipe */
total; /* Total bytes from pipe */
char buffer[2048]; /* Copy buffer */
int i; /* Looping var */
char option[PPD_MAX_NAME], /* Option name */
choice[PPD_MAX_NAME]; /* Choice name */
ppd_size_t *size; /* Default size */
int num_defaults; /* Number of default options */
cups_option_t *defaults; /* Default options */
char cups_protocol[PPD_MAX_LINE];
/* cupsProtocol attribute */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "copy_model(con=%p, from=\"%s\", to=\"%s\")", con, from, to);
/*
* Run cups-driverd to get the PPD file...
*/
argv[0] = "cups-driverd";
argv[1] = "cat";
argv[2] = (char *)from;
argv[3] = NULL;
cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
snprintf(buffer, sizeof(buffer), "%s/daemon/cups-driverd", ServerBin);
snprintf(tempfile, sizeof(tempfile), "%s/%d.ppd", TempDir, con->number);
tempfd = open(tempfile, O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (tempfd < 0 || cupsdOpenPipe(temppipe))
return (-1);
cupsdLogMessage(CUPSD_LOG_DEBUG,
"copy_model: Running \"cups-driverd cat %s\"...", from);
if (!cupsdStartProcess(buffer, argv, envp, -1, temppipe[1], CGIPipes[1],
-1, -1, 0, DefaultProfile, NULL, &temppid))
{
close(tempfd);
unlink(tempfile);
return (-1);
}
close(temppipe[1]);
/*
* Wait up to 30 seconds for the PPD file to be copied...
*/
total = 0;
if (temppipe[0] > CGIPipes[0])
maxfd = temppipe[0] + 1;
else
maxfd = CGIPipes[0] + 1;
for (;;)
{
/*
* See if we have data ready...
*/
FD_ZERO(&input);
FD_SET(temppipe[0], &input);
FD_SET(CGIPipes[0], &input);
timeout.tv_sec = 30;
timeout.tv_usec = 0;
if ((i = select(maxfd, &input, NULL, NULL, &timeout)) < 0)
{
if (errno == EINTR)
continue;
else
break;
}
else if (i == 0)
{
/*
* We have timed out...
*/
break;
}
if (FD_ISSET(temppipe[0], &input))
{
/*
* Read the PPD file from the pipe, and write it to the PPD file.
*/
if ((bytes = read(temppipe[0], buffer, sizeof(buffer))) > 0)
{
if (write(tempfd, buffer, (size_t)bytes) < bytes)
break;
total += bytes;
}
else
break;
}
if (FD_ISSET(CGIPipes[0], &input))
cupsdUpdateCGI();
}
close(temppipe[0]);
close(tempfd);
if (!total)
{
/*
* No data from cups-deviced...
*/
cupsdLogMessage(CUPSD_LOG_ERROR, "copy_model: empty PPD file");
unlink(tempfile);
return (-1);
}
/*
* Open the source file for a copy...
*/
if ((src = cupsFileOpen(tempfile, "rb")) == NULL)
{
unlink(tempfile);
return (-1);
}
/*
* Read the source file and see what page sizes are supported...
*/
if ((ppd = _ppdOpen(src, _PPD_LOCALIZATION_NONE)) == NULL)
{
cupsFileClose(src);
unlink(tempfile);
return (-1);
}
/*
* Open the destination (if possible) and set the default options...
*/
num_defaults = 0;
defaults = NULL;
cups_protocol[0] = '\0';
if ((dst = cupsFileOpen(to, "rb")) != NULL)
{
/*
* Read all of the default lines from the old PPD...
*/
while (cupsFileGets(dst, buffer, sizeof(buffer)))
if (!strncmp(buffer, "*Default", 8))
{
/*
* Add the default option...
*/
if (!ppd_parse_line(buffer, option, sizeof(option),
choice, sizeof(choice)))
{
ppd_option_t *ppdo; /* PPD option */
/*
* Only add the default if the default hasn't already been
* set and the choice exists in the new PPD...
*/
if (!cupsGetOption(option, num_defaults, defaults) &&
(ppdo = ppdFindOption(ppd, option)) != NULL &&
ppdFindChoice(ppdo, choice))
num_defaults = cupsAddOption(option, choice, num_defaults,
&defaults);
}
}
else if (!strncmp(buffer, "*cupsProtocol:", 14))
strlcpy(cups_protocol, buffer, sizeof(cups_protocol));
cupsFileClose(dst);
}
else if ((size = ppdPageSize(ppd, DefaultPaperSize)) != NULL)
{
/*
* Add the default media sizes...
*/
num_defaults = cupsAddOption("PageSize", size->name,
num_defaults, &defaults);
num_defaults = cupsAddOption("PageRegion", size->name,
num_defaults, &defaults);
num_defaults = cupsAddOption("PaperDimension", size->name,
num_defaults, &defaults);
num_defaults = cupsAddOption("ImageableArea", size->name,
num_defaults, &defaults);
}
ppdClose(ppd);
/*
* Open the destination file for a copy...
*/
if ((dst = cupsdCreateConfFile(to, ConfigFilePerm)) == NULL)
{
cupsFreeOptions(num_defaults, defaults);
cupsFileClose(src);
unlink(tempfile);
return (-1);
}
/*
* Copy the source file to the destination...
*/
cupsFileRewind(src);
while (cupsFileGets(src, buffer, sizeof(buffer)))
{
if (!strncmp(buffer, "*Default", 8))
{
/*
* Check for an previous default option choice...
*/
if (!ppd_parse_line(buffer, option, sizeof(option),
choice, sizeof(choice)))
{
const char *val; /* Default option value */
if ((val = cupsGetOption(option, num_defaults, defaults)) != NULL)
{
/*
* Substitute the previous choice...
*/
snprintf(buffer, sizeof(buffer), "*Default%s: %s", option, val);
}
}
}
cupsFilePrintf(dst, "%s\n", buffer);
}
if (cups_protocol[0])
cupsFilePrintf(dst, "%s\n", cups_protocol);
cupsFreeOptions(num_defaults, defaults);
/*
* Close both files and return...
*/
cupsFileClose(src);
unlink(tempfile);
return (cupsdCloseCreatedConfFile(dst, to));
}
/*
* 'copy_job_attrs()' - Copy job attributes.
*/
static void
copy_job_attrs(cupsd_client_t *con, /* I - Client connection */
cupsd_job_t *job, /* I - Job */
cups_array_t *ra, /* I - Requested attributes array */
cups_array_t *exclude) /* I - Private attributes array */
{
char job_uri[HTTP_MAX_URI]; /* Job URI */
/*
* Send the requested attributes for each job...
*/
if (!cupsArrayFind(exclude, "all"))
{
if ((!exclude || !cupsArrayFind(exclude, "number-of-documents")) &&
(!ra || cupsArrayFind(ra, "number-of-documents")))
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER,
"number-of-documents", job->num_files);
if ((!exclude || !cupsArrayFind(exclude, "job-media-progress")) &&
(!ra || cupsArrayFind(ra, "job-media-progress")))
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER,
"job-media-progress", job->progress);
if ((!exclude || !cupsArrayFind(exclude, "job-more-info")) &&
(!ra || cupsArrayFind(ra, "job-more-info")))
{
httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "http",
NULL, con->clientname, con->clientport, "/jobs/%d",
job->id);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI,
"job-more-info", NULL, job_uri);
}
if (job->state_value > IPP_JOB_PROCESSING &&
(!exclude || !cupsArrayFind(exclude, "job-preserved")) &&
(!ra || cupsArrayFind(ra, "job-preserved")))
ippAddBoolean(con->response, IPP_TAG_JOB, "job-preserved",
job->num_files > 0);
if ((!exclude || !cupsArrayFind(exclude, "job-printer-up-time")) &&
(!ra || cupsArrayFind(ra, "job-printer-up-time")))
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER,
"job-printer-up-time", time(NULL));
}
if (!ra || cupsArrayFind(ra, "job-printer-uri"))
{
httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "ipp", NULL,
con->clientname, con->clientport,
(job->dtype & CUPS_PRINTER_CLASS) ? "/classes/%s" :
"/printers/%s",
job->dest);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI,
"job-printer-uri", NULL, job_uri);
}
if (!ra || cupsArrayFind(ra, "job-uri"))
{
httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "ipp", NULL,
con->clientname, con->clientport, "/jobs/%d",
job->id);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI,
"job-uri", NULL, job_uri);
}
if (job->attrs)
{
copy_attrs(con->response, job->attrs, ra, IPP_TAG_JOB, 0, exclude);
}
else
{
/*
* Generate attributes from the job structure...
*/
if (job->completed_time && (!ra || cupsArrayFind(ra, "date-time-at-completed")))
ippAddDate(con->response, IPP_TAG_JOB, "date-time-at-completed", ippTimeToDate(job->completed_time));
if (job->creation_time && (!ra || cupsArrayFind(ra, "date-time-at-creation")))
ippAddDate(con->response, IPP_TAG_JOB, "date-time-at-creation", ippTimeToDate(job->creation_time));
if (!ra || cupsArrayFind(ra, "job-id"))
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id);
if (!ra || cupsArrayFind(ra, "job-k-octets"))
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-k-octets", job->koctets);
if (job->name && (!ra || cupsArrayFind(ra, "job-name")))
ippAddString(con->response, IPP_TAG_JOB, IPP_CONST_TAG(IPP_TAG_NAME), "job-name", NULL, job->name);
if (job->username && (!ra || cupsArrayFind(ra, "job-originating-user-name")))
ippAddString(con->response, IPP_TAG_JOB, IPP_CONST_TAG(IPP_TAG_NAME), "job-originating-user-name", NULL, job->username);
if (!ra || cupsArrayFind(ra, "job-state"))
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_ENUM, "job-state", (int)job->state_value);
if (!ra || cupsArrayFind(ra, "job-state-reasons"))
{
switch (job->state_value)
{
default : /* Should never get here for processing, pending, held, or stopped jobs since they don't get unloaded... */
break;
case IPP_JSTATE_ABORTED :
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons", NULL, "job-aborted-by-system");
break;
case IPP_JSTATE_CANCELED :
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons", NULL, "job-canceled-by-user");
break;
case IPP_JSTATE_COMPLETED :
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons", NULL, "job-completed-successfully");
break;
}
}
if (job->completed_time && (!ra || cupsArrayFind(ra, "time-at-completed")))
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "time-at-completed", (int)job->completed_time);
if (job->creation_time && (!ra || cupsArrayFind(ra, "time-at-creation")))
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "time-at-creation", (int)job->creation_time);
}
}
/*
* 'copy_printer_attrs()' - Copy printer attributes.
*/
static void
copy_printer_attrs(
cupsd_client_t *con, /* I - Client connection */
cupsd_printer_t *printer, /* I - Printer */
cups_array_t *ra) /* I - Requested attributes array */
{
char printer_uri[HTTP_MAX_URI];
/* Printer URI */
char printer_icons[HTTP_MAX_URI];
/* Printer icons */
time_t curtime; /* Current time */
int i; /* Looping var */
/*
* Copy the printer attributes to the response using requested-attributes
* and document-format attributes that may be provided by the client.
*/
curtime = time(NULL);
if (!ra || cupsArrayFind(ra, "marker-change-time"))
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_INTEGER,
"marker-change-time", printer->marker_time);
if (printer->num_printers > 0 &&
(!ra || cupsArrayFind(ra, "member-uris")))
{
ipp_attribute_t *member_uris; /* member-uris attribute */
cupsd_printer_t *p2; /* Printer in class */
ipp_attribute_t *p2_uri; /* printer-uri-supported for class printer */
if ((member_uris = ippAddStrings(con->response, IPP_TAG_PRINTER,
IPP_TAG_URI, "member-uris",
printer->num_printers, NULL,
NULL)) != NULL)
{
for (i = 0; i < printer->num_printers; i ++)
{
p2 = printer->printers[i];
if ((p2_uri = ippFindAttribute(p2->attrs, "printer-uri-supported",
IPP_TAG_URI)) != NULL)
member_uris->values[i].string.text =
_cupsStrRetain(p2_uri->values[0].string.text);
else
{
httpAssembleURIf(HTTP_URI_CODING_ALL, printer_uri,
sizeof(printer_uri), "ipp", NULL, con->clientname,
con->clientport,
(p2->type & CUPS_PRINTER_CLASS) ?
"/classes/%s" : "/printers/%s", p2->name);
member_uris->values[i].string.text = _cupsStrAlloc(printer_uri);
}
}
}
}
if (printer->alert && (!ra || cupsArrayFind(ra, "printer-alert")))
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_STRING,
"printer-alert", NULL, printer->alert);
if (printer->alert_description &&
(!ra || cupsArrayFind(ra, "printer-alert-description")))
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_TEXT,
"printer-alert-description", NULL,
printer->alert_description);
if (!ra || cupsArrayFind(ra, "printer-config-change-date-time"))
ippAddDate(con->response, IPP_TAG_PRINTER, "printer-config-change-date-time", ippTimeToDate(printer->config_time));
if (!ra || cupsArrayFind(ra, "printer-config-change-time"))
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_INTEGER,
"printer-config-change-time", printer->config_time);
if (!ra || cupsArrayFind(ra, "printer-current-time"))
ippAddDate(con->response, IPP_TAG_PRINTER, "printer-current-time",
ippTimeToDate(curtime));
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
if (!ra || cupsArrayFind(ra, "printer-dns-sd-name"))
{
if (printer->reg_name)
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_NAME,
"printer-dns-sd-name", NULL, printer->reg_name);
else
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_NOVALUE,
"printer-dns-sd-name", 0);
}
#endif /* HAVE_DNSSD || HAVE_AVAHI */
if (!ra || cupsArrayFind(ra, "printer-error-policy"))
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_NAME,
"printer-error-policy", NULL, printer->error_policy);
if (!ra || cupsArrayFind(ra, "printer-error-policy-supported"))
{
static const char * const errors[] =/* printer-error-policy-supported values */
{
"abort-job",
"retry-current-job",
"retry-job",
"stop-printer"
};
if (printer->type & CUPS_PRINTER_CLASS)
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_NAME | IPP_TAG_COPY,
"printer-error-policy-supported", NULL, "retry-current-job");
else
ippAddStrings(con->response, IPP_TAG_PRINTER, IPP_TAG_NAME | IPP_TAG_COPY,
"printer-error-policy-supported",
sizeof(errors) / sizeof(errors[0]), NULL, errors);
}
if (!ra || cupsArrayFind(ra, "printer-icons"))
{
httpAssembleURIf(HTTP_URI_CODING_ALL, printer_icons, sizeof(printer_icons),
"http", NULL, con->clientname, con->clientport,
"/icons/%s.png", printer->name);
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_URI, "printer-icons",
NULL, printer_icons);
cupsdLogMessage(CUPSD_LOG_DEBUG2, "printer-icons=\"%s\"", printer_icons);
}
if (!ra || cupsArrayFind(ra, "printer-is-accepting-jobs"))
ippAddBoolean(con->response, IPP_TAG_PRINTER, "printer-is-accepting-jobs", (char)printer->accepting);
if (!ra || cupsArrayFind(ra, "printer-is-shared"))
ippAddBoolean(con->response, IPP_TAG_PRINTER, "printer-is-shared", (char)printer->shared);
if (!ra || cupsArrayFind(ra, "printer-is-temporary"))
ippAddBoolean(con->response, IPP_TAG_PRINTER, "printer-is-temporary", (char)printer->temporary);
if (!ra || cupsArrayFind(ra, "printer-more-info"))
{
httpAssembleURIf(HTTP_URI_CODING_ALL, printer_uri, sizeof(printer_uri),
"http", NULL, con->clientname, con->clientport,
(printer->type & CUPS_PRINTER_CLASS) ?
"/classes/%s" : "/printers/%s", printer->name);
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_URI,
"printer-more-info", NULL, printer_uri);
}
if (!ra || cupsArrayFind(ra, "printer-op-policy"))
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_NAME,
"printer-op-policy", NULL, printer->op_policy);
if (!ra || cupsArrayFind(ra, "printer-state"))
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_ENUM, "printer-state",
printer->state);
if (!ra || cupsArrayFind(ra, "printer-state-change-date-time"))
ippAddDate(con->response, IPP_TAG_PRINTER, "printer-state-change-date-time", ippTimeToDate(printer->state_time));
if (!ra || cupsArrayFind(ra, "printer-state-change-time"))
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_INTEGER,
"printer-state-change-time", printer->state_time);
if (!ra || cupsArrayFind(ra, "printer-state-message"))
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_TEXT,
"printer-state-message", NULL, printer->state_message);
if (!ra || cupsArrayFind(ra, "printer-state-reasons"))
add_printer_state_reasons(con, printer);
if (!ra || cupsArrayFind(ra, "printer-type"))
{
cups_ptype_t type; /* printer-type value */
/*
* Add the CUPS-specific printer-type attribute...
*/
type = printer->type;
if (printer == DefaultPrinter)
type |= CUPS_PRINTER_DEFAULT;
if (!printer->accepting)
type |= CUPS_PRINTER_REJECTING;
if (!printer->shared)
type |= CUPS_PRINTER_NOT_SHARED;
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_ENUM, "printer-type", (int)type);
}
if (!ra || cupsArrayFind(ra, "printer-up-time"))
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_INTEGER,
"printer-up-time", curtime);
if (!ra || cupsArrayFind(ra, "printer-uri-supported"))
{
httpAssembleURIf(HTTP_URI_CODING_ALL, printer_uri, sizeof(printer_uri),
"ipp", NULL, con->clientname, con->clientport,
(printer->type & CUPS_PRINTER_CLASS) ?
"/classes/%s" : "/printers/%s", printer->name);
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_URI,
"printer-uri-supported", NULL, printer_uri);
cupsdLogMessage(CUPSD_LOG_DEBUG2, "printer-uri-supported=\"%s\"",
printer_uri);
}
if (!ra || cupsArrayFind(ra, "queued-job-count"))
add_queued_job_count(con, printer);
copy_attrs(con->response, printer->attrs, ra, IPP_TAG_ZERO, 0, NULL);
if (printer->ppd_attrs)
copy_attrs(con->response, printer->ppd_attrs, ra, IPP_TAG_ZERO, 0, NULL);
copy_attrs(con->response, CommonData, ra, IPP_TAG_ZERO, IPP_TAG_COPY, NULL);
}
/*
* 'copy_subscription_attrs()' - Copy subscription attributes.
*/
static void
copy_subscription_attrs(
cupsd_client_t *con, /* I - Client connection */
cupsd_subscription_t *sub, /* I - Subscription */
cups_array_t *ra, /* I - Requested attributes array */
cups_array_t *exclude) /* I - Private attributes array */
{
ipp_attribute_t *attr; /* Current attribute */
char printer_uri[HTTP_MAX_URI];
/* Printer URI */
int count; /* Number of events */
unsigned mask; /* Current event mask */
const char *name; /* Current event name */
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"copy_subscription_attrs(con=%p, sub=%p, ra=%p, exclude=%p)",
con, sub, ra, exclude);
/*
* Copy the subscription attributes to the response using the
* requested-attributes attribute that may be provided by the client.
*/
if (!exclude || !cupsArrayFind(exclude, "all"))
{
if ((!exclude || !cupsArrayFind(exclude, "notify-events")) &&
(!ra || cupsArrayFind(ra, "notify-events")))
{
cupsdLogMessage(CUPSD_LOG_DEBUG2, "copy_subscription_attrs: notify-events");
if ((name = cupsdEventName((cupsd_eventmask_t)sub->mask)) != NULL)
{
/*
* Simple event list...
*/
ippAddString(con->response, IPP_TAG_SUBSCRIPTION,
(ipp_tag_t)(IPP_TAG_KEYWORD | IPP_TAG_COPY),
"notify-events", NULL, name);
}
else
{
/*
* Complex event list...
*/
for (mask = 1, count = 0; mask < CUPSD_EVENT_ALL; mask <<= 1)
if (sub->mask & mask)
count ++;
attr = ippAddStrings(con->response, IPP_TAG_SUBSCRIPTION,
(ipp_tag_t)(IPP_TAG_KEYWORD | IPP_TAG_COPY),
"notify-events", count, NULL, NULL);
for (mask = 1, count = 0; mask < CUPSD_EVENT_ALL; mask <<= 1)
if (sub->mask & mask)
{
attr->values[count].string.text =
(char *)cupsdEventName((cupsd_eventmask_t)mask);
count ++;
}
}
}
if ((!exclude || !cupsArrayFind(exclude, "notify-lease-duration")) &&
(!sub->job && (!ra || cupsArrayFind(ra, "notify-lease-duration"))))
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER,
"notify-lease-duration", sub->lease);
if ((!exclude || !cupsArrayFind(exclude, "notify-recipient-uri")) &&
(sub->recipient && (!ra || cupsArrayFind(ra, "notify-recipient-uri"))))
ippAddString(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_URI,
"notify-recipient-uri", NULL, sub->recipient);
else if ((!exclude || !cupsArrayFind(exclude, "notify-pull-method")) &&
(!ra || cupsArrayFind(ra, "notify-pull-method")))
ippAddString(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_KEYWORD,
"notify-pull-method", NULL, "ippget");
if ((!exclude || !cupsArrayFind(exclude, "notify-subscriber-user-name")) &&
(!ra || cupsArrayFind(ra, "notify-subscriber-user-name")))
ippAddString(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_NAME,
"notify-subscriber-user-name", NULL, sub->owner);
if ((!exclude || !cupsArrayFind(exclude, "notify-time-interval")) &&
(!ra || cupsArrayFind(ra, "notify-time-interval")))
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER,
"notify-time-interval", sub->interval);
if (sub->user_data_len > 0 &&
(!exclude || !cupsArrayFind(exclude, "notify-user-data")) &&
(!ra || cupsArrayFind(ra, "notify-user-data")))
ippAddOctetString(con->response, IPP_TAG_SUBSCRIPTION, "notify-user-data",
sub->user_data, sub->user_data_len);
}
if (sub->job && (!ra || cupsArrayFind(ra, "notify-job-id")))
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER,
"notify-job-id", sub->job->id);
if (sub->dest && (!ra || cupsArrayFind(ra, "notify-printer-uri")))
{
httpAssembleURIf(HTTP_URI_CODING_ALL, printer_uri, sizeof(printer_uri),
"ipp", NULL, con->clientname, con->clientport,
"/printers/%s", sub->dest->name);
ippAddString(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_URI,
"notify-printer-uri", NULL, printer_uri);
}
if (!ra || cupsArrayFind(ra, "notify-subscription-id"))
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER,
"notify-subscription-id", sub->id);
}
/*
* 'create_job()' - Print a file to a printer or class.
*/
static void
create_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
int i; /* Looping var */
cupsd_printer_t *printer; /* Printer */
cupsd_job_t *job; /* New job */
static const char * const forbidden_attrs[] =
{ /* List of forbidden attributes */
"compression",
"document-format",
"document-name",
"document-natural-language"
};
cupsdLogMessage(CUPSD_LOG_DEBUG2, "create_job(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, NULL, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check for invalid Create-Job attributes and log a warning or error depending
* on whether cupsd is running in "strict conformance" mode...
*/
for (i = 0;
i < (int)(sizeof(forbidden_attrs) / sizeof(forbidden_attrs[0]));
i ++)
if (ippFindAttribute(con->request, forbidden_attrs[i], IPP_TAG_ZERO))
{
if (StrictConformance)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("The '%s' operation attribute cannot be supplied in a "
"Create-Job request."), forbidden_attrs[i]);
return;
}
cupsdLogMessage(CUPSD_LOG_WARN,
"Unexpected '%s' operation attribute in a Create-Job "
"request.", forbidden_attrs[i]);
}
/*
* Create the job object...
*/
if ((job = add_job(con, printer, NULL)) == NULL)
return;
job->pending_timeout = 1;
/*
* Save and log the job...
*/
cupsdLogJob(job, CUPSD_LOG_INFO, "Queued on \"%s\" by \"%s\".",
job->dest, job->username);
}
/*
* 'create_local_bg_thread()' - Background thread for creating a local print queue.
*/
static void * /* O - Exit status */
create_local_bg_thread(
cupsd_printer_t *printer) /* I - Printer */
{
cups_file_t *from, /* Source file */
*to; /* Destination file */
char fromppd[1024], /* Source PPD */
toppd[1024], /* Destination PPD */
scheme[32], /* URI scheme */
userpass[256], /* User:pass */
host[256], /* Hostname */
resource[1024], /* Resource path */
line[1024]; /* Line from PPD */
int port; /* Port number */
http_encryption_t encryption; /* Type of encryption to use */
http_t *http; /* Connection to printer */
ipp_t *request, /* Request to printer */
*response; /* Response from printer */
ipp_attribute_t *attr; /* Attribute in response */
/*
* Try connecting to the printer...
*/
cupsdLogMessage(CUPSD_LOG_DEBUG, "%s: Generating PPD file from \"%s\"...", printer->name, printer->device_uri);
if (httpSeparateURI(HTTP_URI_CODING_ALL, printer->device_uri, scheme, sizeof(scheme), userpass, sizeof(userpass), host, sizeof(host), &port, resource, sizeof(resource)) < HTTP_URI_STATUS_OK)
{
cupsdLogMessage(CUPSD_LOG_ERROR, "%s: Bad device URI \"%s\".", printer->name, printer->device_uri);
return (NULL);
}
if (!strcmp(scheme, "ipps") || port == 443)
encryption = HTTP_ENCRYPTION_ALWAYS;
else
encryption = HTTP_ENCRYPTION_IF_REQUESTED;
if ((http = httpConnect2(host, port, NULL, AF_UNSPEC, encryption, 1, 30000, NULL)) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR, "%s: Unable to connect to %s:%d: %s", printer->name, host, port, cupsLastErrorString());
return (NULL);
}
/*
* Query the printer for its capabilities...
*/
cupsdLogMessage(CUPSD_LOG_DEBUG, "%s: Connected to %s:%d, sending Get-Printer-Attributes request...", printer->name, host, port);
request = ippNewRequest(IPP_OP_GET_PRINTER_ATTRIBUTES);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printer->device_uri);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", NULL, "all");
response = cupsDoRequest(http, request, resource);
cupsdLogMessage(CUPSD_LOG_DEBUG, "%s: Get-Printer-Attributes returned %s", printer->name, ippErrorString(cupsLastError()));
// TODO: Grab printer icon file...
httpClose(http);
/*
* Write the PPD for the queue...
*/
if (_ppdCreateFromIPP(fromppd, sizeof(fromppd), response))
{
if ((!printer->info || !*(printer->info)) && (attr = ippFindAttribute(response, "printer-info", IPP_TAG_TEXT)) != NULL)
cupsdSetString(&printer->info, ippGetString(attr, 0, NULL));
if ((!printer->location || !*(printer->location)) && (attr = ippFindAttribute(response, "printer-location", IPP_TAG_TEXT)) != NULL)
cupsdSetString(&printer->location, ippGetString(attr, 0, NULL));
if ((!printer->geo_location || !*(printer->geo_location)) && (attr = ippFindAttribute(response, "printer-geo-location", IPP_TAG_URI)) != NULL)
cupsdSetString(&printer->geo_location, ippGetString(attr, 0, NULL));
if ((from = cupsFileOpen(fromppd, "r")) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR, "%s: Unable to read generated PPD: %s", printer->name, strerror(errno));
return (NULL);
}
snprintf(toppd, sizeof(toppd), "%s/ppd/%s.ppd", ServerRoot, printer->name);
if ((to = cupsdCreateConfFile(toppd, ConfigFilePerm)) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR, "%s: Unable to create PPD for printer: %s", printer->name, strerror(errno));
cupsFileClose(from);
return (NULL);
}
while (cupsFileGets(from, line, sizeof(line)))
cupsFilePrintf(to, "%s\n", line);
cupsFileClose(from);
if (!cupsdCloseCreatedConfFile(to, toppd))
{
printer->config_time = time(NULL);
printer->state = IPP_PSTATE_IDLE;
printer->accepting = 1;
cupsdSetPrinterAttrs(printer);
cupsdAddEvent(CUPSD_EVENT_PRINTER_CONFIG, printer, NULL, "Printer \"%s\" is now available.", printer->name);
cupsdLogMessage(CUPSD_LOG_INFO, "Printer \"%s\" is now available.", printer->name);
}
}
else
cupsdLogMessage(CUPSD_LOG_ERROR, "%s: PPD creation failed: %s", printer->name, cupsLastErrorString());
return (NULL);
}
/*
* 'create_local_printer()' - Create a local (temporary) print queue.
*/
static void
create_local_printer(
cupsd_client_t *con) /* I - Client connection */
{
ipp_attribute_t *device_uri, /* device-uri attribute */
*printer_geo_location, /* printer-geo-location attribute */
*printer_info, /* printer-info attribute */
*printer_location, /* printer-location attribute */
*printer_name; /* printer-name attribute */
cupsd_printer_t *printer; /* New printer */
http_status_t status; /* Policy status */
char name[128], /* Sanitized printer name */
*nameptr, /* Pointer into name */
uri[1024]; /* printer-uri-supported value */
const char *ptr; /* Pointer into attribute value */
/*
* Require local access to create a local printer...
*/
if (!httpAddrLocalhost(httpGetAddress(con->http)))
{
send_ipp_status(con, IPP_STATUS_ERROR_FORBIDDEN, _("Only local users can create a local printer."));
return;
}
/*
* Check any other policy limits...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Grab needed attributes...
*/
if ((printer_name = ippFindAttribute(con->request, "printer-name", IPP_TAG_ZERO)) == NULL || ippGetGroupTag(printer_name) != IPP_TAG_PRINTER || ippGetValueTag(printer_name) != IPP_TAG_NAME)
{
if (!printer_name)
send_ipp_status(con, IPP_STATUS_ERROR_BAD_REQUEST, _("Missing required attribute \"%s\"."), "printer-name");
else if (ippGetGroupTag(printer_name) != IPP_TAG_PRINTER)
send_ipp_status(con, IPP_STATUS_ERROR_BAD_REQUEST, _("Attribute \"%s\" is in the wrong group."), "printer-name");
else
send_ipp_status(con, IPP_STATUS_ERROR_BAD_REQUEST, _("Attribute \"%s\" is the wrong value type."), "printer-name");
return;
}
for (nameptr = name, ptr = ippGetString(printer_name, 0, NULL); *ptr && nameptr < (name + sizeof(name) - 1); ptr ++)
{
/*
* Sanitize the printer name...
*/
if (_cups_isalnum(*ptr))
*nameptr++ = *ptr;
else if (nameptr == name || nameptr[-1] != '_')
*nameptr++ = '_';
}
*nameptr = '\0';
if ((device_uri = ippFindAttribute(con->request, "device-uri", IPP_TAG_ZERO)) == NULL || ippGetGroupTag(device_uri) != IPP_TAG_PRINTER || ippGetValueTag(device_uri) != IPP_TAG_URI)
{
if (!device_uri)
send_ipp_status(con, IPP_STATUS_ERROR_BAD_REQUEST, _("Missing required attribute \"%s\"."), "device-uri");
else if (ippGetGroupTag(device_uri) != IPP_TAG_PRINTER)
send_ipp_status(con, IPP_STATUS_ERROR_BAD_REQUEST, _("Attribute \"%s\" is in the wrong group."), "device-uri");
else
send_ipp_status(con, IPP_STATUS_ERROR_BAD_REQUEST, _("Attribute \"%s\" is the wrong value type."), "device-uri");
return;
}
printer_geo_location = ippFindAttribute(con->request, "printer-geo-location", IPP_TAG_URI);
printer_info = ippFindAttribute(con->request, "printer-info", IPP_TAG_TEXT);
printer_location = ippFindAttribute(con->request, "printer-location", IPP_TAG_TEXT);
/*
* See if the printer already exists...
*/
if ((printer = cupsdFindDest(name)) != NULL)
{
send_ipp_status(con, IPP_STATUS_ERROR_NOT_POSSIBLE, _("Printer \"%s\" already exists."), name);
goto add_printer_attributes;
}
/*
* Create the printer...
*/
if ((printer = cupsdAddPrinter(name)) == NULL)
{
send_ipp_status(con, IPP_STATUS_ERROR_INTERNAL, _("Unable to create printer."));
return;
}
printer->shared = 0;
printer->temporary = 1;
cupsdSetDeviceURI(printer, ippGetString(device_uri, 0, NULL));
if (printer_geo_location)
cupsdSetString(&printer->geo_location, ippGetString(printer_geo_location, 0, NULL));
if (printer_info)
cupsdSetString(&printer->info, ippGetString(printer_info, 0, NULL));
if (printer_location)
cupsdSetString(&printer->location, ippGetString(printer_location, 0, NULL));
cupsdSetPrinterAttrs(printer);
/*
* Run a background thread to create the PPD...
*/
_cupsThreadCreate((_cups_thread_func_t)create_local_bg_thread, printer);
/*
* Return printer attributes...
*/
send_ipp_status(con, IPP_STATUS_OK, _("Local printer created."));
add_printer_attributes:
ippAddBoolean(con->response, IPP_TAG_PRINTER, "printer-is-accepting-jobs", (char)printer->accepting);
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_ENUM, "printer-state", printer->state);
add_printer_state_reasons(con, printer);
httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), httpIsEncrypted(con->http) ? "ipps" : "ipp", NULL, con->clientname, con->clientport, "/printers/%s", printer->name);
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_URI, "printer-uri-supported", NULL, uri);
}
/*
* 'create_requested_array()' - Create an array for the requested-attributes.
*/
static cups_array_t * /* O - Array of attributes or NULL */
create_requested_array(ipp_t *request) /* I - IPP request */
{
cups_array_t *ra; /* Requested attributes array */
/*
* Create the array for standard attributes...
*/
ra = ippCreateRequestedArray(request);
/*
* Add CUPS defaults as needed...
*/
if (cupsArrayFind(ra, "printer-defaults"))
{
/*
* Include user-set defaults...
*/
char *name; /* Option name */
cupsArrayRemove(ra, "printer-defaults");
for (name = (char *)cupsArrayFirst(CommonDefaults);
name;
name = (char *)cupsArrayNext(CommonDefaults))
if (!cupsArrayFind(ra, name))
cupsArrayAdd(ra, name);
}
return (ra);
}
/*
* 'create_subscriptions()' - Create one or more notification subscriptions.
*/
static void
create_subscriptions(
cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
int i; /* Looping var */
ipp_attribute_t *attr; /* Current attribute */
cups_ptype_t dtype; /* Destination type (printer/class) */
char scheme[HTTP_MAX_URI],
/* Scheme portion of URI */
userpass[HTTP_MAX_URI],
/* Username portion of URI */
host[HTTP_MAX_URI],
/* Host portion of URI */
resource[HTTP_MAX_URI];
/* Resource portion of URI */
int port; /* Port portion of URI */
cupsd_printer_t *printer; /* Printer/class */
cupsd_job_t *job; /* Job */
int jobid; /* Job ID */
cupsd_subscription_t *sub; /* Subscription object */
const char *username, /* requesting-user-name or
authenticated username */
*recipient, /* notify-recipient-uri */
*pullmethod; /* notify-pull-method */
ipp_attribute_t *user_data; /* notify-user-data */
int interval, /* notify-time-interval */
lease; /* notify-lease-duration */
unsigned mask; /* notify-events */
ipp_attribute_t *notify_events,/* notify-events(-default) */
*notify_lease; /* notify-lease-duration(-default) */
#ifdef DEBUG
for (attr = con->request->attrs; attr; attr = attr->next)
{
if (attr->group_tag != IPP_TAG_ZERO)
cupsdLogMessage(CUPSD_LOG_DEBUG2, "g%04x v%04x %s", attr->group_tag,
attr->value_tag, attr->name);
else
cupsdLogMessage(CUPSD_LOG_DEBUG2, "----SEP----");
}
#endif /* DEBUG */
/*
* Is the destination valid?
*/
cupsdLogMessage(CUPSD_LOG_DEBUG, "create_subscriptions(con=%p(%d), uri=\"%s\")", con, con->number, uri->values[0].string.text);
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), userpass, sizeof(userpass), host,
sizeof(host), &port, resource, sizeof(resource));
if (!strcmp(resource, "/"))
{
dtype = (cups_ptype_t)0;
printer = NULL;
}
else if (!strncmp(resource, "/printers", 9) && strlen(resource) <= 10)
{
dtype = (cups_ptype_t)0;
printer = NULL;
}
else if (!strncmp(resource, "/classes", 8) && strlen(resource) <= 9)
{
dtype = CUPS_PRINTER_CLASS;
printer = NULL;
}
else if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if (printer)
{
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con,
NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
}
else if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Get the user that is requesting the subscription...
*/
username = get_username(con);
/*
* Find the first subscription group attribute; return if we have
* none...
*/
for (attr = con->request->attrs; attr; attr = attr->next)
if (attr->group_tag == IPP_TAG_SUBSCRIPTION)
break;
if (!attr)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("No subscription attributes in request."));
return;
}
/*
* Process the subscription attributes in the request...
*/
con->response->request.status.status_code = IPP_BAD_REQUEST;
while (attr)
{
recipient = NULL;
pullmethod = NULL;
user_data = NULL;
interval = 0;
lease = DefaultLeaseDuration;
jobid = 0;
mask = CUPSD_EVENT_NONE;
if (printer)
{
notify_events = ippFindAttribute(printer->attrs, "notify-events-default",
IPP_TAG_KEYWORD);
notify_lease = ippFindAttribute(printer->attrs,
"notify-lease-duration-default",
IPP_TAG_INTEGER);
if (notify_lease)
lease = notify_lease->values[0].integer;
}
else
{
notify_events = NULL;
notify_lease = NULL;
}
while (attr && attr->group_tag != IPP_TAG_ZERO)
{
if (!strcmp(attr->name, "notify-recipient-uri") &&
attr->value_tag == IPP_TAG_URI)
{
/*
* Validate the recipient scheme against the ServerBin/notifier
* directory...
*/
char notifier[1024]; /* Notifier filename */
recipient = attr->values[0].string.text;
if (httpSeparateURI(HTTP_URI_CODING_ALL, recipient,
scheme, sizeof(scheme), userpass, sizeof(userpass),
host, sizeof(host), &port,
resource, sizeof(resource)) < HTTP_URI_OK)
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Bad notify-recipient-uri \"%s\"."), recipient);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_ENUM,
"notify-status-code", IPP_URI_SCHEME);
return;
}
snprintf(notifier, sizeof(notifier), "%s/notifier/%s", ServerBin,
scheme);
if (access(notifier, X_OK))
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("notify-recipient-uri URI \"%s\" uses unknown "
"scheme."), recipient);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_ENUM,
"notify-status-code", IPP_URI_SCHEME);
return;
}
if (!strcmp(scheme, "rss") && !check_rss_recipient(recipient))
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("notify-recipient-uri URI \"%s\" is already used."),
recipient);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_ENUM,
"notify-status-code", IPP_ATTRIBUTES);
return;
}
}
else if (!strcmp(attr->name, "notify-pull-method") &&
attr->value_tag == IPP_TAG_KEYWORD)
{
pullmethod = attr->values[0].string.text;
if (strcmp(pullmethod, "ippget"))
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Bad notify-pull-method \"%s\"."), pullmethod);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_ENUM,
"notify-status-code", IPP_ATTRIBUTES);
return;
}
}
else if (!strcmp(attr->name, "notify-charset") &&
attr->value_tag == IPP_TAG_CHARSET &&
strcmp(attr->values[0].string.text, "us-ascii") &&
strcmp(attr->values[0].string.text, "utf-8"))
{
send_ipp_status(con, IPP_CHARSET,
_("Character set \"%s\" not supported."),
attr->values[0].string.text);
return;
}
else if (!strcmp(attr->name, "notify-natural-language") &&
(attr->value_tag != IPP_TAG_LANGUAGE ||
strcmp(attr->values[0].string.text, DefaultLanguage)))
{
send_ipp_status(con, IPP_CHARSET,
_("Language \"%s\" not supported."),
attr->values[0].string.text);
return;
}
else if (!strcmp(attr->name, "notify-user-data") &&
attr->value_tag == IPP_TAG_STRING)
{
if (attr->num_values > 1 || attr->values[0].unknown.length > 63)
{
send_ipp_status(con, IPP_REQUEST_VALUE,
_("The notify-user-data value is too large "
"(%d > 63 octets)."),
attr->values[0].unknown.length);
return;
}
user_data = attr;
}
else if (!strcmp(attr->name, "notify-events") &&
attr->value_tag == IPP_TAG_KEYWORD)
notify_events = attr;
else if (!strcmp(attr->name, "notify-lease-duration") &&
attr->value_tag == IPP_TAG_INTEGER)
lease = attr->values[0].integer;
else if (!strcmp(attr->name, "notify-time-interval") &&
attr->value_tag == IPP_TAG_INTEGER)
interval = attr->values[0].integer;
else if (!strcmp(attr->name, "notify-job-id") &&
attr->value_tag == IPP_TAG_INTEGER)
jobid = attr->values[0].integer;
attr = attr->next;
}
if (notify_events)
{
for (i = 0; i < notify_events->num_values; i ++)
mask |= cupsdEventValue(notify_events->values[i].string.text);
}
if (recipient)
cupsdLogMessage(CUPSD_LOG_DEBUG, "recipient=\"%s\"", recipient);
if (pullmethod)
cupsdLogMessage(CUPSD_LOG_DEBUG, "pullmethod=\"%s\"", pullmethod);
cupsdLogMessage(CUPSD_LOG_DEBUG, "notify-lease-duration=%d", lease);
cupsdLogMessage(CUPSD_LOG_DEBUG, "notify-time-interval=%d", interval);
if (!recipient && !pullmethod)
break;
if (mask == CUPSD_EVENT_NONE)
{
if (jobid)
mask = CUPSD_EVENT_JOB_COMPLETED;
else if (printer)
mask = CUPSD_EVENT_PRINTER_STATE_CHANGED;
else
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("notify-events not specified."));
return;
}
}
if (MaxLeaseDuration && (lease == 0 || lease > MaxLeaseDuration))
{
cupsdLogMessage(CUPSD_LOG_INFO,
"create_subscriptions: Limiting notify-lease-duration to "
"%d seconds.",
MaxLeaseDuration);
lease = MaxLeaseDuration;
}
if (jobid)
{
if ((job = cupsdFindJob(jobid)) == NULL)
{
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."),
jobid);
return;
}
}
else
job = NULL;
if ((sub = cupsdAddSubscription(mask, printer, job, recipient, 0)) == NULL)
{
send_ipp_status(con, IPP_TOO_MANY_SUBSCRIPTIONS,
_("There are too many subscriptions."));
return;
}
if (job)
cupsdLogMessage(CUPSD_LOG_DEBUG, "Added subscription #%d for job %d.",
sub->id, job->id);
else if (printer)
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Added subscription #%d for printer \"%s\".",
sub->id, printer->name);
else
cupsdLogMessage(CUPSD_LOG_DEBUG, "Added subscription #%d for server.",
sub->id);
sub->interval = interval;
sub->lease = lease;
sub->expire = lease ? time(NULL) + lease : 0;
cupsdSetString(&sub->owner, username);
if (user_data)
{
sub->user_data_len = user_data->values[0].unknown.length;
memcpy(sub->user_data, user_data->values[0].unknown.data,
(size_t)sub->user_data_len);
}
ippAddSeparator(con->response);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER,
"notify-subscription-id", sub->id);
con->response->request.status.status_code = IPP_OK;
if (attr)
attr = attr->next;
}
cupsdMarkDirty(CUPSD_DIRTY_SUBSCRIPTIONS);
}
/*
* 'delete_printer()' - Remove a printer or class from the system.
*/
static void
delete_printer(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - URI of printer or class */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer/class */
char filename[1024]; /* Script/PPD filename */
int temporary; /* Temporary queue? */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "delete_printer(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Do we have a valid URI?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Remove old jobs...
*/
cupsdCancelJobs(printer->name, NULL, 1);
/*
* Remove old subscriptions and send a "deleted printer" event...
*/
cupsdAddEvent(CUPSD_EVENT_PRINTER_DELETED, printer, NULL,
"%s \"%s\" deleted by \"%s\".",
(dtype & CUPS_PRINTER_CLASS) ? "Class" : "Printer",
printer->name, get_username(con));
cupsdExpireSubscriptions(printer, NULL);
/*
* Remove any old PPD or script files...
*/
snprintf(filename, sizeof(filename), "%s/ppd/%s.ppd", ServerRoot,
printer->name);
unlink(filename);
snprintf(filename, sizeof(filename), "%s/ppd/%s.ppd.O", ServerRoot,
printer->name);
unlink(filename);
snprintf(filename, sizeof(filename), "%s/%s.png", CacheDir, printer->name);
unlink(filename);
snprintf(filename, sizeof(filename), "%s/%s.data", CacheDir, printer->name);
unlink(filename);
/*
* Unregister color profiles...
*/
cupsdUnregisterColor(printer);
temporary = printer->temporary;
if (dtype & CUPS_PRINTER_CLASS)
{
cupsdLogMessage(CUPSD_LOG_INFO, "Class \"%s\" deleted by \"%s\".",
printer->name, get_username(con));
cupsdDeletePrinter(printer, 0);
if (!temporary)
cupsdMarkDirty(CUPSD_DIRTY_CLASSES);
}
else
{
cupsdLogMessage(CUPSD_LOG_INFO, "Printer \"%s\" deleted by \"%s\".",
printer->name, get_username(con));
if (cupsdDeletePrinter(printer, 0) && !temporary)
cupsdMarkDirty(CUPSD_DIRTY_CLASSES);
if (!temporary)
cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
}
if (!temporary)
cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP);
/*
* Return with no errors...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'get_default()' - Get the default destination.
*/
static void
get_default(cupsd_client_t *con) /* I - Client connection */
{
http_status_t status; /* Policy status */
cups_array_t *ra; /* Requested attributes array */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_default(%p[%d])", con, con->number);
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
if (DefaultPrinter)
{
ra = create_requested_array(con->request);
copy_printer_attrs(con, DefaultPrinter, ra);
cupsArrayDelete(ra);
con->response->request.status.status_code = IPP_OK;
}
else
send_ipp_status(con, IPP_NOT_FOUND, _("No default printer."));
}
/*
* 'get_devices()' - Get the list of available devices on the local system.
*/
static void
get_devices(cupsd_client_t *con) /* I - Client connection */
{
http_status_t status; /* Policy status */
ipp_attribute_t *limit, /* limit attribute */
*timeout, /* timeout attribute */
*requested, /* requested-attributes attribute */
*exclude, /* exclude-schemes attribute */
*include; /* include-schemes attribute */
char command[1024], /* cups-deviced command */
options[2048], /* Options to pass to command */
requested_str[256],
/* String for requested attributes */
exclude_str[512],
/* String for excluded schemes */
include_str[512];
/* String for included schemes */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_devices(%p[%d])", con, con->number);
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Run cups-deviced command with the given options...
*/
limit = ippFindAttribute(con->request, "limit", IPP_TAG_INTEGER);
timeout = ippFindAttribute(con->request, "timeout", IPP_TAG_INTEGER);
requested = ippFindAttribute(con->request, "requested-attributes",
IPP_TAG_KEYWORD);
exclude = ippFindAttribute(con->request, "exclude-schemes", IPP_TAG_NAME);
include = ippFindAttribute(con->request, "include-schemes", IPP_TAG_NAME);
if (requested)
url_encode_attr(requested, requested_str, sizeof(requested_str));
else
strlcpy(requested_str, "requested-attributes=all", sizeof(requested_str));
if (exclude)
url_encode_attr(exclude, exclude_str, sizeof(exclude_str));
else
exclude_str[0] = '\0';
if (include)
url_encode_attr(include, include_str, sizeof(include_str));
else
include_str[0] = '\0';
snprintf(command, sizeof(command), "%s/daemon/cups-deviced", ServerBin);
snprintf(options, sizeof(options),
"%d+%d+%d+%d+%s%s%s%s%s",
con->request->request.op.request_id,
limit ? limit->values[0].integer : 0,
timeout ? timeout->values[0].integer : 15,
(int)User,
requested_str,
exclude_str[0] ? "%20" : "", exclude_str,
include_str[0] ? "%20" : "", include_str);
if (cupsdSendCommand(con, command, options, 1))
{
/*
* Command started successfully, don't send an IPP response here...
*/
ippDelete(con->response);
con->response = NULL;
}
else
{
/*
* Command failed, return "internal error" so the user knows something
* went wrong...
*/
send_ipp_status(con, IPP_INTERNAL_ERROR,
_("cups-deviced failed to execute."));
}
}
/*
* 'get_document()' - Get a copy of a job file.
*/
static void
get_document(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job URI */
{
http_status_t status; /* Policy status */
ipp_attribute_t *attr; /* Current attribute */
int jobid; /* Job ID */
int docnum; /* Document number */
cupsd_job_t *job; /* Current job */
char scheme[HTTP_MAX_URI], /* Method portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
char filename[1024], /* Filename for document */
format[1024]; /* Format for document */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_document(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
jobid = attr->values[0].integer;
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con,
job->username)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Get the document number...
*/
if ((attr = ippFindAttribute(con->request, "document-number",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Missing document-number attribute."));
return;
}
if ((docnum = attr->values[0].integer) < 1 || docnum > job->num_files ||
attr->num_values > 1)
{
send_ipp_status(con, IPP_NOT_FOUND,
_("Document #%d does not exist in job #%d."), docnum,
jobid);
return;
}
snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot, jobid,
docnum);
if ((con->file = open(filename, O_RDONLY)) == -1)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to open document %d in job %d - %s", docnum, jobid,
strerror(errno));
send_ipp_status(con, IPP_NOT_FOUND,
_("Unable to open document #%d in job #%d."), docnum,
jobid);
return;
}
fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
cupsdLoadJob(job);
snprintf(format, sizeof(format), "%s/%s", job->filetypes[docnum - 1]->super,
job->filetypes[docnum - 1]->type);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_MIMETYPE, "document-format",
NULL, format);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "document-number",
docnum);
if ((attr = ippFindAttribute(job->attrs, "document-name",
IPP_TAG_NAME)) != NULL)
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_NAME, "document-name",
NULL, attr->values[0].string.text);
}
/*
* 'get_job_attrs()' - Get job attributes.
*/
static void
get_job_attrs(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job URI */
{
http_status_t status; /* Policy status */
ipp_attribute_t *attr; /* Current attribute */
int jobid; /* Job ID */
cupsd_job_t *job; /* Current job */
cupsd_printer_t *printer; /* Current printer */
cupsd_policy_t *policy; /* Current security policy */
char scheme[HTTP_MAX_URI], /* Scheme portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
cups_array_t *ra, /* Requested attributes array */
*exclude; /* Private attributes array */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_job_attrs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
jobid = attr->values[0].integer;
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
/*
* Check policy...
*/
if ((printer = job->printer) == NULL)
printer = cupsdFindDest(job->dest);
if (printer)
policy = printer->op_policy_ptr;
else
policy = DefaultPolicyPtr;
if ((status = cupsdCheckPolicy(policy, con, job->username)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
exclude = cupsdGetPrivateAttrs(policy, con, printer, job->username);
/*
* Copy attributes...
*/
cupsdLoadJob(job);
ra = create_requested_array(con->request);
copy_job_attrs(con, job, ra, exclude);
cupsArrayDelete(ra);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'get_jobs()' - Get a list of jobs for the specified printer.
*/
static void
get_jobs(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
ipp_attribute_t *attr; /* Current attribute */
const char *dest; /* Destination */
cups_ptype_t dtype; /* Destination type (printer/class) */
cups_ptype_t dmask; /* Destination type mask */
char scheme[HTTP_MAX_URI], /* Scheme portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
int job_comparison; /* Job comparison */
ipp_jstate_t job_state; /* job-state value */
int first_job_id = 1, /* First job ID */
first_index = 1, /* First index */
limit = 0, /* Maximum number of jobs to return */
count, /* Number of jobs that match */
need_load_job = 0; /* Do we need to load the job? */
const char *job_attr; /* Job attribute requested */
ipp_attribute_t *job_ids; /* job-ids attribute */
cupsd_job_t *job; /* Current job pointer */
cupsd_printer_t *printer; /* Printer */
cups_array_t *list; /* Which job list... */
int delete_list = 0; /* Delete the list afterwards? */
cups_array_t *ra, /* Requested attributes array */
*exclude; /* Private attributes array */
cupsd_policy_t *policy; /* Current policy */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_jobs(%p[%d], %s)", con, con->number,
uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (strcmp(uri->name, "printer-uri"))
{
send_ipp_status(con, IPP_BAD_REQUEST, _("No printer-uri in request."));
return;
}
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (!strcmp(resource, "/") || !strcmp(resource, "/jobs"))
{
dest = NULL;
dtype = (cups_ptype_t)0;
dmask = (cups_ptype_t)0;
printer = NULL;
}
else if (!strncmp(resource, "/printers", 9) && strlen(resource) <= 10)
{
dest = NULL;
dtype = (cups_ptype_t)0;
dmask = CUPS_PRINTER_CLASS;
printer = NULL;
}
else if (!strncmp(resource, "/classes", 8) && strlen(resource) <= 9)
{
dest = NULL;
dtype = CUPS_PRINTER_CLASS;
dmask = CUPS_PRINTER_CLASS;
printer = NULL;
}
else if ((dest = cupsdValidateDest(uri->values[0].string.text, &dtype,
&printer)) == NULL)
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
else
{
dtype &= CUPS_PRINTER_CLASS;
dmask = CUPS_PRINTER_CLASS;
}
/*
* Check policy...
*/
if (printer)
policy = printer->op_policy_ptr;
else
policy = DefaultPolicyPtr;
if ((status = cupsdCheckPolicy(policy, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
job_ids = ippFindAttribute(con->request, "job-ids", IPP_TAG_INTEGER);
/*
* See if the "which-jobs" attribute have been specified...
*/
if ((attr = ippFindAttribute(con->request, "which-jobs",
IPP_TAG_KEYWORD)) != NULL && job_ids)
{
send_ipp_status(con, IPP_CONFLICT,
_("The %s attribute cannot be provided with job-ids."),
"which-jobs");
return;
}
else if (!attr || !strcmp(attr->values[0].string.text, "not-completed"))
{
job_comparison = -1;
job_state = IPP_JOB_STOPPED;
list = ActiveJobs;
}
else if (!strcmp(attr->values[0].string.text, "completed"))
{
job_comparison = 1;
job_state = IPP_JOB_CANCELED;
list = cupsdGetCompletedJobs(printer);
delete_list = 1;
}
else if (!strcmp(attr->values[0].string.text, "aborted"))
{
job_comparison = 0;
job_state = IPP_JOB_ABORTED;
list = cupsdGetCompletedJobs(printer);
delete_list = 1;
}
else if (!strcmp(attr->values[0].string.text, "all"))
{
job_comparison = 1;
job_state = IPP_JOB_PENDING;
list = Jobs;
}
else if (!strcmp(attr->values[0].string.text, "canceled"))
{
job_comparison = 0;
job_state = IPP_JOB_CANCELED;
list = cupsdGetCompletedJobs(printer);
delete_list = 1;
}
else if (!strcmp(attr->values[0].string.text, "pending"))
{
job_comparison = 0;
job_state = IPP_JOB_PENDING;
list = ActiveJobs;
}
else if (!strcmp(attr->values[0].string.text, "pending-held"))
{
job_comparison = 0;
job_state = IPP_JOB_HELD;
list = ActiveJobs;
}
else if (!strcmp(attr->values[0].string.text, "processing"))
{
job_comparison = 0;
job_state = IPP_JOB_PROCESSING;
list = PrintingJobs;
}
else if (!strcmp(attr->values[0].string.text, "processing-stopped"))
{
job_comparison = 0;
job_state = IPP_JOB_STOPPED;
list = ActiveJobs;
}
else
{
send_ipp_status(con, IPP_ATTRIBUTES,
_("The which-jobs value \"%s\" is not supported."),
attr->values[0].string.text);
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_KEYWORD,
"which-jobs", NULL, attr->values[0].string.text);
return;
}
/*
* See if they want to limit the number of jobs reported...
*/
if ((attr = ippFindAttribute(con->request, "limit", IPP_TAG_INTEGER)) != NULL)
{
if (job_ids)
{
send_ipp_status(con, IPP_CONFLICT,
_("The %s attribute cannot be provided with job-ids."),
"limit");
return;
}
limit = attr->values[0].integer;
}
if ((attr = ippFindAttribute(con->request, "first-index", IPP_TAG_INTEGER)) != NULL)
{
if (job_ids)
{
send_ipp_status(con, IPP_CONFLICT,
_("The %s attribute cannot be provided with job-ids."),
"first-index");
return;
}
first_index = attr->values[0].integer;
}
else if ((attr = ippFindAttribute(con->request, "first-job-id", IPP_TAG_INTEGER)) != NULL)
{
if (job_ids)
{
send_ipp_status(con, IPP_CONFLICT,
_("The %s attribute cannot be provided with job-ids."),
"first-job-id");
return;
}
first_job_id = attr->values[0].integer;
}
/*
* See if we only want to see jobs for a specific user...
*/
if ((attr = ippFindAttribute(con->request, "my-jobs", IPP_TAG_BOOLEAN)) != NULL && job_ids)
{
send_ipp_status(con, IPP_CONFLICT,
_("The %s attribute cannot be provided with job-ids."),
"my-jobs");
return;
}
else if (attr && attr->values[0].boolean)
strlcpy(username, get_username(con), sizeof(username));
else
username[0] = '\0';
ra = create_requested_array(con->request);
for (job_attr = (char *)cupsArrayFirst(ra); job_attr; job_attr = (char *)cupsArrayNext(ra))
if (strcmp(job_attr, "job-id") &&
strcmp(job_attr, "job-k-octets") &&
strcmp(job_attr, "job-media-progress") &&
strcmp(job_attr, "job-more-info") &&
strcmp(job_attr, "job-name") &&
strcmp(job_attr, "job-originating-user-name") &&
strcmp(job_attr, "job-preserved") &&
strcmp(job_attr, "job-printer-up-time") &&
strcmp(job_attr, "job-printer-uri") &&
strcmp(job_attr, "job-state") &&
strcmp(job_attr, "job-state-reasons") &&
strcmp(job_attr, "job-uri") &&
strcmp(job_attr, "time-at-completed") &&
strcmp(job_attr, "time-at-creation") &&
strcmp(job_attr, "number-of-documents"))
{
need_load_job = 1;
break;
}
if (need_load_job && (limit == 0 || limit > 500) && (list == Jobs || delete_list))
{
/*
* Limit expensive Get-Jobs for job history to 500 jobs...
*/
ippAddInteger(con->response, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "limit", 500);
if (limit)
ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER, "limit", limit);
limit = 500;
cupsdLogClient(con, CUPSD_LOG_INFO, "Limiting Get-Jobs response to %d jobs.", limit);
}
/*
* OK, build a list of jobs for this printer...
*/
if (job_ids)
{
int i; /* Looping var */
for (i = 0; i < job_ids->num_values; i ++)
{
if (!cupsdFindJob(job_ids->values[i].integer))
break;
}
if (i < job_ids->num_values)
{
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."),
job_ids->values[i].integer);
return;
}
for (i = 0; i < job_ids->num_values; i ++)
{
job = cupsdFindJob(job_ids->values[i].integer);
if (need_load_job && !job->attrs)
{
cupsdLoadJob(job);
if (!job->attrs)
{
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_jobs: No attributes for job %d", job->id);
continue;
}
}
if (i > 0)
ippAddSeparator(con->response);
exclude = cupsdGetPrivateAttrs(job->printer ?
job->printer->op_policy_ptr :
policy, con, job->printer,
job->username);
copy_job_attrs(con, job, ra, exclude);
}
}
else
{
if (first_index > 1)
job = (cupsd_job_t *)cupsArrayIndex(list, first_index - 1);
else
job = (cupsd_job_t *)cupsArrayFirst(list);
for (count = 0; (limit <= 0 || count < limit) && job; job = (cupsd_job_t *)cupsArrayNext(list))
{
/*
* Filter out jobs that don't match...
*/
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"get_jobs: job->id=%d, dest=\"%s\", username=\"%s\", "
"state_value=%d, attrs=%p", job->id, job->dest,
job->username, job->state_value, job->attrs);
if (!job->dest || !job->username)
cupsdLoadJob(job);
if (!job->dest || !job->username)
continue;
if ((dest && strcmp(job->dest, dest)) &&
(!job->printer || !dest || strcmp(job->printer->name, dest)))
continue;
if ((job->dtype & dmask) != dtype &&
(!job->printer || (job->printer->type & dmask) != dtype))
continue;
if ((job_comparison < 0 && job->state_value > job_state) ||
(job_comparison == 0 && job->state_value != job_state) ||
(job_comparison > 0 && job->state_value < job_state))
continue;
if (job->id < first_job_id)
continue;
if (need_load_job && !job->attrs)
{
cupsdLoadJob(job);
if (!job->attrs)
{
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_jobs: No attributes for job %d", job->id);
continue;
}
}
if (username[0] && _cups_strcasecmp(username, job->username))
continue;
if (count > 0)
ippAddSeparator(con->response);
count ++;
exclude = cupsdGetPrivateAttrs(job->printer ?
job->printer->op_policy_ptr :
policy, con, job->printer,
job->username);
copy_job_attrs(con, job, ra, exclude);
}
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_jobs: count=%d", count);
}
cupsArrayDelete(ra);
if (delete_list)
cupsArrayDelete(list);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'get_notifications()' - Get events for a subscription.
*/
static void
get_notifications(cupsd_client_t *con) /* I - Client connection */
{
int i, j; /* Looping vars */
http_status_t status; /* Policy status */
cupsd_subscription_t *sub; /* Subscription */
ipp_attribute_t *ids, /* notify-subscription-ids */
*sequences; /* notify-sequence-numbers */
int min_seq; /* Minimum sequence number */
int interval; /* Poll interval */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_notifications(con=%p[%d])",
con, con->number);
/*
* Get subscription attributes...
*/
ids = ippFindAttribute(con->request, "notify-subscription-ids",
IPP_TAG_INTEGER);
sequences = ippFindAttribute(con->request, "notify-sequence-numbers",
IPP_TAG_INTEGER);
if (!ids)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Missing notify-subscription-ids attribute."));
return;
}
/*
* Are the subscription IDs valid?
*/
for (i = 0, interval = 60; i < ids->num_values; i ++)
{
if ((sub = cupsdFindSubscription(ids->values[i].integer)) == NULL)
{
/*
* Bad subscription ID...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Subscription #%d does not exist."),
ids->values[i].integer);
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(sub->dest ? sub->dest->op_policy_ptr :
DefaultPolicyPtr,
con, sub->owner)) != HTTP_OK)
{
send_http_error(con, status, sub->dest);
return;
}
/*
* Check the subscription type and update the interval accordingly.
*/
if (sub->job && sub->job->state_value == IPP_JOB_PROCESSING &&
interval > 10)
interval = 10;
else if (sub->job && sub->job->state_value >= IPP_JOB_STOPPED)
interval = 0;
else if (sub->dest && sub->dest->state == IPP_PRINTER_PROCESSING &&
interval > 30)
interval = 30;
}
/*
* Tell the client to poll again in N seconds...
*/
if (interval > 0)
ippAddInteger(con->response, IPP_TAG_OPERATION, IPP_TAG_INTEGER,
"notify-get-interval", interval);
ippAddInteger(con->response, IPP_TAG_OPERATION, IPP_TAG_INTEGER,
"printer-up-time", time(NULL));
/*
* Copy the subscription event attributes to the response.
*/
con->response->request.status.status_code =
interval ? IPP_OK : IPP_OK_EVENTS_COMPLETE;
for (i = 0; i < ids->num_values; i ++)
{
/*
* Get the subscription and sequence number...
*/
sub = cupsdFindSubscription(ids->values[i].integer);
if (sequences && i < sequences->num_values)
min_seq = sequences->values[i].integer;
else
min_seq = 1;
/*
* If we don't have any new events, nothing to do here...
*/
if (min_seq > (sub->first_event_id + cupsArrayCount(sub->events)))
continue;
/*
* Otherwise copy all of the new events...
*/
if (sub->first_event_id > min_seq)
j = 0;
else
j = min_seq - sub->first_event_id;
for (; j < cupsArrayCount(sub->events); j ++)
{
ippAddSeparator(con->response);
copy_attrs(con->response,
((cupsd_event_t *)cupsArrayIndex(sub->events, j))->attrs, NULL,
IPP_TAG_EVENT_NOTIFICATION, 0, NULL);
}
}
}
/*
* 'get_ppd()' - Get a named PPD from the local system.
*/
static void
get_ppd(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI or PPD name */
{
http_status_t status; /* Policy status */
cupsd_printer_t *dest; /* Destination */
cups_ptype_t dtype; /* Destination type */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_ppd(%p[%d], %p[%s=%s])", con,
con->number, uri, uri->name, uri->values[0].string.text);
if (!strcmp(ippGetName(uri), "ppd-name"))
{
/*
* Return a PPD file from cups-driverd...
*/
const char *ppd_name = ippGetString(uri, 0, NULL);
/* ppd-name value */
char command[1024], /* cups-driverd command */
options[1024], /* Options to pass to command */
oppd_name[1024]; /* Escaped ppd-name */
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Check ppd-name value...
*/
if (strstr(ppd_name, "../"))
{
send_ipp_status(con, IPP_STATUS_ERROR_ATTRIBUTES_OR_VALUES, _("Invalid ppd-name value."));
return;
}
/*
* Run cups-driverd command with the given options...
*/
snprintf(command, sizeof(command), "%s/daemon/cups-driverd", ServerBin);
url_encode_string(ppd_name, oppd_name, sizeof(oppd_name));
snprintf(options, sizeof(options), "get+%d+%s", ippGetRequestId(con->request), oppd_name);
if (cupsdSendCommand(con, command, options, 0))
{
/*
* Command started successfully, don't send an IPP response here...
*/
ippDelete(con->response);
con->response = NULL;
}
else
{
/*
* Command failed, return "internal error" so the user knows something
* went wrong...
*/
send_ipp_status(con, IPP_INTERNAL_ERROR, _("cups-driverd failed to execute."));
}
}
else if (!strcmp(ippGetName(uri), "printer-uri") && cupsdValidateDest(ippGetString(uri, 0, NULL), &dtype, &dest))
{
int i; /* Looping var */
char filename[1024]; /* PPD filename */
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(dest->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, dest);
return;
}
/*
* See if we need the PPD for a class or remote printer...
*/
snprintf(filename, sizeof(filename), "%s/ppd/%s.ppd", ServerRoot, dest->name);
if ((dtype & CUPS_PRINTER_REMOTE) && access(filename, 0))
{
send_ipp_status(con, IPP_STATUS_CUPS_SEE_OTHER, _("See remote printer."));
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, dest->uri);
return;
}
else if (dtype & CUPS_PRINTER_CLASS)
{
for (i = 0; i < dest->num_printers; i ++)
if (!(dest->printers[i]->type & CUPS_PRINTER_CLASS))
{
snprintf(filename, sizeof(filename), "%s/ppd/%s.ppd", ServerRoot, dest->printers[i]->name);
if (!access(filename, 0))
break;
}
if (i < dest->num_printers)
dest = dest->printers[i];
else
{
send_ipp_status(con, IPP_STATUS_CUPS_SEE_OTHER, _("See remote printer."));
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, dest->printers[0]->uri);
return;
}
}
/*
* Found the printer with the PPD file, now see if there is one...
*/
if ((con->file = open(filename, O_RDONLY)) < 0)
{
send_ipp_status(con, IPP_STATUS_ERROR_NOT_FOUND, _("The PPD file \"%s\" could not be opened: %s"), ippGetString(uri, 0, NULL), strerror(errno));
return;
}
fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
con->pipe_pid = 0;
ippSetStatusCode(con->response, IPP_STATUS_OK);
}
else
send_ipp_status(con, IPP_STATUS_ERROR_NOT_FOUND, _("The PPD file \"%s\" could not be found."), ippGetString(uri, 0, NULL));
}
/*
* 'get_ppds()' - Get the list of PPD files on the local system.
*/
static void
get_ppds(cupsd_client_t *con) /* I - Client connection */
{
http_status_t status; /* Policy status */
ipp_attribute_t *limit, /* Limit attribute */
*device, /* ppd-device-id attribute */
*language, /* ppd-natural-language attribute */
*make, /* ppd-make attribute */
*model, /* ppd-make-and-model attribute */
*model_number, /* ppd-model-number attribute */
*product, /* ppd-product attribute */
*psversion, /* ppd-psverion attribute */
*type, /* ppd-type attribute */
*requested, /* requested-attributes attribute */
*exclude, /* exclude-schemes attribute */
*include; /* include-schemes attribute */
char command[1024], /* cups-driverd command */
options[4096], /* Options to pass to command */
device_str[256],/* Escaped ppd-device-id string */
language_str[256],
/* Escaped ppd-natural-language */
make_str[256], /* Escaped ppd-make string */
model_str[256], /* Escaped ppd-make-and-model string */
model_number_str[256],
/* ppd-model-number string */
product_str[256],
/* Escaped ppd-product string */
psversion_str[256],
/* Escaped ppd-psversion string */
type_str[256], /* Escaped ppd-type string */
requested_str[256],
/* String for requested attributes */
exclude_str[512],
/* String for excluded schemes */
include_str[512];
/* String for included schemes */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_ppds(%p[%d])", con, con->number);
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Run cups-driverd command with the given options...
*/
limit = ippFindAttribute(con->request, "limit", IPP_TAG_INTEGER);
device = ippFindAttribute(con->request, "ppd-device-id", IPP_TAG_TEXT);
language = ippFindAttribute(con->request, "ppd-natural-language",
IPP_TAG_LANGUAGE);
make = ippFindAttribute(con->request, "ppd-make", IPP_TAG_TEXT);
model = ippFindAttribute(con->request, "ppd-make-and-model",
IPP_TAG_TEXT);
model_number = ippFindAttribute(con->request, "ppd-model-number",
IPP_TAG_INTEGER);
product = ippFindAttribute(con->request, "ppd-product", IPP_TAG_TEXT);
psversion = ippFindAttribute(con->request, "ppd-psversion", IPP_TAG_TEXT);
type = ippFindAttribute(con->request, "ppd-type", IPP_TAG_KEYWORD);
requested = ippFindAttribute(con->request, "requested-attributes",
IPP_TAG_KEYWORD);
exclude = ippFindAttribute(con->request, "exclude-schemes",
IPP_TAG_NAME);
include = ippFindAttribute(con->request, "include-schemes",
IPP_TAG_NAME);
if (requested)
url_encode_attr(requested, requested_str, sizeof(requested_str));
else
strlcpy(requested_str, "requested-attributes=all", sizeof(requested_str));
if (device)
url_encode_attr(device, device_str, sizeof(device_str));
else
device_str[0] = '\0';
if (language)
url_encode_attr(language, language_str, sizeof(language_str));
else
language_str[0] = '\0';
if (make)
url_encode_attr(make, make_str, sizeof(make_str));
else
make_str[0] = '\0';
if (model)
url_encode_attr(model, model_str, sizeof(model_str));
else
model_str[0] = '\0';
if (model_number)
snprintf(model_number_str, sizeof(model_number_str), "ppd-model-number=%d",
model_number->values[0].integer);
else
model_number_str[0] = '\0';
if (product)
url_encode_attr(product, product_str, sizeof(product_str));
else
product_str[0] = '\0';
if (psversion)
url_encode_attr(psversion, psversion_str, sizeof(psversion_str));
else
psversion_str[0] = '\0';
if (type)
url_encode_attr(type, type_str, sizeof(type_str));
else
type_str[0] = '\0';
if (exclude)
url_encode_attr(exclude, exclude_str, sizeof(exclude_str));
else
exclude_str[0] = '\0';
if (include)
url_encode_attr(include, include_str, sizeof(include_str));
else
include_str[0] = '\0';
snprintf(command, sizeof(command), "%s/daemon/cups-driverd", ServerBin);
snprintf(options, sizeof(options),
"list+%d+%d+%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
con->request->request.op.request_id,
limit ? limit->values[0].integer : 0,
requested_str,
device ? "%20" : "", device_str,
language ? "%20" : "", language_str,
make ? "%20" : "", make_str,
model ? "%20" : "", model_str,
model_number ? "%20" : "", model_number_str,
product ? "%20" : "", product_str,
psversion ? "%20" : "", psversion_str,
type ? "%20" : "", type_str,
exclude_str[0] ? "%20" : "", exclude_str,
include_str[0] ? "%20" : "", include_str);
if (cupsdSendCommand(con, command, options, 0))
{
/*
* Command started successfully, don't send an IPP response here...
*/
ippDelete(con->response);
con->response = NULL;
}
else
{
/*
* Command failed, return "internal error" so the user knows something
* went wrong...
*/
send_ipp_status(con, IPP_INTERNAL_ERROR,
_("cups-driverd failed to execute."));
}
}
/*
* 'get_printer_attrs()' - Get printer attributes.
*/
static void
get_printer_attrs(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer/class */
cups_array_t *ra; /* Requested attributes array */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_printer_attrs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Send the attributes...
*/
ra = create_requested_array(con->request);
copy_printer_attrs(con, printer, ra);
cupsArrayDelete(ra);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'get_printer_supported()' - Get printer supported values.
*/
static void
get_printer_supported(
cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer/class */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_printer_supported(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Return a list of attributes that can be set via Set-Printer-Attributes.
*/
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_ADMINDEFINE,
"printer-geo-location", 0);
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_ADMINDEFINE,
"printer-info", 0);
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_ADMINDEFINE,
"printer-location", 0);
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_ADMINDEFINE,
"printer-organization", 0);
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_ADMINDEFINE,
"printer-organizational-unit", 0);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'get_printers()' - Get a list of printers or classes.
*/
static void
get_printers(cupsd_client_t *con, /* I - Client connection */
int type) /* I - 0 or CUPS_PRINTER_CLASS */
{
http_status_t status; /* Policy status */
ipp_attribute_t *attr; /* Current attribute */
int limit; /* Max number of printers to return */
int count; /* Number of printers that match */
cupsd_printer_t *printer; /* Current printer pointer */
cups_ptype_t printer_type, /* printer-type attribute */
printer_mask; /* printer-type-mask attribute */
char *location; /* Location string */
const char *username; /* Current user */
char *first_printer_name; /* first-printer-name attribute */
cups_array_t *ra; /* Requested attributes array */
int local; /* Local connection? */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_printers(%p[%d], %x)", con,
con->number, type);
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Check for printers...
*/
if (!Printers || !cupsArrayCount(Printers))
{
send_ipp_status(con, IPP_NOT_FOUND, _("No destinations added."));
return;
}
/*
* See if they want to limit the number of printers reported...
*/
if ((attr = ippFindAttribute(con->request, "limit",
IPP_TAG_INTEGER)) != NULL)
limit = attr->values[0].integer;
else
limit = 10000000;
if ((attr = ippFindAttribute(con->request, "first-printer-name",
IPP_TAG_NAME)) != NULL)
first_printer_name = attr->values[0].string.text;
else
first_printer_name = NULL;
/*
* Support filtering...
*/
if ((attr = ippFindAttribute(con->request, "printer-type",
IPP_TAG_ENUM)) != NULL)
printer_type = (cups_ptype_t)attr->values[0].integer;
else
printer_type = (cups_ptype_t)0;
if ((attr = ippFindAttribute(con->request, "printer-type-mask",
IPP_TAG_ENUM)) != NULL)
printer_mask = (cups_ptype_t)attr->values[0].integer;
else
printer_mask = (cups_ptype_t)0;
local = httpAddrLocalhost(&(con->clientaddr));
if ((attr = ippFindAttribute(con->request, "printer-location",
IPP_TAG_TEXT)) != NULL)
location = attr->values[0].string.text;
else
location = NULL;
if (con->username[0])
username = con->username;
else if ((attr = ippFindAttribute(con->request, "requesting-user-name",
IPP_TAG_NAME)) != NULL)
username = attr->values[0].string.text;
else
username = NULL;
ra = create_requested_array(con->request);
/*
* OK, build a list of printers for this printer...
*/
if (first_printer_name)
{
if ((printer = cupsdFindDest(first_printer_name)) == NULL)
printer = (cupsd_printer_t *)cupsArrayFirst(Printers);
}
else
printer = (cupsd_printer_t *)cupsArrayFirst(Printers);
for (count = 0;
count < limit && printer;
printer = (cupsd_printer_t *)cupsArrayNext(Printers))
{
if (!local && !printer->shared)
continue;
if ((!type || (printer->type & CUPS_PRINTER_CLASS) == type) &&
(printer->type & printer_mask) == printer_type &&
(!location ||
(printer->location && !_cups_strcasecmp(printer->location, location))))
{
/*
* If a username is specified, see if it is allowed or denied
* access...
*/
if (cupsArrayCount(printer->users) && username &&
!user_allowed(printer, username))
continue;
/*
* Add the group separator as needed...
*/
if (count > 0)
ippAddSeparator(con->response);
count ++;
/*
* Send the attributes...
*/
copy_printer_attrs(con, printer, ra);
}
}
cupsArrayDelete(ra);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'get_subscription_attrs()' - Get subscription attributes.
*/
static void
get_subscription_attrs(
cupsd_client_t *con, /* I - Client connection */
int sub_id) /* I - Subscription ID */
{
http_status_t status; /* Policy status */
cupsd_subscription_t *sub; /* Subscription */
cupsd_policy_t *policy; /* Current security policy */
cups_array_t *ra, /* Requested attributes array */
*exclude; /* Private attributes array */
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"get_subscription_attrs(con=%p[%d], sub_id=%d)",
con, con->number, sub_id);
/*
* Expire subscriptions as needed...
*/
cupsdExpireSubscriptions(NULL, NULL);
/*
* Is the subscription ID valid?
*/
if ((sub = cupsdFindSubscription(sub_id)) == NULL)
{
/*
* Bad subscription ID...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Subscription #%d does not exist."),
sub_id);
return;
}
/*
* Check policy...
*/
if (sub->dest)
policy = sub->dest->op_policy_ptr;
else
policy = DefaultPolicyPtr;
if ((status = cupsdCheckPolicy(policy, con, sub->owner)) != HTTP_OK)
{
send_http_error(con, status, sub->dest);
return;
}
exclude = cupsdGetPrivateAttrs(policy, con, sub->dest, sub->owner);
/*
* Copy the subscription attributes to the response using the
* requested-attributes attribute that may be provided by the client.
*/
ra = create_requested_array(con->request);
copy_subscription_attrs(con, sub, ra, exclude);
cupsArrayDelete(ra);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'get_subscriptions()' - Get subscriptions.
*/
static void
get_subscriptions(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer/job URI */
{
http_status_t status; /* Policy status */
int count; /* Number of subscriptions */
int limit; /* Limit */
cupsd_subscription_t *sub; /* Subscription */
cups_array_t *ra; /* Requested attributes array */
ipp_attribute_t *attr; /* Attribute */
cups_ptype_t dtype; /* Destination type (printer/class) */
char scheme[HTTP_MAX_URI],
/* Scheme portion of URI */
username[HTTP_MAX_URI],
/* Username portion of URI */
host[HTTP_MAX_URI],
/* Host portion of URI */
resource[HTTP_MAX_URI];
/* Resource portion of URI */
int port; /* Port portion of URI */
cupsd_job_t *job; /* Job pointer */
cupsd_printer_t *printer; /* Printer */
cupsd_policy_t *policy; /* Policy */
cups_array_t *exclude; /* Private attributes array */
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"get_subscriptions(con=%p[%d], uri=%s)",
con, con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (!strcmp(resource, "/") ||
(!strncmp(resource, "/jobs", 5) && strlen(resource) <= 6) ||
(!strncmp(resource, "/printers", 9) && strlen(resource) <= 10) ||
(!strncmp(resource, "/classes", 8) && strlen(resource) <= 9))
{
printer = NULL;
job = NULL;
}
else if (!strncmp(resource, "/jobs/", 6) && resource[6])
{
printer = NULL;
job = cupsdFindJob(atoi(resource + 6));
if (!job)
{
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."),
atoi(resource + 6));
return;
}
}
else if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
else if ((attr = ippFindAttribute(con->request, "notify-job-id",
IPP_TAG_INTEGER)) != NULL)
{
job = cupsdFindJob(attr->values[0].integer);
if (!job)
{
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."),
attr->values[0].integer);
return;
}
}
else
job = NULL;
/*
* Check policy...
*/
if (printer)
policy = printer->op_policy_ptr;
else
policy = DefaultPolicyPtr;
if ((status = cupsdCheckPolicy(policy, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Expire subscriptions as needed...
*/
cupsdExpireSubscriptions(NULL, NULL);
/*
* Copy the subscription attributes to the response using the
* requested-attributes attribute that may be provided by the client.
*/
ra = create_requested_array(con->request);
if ((attr = ippFindAttribute(con->request, "limit",
IPP_TAG_INTEGER)) != NULL)
limit = attr->values[0].integer;
else
limit = 0;
/*
* See if we only want to see subscriptions for a specific user...
*/
if ((attr = ippFindAttribute(con->request, "my-subscriptions",
IPP_TAG_BOOLEAN)) != NULL &&
attr->values[0].boolean)
strlcpy(username, get_username(con), sizeof(username));
else
username[0] = '\0';
for (sub = (cupsd_subscription_t *)cupsArrayFirst(Subscriptions), count = 0;
sub;
sub = (cupsd_subscription_t *)cupsArrayNext(Subscriptions))
if ((!printer || sub->dest == printer) && (!job || sub->job == job) &&
(!username[0] || !_cups_strcasecmp(username, sub->owner)))
{
ippAddSeparator(con->response);
exclude = cupsdGetPrivateAttrs(sub->dest ? sub->dest->op_policy_ptr :
policy, con, sub->dest,
sub->owner);
copy_subscription_attrs(con, sub, ra, exclude);
count ++;
if (limit && count >= limit)
break;
}
cupsArrayDelete(ra);
if (count)
con->response->request.status.status_code = IPP_OK;
else
send_ipp_status(con, IPP_NOT_FOUND, _("No subscriptions found."));
}
/*
* 'get_username()' - Get the username associated with a request.
*/
static const char * /* O - Username */
get_username(cupsd_client_t *con) /* I - Connection */
{
ipp_attribute_t *attr; /* Attribute */
if (con->username[0])
return (con->username);
else if ((attr = ippFindAttribute(con->request, "requesting-user-name",
IPP_TAG_NAME)) != NULL)
return (attr->values[0].string.text);
else
return ("anonymous");
}
/*
* 'hold_job()' - Hold a print job.
*/
static void
hold_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job or Printer URI */
{
ipp_attribute_t *attr; /* Current job-hold-until */
const char *when; /* New value */
int jobid; /* Job ID */
char scheme[HTTP_MAX_URI], /* Method portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
cupsd_job_t *job; /* Job information */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "hold_job(%p[%d], %s)", con, con->number,
uri->values[0].string.text);
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
jobid = attr->values[0].integer;
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST,
_("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* See if the job is in a state that allows holding...
*/
if (job->state_value > IPP_JOB_STOPPED)
{
/*
* Return a "not-possible" error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job #%d is finished and cannot be altered."),
job->id);
return;
}
/*
* Hold the job and return...
*/
if ((attr = ippFindAttribute(con->request, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(con->request, "job-hold-until", IPP_TAG_NAME);
if (attr)
{
when = attr->values[0].string.text;
cupsdAddEvent(CUPSD_EVENT_JOB_CONFIG_CHANGED, cupsdFindDest(job->dest), job,
"Job job-hold-until value changed by user.");
}
else
when = "indefinite";
cupsdSetJobHoldUntil(job, when, 1);
cupsdSetJobState(job, IPP_JOB_HELD, CUPSD_JOB_DEFAULT, "Job held by \"%s\".",
username);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'hold_new_jobs()' - Hold pending/new jobs on a printer or class.
*/
static void
hold_new_jobs(cupsd_client_t *con, /* I - Connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer data */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "hold_new_jobs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Hold pending/new jobs sent to the printer...
*/
printer->holding_new_jobs = 1;
cupsdSetPrinterReasons(printer, "+hold-new-jobs");
if (dtype & CUPS_PRINTER_CLASS)
cupsdLogMessage(CUPSD_LOG_INFO,
"Class \"%s\" now holding pending/new jobs (\"%s\").",
printer->name, get_username(con));
else
cupsdLogMessage(CUPSD_LOG_INFO,
"Printer \"%s\" now holding pending/new jobs (\"%s\").",
printer->name, get_username(con));
/*
* Everything was ok, so return OK status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'move_job()' - Move a job to a new destination.
*/
static void
move_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job URI */
{
http_status_t status; /* Policy status */
ipp_attribute_t *attr; /* Current attribute */
int jobid; /* Job ID */
cupsd_job_t *job; /* Current job */
const char *src; /* Source printer/class */
cups_ptype_t stype, /* Source type (printer or class) */
dtype; /* Destination type (printer/class) */
char scheme[HTTP_MAX_URI], /* Scheme portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
cupsd_printer_t *sprinter, /* Source printer */
*dprinter; /* Destination printer */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "move_job(%p[%d], %s)", con, con->number,
uri->values[0].string.text);
/*
* Get the new printer or class...
*/
if ((attr = ippFindAttribute(con->request, "job-printer-uri",
IPP_TAG_URI)) == NULL)
{
/*
* Need job-printer-uri...
*/
send_ipp_status(con, IPP_BAD_REQUEST,
_("job-printer-uri attribute missing."));
return;
}
if (!cupsdValidateDest(attr->values[0].string.text, &dtype, &dprinter))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* See if we have a job URI or a printer URI...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
/*
* Move all jobs...
*/
if ((src = cupsdValidateDest(uri->values[0].string.text, &stype,
&sprinter)) == NULL)
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
job = NULL;
}
else
{
/*
* Otherwise, just move a single job...
*/
if ((job = cupsdFindJob(attr->values[0].integer)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("Job #%d does not exist."), attr->values[0].integer);
return;
}
else
{
/*
* Job found, initialize source pointers...
*/
src = NULL;
sprinter = NULL;
}
}
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
/*
* See if the job exists...
*/
jobid = atoi(resource + 6);
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
else
{
/*
* Job found, initialize source pointers...
*/
src = NULL;
sprinter = NULL;
}
}
/*
* Check the policy of the destination printer...
*/
if ((status = cupsdCheckPolicy(dprinter->op_policy_ptr, con,
job ? job->username : NULL)) != HTTP_OK)
{
send_http_error(con, status, dprinter);
return;
}
/*
* Now move the job or jobs...
*/
if (job)
{
/*
* See if the job has been completed...
*/
if (job->state_value > IPP_JOB_STOPPED)
{
/*
* Return a "not-possible" error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job #%d is finished and cannot be altered."),
job->id);
return;
}
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* Move the job to a different printer or class...
*/
cupsdMoveJob(job, dprinter);
}
else
{
/*
* Got the source printer, now look through the jobs...
*/
for (job = (cupsd_job_t *)cupsArrayFirst(Jobs);
job;
job = (cupsd_job_t *)cupsArrayNext(Jobs))
{
/*
* See if the job is pointing at the source printer or has not been
* completed...
*/
if (_cups_strcasecmp(job->dest, src) ||
job->state_value > IPP_JOB_STOPPED)
continue;
/*
* See if the job can be moved by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
continue;
/*
* Move the job to a different printer or class...
*/
cupsdMoveJob(job, dprinter);
}
}
/*
* Start jobs if possible...
*/
cupsdCheckJobs();
/*
* Return with "everything is OK" status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'ppd_parse_line()' - Parse a PPD default line.
*/
static int /* O - 0 on success, -1 on failure */
ppd_parse_line(const char *line, /* I - Line */
char *option, /* O - Option name */
int olen, /* I - Size of option name */
char *choice, /* O - Choice name */
int clen) /* I - Size of choice name */
{
/*
* Verify this is a default option line...
*/
if (strncmp(line, "*Default", 8))
return (-1);
/*
* Read the option name...
*/
for (line += 8, olen --;
*line > ' ' && *line < 0x7f && *line != ':' && *line != '/';
line ++)
if (olen > 0)
{
*option++ = *line;
olen --;
}
*option = '\0';
/*
* Skip everything else up to the colon (:)...
*/
while (*line && *line != ':')
line ++;
if (!*line)
return (-1);
line ++;
/*
* Now grab the option choice, skipping leading whitespace...
*/
while (isspace(*line & 255))
line ++;
for (clen --;
*line > ' ' && *line < 0x7f && *line != ':' && *line != '/';
line ++)
if (clen > 0)
{
*choice++ = *line;
clen --;
}
*choice = '\0';
/*
* Return with no errors...
*/
return (0);
}
/*
* 'print_job()' - Print a file to a printer or class.
*/
static void
print_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
ipp_attribute_t *attr; /* Current attribute */
ipp_attribute_t *doc_name; /* document-name attribute */
ipp_attribute_t *format; /* Document-format attribute */
const char *default_format; /* document-format-default value */
cupsd_job_t *job; /* New job */
char filename[1024]; /* Job filename */
mime_type_t *filetype; /* Type of file */
char super[MIME_MAX_SUPER], /* Supertype of file */
type[MIME_MAX_TYPE], /* Subtype of file */
mimetype[MIME_MAX_SUPER + MIME_MAX_TYPE + 2];
/* Textual name of mime type */
cupsd_printer_t *printer; /* Printer data */
struct stat fileinfo; /* File information */
int kbytes; /* Size of file */
int compression; /* Document compression */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "print_job(%p[%d], %s)", con, con->number,
uri->values[0].string.text);
/*
* Validate print file attributes, for now just document-format and
* compression (CUPS only supports "none" and "gzip")...
*/
compression = CUPS_FILE_NONE;
if ((attr = ippFindAttribute(con->request, "compression",
IPP_TAG_KEYWORD)) != NULL)
{
if (strcmp(attr->values[0].string.text, "none")
#ifdef HAVE_LIBZ
&& strcmp(attr->values[0].string.text, "gzip")
#endif /* HAVE_LIBZ */
)
{
send_ipp_status(con, IPP_ATTRIBUTES,
_("Unsupported compression \"%s\"."),
attr->values[0].string.text);
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_KEYWORD,
"compression", NULL, attr->values[0].string.text);
return;
}
#ifdef HAVE_LIBZ
if (!strcmp(attr->values[0].string.text, "gzip"))
compression = CUPS_FILE_GZIP;
#endif /* HAVE_LIBZ */
}
/*
* Do we have a file to print?
*/
if (!con->filename)
{
send_ipp_status(con, IPP_BAD_REQUEST, _("No file in print request."));
return;
}
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, NULL, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Is it a format we support?
*/
doc_name = ippFindAttribute(con->request, "document-name", IPP_TAG_NAME);
if (doc_name)
ippSetName(con->request, &doc_name, "document-name-supplied");
if ((format = ippFindAttribute(con->request, "document-format",
IPP_TAG_MIMETYPE)) != NULL)
{
/*
* Grab format from client...
*/
if (sscanf(format->values[0].string.text, "%15[^/]/%255[^;]", super,
type) != 2)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Bad document-format \"%s\"."),
format->values[0].string.text);
return;
}
ippAddString(con->request, IPP_TAG_JOB, IPP_TAG_MIMETYPE, "document-format-supplied", NULL, ippGetString(format, 0, NULL));
}
else if ((default_format = cupsGetOption("document-format",
printer->num_options,
printer->options)) != NULL)
{
/*
* Use default document format...
*/
if (sscanf(default_format, "%15[^/]/%255[^;]", super, type) != 2)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Bad document-format \"%s\"."),
default_format);
return;
}
}
else
{
/*
* Auto-type it!
*/
strlcpy(super, "application", sizeof(super));
strlcpy(type, "octet-stream", sizeof(type));
}
if (!strcmp(super, "application") && !strcmp(type, "octet-stream"))
{
/*
* Auto-type the file...
*/
cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job ???] Auto-typing file...");
filetype = mimeFileType(MimeDatabase, con->filename,
doc_name ? doc_name->values[0].string.text : NULL,
&compression);
if (!filetype)
filetype = mimeType(MimeDatabase, super, type);
cupsdLogMessage(CUPSD_LOG_INFO, "[Job ???] Request file type is %s/%s.",
filetype->super, filetype->type);
snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super, filetype->type);
ippAddString(con->request, IPP_TAG_JOB, IPP_TAG_MIMETYPE, "document-format-detected", NULL, mimetype);
}
else
filetype = mimeType(MimeDatabase, super, type);
if (filetype &&
(!format ||
(!strcmp(super, "application") && !strcmp(type, "octet-stream"))))
{
/*
* Replace the document-format attribute value with the auto-typed or
* default one.
*/
snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super,
filetype->type);
if (format)
ippSetString(con->request, &format, 0, mimetype);
else
ippAddString(con->request, IPP_TAG_JOB, IPP_TAG_MIMETYPE,
"document-format", NULL, mimetype);
}
else if (!filetype)
{
send_ipp_status(con, IPP_DOCUMENT_FORMAT,
_("Unsupported document-format \"%s\"."),
format ? format->values[0].string.text :
"application/octet-stream");
cupsdLogMessage(CUPSD_LOG_INFO,
"Hint: Do you have the raw file printing rules enabled?");
if (format)
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE,
"document-format", NULL, format->values[0].string.text);
return;
}
/*
* Read any embedded job ticket info from PS files...
*/
if (!_cups_strcasecmp(filetype->super, "application") &&
(!_cups_strcasecmp(filetype->type, "postscript") ||
!_cups_strcasecmp(filetype->type, "pdf")))
read_job_ticket(con);
/*
* Create the job object...
*/
if ((job = add_job(con, printer, filetype)) == NULL)
return;
/*
* Update quota data...
*/
if (stat(con->filename, &fileinfo))
kbytes = 0;
else
kbytes = (fileinfo.st_size + 1023) / 1024;
cupsdUpdateQuota(printer, job->username, 0, kbytes);
job->koctets += kbytes;
if ((attr = ippFindAttribute(job->attrs, "job-k-octets", IPP_TAG_INTEGER)) != NULL)
attr->values[0].integer += kbytes;
/*
* Add the job file...
*/
if (add_file(con, job, filetype, compression))
return;
snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot, job->id, job->num_files);
if (rename(con->filename, filename))
{
cupsdLogJob(job, CUPSD_LOG_ERROR, "Unable to rename job document file \"%s\": %s", filename, strerror(errno));
send_ipp_status(con, IPP_INTERNAL_ERROR, _("Unable to rename job document file."));
return;
}
cupsdClearString(&con->filename);
/*
* See if we need to add the ending sheet...
*/
if (cupsdTimeoutJob(job))
return;
/*
* Log and save the job...
*/
cupsdLogJob(job, CUPSD_LOG_INFO,
"File of type %s/%s queued by \"%s\".",
filetype->super, filetype->type, job->username);
cupsdLogJob(job, CUPSD_LOG_DEBUG, "hold_until=%d", (int)job->hold_until);
cupsdLogJob(job, CUPSD_LOG_INFO, "Queued on \"%s\" by \"%s\".",
job->dest, job->username);
/*
* Start the job if possible...
*/
cupsdCheckJobs();
}
/*
* 'read_job_ticket()' - Read a job ticket embedded in a print file.
*
* This function only gets called when printing a single PDF or PostScript
* file using the Print-Job operation. It doesn't work for Create-Job +
* Send-File, since the job attributes need to be set at job creation
* time for banners to work. The embedded job ticket stuff is here
* primarily to allow the Windows printer driver for CUPS to pass in JCL
* options and IPP attributes which otherwise would be lost.
*
* The format of a job ticket is simple:
*
* %cupsJobTicket: attr1=value1 attr2=value2 ... attrN=valueN
*
* %cupsJobTicket: attr1=value1
* %cupsJobTicket: attr2=value2
* ...
* %cupsJobTicket: attrN=valueN
*
* Job ticket lines must appear immediately after the first line that
* specifies PostScript (%!PS-Adobe-3.0) or PDF (%PDF) format, and CUPS
* stops looking for job ticket info when it finds a line that does not begin
* with "%cupsJobTicket:".
*
* The maximum length of a job ticket line, including the prefix, is
* 255 characters to conform with the Adobe DSC.
*
* Read-only attributes are rejected with a notice to the error log in
* case a malicious user tries anything. Since the job ticket is read
* prior to attribute validation in print_job(), job ticket attributes
* will go through the same validation as IPP attributes...
*/
static void
read_job_ticket(cupsd_client_t *con) /* I - Client connection */
{
cups_file_t *fp; /* File to read from */
char line[256]; /* Line data */
int num_options; /* Number of options */
cups_option_t *options; /* Options */
ipp_t *ticket; /* New attributes */
ipp_attribute_t *attr, /* Current attribute */
*attr2, /* Job attribute */
*prev2; /* Previous job attribute */
/*
* First open the print file...
*/
if ((fp = cupsFileOpen(con->filename, "rb")) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to open print file for job ticket - %s",
strerror(errno));
return;
}
/*
* Skip the first line...
*/
if (cupsFileGets(fp, line, sizeof(line)) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to read from print file for job ticket - %s",
strerror(errno));
cupsFileClose(fp);
return;
}
if (strncmp(line, "%!PS-Adobe-", 11) && strncmp(line, "%PDF-", 5))
{
/*
* Not a DSC-compliant file, so no job ticket info will be available...
*/
cupsFileClose(fp);
return;
}
/*
* Read job ticket info from the file...
*/
num_options = 0;
options = NULL;
while (cupsFileGets(fp, line, sizeof(line)))
{
/*
* Stop at the first non-ticket line...
*/
if (strncmp(line, "%cupsJobTicket:", 15))
break;
/*
* Add the options to the option array...
*/
num_options = cupsParseOptions(line + 15, num_options, &options);
}
/*
* Done with the file; see if we have any options...
*/
cupsFileClose(fp);
if (num_options == 0)
return;
/*
* OK, convert the options to an attribute list, and apply them to
* the request...
*/
ticket = ippNew();
cupsEncodeOptions(ticket, num_options, options);
/*
* See what the user wants to change.
*/
for (attr = ticket->attrs; attr; attr = attr->next)
{
if (attr->group_tag != IPP_TAG_JOB || !attr->name)
continue;
if (!strncmp(attr->name, "date-time-at-", 13) ||
!strcmp(attr->name, "job-impressions-completed") ||
!strcmp(attr->name, "job-media-sheets-completed") ||
!strncmp(attr->name, "job-k-octets", 12) ||
!strcmp(attr->name, "job-id") ||
!strcmp(attr->name, "job-originating-host-name") ||
!strcmp(attr->name, "job-originating-user-name") ||
!strcmp(attr->name, "job-pages-completed") ||
!strcmp(attr->name, "job-printer-uri") ||
!strncmp(attr->name, "job-state", 9) ||
!strcmp(attr->name, "job-uri") ||
!strncmp(attr->name, "time-at-", 8))
continue; /* Read-only attrs */
if ((attr2 = ippFindAttribute(con->request, attr->name,
IPP_TAG_ZERO)) != NULL)
{
/*
* Some other value; first free the old value...
*/
if (con->request->attrs == attr2)
{
con->request->attrs = attr2->next;
prev2 = NULL;
}
else
{
for (prev2 = con->request->attrs; prev2; prev2 = prev2->next)
if (prev2->next == attr2)
{
prev2->next = attr2->next;
break;
}
}
if (con->request->last == attr2)
con->request->last = prev2;
ippDeleteAttribute(NULL, attr2);
}
/*
* Add new option by copying it...
*/
ippCopyAttribute(con->request, attr, 0);
}
/*
* Then free the attribute list and option array...
*/
ippDelete(ticket);
cupsFreeOptions(num_options, options);
}
/*
* 'reject_jobs()' - Reject print jobs to a printer.
*/
static void
reject_jobs(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer or class URI */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer data */
ipp_attribute_t *attr; /* printer-state-message text */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "reject_jobs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Reject jobs sent to the printer...
*/
printer->accepting = 0;
if ((attr = ippFindAttribute(con->request, "printer-state-message",
IPP_TAG_TEXT)) == NULL)
strlcpy(printer->state_message, "Rejecting Jobs",
sizeof(printer->state_message));
else
strlcpy(printer->state_message, attr->values[0].string.text,
sizeof(printer->state_message));
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, printer, NULL,
"No longer accepting jobs.");
if (dtype & CUPS_PRINTER_CLASS)
{
cupsdMarkDirty(CUPSD_DIRTY_CLASSES);
cupsdLogMessage(CUPSD_LOG_INFO, "Class \"%s\" rejecting jobs (\"%s\").",
printer->name, get_username(con));
}
else
{
cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
cupsdLogMessage(CUPSD_LOG_INFO, "Printer \"%s\" rejecting jobs (\"%s\").",
printer->name, get_username(con));
}
/*
* Everything was ok, so return OK status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'release_held_new_jobs()' - Release pending/new jobs on a printer or class.
*/
static void
release_held_new_jobs(
cupsd_client_t *con, /* I - Connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer data */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "release_held_new_jobs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Hold pending/new jobs sent to the printer...
*/
printer->holding_new_jobs = 0;
cupsdSetPrinterReasons(printer, "-hold-new-jobs");
if (dtype & CUPS_PRINTER_CLASS)
cupsdLogMessage(CUPSD_LOG_INFO,
"Class \"%s\" now printing pending/new jobs (\"%s\").",
printer->name, get_username(con));
else
cupsdLogMessage(CUPSD_LOG_INFO,
"Printer \"%s\" now printing pending/new jobs (\"%s\").",
printer->name, get_username(con));
cupsdCheckJobs();
/*
* Everything was ok, so return OK status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'release_job()' - Release a held print job.
*/
static void
release_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job or Printer URI */
{
ipp_attribute_t *attr; /* Current attribute */
int jobid; /* Job ID */
char scheme[HTTP_MAX_URI], /* Method portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
cupsd_job_t *job; /* Job information */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "release_job(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
jobid = attr->values[0].integer;
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
/*
* See if job is "held"...
*/
if (job->state_value != IPP_JOB_HELD)
{
/*
* Nope - return a "not possible" error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Job #%d is not held."), jobid);
return;
}
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* Reset the job-hold-until value to "no-hold"...
*/
if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
if (attr)
{
ippSetValueTag(job->attrs, &attr, IPP_TAG_KEYWORD);
ippSetString(job->attrs, &attr, 0, "no-hold");
cupsdAddEvent(CUPSD_EVENT_JOB_CONFIG_CHANGED, cupsdFindDest(job->dest), job,
"Job job-hold-until value changed by user.");
ippSetString(job->attrs, &job->reasons, 0, "none");
}
/*
* Release the job and return...
*/
cupsdReleaseJob(job);
cupsdAddEvent(CUPSD_EVENT_JOB_STATE, cupsdFindDest(job->dest), job,
"Job released by user.");
cupsdLogJob(job, CUPSD_LOG_INFO, "Released by \"%s\".", username);
con->response->request.status.status_code = IPP_OK;
cupsdCheckJobs();
}
/*
* 'renew_subscription()' - Renew an existing subscription...
*/
static void
renew_subscription(
cupsd_client_t *con, /* I - Client connection */
int sub_id) /* I - Subscription ID */
{
http_status_t status; /* Policy status */
cupsd_subscription_t *sub; /* Subscription */
ipp_attribute_t *lease; /* notify-lease-duration */
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"renew_subscription(con=%p[%d], sub_id=%d)",
con, con->number, sub_id);
/*
* Is the subscription ID valid?
*/
if ((sub = cupsdFindSubscription(sub_id)) == NULL)
{
/*
* Bad subscription ID...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Subscription #%d does not exist."),
sub_id);
return;
}
if (sub->job)
{
/*
* Job subscriptions cannot be renewed...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job subscriptions cannot be renewed."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(sub->dest ? sub->dest->op_policy_ptr :
DefaultPolicyPtr,
con, sub->owner)) != HTTP_OK)
{
send_http_error(con, status, sub->dest);
return;
}
/*
* Renew the subscription...
*/
lease = ippFindAttribute(con->request, "notify-lease-duration",
IPP_TAG_INTEGER);
sub->lease = lease ? lease->values[0].integer : DefaultLeaseDuration;
if (MaxLeaseDuration && (sub->lease == 0 || sub->lease > MaxLeaseDuration))
{
cupsdLogMessage(CUPSD_LOG_INFO,
"renew_subscription: Limiting notify-lease-duration to "
"%d seconds.",
MaxLeaseDuration);
sub->lease = MaxLeaseDuration;
}
sub->expire = sub->lease ? time(NULL) + sub->lease : 0;
cupsdMarkDirty(CUPSD_DIRTY_SUBSCRIPTIONS);
con->response->request.status.status_code = IPP_OK;
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER,
"notify-lease-duration", sub->lease);
}
/*
* 'restart_job()' - Restart an old print job.
*/
static void
restart_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job or Printer URI */
{
ipp_attribute_t *attr; /* Current attribute */
int jobid; /* Job ID */
cupsd_job_t *job; /* Job information */
char scheme[HTTP_MAX_URI], /* Method portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "restart_job(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
jobid = attr->values[0].integer;
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
/*
* See if job is in any of the "completed" states...
*/
if (job->state_value <= IPP_JOB_PROCESSING)
{
/*
* Nope - return a "not possible" error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Job #%d is not complete."),
jobid);
return;
}
/*
* See if we have retained the job files...
*/
cupsdLoadJob(job);
if (!job->attrs || job->num_files == 0)
{
/*
* Nope - return a "not possible" error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job #%d cannot be restarted - no files."), jobid);
return;
}
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* See if the job-hold-until attribute is specified...
*/
if ((attr = ippFindAttribute(con->request, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(con->request, "job-hold-until", IPP_TAG_NAME);
if (attr && strcmp(attr->values[0].string.text, "no-hold"))
{
/*
* Return the job to a held state...
*/
cupsdLogJob(job, CUPSD_LOG_DEBUG,
"Restarted by \"%s\" with job-hold-until=%s.",
username, attr->values[0].string.text);
cupsdSetJobHoldUntil(job, attr->values[0].string.text, 0);
cupsdAddEvent(CUPSD_EVENT_JOB_CONFIG_CHANGED | CUPSD_EVENT_JOB_STATE,
NULL, job, "Job restarted by user with job-hold-until=%s",
attr->values[0].string.text);
}
else
{
/*
* Restart the job...
*/
cupsdRestartJob(job);
cupsdCheckJobs();
}
cupsdLogJob(job, CUPSD_LOG_INFO, "Restarted by \"%s\".", username);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'save_auth_info()' - Save authentication information for a job.
*/
static void
save_auth_info(
cupsd_client_t *con, /* I - Client connection */
cupsd_job_t *job, /* I - Job */
ipp_attribute_t *auth_info) /* I - auth-info attribute, if any */
{
int i; /* Looping var */
char filename[1024]; /* Job authentication filename */
cups_file_t *fp; /* Job authentication file */
char line[65536]; /* Line for file */
cupsd_printer_t *dest; /* Destination printer/class */
/*
* This function saves the in-memory authentication information for
* a job so that it can be used to authenticate with a remote host.
* The information is stored in a file that is readable only by the
* root user. The fields are Base-64 encoded, each on a separate line,
* followed by random number (up to 1024) of newlines to limit the
* amount of information that is exposed.
*
* Because of the potential for exposing of authentication information,
* this functionality is only enabled when running cupsd as root.
*
* This caching only works for the Basic and BasicDigest authentication
* types. Digest authentication cannot be cached this way, and in
* the future Kerberos authentication may make all of this obsolete.
*
* Authentication information is saved whenever an authenticated
* Print-Job, Create-Job, or CUPS-Authenticate-Job operation is
* performed.
*
* This information is deleted after a job is completed or canceled,
* so reprints may require subsequent re-authentication.
*/
if (RunUser)
return;
if ((dest = cupsdFindDest(job->dest)) == NULL)
return;
/*
* Create the authentication file and change permissions...
*/
snprintf(filename, sizeof(filename), "%s/a%05d", RequestRoot, job->id);
if ((fp = cupsFileOpen(filename, "w")) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to save authentication info to \"%s\" - %s",
filename, strerror(errno));
return;
}
fchown(cupsFileNumber(fp), 0, 0);
fchmod(cupsFileNumber(fp), 0400);
cupsFilePuts(fp, "CUPSD-AUTH-V3\n");
for (i = 0;
i < (int)(sizeof(job->auth_env) / sizeof(job->auth_env[0]));
i ++)
cupsdClearString(job->auth_env + i);
if (auth_info && auth_info->num_values == dest->num_auth_info_required)
{
/*
* Write 1 to 3 auth values...
*/
for (i = 0;
i < auth_info->num_values &&
i < (int)(sizeof(job->auth_env) / sizeof(job->auth_env[0]));
i ++)
{
if (strcmp(dest->auth_info_required[i], "negotiate"))
{
httpEncode64_2(line, sizeof(line), auth_info->values[i].string.text, (int)strlen(auth_info->values[i].string.text));
cupsFilePutConf(fp, dest->auth_info_required[i], line);
}
else
cupsFilePutConf(fp, dest->auth_info_required[i],
auth_info->values[i].string.text);
if (!strcmp(dest->auth_info_required[i], "username"))
cupsdSetStringf(job->auth_env + i, "AUTH_USERNAME=%s",
auth_info->values[i].string.text);
else if (!strcmp(dest->auth_info_required[i], "domain"))
cupsdSetStringf(job->auth_env + i, "AUTH_DOMAIN=%s",
auth_info->values[i].string.text);
else if (!strcmp(dest->auth_info_required[i], "password"))
cupsdSetStringf(job->auth_env + i, "AUTH_PASSWORD=%s",
auth_info->values[i].string.text);
else if (!strcmp(dest->auth_info_required[i], "negotiate"))
cupsdSetStringf(job->auth_env + i, "AUTH_NEGOTIATE=%s",
auth_info->values[i].string.text);
else
i --;
}
}
else if (auth_info && auth_info->num_values == 2 &&
dest->num_auth_info_required == 1 &&
!strcmp(dest->auth_info_required[0], "negotiate"))
{
/*
* Allow fallback to username+password for Kerberized queues...
*/
httpEncode64_2(line, sizeof(line), auth_info->values[0].string.text, (int)strlen(auth_info->values[0].string.text));
cupsFilePutConf(fp, "username", line);
cupsdSetStringf(job->auth_env + 0, "AUTH_USERNAME=%s",
auth_info->values[0].string.text);
httpEncode64_2(line, sizeof(line), auth_info->values[1].string.text, (int)strlen(auth_info->values[1].string.text));
cupsFilePutConf(fp, "password", line);
cupsdSetStringf(job->auth_env + 1, "AUTH_PASSWORD=%s",
auth_info->values[1].string.text);
}
else if (con->username[0])
{
/*
* Write the authenticated username...
*/
httpEncode64_2(line, sizeof(line), con->username, (int)strlen(con->username));
cupsFilePutConf(fp, "username", line);
cupsdSetStringf(job->auth_env + 0, "AUTH_USERNAME=%s", con->username);
/*
* Write the authenticated password...
*/
httpEncode64_2(line, sizeof(line), con->password, (int)strlen(con->password));
cupsFilePutConf(fp, "password", line);
cupsdSetStringf(job->auth_env + 1, "AUTH_PASSWORD=%s", con->password);
}
#ifdef HAVE_GSSAPI
if (con->gss_uid > 0)
{
cupsFilePrintf(fp, "uid %d\n", (int)con->gss_uid);
cupsdSetStringf(&job->auth_uid, "AUTH_UID=%d", (int)con->gss_uid);
}
#endif /* HAVE_GSSAPI */
/*
* Write a random number of newlines to the end of the file...
*/
for (i = (CUPS_RAND() % 1024); i >= 0; i --)
cupsFilePutChar(fp, '\n');
/*
* Close the file and return...
*/
cupsFileClose(fp);
}
/*
* 'send_document()' - Send a file to a printer or class.
*/
static void
send_document(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
ipp_attribute_t *attr; /* Current attribute */
ipp_attribute_t *format; /* Request's document-format attribute */
ipp_attribute_t *jformat; /* Job's document-format attribute */
const char *default_format;/* document-format-default value */
int jobid; /* Job ID number */
cupsd_job_t *job; /* Current job */
char job_uri[HTTP_MAX_URI],
/* Job URI */
scheme[HTTP_MAX_URI],
/* Method portion of URI */
username[HTTP_MAX_URI],
/* Username portion of URI */
host[HTTP_MAX_URI],
/* Host portion of URI */
resource[HTTP_MAX_URI];
/* Resource portion of URI */
int port; /* Port portion of URI */
mime_type_t *filetype; /* Type of file */
char super[MIME_MAX_SUPER],
/* Supertype of file */
type[MIME_MAX_TYPE],
/* Subtype of file */
mimetype[MIME_MAX_SUPER + MIME_MAX_TYPE + 2];
/* Textual name of mime type */
char filename[1024]; /* Job filename */
cupsd_printer_t *printer; /* Current printer */
struct stat fileinfo; /* File information */
int kbytes; /* Size of file */
int compression; /* Type of compression */
int start_job; /* Start the job? */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "send_document(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
jobid = attr->values[0].integer;
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
printer = cupsdFindDest(job->dest);
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* OK, see if the client is sending the document compressed - CUPS
* only supports "none" and "gzip".
*/
compression = CUPS_FILE_NONE;
if ((attr = ippFindAttribute(con->request, "compression",
IPP_TAG_KEYWORD)) != NULL)
{
if (strcmp(attr->values[0].string.text, "none")
#ifdef HAVE_LIBZ
&& strcmp(attr->values[0].string.text, "gzip")
#endif /* HAVE_LIBZ */
)
{
send_ipp_status(con, IPP_ATTRIBUTES, _("Unsupported compression \"%s\"."),
attr->values[0].string.text);
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_KEYWORD,
"compression", NULL, attr->values[0].string.text);
return;
}
#ifdef HAVE_LIBZ
if (!strcmp(attr->values[0].string.text, "gzip"))
compression = CUPS_FILE_GZIP;
#endif /* HAVE_LIBZ */
}
/*
* Do we have a file to print?
*/
if ((attr = ippFindAttribute(con->request, "last-document",
IPP_TAG_BOOLEAN)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Missing last-document attribute in request."));
return;
}
if (!con->filename)
{
/*
* Check for an empty request with "last-document" set to true, which is
* used to close an "open" job by RFC 2911, section 3.3.2.
*/
if (job->num_files > 0 && attr->values[0].boolean)
goto last_document;
send_ipp_status(con, IPP_BAD_REQUEST, _("No file in print request."));
return;
}
/*
* Is it a format we support?
*/
cupsdLoadJob(job);
if ((format = ippFindAttribute(con->request, "document-format",
IPP_TAG_MIMETYPE)) != NULL)
{
/*
* Grab format from client...
*/
if (sscanf(format->values[0].string.text, "%15[^/]/%255[^;]",
super, type) != 2)
{
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad document-format \"%s\"."),
format->values[0].string.text);
return;
}
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_MIMETYPE, "document-format-supplied", NULL, ippGetString(format, 0, NULL));
}
else if ((default_format = cupsGetOption("document-format",
printer->num_options,
printer->options)) != NULL)
{
/*
* Use default document format...
*/
if (sscanf(default_format, "%15[^/]/%255[^;]", super, type) != 2)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Bad document-format-default \"%s\"."), default_format);
return;
}
}
else
{
/*
* No document format attribute? Auto-type it!
*/
strlcpy(super, "application", sizeof(super));
strlcpy(type, "octet-stream", sizeof(type));
}
if (!strcmp(super, "application") && !strcmp(type, "octet-stream"))
{
/*
* Auto-type the file...
*/
ipp_attribute_t *doc_name; /* document-name attribute */
cupsdLogJob(job, CUPSD_LOG_DEBUG, "Auto-typing file...");
doc_name = ippFindAttribute(con->request, "document-name", IPP_TAG_NAME);
filetype = mimeFileType(MimeDatabase, con->filename,
doc_name ? doc_name->values[0].string.text : NULL,
&compression);
if (!filetype)
filetype = mimeType(MimeDatabase, super, type);
if (filetype)
cupsdLogJob(job, CUPSD_LOG_DEBUG, "Request file type is %s/%s.",
filetype->super, filetype->type);
snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super, filetype->type);
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_MIMETYPE, "document-format-detected", NULL, mimetype);
}
else
filetype = mimeType(MimeDatabase, super, type);
if (filetype)
{
/*
* Replace the document-format attribute value with the auto-typed or
* default one.
*/
snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super,
filetype->type);
if ((jformat = ippFindAttribute(job->attrs, "document-format",
IPP_TAG_MIMETYPE)) != NULL)
ippSetString(job->attrs, &jformat, 0, mimetype);
else
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_MIMETYPE,
"document-format", NULL, mimetype);
}
else if (!filetype)
{
send_ipp_status(con, IPP_DOCUMENT_FORMAT,
_("Unsupported document-format \"%s/%s\"."), super, type);
cupsdLogMessage(CUPSD_LOG_INFO,
"Hint: Do you have the raw file printing rules enabled?");
if (format)
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE,
"document-format", NULL, format->values[0].string.text);
return;
}
if (printer->filetypes && !cupsArrayFind(printer->filetypes, filetype))
{
snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super,
filetype->type);
send_ipp_status(con, IPP_DOCUMENT_FORMAT,
_("Unsupported document-format \"%s\"."), mimetype);
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE,
"document-format", NULL, mimetype);
return;
}
/*
* Add the file to the job...
*/
if (add_file(con, job, filetype, compression))
return;
if ((attr = ippFindAttribute(con->request, "document-name", IPP_TAG_NAME)) != NULL)
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "document-name-supplied", NULL, ippGetString(attr, 0, NULL));
if (stat(con->filename, &fileinfo))
kbytes = 0;
else
kbytes = (fileinfo.st_size + 1023) / 1024;
cupsdUpdateQuota(printer, job->username, 0, kbytes);
job->koctets += kbytes;
if ((attr = ippFindAttribute(job->attrs, "job-k-octets", IPP_TAG_INTEGER)) != NULL)
attr->values[0].integer += kbytes;
snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot, job->id, job->num_files);
if (rename(con->filename, filename))
{
cupsdLogJob(job, CUPSD_LOG_ERROR, "Unable to rename job document file \"%s\": %s", filename, strerror(errno));
send_ipp_status(con, IPP_INTERNAL_ERROR, _("Unable to rename job document file."));
return;
}
cupsdClearString(&con->filename);
cupsdLogJob(job, CUPSD_LOG_INFO, "File of type %s/%s queued by \"%s\".",
filetype->super, filetype->type, job->username);
/*
* Start the job if this is the last document...
*/
last_document:
if ((attr = ippFindAttribute(con->request, "last-document",
IPP_TAG_BOOLEAN)) != NULL &&
attr->values[0].boolean)
{
/*
* See if we need to add the ending sheet...
*/
if (cupsdTimeoutJob(job))
return;
if (job->state_value == IPP_JOB_STOPPED)
{
job->state->values[0].integer = IPP_JOB_PENDING;
job->state_value = IPP_JOB_PENDING;
ippSetString(job->attrs, &job->reasons, 0, "none");
}
else if (job->state_value == IPP_JOB_HELD)
{
if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
if (!attr || !strcmp(attr->values[0].string.text, "no-hold"))
{
job->state->values[0].integer = IPP_JOB_PENDING;
job->state_value = IPP_JOB_PENDING;
ippSetString(job->attrs, &job->reasons, 0, "none");
}
else
ippSetString(job->attrs, &job->reasons, 0, "job-hold-until-specified");
}
job->dirty = 1;
cupsdMarkDirty(CUPSD_DIRTY_JOBS);
start_job = 1;
}
else
{
if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
if (!attr || !strcmp(attr->values[0].string.text, "no-hold"))
{
job->state->values[0].integer = IPP_JOB_HELD;
job->state_value = IPP_JOB_HELD;
job->hold_until = time(NULL) + MultipleOperationTimeout;
ippSetString(job->attrs, &job->reasons, 0, "job-incoming");
job->dirty = 1;
cupsdMarkDirty(CUPSD_DIRTY_JOBS);
}
start_job = 0;
}
/*
* Fill in the response info...
*/
httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "ipp", NULL,
con->clientname, con->clientport, "/jobs/%d", jobid);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI, "job-uri", NULL,
job_uri);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", jobid);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_ENUM, "job-state",
job->state_value);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons",
NULL, job->reasons->values[0].string.text);
con->response->request.status.status_code = IPP_OK;
/*
* Start the job if necessary...
*/
if (start_job)
cupsdCheckJobs();
}
/*
* 'send_http_error()' - Send a HTTP error back to the IPP client.
*/
static void
send_http_error(
cupsd_client_t *con, /* I - Client connection */
http_status_t status, /* I - HTTP status code */
cupsd_printer_t *printer) /* I - Printer, if any */
{
ipp_attribute_t *uri; /* Request URI, if any */
if ((uri = ippFindAttribute(con->request, "printer-uri",
IPP_TAG_URI)) == NULL)
uri = ippFindAttribute(con->request, "job-uri", IPP_TAG_URI);
cupsdLogMessage(status == HTTP_FORBIDDEN ? CUPSD_LOG_ERROR : CUPSD_LOG_DEBUG,
"[Client %d] Returning HTTP %s for %s (%s) from %s",
con->number, httpStatus(status),
con->request ?
ippOpString(con->request->request.op.operation_id) :
"no operation-id",
uri ? uri->values[0].string.text : "no URI",
con->http->hostname);
if (printer)
{
int auth_type; /* Type of authentication required */
auth_type = CUPSD_AUTH_NONE;
if (status == HTTP_UNAUTHORIZED &&
printer->num_auth_info_required > 0 &&
!strcmp(printer->auth_info_required[0], "negotiate") &&
con->request &&
(con->request->request.op.operation_id == IPP_PRINT_JOB ||
con->request->request.op.operation_id == IPP_CREATE_JOB ||
con->request->request.op.operation_id == CUPS_AUTHENTICATE_JOB))
{
/*
* Creating and authenticating jobs requires Kerberos...
*/
auth_type = CUPSD_AUTH_NEGOTIATE;
}
else
{
/*
* Use policy/location-defined authentication requirements...
*/
char resource[HTTP_MAX_URI]; /* Resource portion of URI */
cupsd_location_t *auth; /* Pointer to authentication element */
if (printer->type & CUPS_PRINTER_CLASS)
snprintf(resource, sizeof(resource), "/classes/%s", printer->name);
else
snprintf(resource, sizeof(resource), "/printers/%s", printer->name);
if ((auth = cupsdFindBest(resource, HTTP_POST)) == NULL ||
auth->type == CUPSD_AUTH_NONE)
auth = cupsdFindPolicyOp(printer->op_policy_ptr,
con->request ?
con->request->request.op.operation_id :
IPP_PRINT_JOB);
if (auth)
{
if (auth->type == CUPSD_AUTH_DEFAULT)
auth_type = cupsdDefaultAuthType();
else
auth_type = auth->type;
}
}
cupsdSendError(con, status, auth_type);
}
else
cupsdSendError(con, status, CUPSD_AUTH_NONE);
ippDelete(con->response);
con->response = NULL;
return;
}
/*
* 'send_ipp_status()' - Send a status back to the IPP client.
*/
static void
send_ipp_status(cupsd_client_t *con, /* I - Client connection */
ipp_status_t status, /* I - IPP status code */
const char *message,/* I - Status message */
...) /* I - Additional args as needed */
{
va_list ap; /* Pointer to additional args */
char formatted[1024]; /* Formatted errror message */
va_start(ap, message);
vsnprintf(formatted, sizeof(formatted),
_cupsLangString(con->language, message), ap);
va_end(ap);
cupsdLogMessage(CUPSD_LOG_DEBUG, "%s %s: %s",
ippOpString(con->request->request.op.operation_id),
ippErrorString(status), formatted);
con->response->request.status.status_code = status;
if (ippFindAttribute(con->response, "attributes-charset",
IPP_TAG_ZERO) == NULL)
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
"attributes-charset", NULL, "utf-8");
if (ippFindAttribute(con->response, "attributes-natural-language",
IPP_TAG_ZERO) == NULL)
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
"attributes-natural-language", NULL, DefaultLanguage);
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_TEXT,
"status-message", NULL, formatted);
}
/*
* 'set_default()' - Set the default destination...
*/
static void
set_default(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer, /* Printer */
*oldprinter; /* Old default printer */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "set_default(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Set it as the default...
*/
oldprinter = DefaultPrinter;
DefaultPrinter = printer;
if (oldprinter)
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, oldprinter, NULL,
"%s is no longer the default printer.", oldprinter->name);
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, printer, NULL,
"%s is now the default printer.", printer->name);
cupsdMarkDirty(CUPSD_DIRTY_PRINTERS | CUPSD_DIRTY_CLASSES |
CUPSD_DIRTY_PRINTCAP);
cupsdLogMessage(CUPSD_LOG_INFO,
"Default destination set to \"%s\" by \"%s\".",
printer->name, get_username(con));
/*
* Everything was ok, so return OK status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'set_job_attrs()' - Set job attributes.
*/
static void
set_job_attrs(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job URI */
{
ipp_attribute_t *attr, /* Current attribute */
*attr2; /* Job attribute */
int jobid; /* Job ID */
cupsd_job_t *job; /* Current job */
char scheme[HTTP_MAX_URI],
/* Method portion of URI */
username[HTTP_MAX_URI],
/* Username portion of URI */
host[HTTP_MAX_URI],
/* Host portion of URI */
resource[HTTP_MAX_URI];
/* Resource portion of URI */
int port; /* Port portion of URI */
int event; /* Events? */
int check_jobs; /* Check jobs? */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "set_job_attrs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Start with "everything is OK" status...
*/
con->response->request.status.status_code = IPP_OK;
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
jobid = attr->values[0].integer;
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
/*
* See if the job has been completed...
*/
if (job->state_value > IPP_JOB_STOPPED)
{
/*
* Return a "not-possible" error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job #%d is finished and cannot be altered."), jobid);
return;
}
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* See what the user wants to change.
*/
cupsdLoadJob(job);
check_jobs = 0;
event = 0;
for (attr = con->request->attrs; attr; attr = attr->next)
{
if (attr->group_tag != IPP_TAG_JOB || !attr->name)
continue;
if (!strcmp(attr->name, "attributes-charset") ||
!strcmp(attr->name, "attributes-natural-language") ||
!strncmp(attr->name, "date-time-at-", 13) ||
!strncmp(attr->name, "document-compression", 20) ||
!strncmp(attr->name, "document-format", 15) ||
!strcmp(attr->name, "job-detailed-status-messages") ||
!strcmp(attr->name, "job-document-access-errors") ||
!strcmp(attr->name, "job-id") ||
!strcmp(attr->name, "job-impressions-completed") ||
!strcmp(attr->name, "job-k-octets-completed") ||
!strcmp(attr->name, "job-media-sheets-completed") ||
!strcmp(attr->name, "job-originating-host-name") ||
!strcmp(attr->name, "job-originating-user-name") ||
!strcmp(attr->name, "job-pages-completed") ||
!strcmp(attr->name, "job-printer-up-time") ||
!strcmp(attr->name, "job-printer-uri") ||
!strcmp(attr->name, "job-sheets") ||
!strcmp(attr->name, "job-state-message") ||
!strcmp(attr->name, "job-state-reasons") ||
!strcmp(attr->name, "job-uri") ||
!strcmp(attr->name, "number-of-documents") ||
!strcmp(attr->name, "number-of-intervening-jobs") ||
!strcmp(attr->name, "output-device-assigned") ||
!strncmp(attr->name, "time-at-", 8))
{
/*
* Read-only attrs!
*/
send_ipp_status(con, IPP_ATTRIBUTES_NOT_SETTABLE,
_("%s cannot be changed."), attr->name);
attr2 = ippCopyAttribute(con->response, attr, 0);
ippSetGroupTag(con->response, &attr2, IPP_TAG_UNSUPPORTED_GROUP);
continue;
}
if (!strcmp(attr->name, "job-priority"))
{
/*
* Change the job priority...
*/
if (attr->value_tag != IPP_TAG_INTEGER)
{
send_ipp_status(con, IPP_REQUEST_VALUE, _("Bad job-priority value."));
attr2 = ippCopyAttribute(con->response, attr, 0);
ippSetGroupTag(con->response, &attr2, IPP_TAG_UNSUPPORTED_GROUP);
}
else if (job->state_value >= IPP_JOB_PROCESSING)
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job is completed and cannot be changed."));
return;
}
else if (con->response->request.status.status_code == IPP_OK)
{
cupsdLogJob(job, CUPSD_LOG_DEBUG, "Setting job-priority to %d",
attr->values[0].integer);
cupsdSetJobPriority(job, attr->values[0].integer);
check_jobs = 1;
event |= CUPSD_EVENT_JOB_CONFIG_CHANGED |
CUPSD_EVENT_PRINTER_QUEUE_ORDER_CHANGED;
}
}
else if (!strcmp(attr->name, "job-state"))
{
/*
* Change the job state...
*/
if (attr->value_tag != IPP_TAG_ENUM)
{
send_ipp_status(con, IPP_REQUEST_VALUE, _("Bad job-state value."));
attr2 = ippCopyAttribute(con->response, attr, 0);
ippSetGroupTag(con->response, &attr2, IPP_TAG_UNSUPPORTED_GROUP);
}
else
{
switch (attr->values[0].integer)
{
case IPP_JOB_PENDING :
case IPP_JOB_HELD :
if (job->state_value > IPP_JOB_HELD)
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job state cannot be changed."));
return;
}
else if (con->response->request.status.status_code == IPP_OK)
{
cupsdLogJob(job, CUPSD_LOG_DEBUG, "Setting job-state to %d",
attr->values[0].integer);
cupsdSetJobState(job, (ipp_jstate_t)attr->values[0].integer, CUPSD_JOB_DEFAULT, "Job state changed by \"%s\"", username);
check_jobs = 1;
}
break;
case IPP_JOB_PROCESSING :
case IPP_JOB_STOPPED :
if (job->state_value != attr->values[0].integer)
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job state cannot be changed."));
return;
}
break;
case IPP_JOB_CANCELED :
case IPP_JOB_ABORTED :
case IPP_JOB_COMPLETED :
if (job->state_value > IPP_JOB_PROCESSING)
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job state cannot be changed."));
return;
}
else if (con->response->request.status.status_code == IPP_OK)
{
cupsdLogJob(job, CUPSD_LOG_DEBUG, "Setting job-state to %d",
attr->values[0].integer);
cupsdSetJobState(job, (ipp_jstate_t)attr->values[0].integer,
CUPSD_JOB_DEFAULT,
"Job state changed by \"%s\"", username);
check_jobs = 1;
}
break;
}
}
}
else if (con->response->request.status.status_code != IPP_OK)
continue;
else if ((attr2 = ippFindAttribute(job->attrs, attr->name,
IPP_TAG_ZERO)) != NULL)
{
/*
* Some other value; first free the old value...
*/
if (job->attrs->prev)
job->attrs->prev->next = attr2->next;
else
job->attrs->attrs = attr2->next;
if (job->attrs->last == attr2)
job->attrs->last = job->attrs->prev;
ippDeleteAttribute(NULL, attr2);
/*
* Then copy the attribute...
*/
ippCopyAttribute(job->attrs, attr, 0);
/*
* See if the job-name or job-hold-until is being changed.
*/
if (!strcmp(attr->name, "job-hold-until"))
{
cupsdLogJob(job, CUPSD_LOG_DEBUG, "Setting job-hold-until to %s",
attr->values[0].string.text);
cupsdSetJobHoldUntil(job, attr->values[0].string.text, 0);
if (!strcmp(attr->values[0].string.text, "no-hold"))
{
cupsdReleaseJob(job);
check_jobs = 1;
}
else
cupsdSetJobState(job, IPP_JOB_HELD, CUPSD_JOB_DEFAULT,
"Job held by \"%s\".", username);
event |= CUPSD_EVENT_JOB_CONFIG_CHANGED | CUPSD_EVENT_JOB_STATE;
}
}
else if (attr->value_tag == IPP_TAG_DELETEATTR)
{
/*
* Delete the attribute...
*/
if ((attr2 = ippFindAttribute(job->attrs, attr->name,
IPP_TAG_ZERO)) != NULL)
{
if (job->attrs->prev)
job->attrs->prev->next = attr2->next;
else
job->attrs->attrs = attr2->next;
if (attr2 == job->attrs->last)
job->attrs->last = job->attrs->prev;
ippDeleteAttribute(NULL, attr2);
event |= CUPSD_EVENT_JOB_CONFIG_CHANGED;
}
}
else
{
/*
* Add new option by copying it...
*/
ippCopyAttribute(job->attrs, attr, 0);
event |= CUPSD_EVENT_JOB_CONFIG_CHANGED;
}
}
/*
* Save the job...
*/
job->dirty = 1;
cupsdMarkDirty(CUPSD_DIRTY_JOBS);
/*
* Send events as needed...
*/
if (event & CUPSD_EVENT_PRINTER_QUEUE_ORDER_CHANGED)
cupsdAddEvent(CUPSD_EVENT_PRINTER_QUEUE_ORDER_CHANGED,
cupsdFindDest(job->dest), job,
"Job priority changed by user.");
if (event & CUPSD_EVENT_JOB_STATE)
cupsdAddEvent(CUPSD_EVENT_JOB_STATE, cupsdFindDest(job->dest), job,
job->state_value == IPP_JOB_HELD ?
"Job held by user." : "Job restarted by user.");
if (event & CUPSD_EVENT_JOB_CONFIG_CHANGED)
cupsdAddEvent(CUPSD_EVENT_JOB_CONFIG_CHANGED, cupsdFindDest(job->dest), job,
"Job options changed by user.");
/*
* Start jobs if possible...
*/
if (check_jobs)
cupsdCheckJobs();
}
/*
* 'set_printer_attrs()' - Set printer attributes.
*/
static void
set_printer_attrs(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer/class */
ipp_attribute_t *attr; /* Printer attribute */
int changed = 0; /* Was anything changed? */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "set_printer_attrs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Return a list of attributes that can be set via Set-Printer-Attributes.
*/
if ((attr = ippFindAttribute(con->request, "printer-location",
IPP_TAG_TEXT)) != NULL)
{
cupsdSetString(&printer->location, attr->values[0].string.text);
changed = 1;
}
if ((attr = ippFindAttribute(con->request, "printer-geo-location", IPP_TAG_URI)) != NULL && !strncmp(attr->values[0].string.text, "geo:", 4))
{
cupsdSetString(&printer->geo_location, attr->values[0].string.text);
changed = 1;
}
if ((attr = ippFindAttribute(con->request, "printer-organization", IPP_TAG_TEXT)) != NULL)
{
cupsdSetString(&printer->organization, attr->values[0].string.text);
changed = 1;
}
if ((attr = ippFindAttribute(con->request, "printer-organizational-unit", IPP_TAG_TEXT)) != NULL)
{
cupsdSetString(&printer->organizational_unit, attr->values[0].string.text);
changed = 1;
}
if ((attr = ippFindAttribute(con->request, "printer-info",
IPP_TAG_TEXT)) != NULL)
{
cupsdSetString(&printer->info, attr->values[0].string.text);
changed = 1;
}
/*
* Update the printer attributes and return...
*/
if (changed)
{
printer->config_time = time(NULL);
cupsdSetPrinterAttrs(printer);
cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
cupsdAddEvent(CUPSD_EVENT_PRINTER_CONFIG, printer, NULL,
"Printer \"%s\" description or location changed by \"%s\".",
printer->name, get_username(con));
cupsdLogMessage(CUPSD_LOG_INFO,
"Printer \"%s\" description or location changed by \"%s\".",
printer->name, get_username(con));
}
con->response->request.status.status_code = IPP_OK;
}
/*
* 'set_printer_defaults()' - Set printer default options from a request.
*/
static int /* O - 1 on success, 0 on failure */
set_printer_defaults(
cupsd_client_t *con, /* I - Client connection */
cupsd_printer_t *printer) /* I - Printer */
{
int i; /* Looping var */
ipp_attribute_t *attr; /* Current attribute */
size_t namelen; /* Length of attribute name */
char name[256], /* New attribute name */
value[256]; /* String version of integer attrs */
for (attr = con->request->attrs; attr; attr = attr->next)
{
/*
* Skip non-printer attributes...
*/
if (attr->group_tag != IPP_TAG_PRINTER || !attr->name)
continue;
cupsdLogMessage(CUPSD_LOG_DEBUG2, "set_printer_defaults: %s", attr->name);
if (!strcmp(attr->name, "job-sheets-default"))
{
/*
* Only allow keywords and names...
*/
if (attr->value_tag != IPP_TAG_NAME && attr->value_tag != IPP_TAG_KEYWORD)
continue;
/*
* Only allow job-sheets-default to be set when running without a
* system high classification level...
*/
if (Classification)
continue;
cupsdSetString(&printer->job_sheets[0], attr->values[0].string.text);
if (attr->num_values > 1)
cupsdSetString(&printer->job_sheets[1], attr->values[1].string.text);
else
cupsdSetString(&printer->job_sheets[1], "none");
}
else if (!strcmp(attr->name, "requesting-user-name-allowed"))
{
cupsdFreeStrings(&(printer->users));
printer->deny_users = 0;
if (attr->value_tag == IPP_TAG_NAME &&
(attr->num_values > 1 ||
strcmp(attr->values[0].string.text, "all")))
{
for (i = 0; i < attr->num_values; i ++)
cupsdAddString(&(printer->users), attr->values[i].string.text);
}
}
else if (!strcmp(attr->name, "requesting-user-name-denied"))
{
cupsdFreeStrings(&(printer->users));
printer->deny_users = 1;
if (attr->value_tag == IPP_TAG_NAME &&
(attr->num_values > 1 ||
strcmp(attr->values[0].string.text, "none")))
{
for (i = 0; i < attr->num_values; i ++)
cupsdAddString(&(printer->users), attr->values[i].string.text);
}
}
else if (!strcmp(attr->name, "job-quota-period"))
{
if (attr->value_tag != IPP_TAG_INTEGER)
continue;
cupsdLogMessage(CUPSD_LOG_DEBUG, "Setting job-quota-period to %d...",
attr->values[0].integer);
cupsdFreeQuotas(printer);
printer->quota_period = attr->values[0].integer;
}
else if (!strcmp(attr->name, "job-k-limit"))
{
if (attr->value_tag != IPP_TAG_INTEGER)
continue;
cupsdLogMessage(CUPSD_LOG_DEBUG, "Setting job-k-limit to %d...",
attr->values[0].integer);
cupsdFreeQuotas(printer);
printer->k_limit = attr->values[0].integer;
}
else if (!strcmp(attr->name, "job-page-limit"))
{
if (attr->value_tag != IPP_TAG_INTEGER)
continue;
cupsdLogMessage(CUPSD_LOG_DEBUG, "Setting job-page-limit to %d...",
attr->values[0].integer);
cupsdFreeQuotas(printer);
printer->page_limit = attr->values[0].integer;
}
else if (!strcmp(attr->name, "printer-op-policy"))
{
cupsd_policy_t *p; /* Policy */
if (attr->value_tag != IPP_TAG_NAME)
continue;
if ((p = cupsdFindPolicy(attr->values[0].string.text)) != NULL)
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Setting printer-op-policy to \"%s\"...",
attr->values[0].string.text);
cupsdSetString(&printer->op_policy, attr->values[0].string.text);
printer->op_policy_ptr = p;
}
else
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Unknown printer-op-policy \"%s\"."),
attr->values[0].string.text);
return (0);
}
}
else if (!strcmp(attr->name, "printer-error-policy"))
{
if (attr->value_tag != IPP_TAG_NAME && attr->value_tag != IPP_TAG_KEYWORD)
continue;
if (strcmp(attr->values[0].string.text, "retry-current-job") &&
((printer->type & CUPS_PRINTER_CLASS) ||
(strcmp(attr->values[0].string.text, "abort-job") &&
strcmp(attr->values[0].string.text, "retry-job") &&
strcmp(attr->values[0].string.text, "stop-printer"))))
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Unknown printer-error-policy \"%s\"."),
attr->values[0].string.text);
return (0);
}
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Setting printer-error-policy to \"%s\"...",
attr->values[0].string.text);
cupsdSetString(&printer->error_policy, attr->values[0].string.text);
}
/*
* Skip any other non-default attributes...
*/
namelen = strlen(attr->name);
if (namelen < 9 || strcmp(attr->name + namelen - 8, "-default") ||
namelen > (sizeof(name) - 1) || attr->num_values != 1)
continue;
/*
* OK, anything else must be a user-defined default...
*/
strlcpy(name, attr->name, sizeof(name));
name[namelen - 8] = '\0'; /* Strip "-default" */
switch (attr->value_tag)
{
case IPP_TAG_DELETEATTR :
printer->num_options = cupsRemoveOption(name,
printer->num_options,
&(printer->options));
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Deleting %s", attr->name);
break;
case IPP_TAG_NAME :
case IPP_TAG_TEXT :
case IPP_TAG_KEYWORD :
case IPP_TAG_URI :
printer->num_options = cupsAddOption(name,
attr->values[0].string.text,
printer->num_options,
&(printer->options));
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Setting %s to \"%s\"...", attr->name,
attr->values[0].string.text);
break;
case IPP_TAG_BOOLEAN :
printer->num_options = cupsAddOption(name,
attr->values[0].boolean ?
"true" : "false",
printer->num_options,
&(printer->options));
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Setting %s to %s...", attr->name,
attr->values[0].boolean ? "true" : "false");
break;
case IPP_TAG_INTEGER :
case IPP_TAG_ENUM :
sprintf(value, "%d", attr->values[0].integer);
printer->num_options = cupsAddOption(name, value,
printer->num_options,
&(printer->options));
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Setting %s to %s...", attr->name, value);
break;
case IPP_TAG_RANGE :
sprintf(value, "%d-%d", attr->values[0].range.lower,
attr->values[0].range.upper);
printer->num_options = cupsAddOption(name, value,
printer->num_options,
&(printer->options));
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Setting %s to %s...", attr->name, value);
break;
case IPP_TAG_RESOLUTION :
sprintf(value, "%dx%d%s", attr->values[0].resolution.xres,
attr->values[0].resolution.yres,
attr->values[0].resolution.units == IPP_RES_PER_INCH ?
"dpi" : "dpcm");
printer->num_options = cupsAddOption(name, value,
printer->num_options,
&(printer->options));
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Setting %s to %s...", attr->name, value);
break;
default :
/* Do nothing for other values */
break;
}
}
return (1);
}
/*
* 'start_printer()' - Start a printer.
*/
static void
start_printer(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
int i; /* Temporary variable */
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer data */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "start_printer(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Start the printer...
*/
printer->state_message[0] = '\0';
cupsdStartPrinter(printer, 1);
if (dtype & CUPS_PRINTER_CLASS)
cupsdLogMessage(CUPSD_LOG_INFO, "Class \"%s\" started by \"%s\".",
printer->name, get_username(con));
else
cupsdLogMessage(CUPSD_LOG_INFO, "Printer \"%s\" started by \"%s\".",
printer->name, get_username(con));
cupsdCheckJobs();
/*
* Check quotas...
*/
if ((i = check_quotas(con, printer)) < 0)
{
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Quota limit reached."));
return;
}
else if (i == 0)
{
send_ipp_status(con, IPP_NOT_AUTHORIZED, _("Not allowed to print."));
return;
}
/*
* Everything was ok, so return OK status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'stop_printer()' - Stop a printer.
*/
static void
stop_printer(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer data */
ipp_attribute_t *attr; /* printer-state-message attribute */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "stop_printer(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Stop the printer...
*/
if ((attr = ippFindAttribute(con->request, "printer-state-message",
IPP_TAG_TEXT)) == NULL)
strlcpy(printer->state_message, "Paused", sizeof(printer->state_message));
else
{
strlcpy(printer->state_message, attr->values[0].string.text,
sizeof(printer->state_message));
}
cupsdStopPrinter(printer, 1);
if (dtype & CUPS_PRINTER_CLASS)
cupsdLogMessage(CUPSD_LOG_INFO, "Class \"%s\" stopped by \"%s\".",
printer->name, get_username(con));
else
cupsdLogMessage(CUPSD_LOG_INFO, "Printer \"%s\" stopped by \"%s\".",
printer->name, get_username(con));
/*
* Everything was ok, so return OK status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'url_encode_attr()' - URL-encode a string attribute.
*/
static void
url_encode_attr(ipp_attribute_t *attr, /* I - Attribute */
char *buffer,/* I - String buffer */
size_t bufsize)/* I - Size of buffer */
{
int i; /* Looping var */
char *bufptr, /* Pointer into buffer */
*bufend; /* End of buffer */
strlcpy(buffer, attr->name, bufsize);
bufptr = buffer + strlen(buffer);
bufend = buffer + bufsize - 1;
for (i = 0; i < attr->num_values; i ++)
{
if (bufptr >= bufend)
break;
if (i)
*bufptr++ = ',';
else
*bufptr++ = '=';
if (bufptr >= bufend)
break;
*bufptr++ = '\'';
bufptr = url_encode_string(attr->values[i].string.text, bufptr, (size_t)(bufend - bufptr + 1));
if (bufptr >= bufend)
break;
*bufptr++ = '\'';
}
*bufptr = '\0';
}
/*
* 'url_encode_string()' - URL-encode a string.
*/
static char * /* O - End of string */
url_encode_string(const char *s, /* I - String */
char *buffer, /* I - String buffer */
size_t bufsize) /* I - Size of buffer */
{
char *bufptr, /* Pointer into buffer */
*bufend; /* End of buffer */
static const char *hex = "0123456789ABCDEF";
/* Hex digits */
bufptr = buffer;
bufend = buffer + bufsize - 1;
while (*s && bufptr < bufend)
{
if (*s == ' ' || *s == '%' || *s == '+')
{
if (bufptr >= (bufend - 2))
break;
*bufptr++ = '%';
*bufptr++ = hex[(*s >> 4) & 15];
*bufptr++ = hex[*s & 15];
s ++;
}
else if (*s == '\'' || *s == '\\')
{
if (bufptr >= (bufend - 1))
break;
*bufptr++ = '\\';
*bufptr++ = *s++;
}
else
*bufptr++ = *s++;
}
*bufptr = '\0';
return (bufptr);
}
/*
* 'user_allowed()' - See if a user is allowed to print to a queue.
*/
static int /* O - 0 if not allowed, 1 if allowed */
user_allowed(cupsd_printer_t *p, /* I - Printer or class */
const char *username) /* I - Username */
{
struct passwd *pw; /* User password data */
char baseuser[256], /* Base username */
*baseptr, /* Pointer to "@" in base username */
*name; /* Current user name */
if (cupsArrayCount(p->users) == 0)
return (1);
if (!strcmp(username, "root"))
return (1);
if (strchr(username, '@'))
{
/*
* Strip @REALM for username check...
*/
strlcpy(baseuser, username, sizeof(baseuser));
if ((baseptr = strchr(baseuser, '@')) != NULL)
*baseptr = '\0';
username = baseuser;
}
pw = getpwnam(username);
endpwent();
for (name = (char *)cupsArrayFirst(p->users);
name;
name = (char *)cupsArrayNext(p->users))
{
if (name[0] == '@')
{
/*
* Check group membership...
*/
if (cupsdCheckGroup(username, pw, name + 1))
break;
}
else if (name[0] == '#')
{
/*
* Check UUID...
*/
if (cupsdCheckGroup(username, pw, name))
break;
}
else if (!_cups_strcasecmp(username, name))
break;
}
return ((name != NULL) != p->deny_users);
}
/*
* 'validate_job()' - Validate printer options and destination.
*/
static void
validate_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
ipp_attribute_t *attr; /* Current attribute */
#ifdef HAVE_SSL
ipp_attribute_t *auth_info; /* auth-info attribute */
#endif /* HAVE_SSL */
ipp_attribute_t *format, /* Document-format attribute */
*name; /* Job-name attribute */
cups_ptype_t dtype; /* Destination type (printer/class) */
char super[MIME_MAX_SUPER],
/* Supertype of file */
type[MIME_MAX_TYPE];
/* Subtype of file */
cupsd_printer_t *printer; /* Printer */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "validate_job(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* OK, see if the client is sending the document compressed - CUPS
* doesn't support compression yet...
*/
if ((attr = ippFindAttribute(con->request, "compression",
IPP_TAG_KEYWORD)) != NULL)
{
if (strcmp(attr->values[0].string.text, "none")
#ifdef HAVE_LIBZ
&& strcmp(attr->values[0].string.text, "gzip")
#endif /* HAVE_LIBZ */
)
{
send_ipp_status(con, IPP_ATTRIBUTES,
_("Unsupported 'compression' value \"%s\"."),
attr->values[0].string.text);
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_KEYWORD,
"compression", NULL, attr->values[0].string.text);
return;
}
}
/*
* Is it a format we support?
*/
if ((format = ippFindAttribute(con->request, "document-format",
IPP_TAG_MIMETYPE)) != NULL)
{
if (sscanf(format->values[0].string.text, "%15[^/]/%255[^;]",
super, type) != 2)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Bad 'document-format' value \"%s\"."),
format->values[0].string.text);
return;
}
if ((strcmp(super, "application") || strcmp(type, "octet-stream")) &&
!mimeType(MimeDatabase, super, type))
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Hint: Do you have the raw file printing rules enabled?");
send_ipp_status(con, IPP_DOCUMENT_FORMAT,
_("Unsupported 'document-format' value \"%s\"."),
format->values[0].string.text);
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE,
"document-format", NULL, format->values[0].string.text);
return;
}
}
/*
* Is the job-name valid?
*/
if ((name = ippFindAttribute(con->request, "job-name", IPP_TAG_ZERO)) != NULL)
{
int bad_name = 0; /* Is the job-name value bad? */
if ((name->value_tag != IPP_TAG_NAME && name->value_tag != IPP_TAG_NAMELANG) ||
name->num_values != 1)
{
bad_name = 1;
}
else
{
/*
* Validate that job-name conforms to RFC 5198 (Network Unicode) and
* IPP Everywhere requirements for "name" values...
*/
const unsigned char *nameptr; /* Pointer into "job-name" attribute */
for (nameptr = (unsigned char *)name->values[0].string.text;
*nameptr;
nameptr ++)
{
if (*nameptr < ' ' && *nameptr != '\t')
break;
else if (*nameptr == 0x7f)
break;
else if ((*nameptr & 0xe0) == 0xc0)
{
if ((nameptr[1] & 0xc0) != 0x80)
break;
nameptr ++;
}
else if ((*nameptr & 0xf0) == 0xe0)
{
if ((nameptr[1] & 0xc0) != 0x80 ||
(nameptr[2] & 0xc0) != 0x80)
break;
nameptr += 2;
}
else if ((*nameptr & 0xf8) == 0xf0)
{
if ((nameptr[1] & 0xc0) != 0x80 ||
(nameptr[2] & 0xc0) != 0x80 ||
(nameptr[3] & 0xc0) != 0x80)
break;
nameptr += 3;
}
else if (*nameptr & 0x80)
break;
}
if (*nameptr)
bad_name = 1;
}
if (bad_name)
{
if (StrictConformance)
{
send_ipp_status(con, IPP_ATTRIBUTES,
_("Unsupported 'job-name' value."));
ippCopyAttribute(con->response, name, 0);
return;
}
else
{
cupsdLogMessage(CUPSD_LOG_WARN,
"Unsupported 'job-name' value, deleting from request.");
ippDeleteAttribute(con->request, name);
}
}
}
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
#ifdef HAVE_SSL
auth_info = ippFindAttribute(con->request, "auth-info", IPP_TAG_TEXT);
#endif /* HAVE_SSL */
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
else if (printer->num_auth_info_required == 1 &&
!strcmp(printer->auth_info_required[0], "negotiate") &&
!con->username[0])
{
send_http_error(con, HTTP_UNAUTHORIZED, printer);
return;
}
#ifdef HAVE_SSL
else if (auth_info && !con->http->tls &&
!httpAddrLocalhost(con->http->hostaddr))
{
/*
* Require encryption of auth-info over non-local connections...
*/
send_http_error(con, HTTP_UPGRADE_REQUIRED, printer);
return;
}
#endif /* HAVE_SSL */
/*
* Everything was ok, so return OK status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'validate_name()' - Make sure the printer name only contains valid chars.
*/
static int /* O - 0 if name is no good, 1 if good */
validate_name(const char *name) /* I - Name to check */
{
const char *ptr; /* Pointer into name */
/*
* Scan the whole name...
*/
for (ptr = name; *ptr; ptr ++)
if ((*ptr > 0 && *ptr <= ' ') || *ptr == 127 || *ptr == '/' || *ptr == '#')
return (0);
/*
* All the characters are good; validate the length, too...
*/
return ((ptr - name) < 128);
}
/*
* 'validate_user()' - Validate the user for the request.
*/
static int /* O - 1 if permitted, 0 otherwise */
validate_user(cupsd_job_t *job, /* I - Job */
cupsd_client_t *con, /* I - Client connection */
const char *owner, /* I - Owner of job/resource */
char *username, /* O - Authenticated username */
size_t userlen) /* I - Length of username */
{
cupsd_printer_t *printer; /* Printer for job */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "validate_user(job=%d, con=%d, owner=\"%s\", username=%p, userlen=" CUPS_LLFMT ")", job->id, con ? con->number : 0, owner ? owner : "(null)", username, CUPS_LLCAST userlen);
/*
* Validate input...
*/
if (!con || !owner || !username || userlen <= 0)
return (0);
/*
* Get the best authenticated username that is available.
*/
strlcpy(username, get_username(con), userlen);
/*
* Check the username against the owner...
*/
printer = cupsdFindDest(job->dest);
return (cupsdCheckPolicy(printer ? printer->op_policy_ptr : DefaultPolicyPtr,
con, owner) == HTTP_OK);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3025_1 |
crossvul-cpp_data_good_5845_24 | /*
* Copyright (C) 2011 Instituto Nokia de Tecnologia
*
* Authors:
* Aloisio Almeida Jr <aloisio.almeida@openbossa.org>
* Lauro Ramos Venancio <lauro.venancio@openbossa.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": %s: " fmt, __func__
#include <net/tcp_states.h>
#include <linux/nfc.h>
#include <linux/export.h>
#include "nfc.h"
static void rawsock_write_queue_purge(struct sock *sk)
{
pr_debug("sk=%p\n", sk);
spin_lock_bh(&sk->sk_write_queue.lock);
__skb_queue_purge(&sk->sk_write_queue);
nfc_rawsock(sk)->tx_work_scheduled = false;
spin_unlock_bh(&sk->sk_write_queue.lock);
}
static void rawsock_report_error(struct sock *sk, int err)
{
pr_debug("sk=%p err=%d\n", sk, err);
sk->sk_shutdown = SHUTDOWN_MASK;
sk->sk_err = -err;
sk->sk_error_report(sk);
rawsock_write_queue_purge(sk);
}
static int rawsock_release(struct socket *sock)
{
struct sock *sk = sock->sk;
pr_debug("sock=%p sk=%p\n", sock, sk);
if (!sk)
return 0;
sock_orphan(sk);
sock_put(sk);
return 0;
}
static int rawsock_connect(struct socket *sock, struct sockaddr *_addr,
int len, int flags)
{
struct sock *sk = sock->sk;
struct sockaddr_nfc *addr = (struct sockaddr_nfc *)_addr;
struct nfc_dev *dev;
int rc = 0;
pr_debug("sock=%p sk=%p flags=%d\n", sock, sk, flags);
if (!addr || len < sizeof(struct sockaddr_nfc) ||
addr->sa_family != AF_NFC)
return -EINVAL;
pr_debug("addr dev_idx=%u target_idx=%u protocol=%u\n",
addr->dev_idx, addr->target_idx, addr->nfc_protocol);
lock_sock(sk);
if (sock->state == SS_CONNECTED) {
rc = -EISCONN;
goto error;
}
dev = nfc_get_device(addr->dev_idx);
if (!dev) {
rc = -ENODEV;
goto error;
}
if (addr->target_idx > dev->target_next_idx - 1 ||
addr->target_idx < dev->target_next_idx - dev->n_targets) {
rc = -EINVAL;
goto error;
}
rc = nfc_activate_target(dev, addr->target_idx, addr->nfc_protocol);
if (rc)
goto put_dev;
nfc_rawsock(sk)->dev = dev;
nfc_rawsock(sk)->target_idx = addr->target_idx;
sock->state = SS_CONNECTED;
sk->sk_state = TCP_ESTABLISHED;
sk->sk_state_change(sk);
release_sock(sk);
return 0;
put_dev:
nfc_put_device(dev);
error:
release_sock(sk);
return rc;
}
static int rawsock_add_header(struct sk_buff *skb)
{
*skb_push(skb, NFC_HEADER_SIZE) = 0;
return 0;
}
static void rawsock_data_exchange_complete(void *context, struct sk_buff *skb,
int err)
{
struct sock *sk = (struct sock *) context;
BUG_ON(in_irq());
pr_debug("sk=%p err=%d\n", sk, err);
if (err)
goto error;
err = rawsock_add_header(skb);
if (err)
goto error_skb;
err = sock_queue_rcv_skb(sk, skb);
if (err)
goto error_skb;
spin_lock_bh(&sk->sk_write_queue.lock);
if (!skb_queue_empty(&sk->sk_write_queue))
schedule_work(&nfc_rawsock(sk)->tx_work);
else
nfc_rawsock(sk)->tx_work_scheduled = false;
spin_unlock_bh(&sk->sk_write_queue.lock);
sock_put(sk);
return;
error_skb:
kfree_skb(skb);
error:
rawsock_report_error(sk, err);
sock_put(sk);
}
static void rawsock_tx_work(struct work_struct *work)
{
struct sock *sk = to_rawsock_sk(work);
struct nfc_dev *dev = nfc_rawsock(sk)->dev;
u32 target_idx = nfc_rawsock(sk)->target_idx;
struct sk_buff *skb;
int rc;
pr_debug("sk=%p target_idx=%u\n", sk, target_idx);
if (sk->sk_shutdown & SEND_SHUTDOWN) {
rawsock_write_queue_purge(sk);
return;
}
skb = skb_dequeue(&sk->sk_write_queue);
sock_hold(sk);
rc = nfc_data_exchange(dev, target_idx, skb,
rawsock_data_exchange_complete, sk);
if (rc) {
rawsock_report_error(sk, rc);
sock_put(sk);
}
}
static int rawsock_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct nfc_dev *dev = nfc_rawsock(sk)->dev;
struct sk_buff *skb;
int rc;
pr_debug("sock=%p sk=%p len=%zu\n", sock, sk, len);
if (msg->msg_namelen)
return -EOPNOTSUPP;
if (sock->state != SS_CONNECTED)
return -ENOTCONN;
skb = nfc_alloc_send_skb(dev, sk, msg->msg_flags, len, &rc);
if (skb == NULL)
return rc;
rc = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len);
if (rc < 0) {
kfree_skb(skb);
return rc;
}
spin_lock_bh(&sk->sk_write_queue.lock);
__skb_queue_tail(&sk->sk_write_queue, skb);
if (!nfc_rawsock(sk)->tx_work_scheduled) {
schedule_work(&nfc_rawsock(sk)->tx_work);
nfc_rawsock(sk)->tx_work_scheduled = true;
}
spin_unlock_bh(&sk->sk_write_queue.lock);
return len;
}
static int rawsock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
int noblock = flags & MSG_DONTWAIT;
struct sock *sk = sock->sk;
struct sk_buff *skb;
int copied;
int rc;
pr_debug("sock=%p sk=%p len=%zu flags=%d\n", sock, sk, len, flags);
skb = skb_recv_datagram(sk, flags, noblock, &rc);
if (!skb)
return rc;
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
rc = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
skb_free_datagram(sk, skb);
return rc ? : copied;
}
static const struct proto_ops rawsock_ops = {
.family = PF_NFC,
.owner = THIS_MODULE,
.release = rawsock_release,
.bind = sock_no_bind,
.connect = rawsock_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = sock_no_getname,
.poll = datagram_poll,
.ioctl = sock_no_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = rawsock_sendmsg,
.recvmsg = rawsock_recvmsg,
.mmap = sock_no_mmap,
};
static void rawsock_destruct(struct sock *sk)
{
pr_debug("sk=%p\n", sk);
if (sk->sk_state == TCP_ESTABLISHED) {
nfc_deactivate_target(nfc_rawsock(sk)->dev,
nfc_rawsock(sk)->target_idx);
nfc_put_device(nfc_rawsock(sk)->dev);
}
skb_queue_purge(&sk->sk_receive_queue);
if (!sock_flag(sk, SOCK_DEAD)) {
pr_err("Freeing alive NFC raw socket %p\n", sk);
return;
}
}
static int rawsock_create(struct net *net, struct socket *sock,
const struct nfc_protocol *nfc_proto)
{
struct sock *sk;
pr_debug("sock=%p\n", sock);
if (sock->type != SOCK_SEQPACKET)
return -ESOCKTNOSUPPORT;
sock->ops = &rawsock_ops;
sk = sk_alloc(net, PF_NFC, GFP_ATOMIC, nfc_proto->proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
sk->sk_protocol = nfc_proto->id;
sk->sk_destruct = rawsock_destruct;
sock->state = SS_UNCONNECTED;
INIT_WORK(&nfc_rawsock(sk)->tx_work, rawsock_tx_work);
nfc_rawsock(sk)->tx_work_scheduled = false;
return 0;
}
static struct proto rawsock_proto = {
.name = "NFC_RAW",
.owner = THIS_MODULE,
.obj_size = sizeof(struct nfc_rawsock),
};
static const struct nfc_protocol rawsock_nfc_proto = {
.id = NFC_SOCKPROTO_RAW,
.proto = &rawsock_proto,
.owner = THIS_MODULE,
.create = rawsock_create
};
int __init rawsock_init(void)
{
int rc;
rc = nfc_proto_register(&rawsock_nfc_proto);
return rc;
}
void rawsock_exit(void)
{
nfc_proto_unregister(&rawsock_nfc_proto);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_24 |
crossvul-cpp_data_good_5845_13 | /*
* 32bit Socket syscall emulation. Based on arch/sparc64/kernel/sys_sparc32.c.
*
* Copyright (C) 2000 VA Linux Co
* Copyright (C) 2000 Don Dugger <n0ano@valinux.com>
* Copyright (C) 1999 Arun Sharma <arun.sharma@intel.com>
* Copyright (C) 1997,1998 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
* Copyright (C) 1997 David S. Miller (davem@caip.rutgers.edu)
* Copyright (C) 2000 Hewlett-Packard Co.
* Copyright (C) 2000 David Mosberger-Tang <davidm@hpl.hp.com>
* Copyright (C) 2000,2001 Andi Kleen, SuSE Labs
*/
#include <linux/kernel.h>
#include <linux/gfp.h>
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/file.h>
#include <linux/icmpv6.h>
#include <linux/socket.h>
#include <linux/syscalls.h>
#include <linux/filter.h>
#include <linux/compat.h>
#include <linux/security.h>
#include <linux/export.h>
#include <net/scm.h>
#include <net/sock.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <asm/uaccess.h>
#include <net/compat.h>
static inline int iov_from_user_compat_to_kern(struct iovec *kiov,
struct compat_iovec __user *uiov32,
int niov)
{
int tot_len = 0;
while (niov > 0) {
compat_uptr_t buf;
compat_size_t len;
if (get_user(len, &uiov32->iov_len) ||
get_user(buf, &uiov32->iov_base))
return -EFAULT;
if (len > INT_MAX - tot_len)
len = INT_MAX - tot_len;
tot_len += len;
kiov->iov_base = compat_ptr(buf);
kiov->iov_len = (__kernel_size_t) len;
uiov32++;
kiov++;
niov--;
}
return tot_len;
}
int get_compat_msghdr(struct msghdr *kmsg, struct compat_msghdr __user *umsg)
{
compat_uptr_t tmp1, tmp2, tmp3;
if (!access_ok(VERIFY_READ, umsg, sizeof(*umsg)) ||
__get_user(tmp1, &umsg->msg_name) ||
__get_user(kmsg->msg_namelen, &umsg->msg_namelen) ||
__get_user(tmp2, &umsg->msg_iov) ||
__get_user(kmsg->msg_iovlen, &umsg->msg_iovlen) ||
__get_user(tmp3, &umsg->msg_control) ||
__get_user(kmsg->msg_controllen, &umsg->msg_controllen) ||
__get_user(kmsg->msg_flags, &umsg->msg_flags))
return -EFAULT;
if (kmsg->msg_namelen > sizeof(struct sockaddr_storage))
return -EINVAL;
kmsg->msg_name = compat_ptr(tmp1);
kmsg->msg_iov = compat_ptr(tmp2);
kmsg->msg_control = compat_ptr(tmp3);
return 0;
}
/* I've named the args so it is easy to tell whose space the pointers are in. */
int verify_compat_iovec(struct msghdr *kern_msg, struct iovec *kern_iov,
struct sockaddr_storage *kern_address, int mode)
{
int tot_len;
if (kern_msg->msg_namelen) {
if (mode == VERIFY_READ) {
int err = move_addr_to_kernel(kern_msg->msg_name,
kern_msg->msg_namelen,
kern_address);
if (err < 0)
return err;
}
if (kern_msg->msg_name)
kern_msg->msg_name = kern_address;
} else
kern_msg->msg_name = NULL;
tot_len = iov_from_user_compat_to_kern(kern_iov,
(struct compat_iovec __user *)kern_msg->msg_iov,
kern_msg->msg_iovlen);
if (tot_len >= 0)
kern_msg->msg_iov = kern_iov;
return tot_len;
}
/* Bleech... */
#define CMSG_COMPAT_ALIGN(len) ALIGN((len), sizeof(s32))
#define CMSG_COMPAT_DATA(cmsg) \
((void __user *)((char __user *)(cmsg) + CMSG_COMPAT_ALIGN(sizeof(struct compat_cmsghdr))))
#define CMSG_COMPAT_SPACE(len) \
(CMSG_COMPAT_ALIGN(sizeof(struct compat_cmsghdr)) + CMSG_COMPAT_ALIGN(len))
#define CMSG_COMPAT_LEN(len) \
(CMSG_COMPAT_ALIGN(sizeof(struct compat_cmsghdr)) + (len))
#define CMSG_COMPAT_FIRSTHDR(msg) \
(((msg)->msg_controllen) >= sizeof(struct compat_cmsghdr) ? \
(struct compat_cmsghdr __user *)((msg)->msg_control) : \
(struct compat_cmsghdr __user *)NULL)
#define CMSG_COMPAT_OK(ucmlen, ucmsg, mhdr) \
((ucmlen) >= sizeof(struct compat_cmsghdr) && \
(ucmlen) <= (unsigned long) \
((mhdr)->msg_controllen - \
((char *)(ucmsg) - (char *)(mhdr)->msg_control)))
static inline struct compat_cmsghdr __user *cmsg_compat_nxthdr(struct msghdr *msg,
struct compat_cmsghdr __user *cmsg, int cmsg_len)
{
char __user *ptr = (char __user *)cmsg + CMSG_COMPAT_ALIGN(cmsg_len);
if ((unsigned long)(ptr + 1 - (char __user *)msg->msg_control) >
msg->msg_controllen)
return NULL;
return (struct compat_cmsghdr __user *)ptr;
}
/* There is a lot of hair here because the alignment rules (and
* thus placement) of cmsg headers and length are different for
* 32-bit apps. -DaveM
*/
int cmsghdr_from_user_compat_to_kern(struct msghdr *kmsg, struct sock *sk,
unsigned char *stackbuf, int stackbuf_size)
{
struct compat_cmsghdr __user *ucmsg;
struct cmsghdr *kcmsg, *kcmsg_base;
compat_size_t ucmlen;
__kernel_size_t kcmlen, tmp;
int err = -EFAULT;
kcmlen = 0;
kcmsg_base = kcmsg = (struct cmsghdr *)stackbuf;
ucmsg = CMSG_COMPAT_FIRSTHDR(kmsg);
while (ucmsg != NULL) {
if (get_user(ucmlen, &ucmsg->cmsg_len))
return -EFAULT;
/* Catch bogons. */
if (!CMSG_COMPAT_OK(ucmlen, ucmsg, kmsg))
return -EINVAL;
tmp = ((ucmlen - CMSG_COMPAT_ALIGN(sizeof(*ucmsg))) +
CMSG_ALIGN(sizeof(struct cmsghdr)));
tmp = CMSG_ALIGN(tmp);
kcmlen += tmp;
ucmsg = cmsg_compat_nxthdr(kmsg, ucmsg, ucmlen);
}
if (kcmlen == 0)
return -EINVAL;
/* The kcmlen holds the 64-bit version of the control length.
* It may not be modified as we do not stick it into the kmsg
* until we have successfully copied over all of the data
* from the user.
*/
if (kcmlen > stackbuf_size)
kcmsg_base = kcmsg = sock_kmalloc(sk, kcmlen, GFP_KERNEL);
if (kcmsg == NULL)
return -ENOBUFS;
/* Now copy them over neatly. */
memset(kcmsg, 0, kcmlen);
ucmsg = CMSG_COMPAT_FIRSTHDR(kmsg);
while (ucmsg != NULL) {
if (__get_user(ucmlen, &ucmsg->cmsg_len))
goto Efault;
if (!CMSG_COMPAT_OK(ucmlen, ucmsg, kmsg))
goto Einval;
tmp = ((ucmlen - CMSG_COMPAT_ALIGN(sizeof(*ucmsg))) +
CMSG_ALIGN(sizeof(struct cmsghdr)));
if ((char *)kcmsg_base + kcmlen - (char *)kcmsg < CMSG_ALIGN(tmp))
goto Einval;
kcmsg->cmsg_len = tmp;
tmp = CMSG_ALIGN(tmp);
if (__get_user(kcmsg->cmsg_level, &ucmsg->cmsg_level) ||
__get_user(kcmsg->cmsg_type, &ucmsg->cmsg_type) ||
copy_from_user(CMSG_DATA(kcmsg),
CMSG_COMPAT_DATA(ucmsg),
(ucmlen - CMSG_COMPAT_ALIGN(sizeof(*ucmsg)))))
goto Efault;
/* Advance. */
kcmsg = (struct cmsghdr *)((char *)kcmsg + tmp);
ucmsg = cmsg_compat_nxthdr(kmsg, ucmsg, ucmlen);
}
/* Ok, looks like we made it. Hook it up and return success. */
kmsg->msg_control = kcmsg_base;
kmsg->msg_controllen = kcmlen;
return 0;
Einval:
err = -EINVAL;
Efault:
if (kcmsg_base != (struct cmsghdr *)stackbuf)
sock_kfree_s(sk, kcmsg_base, kcmlen);
return err;
}
int put_cmsg_compat(struct msghdr *kmsg, int level, int type, int len, void *data)
{
struct compat_cmsghdr __user *cm = (struct compat_cmsghdr __user *) kmsg->msg_control;
struct compat_cmsghdr cmhdr;
struct compat_timeval ctv;
struct compat_timespec cts[3];
int cmlen;
if (cm == NULL || kmsg->msg_controllen < sizeof(*cm)) {
kmsg->msg_flags |= MSG_CTRUNC;
return 0; /* XXX: return error? check spec. */
}
if (!COMPAT_USE_64BIT_TIME) {
if (level == SOL_SOCKET && type == SCM_TIMESTAMP) {
struct timeval *tv = (struct timeval *)data;
ctv.tv_sec = tv->tv_sec;
ctv.tv_usec = tv->tv_usec;
data = &ctv;
len = sizeof(ctv);
}
if (level == SOL_SOCKET &&
(type == SCM_TIMESTAMPNS || type == SCM_TIMESTAMPING)) {
int count = type == SCM_TIMESTAMPNS ? 1 : 3;
int i;
struct timespec *ts = (struct timespec *)data;
for (i = 0; i < count; i++) {
cts[i].tv_sec = ts[i].tv_sec;
cts[i].tv_nsec = ts[i].tv_nsec;
}
data = &cts;
len = sizeof(cts[0]) * count;
}
}
cmlen = CMSG_COMPAT_LEN(len);
if (kmsg->msg_controllen < cmlen) {
kmsg->msg_flags |= MSG_CTRUNC;
cmlen = kmsg->msg_controllen;
}
cmhdr.cmsg_level = level;
cmhdr.cmsg_type = type;
cmhdr.cmsg_len = cmlen;
if (copy_to_user(cm, &cmhdr, sizeof cmhdr))
return -EFAULT;
if (copy_to_user(CMSG_COMPAT_DATA(cm), data, cmlen - sizeof(struct compat_cmsghdr)))
return -EFAULT;
cmlen = CMSG_COMPAT_SPACE(len);
if (kmsg->msg_controllen < cmlen)
cmlen = kmsg->msg_controllen;
kmsg->msg_control += cmlen;
kmsg->msg_controllen -= cmlen;
return 0;
}
void scm_detach_fds_compat(struct msghdr *kmsg, struct scm_cookie *scm)
{
struct compat_cmsghdr __user *cm = (struct compat_cmsghdr __user *) kmsg->msg_control;
int fdmax = (kmsg->msg_controllen - sizeof(struct compat_cmsghdr)) / sizeof(int);
int fdnum = scm->fp->count;
struct file **fp = scm->fp->fp;
int __user *cmfptr;
int err = 0, i;
if (fdnum < fdmax)
fdmax = fdnum;
for (i = 0, cmfptr = (int __user *) CMSG_COMPAT_DATA(cm); i < fdmax; i++, cmfptr++) {
int new_fd;
err = security_file_receive(fp[i]);
if (err)
break;
err = get_unused_fd_flags(MSG_CMSG_CLOEXEC & kmsg->msg_flags
? O_CLOEXEC : 0);
if (err < 0)
break;
new_fd = err;
err = put_user(new_fd, cmfptr);
if (err) {
put_unused_fd(new_fd);
break;
}
/* Bump the usage count and install the file. */
fd_install(new_fd, get_file(fp[i]));
}
if (i > 0) {
int cmlen = CMSG_COMPAT_LEN(i * sizeof(int));
err = put_user(SOL_SOCKET, &cm->cmsg_level);
if (!err)
err = put_user(SCM_RIGHTS, &cm->cmsg_type);
if (!err)
err = put_user(cmlen, &cm->cmsg_len);
if (!err) {
cmlen = CMSG_COMPAT_SPACE(i * sizeof(int));
kmsg->msg_control += cmlen;
kmsg->msg_controllen -= cmlen;
}
}
if (i < fdnum)
kmsg->msg_flags |= MSG_CTRUNC;
/*
* All of the files that fit in the message have had their
* usage counts incremented, so we just free the list.
*/
__scm_destroy(scm);
}
static int do_set_attach_filter(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct compat_sock_fprog __user *fprog32 = (struct compat_sock_fprog __user *)optval;
struct sock_fprog __user *kfprog = compat_alloc_user_space(sizeof(struct sock_fprog));
compat_uptr_t ptr;
u16 len;
if (!access_ok(VERIFY_READ, fprog32, sizeof(*fprog32)) ||
!access_ok(VERIFY_WRITE, kfprog, sizeof(struct sock_fprog)) ||
__get_user(len, &fprog32->len) ||
__get_user(ptr, &fprog32->filter) ||
__put_user(len, &kfprog->len) ||
__put_user(compat_ptr(ptr), &kfprog->filter))
return -EFAULT;
return sock_setsockopt(sock, level, optname, (char __user *)kfprog,
sizeof(struct sock_fprog));
}
static int do_set_sock_timeout(struct socket *sock, int level,
int optname, char __user *optval, unsigned int optlen)
{
struct compat_timeval __user *up = (struct compat_timeval __user *)optval;
struct timeval ktime;
mm_segment_t old_fs;
int err;
if (optlen < sizeof(*up))
return -EINVAL;
if (!access_ok(VERIFY_READ, up, sizeof(*up)) ||
__get_user(ktime.tv_sec, &up->tv_sec) ||
__get_user(ktime.tv_usec, &up->tv_usec))
return -EFAULT;
old_fs = get_fs();
set_fs(KERNEL_DS);
err = sock_setsockopt(sock, level, optname, (char *)&ktime, sizeof(ktime));
set_fs(old_fs);
return err;
}
static int compat_sock_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
if (optname == SO_ATTACH_FILTER)
return do_set_attach_filter(sock, level, optname,
optval, optlen);
if (optname == SO_RCVTIMEO || optname == SO_SNDTIMEO)
return do_set_sock_timeout(sock, level, optname, optval, optlen);
return sock_setsockopt(sock, level, optname, optval, optlen);
}
asmlinkage long compat_sys_setsockopt(int fd, int level, int optname,
char __user *optval, unsigned int optlen)
{
int err;
struct socket *sock = sockfd_lookup(fd, &err);
if (sock) {
err = security_socket_setsockopt(sock, level, optname);
if (err) {
sockfd_put(sock);
return err;
}
if (level == SOL_SOCKET)
err = compat_sock_setsockopt(sock, level,
optname, optval, optlen);
else if (sock->ops->compat_setsockopt)
err = sock->ops->compat_setsockopt(sock, level,
optname, optval, optlen);
else
err = sock->ops->setsockopt(sock, level,
optname, optval, optlen);
sockfd_put(sock);
}
return err;
}
static int do_get_sock_timeout(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct compat_timeval __user *up;
struct timeval ktime;
mm_segment_t old_fs;
int len, err;
up = (struct compat_timeval __user *) optval;
if (get_user(len, optlen))
return -EFAULT;
if (len < sizeof(*up))
return -EINVAL;
len = sizeof(ktime);
old_fs = get_fs();
set_fs(KERNEL_DS);
err = sock_getsockopt(sock, level, optname, (char *) &ktime, &len);
set_fs(old_fs);
if (!err) {
if (put_user(sizeof(*up), optlen) ||
!access_ok(VERIFY_WRITE, up, sizeof(*up)) ||
__put_user(ktime.tv_sec, &up->tv_sec) ||
__put_user(ktime.tv_usec, &up->tv_usec))
err = -EFAULT;
}
return err;
}
static int compat_sock_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
if (optname == SO_RCVTIMEO || optname == SO_SNDTIMEO)
return do_get_sock_timeout(sock, level, optname, optval, optlen);
return sock_getsockopt(sock, level, optname, optval, optlen);
}
int compat_sock_get_timestamp(struct sock *sk, struct timeval __user *userstamp)
{
struct compat_timeval __user *ctv;
int err;
struct timeval tv;
if (COMPAT_USE_64BIT_TIME)
return sock_get_timestamp(sk, userstamp);
ctv = (struct compat_timeval __user *) userstamp;
err = -ENOENT;
if (!sock_flag(sk, SOCK_TIMESTAMP))
sock_enable_timestamp(sk, SOCK_TIMESTAMP);
tv = ktime_to_timeval(sk->sk_stamp);
if (tv.tv_sec == -1)
return err;
if (tv.tv_sec == 0) {
sk->sk_stamp = ktime_get_real();
tv = ktime_to_timeval(sk->sk_stamp);
}
err = 0;
if (put_user(tv.tv_sec, &ctv->tv_sec) ||
put_user(tv.tv_usec, &ctv->tv_usec))
err = -EFAULT;
return err;
}
EXPORT_SYMBOL(compat_sock_get_timestamp);
int compat_sock_get_timestampns(struct sock *sk, struct timespec __user *userstamp)
{
struct compat_timespec __user *ctv;
int err;
struct timespec ts;
if (COMPAT_USE_64BIT_TIME)
return sock_get_timestampns (sk, userstamp);
ctv = (struct compat_timespec __user *) userstamp;
err = -ENOENT;
if (!sock_flag(sk, SOCK_TIMESTAMP))
sock_enable_timestamp(sk, SOCK_TIMESTAMP);
ts = ktime_to_timespec(sk->sk_stamp);
if (ts.tv_sec == -1)
return err;
if (ts.tv_sec == 0) {
sk->sk_stamp = ktime_get_real();
ts = ktime_to_timespec(sk->sk_stamp);
}
err = 0;
if (put_user(ts.tv_sec, &ctv->tv_sec) ||
put_user(ts.tv_nsec, &ctv->tv_nsec))
err = -EFAULT;
return err;
}
EXPORT_SYMBOL(compat_sock_get_timestampns);
asmlinkage long compat_sys_getsockopt(int fd, int level, int optname,
char __user *optval, int __user *optlen)
{
int err;
struct socket *sock = sockfd_lookup(fd, &err);
if (sock) {
err = security_socket_getsockopt(sock, level, optname);
if (err) {
sockfd_put(sock);
return err;
}
if (level == SOL_SOCKET)
err = compat_sock_getsockopt(sock, level,
optname, optval, optlen);
else if (sock->ops->compat_getsockopt)
err = sock->ops->compat_getsockopt(sock, level,
optname, optval, optlen);
else
err = sock->ops->getsockopt(sock, level,
optname, optval, optlen);
sockfd_put(sock);
}
return err;
}
struct compat_group_req {
__u32 gr_interface;
struct __kernel_sockaddr_storage gr_group
__attribute__ ((aligned(4)));
} __packed;
struct compat_group_source_req {
__u32 gsr_interface;
struct __kernel_sockaddr_storage gsr_group
__attribute__ ((aligned(4)));
struct __kernel_sockaddr_storage gsr_source
__attribute__ ((aligned(4)));
} __packed;
struct compat_group_filter {
__u32 gf_interface;
struct __kernel_sockaddr_storage gf_group
__attribute__ ((aligned(4)));
__u32 gf_fmode;
__u32 gf_numsrc;
struct __kernel_sockaddr_storage gf_slist[1]
__attribute__ ((aligned(4)));
} __packed;
#define __COMPAT_GF0_SIZE (sizeof(struct compat_group_filter) - \
sizeof(struct __kernel_sockaddr_storage))
int compat_mc_setsockopt(struct sock *sock, int level, int optname,
char __user *optval, unsigned int optlen,
int (*setsockopt)(struct sock *, int, int, char __user *, unsigned int))
{
char __user *koptval = optval;
int koptlen = optlen;
switch (optname) {
case MCAST_JOIN_GROUP:
case MCAST_LEAVE_GROUP:
{
struct compat_group_req __user *gr32 = (void *)optval;
struct group_req __user *kgr =
compat_alloc_user_space(sizeof(struct group_req));
u32 interface;
if (!access_ok(VERIFY_READ, gr32, sizeof(*gr32)) ||
!access_ok(VERIFY_WRITE, kgr, sizeof(struct group_req)) ||
__get_user(interface, &gr32->gr_interface) ||
__put_user(interface, &kgr->gr_interface) ||
copy_in_user(&kgr->gr_group, &gr32->gr_group,
sizeof(kgr->gr_group)))
return -EFAULT;
koptval = (char __user *)kgr;
koptlen = sizeof(struct group_req);
break;
}
case MCAST_JOIN_SOURCE_GROUP:
case MCAST_LEAVE_SOURCE_GROUP:
case MCAST_BLOCK_SOURCE:
case MCAST_UNBLOCK_SOURCE:
{
struct compat_group_source_req __user *gsr32 = (void *)optval;
struct group_source_req __user *kgsr = compat_alloc_user_space(
sizeof(struct group_source_req));
u32 interface;
if (!access_ok(VERIFY_READ, gsr32, sizeof(*gsr32)) ||
!access_ok(VERIFY_WRITE, kgsr,
sizeof(struct group_source_req)) ||
__get_user(interface, &gsr32->gsr_interface) ||
__put_user(interface, &kgsr->gsr_interface) ||
copy_in_user(&kgsr->gsr_group, &gsr32->gsr_group,
sizeof(kgsr->gsr_group)) ||
copy_in_user(&kgsr->gsr_source, &gsr32->gsr_source,
sizeof(kgsr->gsr_source)))
return -EFAULT;
koptval = (char __user *)kgsr;
koptlen = sizeof(struct group_source_req);
break;
}
case MCAST_MSFILTER:
{
struct compat_group_filter __user *gf32 = (void *)optval;
struct group_filter __user *kgf;
u32 interface, fmode, numsrc;
if (!access_ok(VERIFY_READ, gf32, __COMPAT_GF0_SIZE) ||
__get_user(interface, &gf32->gf_interface) ||
__get_user(fmode, &gf32->gf_fmode) ||
__get_user(numsrc, &gf32->gf_numsrc))
return -EFAULT;
koptlen = optlen + sizeof(struct group_filter) -
sizeof(struct compat_group_filter);
if (koptlen < GROUP_FILTER_SIZE(numsrc))
return -EINVAL;
kgf = compat_alloc_user_space(koptlen);
if (!access_ok(VERIFY_WRITE, kgf, koptlen) ||
__put_user(interface, &kgf->gf_interface) ||
__put_user(fmode, &kgf->gf_fmode) ||
__put_user(numsrc, &kgf->gf_numsrc) ||
copy_in_user(&kgf->gf_group, &gf32->gf_group,
sizeof(kgf->gf_group)) ||
(numsrc && copy_in_user(kgf->gf_slist, gf32->gf_slist,
numsrc * sizeof(kgf->gf_slist[0]))))
return -EFAULT;
koptval = (char __user *)kgf;
break;
}
default:
break;
}
return setsockopt(sock, level, optname, koptval, koptlen);
}
EXPORT_SYMBOL(compat_mc_setsockopt);
int compat_mc_getsockopt(struct sock *sock, int level, int optname,
char __user *optval, int __user *optlen,
int (*getsockopt)(struct sock *, int, int, char __user *, int __user *))
{
struct compat_group_filter __user *gf32 = (void *)optval;
struct group_filter __user *kgf;
int __user *koptlen;
u32 interface, fmode, numsrc;
int klen, ulen, err;
if (optname != MCAST_MSFILTER)
return getsockopt(sock, level, optname, optval, optlen);
koptlen = compat_alloc_user_space(sizeof(*koptlen));
if (!access_ok(VERIFY_READ, optlen, sizeof(*optlen)) ||
__get_user(ulen, optlen))
return -EFAULT;
/* adjust len for pad */
klen = ulen + sizeof(*kgf) - sizeof(*gf32);
if (klen < GROUP_FILTER_SIZE(0))
return -EINVAL;
if (!access_ok(VERIFY_WRITE, koptlen, sizeof(*koptlen)) ||
__put_user(klen, koptlen))
return -EFAULT;
/* have to allow space for previous compat_alloc_user_space, too */
kgf = compat_alloc_user_space(klen+sizeof(*optlen));
if (!access_ok(VERIFY_READ, gf32, __COMPAT_GF0_SIZE) ||
__get_user(interface, &gf32->gf_interface) ||
__get_user(fmode, &gf32->gf_fmode) ||
__get_user(numsrc, &gf32->gf_numsrc) ||
__put_user(interface, &kgf->gf_interface) ||
__put_user(fmode, &kgf->gf_fmode) ||
__put_user(numsrc, &kgf->gf_numsrc) ||
copy_in_user(&kgf->gf_group, &gf32->gf_group, sizeof(kgf->gf_group)))
return -EFAULT;
err = getsockopt(sock, level, optname, (char __user *)kgf, koptlen);
if (err)
return err;
if (!access_ok(VERIFY_READ, koptlen, sizeof(*koptlen)) ||
__get_user(klen, koptlen))
return -EFAULT;
ulen = klen - (sizeof(*kgf)-sizeof(*gf32));
if (!access_ok(VERIFY_WRITE, optlen, sizeof(*optlen)) ||
__put_user(ulen, optlen))
return -EFAULT;
if (!access_ok(VERIFY_READ, kgf, klen) ||
!access_ok(VERIFY_WRITE, gf32, ulen) ||
__get_user(interface, &kgf->gf_interface) ||
__get_user(fmode, &kgf->gf_fmode) ||
__get_user(numsrc, &kgf->gf_numsrc) ||
__put_user(interface, &gf32->gf_interface) ||
__put_user(fmode, &gf32->gf_fmode) ||
__put_user(numsrc, &gf32->gf_numsrc))
return -EFAULT;
if (numsrc) {
int copylen;
klen -= GROUP_FILTER_SIZE(0);
copylen = numsrc * sizeof(gf32->gf_slist[0]);
if (copylen > klen)
copylen = klen;
if (copy_in_user(gf32->gf_slist, kgf->gf_slist, copylen))
return -EFAULT;
}
return err;
}
EXPORT_SYMBOL(compat_mc_getsockopt);
/* Argument list sizes for compat_sys_socketcall */
#define AL(x) ((x) * sizeof(u32))
static unsigned char nas[21] = {
AL(0), AL(3), AL(3), AL(3), AL(2), AL(3),
AL(3), AL(3), AL(4), AL(4), AL(4), AL(6),
AL(6), AL(2), AL(5), AL(5), AL(3), AL(3),
AL(4), AL(5), AL(4)
};
#undef AL
asmlinkage long compat_sys_sendmsg(int fd, struct compat_msghdr __user *msg, unsigned int flags)
{
if (flags & MSG_CMSG_COMPAT)
return -EINVAL;
return __sys_sendmsg(fd, (struct msghdr __user *)msg, flags | MSG_CMSG_COMPAT);
}
asmlinkage long compat_sys_sendmmsg(int fd, struct compat_mmsghdr __user *mmsg,
unsigned int vlen, unsigned int flags)
{
if (flags & MSG_CMSG_COMPAT)
return -EINVAL;
return __sys_sendmmsg(fd, (struct mmsghdr __user *)mmsg, vlen,
flags | MSG_CMSG_COMPAT);
}
asmlinkage long compat_sys_recvmsg(int fd, struct compat_msghdr __user *msg, unsigned int flags)
{
if (flags & MSG_CMSG_COMPAT)
return -EINVAL;
return __sys_recvmsg(fd, (struct msghdr __user *)msg, flags | MSG_CMSG_COMPAT);
}
asmlinkage long compat_sys_recv(int fd, void __user *buf, size_t len, unsigned int flags)
{
return sys_recv(fd, buf, len, flags | MSG_CMSG_COMPAT);
}
asmlinkage long compat_sys_recvfrom(int fd, void __user *buf, size_t len,
unsigned int flags, struct sockaddr __user *addr,
int __user *addrlen)
{
return sys_recvfrom(fd, buf, len, flags | MSG_CMSG_COMPAT, addr, addrlen);
}
asmlinkage long compat_sys_recvmmsg(int fd, struct compat_mmsghdr __user *mmsg,
unsigned int vlen, unsigned int flags,
struct compat_timespec __user *timeout)
{
int datagrams;
struct timespec ktspec;
if (flags & MSG_CMSG_COMPAT)
return -EINVAL;
if (COMPAT_USE_64BIT_TIME)
return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen,
flags | MSG_CMSG_COMPAT,
(struct timespec *) timeout);
if (timeout == NULL)
return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen,
flags | MSG_CMSG_COMPAT, NULL);
if (get_compat_timespec(&ktspec, timeout))
return -EFAULT;
datagrams = __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen,
flags | MSG_CMSG_COMPAT, &ktspec);
if (datagrams > 0 && put_compat_timespec(&ktspec, timeout))
datagrams = -EFAULT;
return datagrams;
}
asmlinkage long compat_sys_socketcall(int call, u32 __user *args)
{
int ret;
u32 a[6];
u32 a0, a1;
if (call < SYS_SOCKET || call > SYS_SENDMMSG)
return -EINVAL;
if (copy_from_user(a, args, nas[call]))
return -EFAULT;
a0 = a[0];
a1 = a[1];
switch (call) {
case SYS_SOCKET:
ret = sys_socket(a0, a1, a[2]);
break;
case SYS_BIND:
ret = sys_bind(a0, compat_ptr(a1), a[2]);
break;
case SYS_CONNECT:
ret = sys_connect(a0, compat_ptr(a1), a[2]);
break;
case SYS_LISTEN:
ret = sys_listen(a0, a1);
break;
case SYS_ACCEPT:
ret = sys_accept4(a0, compat_ptr(a1), compat_ptr(a[2]), 0);
break;
case SYS_GETSOCKNAME:
ret = sys_getsockname(a0, compat_ptr(a1), compat_ptr(a[2]));
break;
case SYS_GETPEERNAME:
ret = sys_getpeername(a0, compat_ptr(a1), compat_ptr(a[2]));
break;
case SYS_SOCKETPAIR:
ret = sys_socketpair(a0, a1, a[2], compat_ptr(a[3]));
break;
case SYS_SEND:
ret = sys_send(a0, compat_ptr(a1), a[2], a[3]);
break;
case SYS_SENDTO:
ret = sys_sendto(a0, compat_ptr(a1), a[2], a[3], compat_ptr(a[4]), a[5]);
break;
case SYS_RECV:
ret = compat_sys_recv(a0, compat_ptr(a1), a[2], a[3]);
break;
case SYS_RECVFROM:
ret = compat_sys_recvfrom(a0, compat_ptr(a1), a[2], a[3],
compat_ptr(a[4]), compat_ptr(a[5]));
break;
case SYS_SHUTDOWN:
ret = sys_shutdown(a0, a1);
break;
case SYS_SETSOCKOPT:
ret = compat_sys_setsockopt(a0, a1, a[2],
compat_ptr(a[3]), a[4]);
break;
case SYS_GETSOCKOPT:
ret = compat_sys_getsockopt(a0, a1, a[2],
compat_ptr(a[3]), compat_ptr(a[4]));
break;
case SYS_SENDMSG:
ret = compat_sys_sendmsg(a0, compat_ptr(a1), a[2]);
break;
case SYS_SENDMMSG:
ret = compat_sys_sendmmsg(a0, compat_ptr(a1), a[2], a[3]);
break;
case SYS_RECVMSG:
ret = compat_sys_recvmsg(a0, compat_ptr(a1), a[2]);
break;
case SYS_RECVMMSG:
ret = compat_sys_recvmmsg(a0, compat_ptr(a1), a[2], a[3],
compat_ptr(a[4]));
break;
case SYS_ACCEPT4:
ret = sys_accept4(a0, compat_ptr(a1), compat_ptr(a[2]), a[3]);
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_13 |
crossvul-cpp_data_bad_3192_0 | /*
* bplist.c
* Binary plist implementation
*
* Copyright (c) 2011-2017 Nikias Bassen, All Rights Reserved.
* Copyright (c) 2008-2010 Jonathan Beck, All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <inttypes.h>
#include <plist/plist.h>
#include "plist.h"
#include "hashtable.h"
#include "bytearray.h"
#include "ptrarray.h"
#include <node.h>
#include <node_iterator.h>
/* Magic marker and size. */
#define BPLIST_MAGIC ((uint8_t*)"bplist")
#define BPLIST_MAGIC_SIZE 6
#define BPLIST_VERSION ((uint8_t*)"00")
#define BPLIST_VERSION_SIZE 2
typedef struct __attribute__((packed)) {
uint8_t unused[6];
uint8_t offset_size;
uint8_t ref_size;
uint64_t num_objects;
uint64_t root_object_index;
uint64_t offset_table_offset;
} bplist_trailer_t;
enum
{
BPLIST_NULL = 0x00,
BPLIST_FALSE = 0x08,
BPLIST_TRUE = 0x09,
BPLIST_FILL = 0x0F, /* will be used for length grabbing */
BPLIST_UINT = 0x10,
BPLIST_REAL = 0x20,
BPLIST_DATE = 0x30,
BPLIST_DATA = 0x40,
BPLIST_STRING = 0x50,
BPLIST_UNICODE = 0x60,
BPLIST_UNK_0x70 = 0x70,
BPLIST_UID = 0x80,
BPLIST_ARRAY = 0xA0,
BPLIST_SET = 0xC0,
BPLIST_DICT = 0xD0,
BPLIST_MASK = 0xF0
};
union plist_uint_ptr
{
const void *src;
uint8_t *u8ptr;
uint16_t *u16ptr;
uint32_t *u32ptr;
uint64_t *u64ptr;
};
#define get_unaligned(ptr) \
({ \
struct __attribute__((packed)) { \
typeof(*(ptr)) __v; \
} *__p = (void *) (ptr); \
__p->__v; \
})
#ifndef bswap16
#define bswap16(x) ((((x) & 0xFF00) >> 8) | (((x) & 0x00FF) << 8))
#endif
#ifndef bswap32
#define bswap32(x) ((((x) & 0xFF000000) >> 24) \
| (((x) & 0x00FF0000) >> 8) \
| (((x) & 0x0000FF00) << 8) \
| (((x) & 0x000000FF) << 24))
#endif
#ifndef bswap64
#define bswap64(x) ((((x) & 0xFF00000000000000ull) >> 56) \
| (((x) & 0x00FF000000000000ull) >> 40) \
| (((x) & 0x0000FF0000000000ull) >> 24) \
| (((x) & 0x000000FF00000000ull) >> 8) \
| (((x) & 0x00000000FF000000ull) << 8) \
| (((x) & 0x0000000000FF0000ull) << 24) \
| (((x) & 0x000000000000FF00ull) << 40) \
| (((x) & 0x00000000000000FFull) << 56))
#endif
#ifndef be16toh
#ifdef __BIG_ENDIAN__
#define be16toh(x) (x)
#else
#define be16toh(x) bswap16(x)
#endif
#endif
#ifndef be32toh
#ifdef __BIG_ENDIAN__
#define be32toh(x) (x)
#else
#define be32toh(x) bswap32(x)
#endif
#endif
#ifndef be64toh
#ifdef __BIG_ENDIAN__
#define be64toh(x) (x)
#else
#define be64toh(x) bswap64(x)
#endif
#endif
#ifdef __BIG_ENDIAN__
#define beNtoh(x,n) (x >> ((8-n) << 3))
#else
#define beNtoh(x,n) be64toh(x << ((8-n) << 3))
#endif
#define UINT_TO_HOST(x, n) \
({ \
union plist_uint_ptr __up; \
__up.src = (n > 8) ? x + (n - 8) : x; \
(n >= 8 ? be64toh( get_unaligned(__up.u64ptr) ) : \
(n == 4 ? be32toh( get_unaligned(__up.u32ptr) ) : \
(n == 2 ? be16toh( get_unaligned(__up.u16ptr) ) : \
(n == 1 ? *__up.u8ptr : \
beNtoh( get_unaligned(__up.u64ptr), n) \
)))); \
})
#define get_needed_bytes(x) \
( ((uint64_t)x) < (1ULL << 8) ? 1 : \
( ((uint64_t)x) < (1ULL << 16) ? 2 : \
( ((uint64_t)x) < (1ULL << 24) ? 3 : \
( ((uint64_t)x) < (1ULL << 32) ? 4 : 8))))
#define get_real_bytes(x) (x == (float) x ? sizeof(float) : sizeof(double))
#if (defined(__LITTLE_ENDIAN__) \
&& !defined(__FLOAT_WORD_ORDER__)) \
|| (defined(__FLOAT_WORD_ORDER__) \
&& __FLOAT_WORD_ORDER__ == __ORDER_LITTLE_ENDIAN__)
#define float_bswap64(x) bswap64(x)
#define float_bswap32(x) bswap32(x)
#else
#define float_bswap64(x) (x)
#define float_bswap32(x) (x)
#endif
#define NODE_IS_ROOT(x) (((node_t*)x)->isRoot)
struct bplist_data {
const char* data;
uint64_t size;
uint64_t num_objects;
uint8_t ref_size;
uint8_t offset_size;
const char* offset_table;
uint32_t level;
plist_t used_indexes;
};
#ifdef DEBUG
static int plist_bin_debug = 0;
#define PLIST_BIN_ERR(...) if (plist_bin_debug) { fprintf(stderr, "libplist[binparser] ERROR: " __VA_ARGS__); }
#else
#define PLIST_BIN_ERR(...)
#endif
void plist_bin_init(void)
{
/* init binary plist stuff */
#ifdef DEBUG
char *env_debug = getenv("PLIST_BIN_DEBUG");
if (env_debug && !strcmp(env_debug, "1")) {
plist_bin_debug = 1;
}
#endif
}
void plist_bin_deinit(void)
{
/* deinit binary plist stuff */
}
static plist_t parse_bin_node_at_index(struct bplist_data *bplist, uint32_t node_index);
static plist_t parse_uint_node(const char **bnode, uint8_t size)
{
plist_data_t data = plist_new_plist_data();
size = 1 << size; // make length less misleading
switch (size)
{
case sizeof(uint8_t):
case sizeof(uint16_t):
case sizeof(uint32_t):
case sizeof(uint64_t):
data->length = sizeof(uint64_t);
break;
case 16:
data->length = size;
break;
default:
free(data);
PLIST_BIN_ERR("%s: Invalid byte size for integer node\n", __func__);
return NULL;
};
data->intval = UINT_TO_HOST(*bnode, size);
(*bnode) += size;
data->type = PLIST_UINT;
return node_create(NULL, data);
}
static plist_t parse_real_node(const char **bnode, uint8_t size)
{
plist_data_t data = plist_new_plist_data();
uint8_t buf[8];
size = 1 << size; // make length less misleading
switch (size)
{
case sizeof(uint32_t):
*(uint32_t*)buf = float_bswap32(*(uint32_t*)*bnode);
data->realval = *(float *) buf;
break;
case sizeof(uint64_t):
*(uint64_t*)buf = float_bswap64(*(uint64_t*)*bnode);
data->realval = *(double *) buf;
break;
default:
free(data);
PLIST_BIN_ERR("%s: Invalid byte size for real node\n", __func__);
return NULL;
}
data->type = PLIST_REAL;
data->length = sizeof(double);
return node_create(NULL, data);
}
static plist_t parse_date_node(const char **bnode, uint8_t size)
{
plist_t node = parse_real_node(bnode, size);
plist_data_t data = plist_get_data(node);
data->type = PLIST_DATE;
return node;
}
static plist_t parse_string_node(const char **bnode, uint64_t size)
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_STRING;
data->strval = (char *) malloc(sizeof(char) * (size + 1));
if (!data->strval) {
plist_free_data(data);
PLIST_BIN_ERR("%s: Could not allocate %" PRIu64 " bytes\n", __func__, sizeof(char) * (size + 1));
return NULL;
}
memcpy(data->strval, *bnode, size);
data->strval[size] = '\0';
data->length = strlen(data->strval);
return node_create(NULL, data);
}
static char *plist_utf16_to_utf8(uint16_t *unistr, long len, long *items_read, long *items_written)
{
if (!unistr || (len <= 0)) return NULL;
char *outbuf;
int p = 0;
long i = 0;
uint16_t wc;
uint32_t w;
int read_lead_surrogate = 0;
outbuf = (char*)malloc(4*(len+1));
if (!outbuf) {
PLIST_BIN_ERR("%s: Could not allocate %" PRIu64 " bytes\n", __func__, (uint64_t)(4*(len+1)));
return NULL;
}
while (i < len) {
wc = unistr[i++];
if (wc >= 0xD800 && wc <= 0xDBFF) {
if (!read_lead_surrogate) {
read_lead_surrogate = 1;
w = 0x010000 + ((wc & 0x3FF) << 10);
} else {
// This is invalid, the next 16 bit char should be a trail surrogate.
// Handling error by skipping.
read_lead_surrogate = 0;
}
} else if (wc >= 0xDC00 && wc <= 0xDFFF) {
if (read_lead_surrogate) {
read_lead_surrogate = 0;
w = w | (wc & 0x3FF);
outbuf[p++] = (char)(0xF0 + ((w >> 18) & 0x7));
outbuf[p++] = (char)(0x80 + ((w >> 12) & 0x3F));
outbuf[p++] = (char)(0x80 + ((w >> 6) & 0x3F));
outbuf[p++] = (char)(0x80 + (w & 0x3F));
} else {
// This is invalid. A trail surrogate should always follow a lead surrogate.
// Handling error by skipping
}
} else if (wc >= 0x800) {
outbuf[p++] = (char)(0xE0 + ((wc >> 12) & 0xF));
outbuf[p++] = (char)(0x80 + ((wc >> 6) & 0x3F));
outbuf[p++] = (char)(0x80 + (wc & 0x3F));
} else if (wc >= 0x80) {
outbuf[p++] = (char)(0xC0 + ((wc >> 6) & 0x1F));
outbuf[p++] = (char)(0x80 + (wc & 0x3F));
} else {
outbuf[p++] = (char)(wc & 0x7F);
}
}
if (items_read) {
*items_read = i;
}
if (items_written) {
*items_written = p;
}
outbuf[p] = 0;
return outbuf;
}
static plist_t parse_unicode_node(const char **bnode, uint64_t size)
{
plist_data_t data = plist_new_plist_data();
uint64_t i = 0;
uint16_t *unicodestr = NULL;
char *tmpstr = NULL;
long items_read = 0;
long items_written = 0;
data->type = PLIST_STRING;
unicodestr = (uint16_t*) malloc(sizeof(uint16_t) * size);
if (!unicodestr) {
plist_free_data(data);
PLIST_BIN_ERR("%s: Could not allocate %" PRIu64 " bytes\n", __func__, sizeof(uint16_t) * size);
return NULL;
}
for (i = 0; i < size; i++)
unicodestr[i] = be16toh(((uint16_t*)*bnode)[i]);
tmpstr = plist_utf16_to_utf8(unicodestr, size, &items_read, &items_written);
free(unicodestr);
if (!tmpstr) {
plist_free_data(data);
return NULL;
}
tmpstr[items_written] = '\0';
data->type = PLIST_STRING;
data->strval = realloc(tmpstr, items_written+1);
if (!data->strval)
data->strval = tmpstr;
data->length = items_written;
return node_create(NULL, data);
}
static plist_t parse_data_node(const char **bnode, uint64_t size)
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_DATA;
data->length = size;
data->buff = (uint8_t *) malloc(sizeof(uint8_t) * size);
if (!data->strval) {
plist_free_data(data);
PLIST_BIN_ERR("%s: Could not allocate %" PRIu64 " bytes\n", __func__, sizeof(uint8_t) * size);
return NULL;
}
memcpy(data->buff, *bnode, sizeof(uint8_t) * size);
return node_create(NULL, data);
}
static plist_t parse_dict_node(struct bplist_data *bplist, const char** bnode, uint64_t size)
{
uint64_t j;
uint64_t str_i = 0, str_j = 0;
uint64_t index1, index2;
plist_data_t data = plist_new_plist_data();
const char *index1_ptr = NULL;
const char *index2_ptr = NULL;
data->type = PLIST_DICT;
data->length = size;
plist_t node = node_create(NULL, data);
for (j = 0; j < data->length; j++) {
str_i = j * bplist->ref_size;
str_j = (j + size) * bplist->ref_size;
index1_ptr = (*bnode) + str_i;
index2_ptr = (*bnode) + str_j;
if ((index1_ptr < bplist->data || index1_ptr + bplist->ref_size > bplist->offset_table) ||
(index2_ptr < bplist->data || index2_ptr + bplist->ref_size > bplist->offset_table)) {
plist_free(node);
PLIST_BIN_ERR("%s: dict entry %" PRIu64 " is outside of valid range\n", __func__, j);
return NULL;
}
index1 = UINT_TO_HOST(index1_ptr, bplist->ref_size);
index2 = UINT_TO_HOST(index2_ptr, bplist->ref_size);
if (index1 >= bplist->num_objects) {
plist_free(node);
PLIST_BIN_ERR("%s: dict entry %" PRIu64 ": key index (%" PRIu64 ") must be smaller than the number of objects (%" PRIu64 ")\n", __func__, j, index1, bplist->num_objects);
return NULL;
}
if (index2 >= bplist->num_objects) {
plist_free(node);
PLIST_BIN_ERR("%s: dict entry %" PRIu64 ": value index (%" PRIu64 ") must be smaller than the number of objects (%" PRIu64 ")\n", __func__, j, index1, bplist->num_objects);
return NULL;
}
/* process key node */
plist_t key = parse_bin_node_at_index(bplist, index1);
if (!key) {
plist_free(node);
return NULL;
}
if (plist_get_data(key)->type != PLIST_STRING) {
PLIST_BIN_ERR("%s: dict entry %" PRIu64 ": invalid node type for key\n", __func__, j);
plist_free(key);
plist_free(node);
return NULL;
}
/* enforce key type */
plist_get_data(key)->type = PLIST_KEY;
if (!plist_get_data(key)->strval) {
PLIST_BIN_ERR("%s: dict entry %" PRIu64 ": key must not be NULL\n", __func__, j);
plist_free(key);
plist_free(node);
return NULL;
}
/* process value node */
plist_t val = parse_bin_node_at_index(bplist, index2);
if (!val) {
plist_free(key);
plist_free(node);
return NULL;
}
node_attach(node, key);
node_attach(node, val);
}
return node;
}
static plist_t parse_array_node(struct bplist_data *bplist, const char** bnode, uint64_t size)
{
uint64_t j;
uint64_t str_j = 0;
uint64_t index1;
plist_data_t data = plist_new_plist_data();
const char *index1_ptr = NULL;
data->type = PLIST_ARRAY;
data->length = size;
plist_t node = node_create(NULL, data);
for (j = 0; j < data->length; j++) {
str_j = j * bplist->ref_size;
index1_ptr = (*bnode) + str_j;
if (index1_ptr < bplist->data || index1_ptr + bplist->ref_size > bplist->offset_table) {
plist_free(node);
PLIST_BIN_ERR("%s: array item %" PRIu64 " is outside of valid range\n", __func__, j);
return NULL;
}
index1 = UINT_TO_HOST(index1_ptr, bplist->ref_size);
if (index1 >= bplist->num_objects) {
plist_free(node);
PLIST_BIN_ERR("%s: array item %" PRIu64 " object index (%" PRIu64 ") must be smaller than the number of objects (%" PRIu64 ")\n", __func__, j, index1, bplist->num_objects);
return NULL;
}
/* process value node */
plist_t val = parse_bin_node_at_index(bplist, index1);
if (!val) {
plist_free(node);
return NULL;
}
node_attach(node, val);
}
return node;
}
static plist_t parse_uid_node(const char **bnode, uint8_t size)
{
plist_data_t data = plist_new_plist_data();
size = size + 1;
data->intval = UINT_TO_HOST(*bnode, size);
if (data->intval > UINT32_MAX) {
PLIST_BIN_ERR("%s: value %" PRIu64 " too large for UID node (must be <= %u)\n", __func__, (uint64_t)data->intval, UINT32_MAX);
free(data);
return NULL;
}
(*bnode) += size;
data->type = PLIST_UID;
data->length = sizeof(uint64_t);
return node_create(NULL, data);
}
static plist_t parse_bin_node(struct bplist_data *bplist, const char** object)
{
uint16_t type = 0;
uint64_t size = 0;
if (!object)
return NULL;
type = (**object) & BPLIST_MASK;
size = (**object) & BPLIST_FILL;
(*object)++;
if (size == BPLIST_FILL) {
switch (type) {
case BPLIST_DATA:
case BPLIST_STRING:
case BPLIST_UNICODE:
case BPLIST_ARRAY:
case BPLIST_SET:
case BPLIST_DICT:
{
uint16_t next_size = **object & BPLIST_FILL;
if ((**object & BPLIST_MASK) != BPLIST_UINT) {
PLIST_BIN_ERR("%s: invalid size node type for node type 0x%02x: found 0x%02x, expected 0x%02x\n", __func__, type, **object & BPLIST_MASK, BPLIST_UINT);
return NULL;
}
(*object)++;
next_size = 1 << next_size;
if (*object + next_size > bplist->offset_table) {
PLIST_BIN_ERR("%s: size node data bytes for node type 0x%02x point outside of valid range\n", __func__, type);
return NULL;
}
size = UINT_TO_HOST(*object, next_size);
(*object) += next_size;
break;
}
default:
break;
}
}
switch (type)
{
case BPLIST_NULL:
switch (size)
{
case BPLIST_TRUE:
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_BOOLEAN;
data->boolval = TRUE;
data->length = 1;
return node_create(NULL, data);
}
case BPLIST_FALSE:
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_BOOLEAN;
data->boolval = FALSE;
data->length = 1;
return node_create(NULL, data);
}
case BPLIST_NULL:
default:
return NULL;
}
case BPLIST_UINT:
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UINT data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_uint_node(object, size);
case BPLIST_REAL:
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_REAL data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_real_node(object, size);
case BPLIST_DATE:
if (3 != size) {
PLIST_BIN_ERR("%s: invalid data size for BPLIST_DATE node\n", __func__);
return NULL;
}
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DATE data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_date_node(object, size);
case BPLIST_DATA:
if (*object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DATA data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_data_node(object, size);
case BPLIST_STRING:
if (*object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_STRING data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_string_node(object, size);
case BPLIST_UNICODE:
if (size*2 < size) {
PLIST_BIN_ERR("%s: Integer overflow when calculating BPLIST_UNICODE data size.\n", __func__);
return NULL;
}
if (*object + size*2 > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UNICODE data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_unicode_node(object, size);
case BPLIST_SET:
case BPLIST_ARRAY:
if (*object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_ARRAY data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_array_node(bplist, object, size);
case BPLIST_UID:
if (*object + size+1 > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UID data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_uid_node(object, size);
case BPLIST_DICT:
if (*object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_REAL data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_dict_node(bplist, object, size);
default:
PLIST_BIN_ERR("%s: unexpected node type 0x%02x\n", __func__, type);
return NULL;
}
return NULL;
}
static plist_t parse_bin_node_at_index(struct bplist_data *bplist, uint32_t node_index)
{
int i = 0;
const char* ptr = NULL;
plist_t plist = NULL;
const char* idx_ptr = NULL;
if (node_index >= bplist->num_objects) {
PLIST_BIN_ERR("node index (%u) must be smaller than the number of objects (%" PRIu64 ")\n", node_index, bplist->num_objects);
return NULL;
}
idx_ptr = bplist->offset_table + node_index * bplist->offset_size;
if (idx_ptr < bplist->offset_table ||
idx_ptr >= bplist->offset_table + bplist->num_objects * bplist->offset_size) {
PLIST_BIN_ERR("node index %u points outside of valid range\n", node_index);
return NULL;
}
ptr = bplist->data + UINT_TO_HOST(idx_ptr, bplist->offset_size);
/* make sure the node offset is in a sane range */
if ((ptr < bplist->data) || (ptr >= bplist->offset_table)) {
PLIST_BIN_ERR("offset for node index %u points outside of valid range\n", node_index);
return NULL;
}
/* store node_index for current recursion level */
if (plist_array_get_size(bplist->used_indexes) < bplist->level+1) {
while (plist_array_get_size(bplist->used_indexes) < bplist->level+1) {
plist_array_append_item(bplist->used_indexes, plist_new_uint(node_index));
}
} else {
plist_array_set_item(bplist->used_indexes, plist_new_uint(node_index), bplist->level);
}
/* recursion check */
if (bplist->level > 0) {
for (i = bplist->level-1; i >= 0; i--) {
plist_t node_i = plist_array_get_item(bplist->used_indexes, i);
plist_t node_level = plist_array_get_item(bplist->used_indexes, bplist->level);
if (plist_compare_node_value(node_i, node_level)) {
PLIST_BIN_ERR("recursion detected in binary plist\n");
return NULL;
}
}
}
/* finally parse node */
bplist->level++;
plist = parse_bin_node(bplist, &ptr);
bplist->level--;
return plist;
}
PLIST_API void plist_from_bin(const char *plist_bin, uint32_t length, plist_t * plist)
{
bplist_trailer_t *trailer = NULL;
uint8_t offset_size = 0;
uint8_t ref_size = 0;
uint64_t num_objects = 0;
uint64_t root_object = 0;
const char *offset_table = NULL;
const char *start_data = NULL;
const char *end_data = NULL;
//first check we have enough data
if (!(length >= BPLIST_MAGIC_SIZE + BPLIST_VERSION_SIZE + sizeof(bplist_trailer_t))) {
PLIST_BIN_ERR("plist data is to small to hold a binary plist\n");
return;
}
//check that plist_bin in actually a plist
if (memcmp(plist_bin, BPLIST_MAGIC, BPLIST_MAGIC_SIZE) != 0) {
PLIST_BIN_ERR("bplist magic mismatch\n");
return;
}
//check for known version
if (memcmp(plist_bin + BPLIST_MAGIC_SIZE, BPLIST_VERSION, BPLIST_VERSION_SIZE) != 0) {
PLIST_BIN_ERR("unsupported binary plist version '%.2s\n", plist_bin+BPLIST_MAGIC_SIZE);
return;
}
start_data = plist_bin + BPLIST_MAGIC_SIZE + BPLIST_VERSION_SIZE;
end_data = plist_bin + length - sizeof(bplist_trailer_t);
//now parse trailer
trailer = (bplist_trailer_t*)end_data;
offset_size = trailer->offset_size;
ref_size = trailer->ref_size;
num_objects = be64toh(trailer->num_objects);
root_object = be64toh(trailer->root_object_index);
offset_table = (char *)(plist_bin + be64toh(trailer->offset_table_offset));
if (num_objects == 0) {
PLIST_BIN_ERR("number of objects must be larger than 0\n");
return;
}
if (offset_size == 0) {
PLIST_BIN_ERR("offset size in trailer must be larger than 0\n");
return;
}
if (ref_size == 0) {
PLIST_BIN_ERR("object reference size in trailer must be larger than 0\n");
return;
}
if (root_object >= num_objects) {
PLIST_BIN_ERR("root object index (%" PRIu64 ") must be smaller than number of objects (%" PRIu64 ")\n", root_object, num_objects);
return;
}
if (offset_table < start_data || offset_table >= end_data) {
PLIST_BIN_ERR("offset table offset points outside of valid range\n");
return;
}
if (num_objects * offset_size < num_objects) {
PLIST_BIN_ERR("integer overflow when calculating offset table size (too many objects)\n");
return;
}
if (offset_table + num_objects * offset_size > end_data) {
PLIST_BIN_ERR("offset table points outside of valid range\n");
return;
}
struct bplist_data bplist;
bplist.data = plist_bin;
bplist.size = length;
bplist.num_objects = num_objects;
bplist.ref_size = ref_size;
bplist.offset_size = offset_size;
bplist.offset_table = offset_table;
bplist.level = 0;
bplist.used_indexes = plist_new_array();
if (!bplist.used_indexes) {
PLIST_BIN_ERR("failed to create array to hold used node indexes. Out of memory?\n");
return;
}
*plist = parse_bin_node_at_index(&bplist, root_object);
plist_free(bplist.used_indexes);
}
static unsigned int plist_data_hash(const void* key)
{
plist_data_t data = plist_get_data((plist_t) key);
unsigned int hash = data->type;
unsigned int i = 0;
char *buff = NULL;
unsigned int size = 0;
switch (data->type)
{
case PLIST_BOOLEAN:
case PLIST_UINT:
case PLIST_REAL:
case PLIST_DATE:
case PLIST_UID:
buff = (char *) &data->intval; //works also for real as we use an union
size = 8;
break;
case PLIST_KEY:
case PLIST_STRING:
buff = data->strval;
size = data->length;
break;
case PLIST_DATA:
case PLIST_ARRAY:
case PLIST_DICT:
//for these types only hash pointer
buff = (char *) &key;
size = sizeof(const void*);
break;
default:
break;
}
// now perform hash using djb2 hashing algorithm
// see: http://www.cse.yorku.ca/~oz/hash.html
hash += 5381;
for (i = 0; i < size; buff++, i++) {
hash = ((hash << 5) + hash) + *buff;
}
return hash;
}
struct serialize_s
{
ptrarray_t* objects;
hashtable_t* ref_table;
};
static void serialize_plist(node_t* node, void* data)
{
uint64_t *index_val = NULL;
struct serialize_s *ser = (struct serialize_s *) data;
uint64_t current_index = ser->objects->len;
//first check that node is not yet in objects
void* val = hash_table_lookup(ser->ref_table, node);
if (val)
{
//data is already in table
return;
}
//insert new ref
index_val = (uint64_t *) malloc(sizeof(uint64_t));
assert(index_val != NULL);
*index_val = current_index;
hash_table_insert(ser->ref_table, node, index_val);
//now append current node to object array
ptr_array_add(ser->objects, node);
//now recurse on children
node_iterator_t *ni = node_iterator_create(node->children);
node_t *ch;
while ((ch = node_iterator_next(ni))) {
serialize_plist(ch, data);
}
node_iterator_destroy(ni);
return;
}
#define Log2(x) (x == 8 ? 3 : (x == 4 ? 2 : (x == 2 ? 1 : 0)))
static void write_int(bytearray_t * bplist, uint64_t val)
{
int size = get_needed_bytes(val);
uint8_t sz;
//do not write 3bytes int node
if (size == 3)
size++;
sz = BPLIST_UINT | Log2(size);
val = be64toh(val);
byte_array_append(bplist, &sz, 1);
byte_array_append(bplist, (uint8_t*)&val + (8-size), size);
}
static void write_uint(bytearray_t * bplist, uint64_t val)
{
uint8_t sz = BPLIST_UINT | 4;
uint64_t zero = 0;
val = be64toh(val);
byte_array_append(bplist, &sz, 1);
byte_array_append(bplist, &zero, sizeof(uint64_t));
byte_array_append(bplist, &val, sizeof(uint64_t));
}
static void write_real(bytearray_t * bplist, double val)
{
int size = get_real_bytes(val); //cheat to know used space
uint8_t buff[9];
buff[0] = BPLIST_REAL | Log2(size);
if (size == sizeof(float)) {
float floatval = (float)val;
*(uint32_t*)(buff+1) = float_bswap32(*(uint32_t*)&floatval);
} else {
*(uint64_t*)(buff+1) = float_bswap64(*(uint64_t*)&val);
}
byte_array_append(bplist, buff, size+1);
}
static void write_date(bytearray_t * bplist, double val)
{
uint8_t buff[9];
buff[0] = BPLIST_DATE | 3;
*(uint64_t*)(buff+1) = float_bswap64(*(uint64_t*)&val);
byte_array_append(bplist, buff, sizeof(buff));
}
static void write_raw_data(bytearray_t * bplist, uint8_t mark, uint8_t * val, uint64_t size)
{
uint8_t marker = mark | (size < 15 ? size : 0xf);
byte_array_append(bplist, &marker, sizeof(uint8_t));
if (size >= 15) {
write_int(bplist, size);
}
if (BPLIST_UNICODE==mark) size <<= 1;
byte_array_append(bplist, val, size);
}
static void write_data(bytearray_t * bplist, uint8_t * val, uint64_t size)
{
write_raw_data(bplist, BPLIST_DATA, val, size);
}
static void write_string(bytearray_t * bplist, char *val)
{
uint64_t size = strlen(val);
write_raw_data(bplist, BPLIST_STRING, (uint8_t *) val, size);
}
static void write_unicode(bytearray_t * bplist, uint16_t * val, uint64_t size)
{
uint64_t i = 0;
uint16_t *buff = (uint16_t*)malloc(size << 1);
for (i = 0; i < size; i++)
buff[i] = be16toh(val[i]);
write_raw_data(bplist, BPLIST_UNICODE, (uint8_t*)buff, size);
free(buff);
}
static void write_array(bytearray_t * bplist, node_t* node, hashtable_t* ref_table, uint8_t ref_size)
{
node_t* cur = NULL;
uint64_t i = 0;
uint64_t size = node_n_children(node);
uint8_t marker = BPLIST_ARRAY | (size < 15 ? size : 0xf);
byte_array_append(bplist, &marker, sizeof(uint8_t));
if (size >= 15) {
write_int(bplist, size);
}
for (i = 0, cur = node_first_child(node); cur && i < size; cur = node_next_sibling(cur), i++) {
uint64_t idx = *(uint64_t *) (hash_table_lookup(ref_table, cur));
idx = be64toh(idx);
byte_array_append(bplist, (uint8_t*)&idx + (sizeof(uint64_t) - ref_size), ref_size);
}
}
static void write_dict(bytearray_t * bplist, node_t* node, hashtable_t* ref_table, uint8_t ref_size)
{
node_t* cur = NULL;
uint64_t i = 0;
uint64_t size = node_n_children(node) / 2;
uint8_t marker = BPLIST_DICT | (size < 15 ? size : 0xf);
byte_array_append(bplist, &marker, sizeof(uint8_t));
if (size >= 15) {
write_int(bplist, size);
}
for (i = 0, cur = node_first_child(node); cur && i < size; cur = node_next_sibling(node_next_sibling(cur)), i++) {
uint64_t idx1 = *(uint64_t *) (hash_table_lookup(ref_table, cur));
idx1 = be64toh(idx1);
byte_array_append(bplist, (uint8_t*)&idx1 + (sizeof(uint64_t) - ref_size), ref_size);
}
for (i = 0, cur = node_first_child(node); cur && i < size; cur = node_next_sibling(node_next_sibling(cur)), i++) {
uint64_t idx2 = *(uint64_t *) (hash_table_lookup(ref_table, cur->next));
idx2 = be64toh(idx2);
byte_array_append(bplist, (uint8_t*)&idx2 + (sizeof(uint64_t) - ref_size), ref_size);
}
}
static void write_uid(bytearray_t * bplist, uint64_t val)
{
val = (uint32_t)val;
int size = get_needed_bytes(val);
uint8_t sz;
//do not write 3bytes int node
if (size == 3)
size++;
sz = BPLIST_UID | (size-1); // yes, this is what Apple does...
val = be64toh(val);
byte_array_append(bplist, &sz, 1);
byte_array_append(bplist, (uint8_t*)&val + (8-size), size);
}
static int is_ascii_string(char* s, int len)
{
int ret = 1, i = 0;
for(i = 0; i < len; i++)
{
if ( !isascii( s[i] ) )
{
ret = 0;
break;
}
}
return ret;
}
static uint16_t *plist_utf8_to_utf16(char *unistr, long size, long *items_read, long *items_written)
{
uint16_t *outbuf;
int p = 0;
long i = 0;
unsigned char c0;
unsigned char c1;
unsigned char c2;
unsigned char c3;
uint32_t w;
outbuf = (uint16_t*)malloc(((size*2)+1)*sizeof(uint16_t));
if (!outbuf) {
PLIST_BIN_ERR("%s: Could not allocate %" PRIu64 " bytes\n", __func__, (uint64_t)((size*2)+1)*sizeof(uint16_t));
return NULL;
}
while (i < size) {
c0 = unistr[i];
c1 = (i < size-1) ? unistr[i+1] : 0;
c2 = (i < size-2) ? unistr[i+2] : 0;
c3 = (i < size-3) ? unistr[i+3] : 0;
if ((c0 >= 0xF0) && (i < size-3) && (c1 >= 0x80) && (c2 >= 0x80) && (c3 >= 0x80)) {
// 4 byte sequence. Need to generate UTF-16 surrogate pair
w = ((((c0 & 7) << 18) + ((c1 & 0x3F) << 12) + ((c2 & 0x3F) << 6) + (c3 & 0x3F)) & 0x1FFFFF) - 0x010000;
outbuf[p++] = 0xD800 + (w >> 10);
outbuf[p++] = 0xDC00 + (w & 0x3FF);
i+=4;
} else if ((c0 >= 0xE0) && (i < size-2) && (c1 >= 0x80) && (c2 >= 0x80)) {
// 3 byte sequence
outbuf[p++] = ((c2 & 0x3F) + ((c1 & 3) << 6)) + (((c1 >> 2) & 15) << 8) + ((c0 & 15) << 12);
i+=3;
} else if ((c0 >= 0xC0) && (i < size-1) && (c1 >= 0x80)) {
// 2 byte sequence
outbuf[p++] = ((c1 & 0x3F) + ((c0 & 3) << 6)) + (((c0 >> 2) & 7) << 8);
i+=2;
} else if (c0 < 0x80) {
// 1 byte sequence
outbuf[p++] = c0;
i+=1;
} else {
// invalid character
PLIST_BIN_ERR("%s: invalid utf8 sequence in string at index %lu\n", __func__, i);
break;
}
}
if (items_read) {
*items_read = i;
}
if (items_written) {
*items_written = p;
}
outbuf[p] = 0;
return outbuf;
}
PLIST_API void plist_to_bin(plist_t plist, char **plist_bin, uint32_t * length)
{
ptrarray_t* objects = NULL;
hashtable_t* ref_table = NULL;
struct serialize_s ser_s;
uint8_t offset_size = 0;
uint8_t ref_size = 0;
uint64_t num_objects = 0;
uint64_t root_object = 0;
uint64_t offset_table_index = 0;
bytearray_t *bplist_buff = NULL;
uint64_t i = 0;
uint8_t *buff = NULL;
uint64_t *offsets = NULL;
bplist_trailer_t trailer;
//for string
long len = 0;
long items_read = 0;
long items_written = 0;
uint16_t *unicodestr = NULL;
uint64_t objects_len = 0;
uint64_t buff_len = 0;
//check for valid input
if (!plist || !plist_bin || *plist_bin || !length)
return;
//list of objects
objects = ptr_array_new(256);
//hashtable to write only once same nodes
ref_table = hash_table_new(plist_data_hash, plist_data_compare, free);
//serialize plist
ser_s.objects = objects;
ser_s.ref_table = ref_table;
serialize_plist(plist, &ser_s);
//now stream to output buffer
offset_size = 0; //unknown yet
objects_len = objects->len;
ref_size = get_needed_bytes(objects_len);
num_objects = objects->len;
root_object = 0; //root is first in list
offset_table_index = 0; //unknown yet
//setup a dynamic bytes array to store bplist in
bplist_buff = byte_array_new();
//set magic number and version
byte_array_append(bplist_buff, BPLIST_MAGIC, BPLIST_MAGIC_SIZE);
byte_array_append(bplist_buff, BPLIST_VERSION, BPLIST_VERSION_SIZE);
//write objects and table
offsets = (uint64_t *) malloc(num_objects * sizeof(uint64_t));
assert(offsets != NULL);
for (i = 0; i < num_objects; i++)
{
plist_data_t data = plist_get_data(ptr_array_index(objects, i));
offsets[i] = bplist_buff->len;
switch (data->type)
{
case PLIST_BOOLEAN:
buff = (uint8_t *) malloc(sizeof(uint8_t));
buff[0] = data->boolval ? BPLIST_TRUE : BPLIST_FALSE;
byte_array_append(bplist_buff, buff, sizeof(uint8_t));
free(buff);
break;
case PLIST_UINT:
if (data->length == 16) {
write_uint(bplist_buff, data->intval);
} else {
write_int(bplist_buff, data->intval);
}
break;
case PLIST_REAL:
write_real(bplist_buff, data->realval);
break;
case PLIST_KEY:
case PLIST_STRING:
len = strlen(data->strval);
if ( is_ascii_string(data->strval, len) )
{
write_string(bplist_buff, data->strval);
}
else
{
unicodestr = plist_utf8_to_utf16(data->strval, len, &items_read, &items_written);
write_unicode(bplist_buff, unicodestr, items_written);
free(unicodestr);
}
break;
case PLIST_DATA:
write_data(bplist_buff, data->buff, data->length);
case PLIST_ARRAY:
write_array(bplist_buff, ptr_array_index(objects, i), ref_table, ref_size);
break;
case PLIST_DICT:
write_dict(bplist_buff, ptr_array_index(objects, i), ref_table, ref_size);
break;
case PLIST_DATE:
write_date(bplist_buff, data->realval);
break;
case PLIST_UID:
write_uid(bplist_buff, data->intval);
break;
default:
break;
}
}
//free intermediate objects
ptr_array_free(objects);
hash_table_destroy(ref_table);
//write offsets
buff_len = bplist_buff->len;
offset_size = get_needed_bytes(buff_len);
offset_table_index = bplist_buff->len;
for (i = 0; i < num_objects; i++) {
uint64_t offset = be64toh(offsets[i]);
byte_array_append(bplist_buff, (uint8_t*)&offset + (sizeof(uint64_t) - offset_size), offset_size);
}
free(offsets);
//setup trailer
memset(trailer.unused, '\0', sizeof(trailer.unused));
trailer.offset_size = offset_size;
trailer.ref_size = ref_size;
trailer.num_objects = be64toh(num_objects);
trailer.root_object_index = be64toh(root_object);
trailer.offset_table_offset = be64toh(offset_table_index);
byte_array_append(bplist_buff, &trailer, sizeof(bplist_trailer_t));
//set output buffer and size
*plist_bin = bplist_buff->data;
*length = bplist_buff->len;
bplist_buff->data = NULL; // make sure we don't free the output buffer
byte_array_free(bplist_buff);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3192_0 |
crossvul-cpp_data_good_5415_1 | /*
* Copyright (c) 1999-2000 Image Power, Inc. and the University of
* British Columbia.
* Copyright (c) 2001-2003 Michael David Adams.
* All rights reserved.
*/
/* __START_OF_JASPER_LICENSE__
*
* JasPer License Version 2.0
*
* Copyright (c) 2001-2006 Michael David Adams
* Copyright (c) 1999-2000 Image Power, Inc.
* Copyright (c) 1999-2000 The University of British Columbia
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person (the
* "User") obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* 1. The above copyright notices and this permission notice (which
* includes the disclaimer below) shall be included in all copies or
* substantial portions of the Software.
*
* 2. The name of a copyright holder shall not be used to endorse or
* promote products derived from the Software without specific prior
* written permission.
*
* THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
* LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
* THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
* "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
* EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
* PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
* THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
* EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
* BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
* PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
* GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
* ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
* IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
* SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
* AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
* SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
* THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
* PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
* RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
* EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
*
* __END_OF_JASPER_LICENSE__
*/
/*
* $Id$
*/
/******************************************************************************\
* Includes.
\******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <inttypes.h>
#include "jasper/jas_types.h"
#include "jasper/jas_math.h"
#include "jasper/jas_tvp.h"
#include "jasper/jas_malloc.h"
#include "jasper/jas_debug.h"
#include "jpc_fix.h"
#include "jpc_dec.h"
#include "jpc_cs.h"
#include "jpc_mct.h"
#include "jpc_t2dec.h"
#include "jpc_t1dec.h"
#include "jpc_math.h"
/******************************************************************************\
*
\******************************************************************************/
#define JPC_MHSOC 0x0001
/* In the main header, expecting a SOC marker segment. */
#define JPC_MHSIZ 0x0002
/* In the main header, expecting a SIZ marker segment. */
#define JPC_MH 0x0004
/* In the main header, expecting "other" marker segments. */
#define JPC_TPHSOT 0x0008
/* In a tile-part header, expecting a SOT marker segment. */
#define JPC_TPH 0x0010
/* In a tile-part header, expecting "other" marker segments. */
#define JPC_MT 0x0020
/* In the main trailer. */
typedef struct {
uint_fast16_t id;
/* The marker segment type. */
int validstates;
/* The states in which this type of marker segment can be
validly encountered. */
int (*action)(jpc_dec_t *dec, jpc_ms_t *ms);
/* The action to take upon encountering this type of marker segment. */
} jpc_dec_mstabent_t;
/******************************************************************************\
*
\******************************************************************************/
/* COD/COC parameters have been specified. */
#define JPC_CSET 0x0001
/* QCD/QCC parameters have been specified. */
#define JPC_QSET 0x0002
/* COD/COC parameters set from a COC marker segment. */
#define JPC_COC 0x0004
/* QCD/QCC parameters set from a QCC marker segment. */
#define JPC_QCC 0x0008
/******************************************************************************\
* Local function prototypes.
\******************************************************************************/
static int jpc_dec_dump(jpc_dec_t *dec, FILE *out);
jpc_ppxstab_t *jpc_ppxstab_create(void);
void jpc_ppxstab_destroy(jpc_ppxstab_t *tab);
int jpc_ppxstab_grow(jpc_ppxstab_t *tab, int maxents);
int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent);
jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab);
int jpc_pptstabwrite(jas_stream_t *out, jpc_ppxstab_t *tab);
jpc_ppxstabent_t *jpc_ppxstabent_create(void);
void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent);
int jpc_streamlist_numstreams(jpc_streamlist_t *streamlist);
jpc_streamlist_t *jpc_streamlist_create(void);
int jpc_streamlist_insert(jpc_streamlist_t *streamlist, int streamno,
jas_stream_t *stream);
jas_stream_t *jpc_streamlist_remove(jpc_streamlist_t *streamlist, int streamno);
void jpc_streamlist_destroy(jpc_streamlist_t *streamlist);
jas_stream_t *jpc_streamlist_get(jpc_streamlist_t *streamlist, int streamno);
static void jpc_dec_cp_resetflags(jpc_dec_cp_t *cp);
static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps);
static int jpc_dec_cp_isvalid(jpc_dec_cp_t *cp);
static jpc_dec_cp_t *jpc_dec_cp_copy(jpc_dec_cp_t *cp);
static int jpc_dec_cp_setfromcod(jpc_dec_cp_t *cp, jpc_cod_t *cod);
static int jpc_dec_cp_setfromcoc(jpc_dec_cp_t *cp, jpc_coc_t *coc);
static int jpc_dec_cp_setfromcox(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp,
jpc_coxcp_t *compparms, int flags);
static int jpc_dec_cp_setfromqcd(jpc_dec_cp_t *cp, jpc_qcd_t *qcd);
static int jpc_dec_cp_setfromqcc(jpc_dec_cp_t *cp, jpc_qcc_t *qcc);
static int jpc_dec_cp_setfromqcx(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp,
jpc_qcxcp_t *compparms, int flags);
static int jpc_dec_cp_setfromrgn(jpc_dec_cp_t *cp, jpc_rgn_t *rgn);
static int jpc_dec_cp_prepare(jpc_dec_cp_t *cp);
static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp);
static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, jpc_poc_t *poc, int reset);
static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, jpc_poc_t *poc);
static int jpc_dec_decode(jpc_dec_t *dec);
static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in);
static void jpc_dec_destroy(jpc_dec_t *dec);
static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize);
static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps);
static jpc_fix_t jpc_calcabsstepsize(int stepsize, int numbits);
static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile);
static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile);
static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile);
static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms);
static int jpc_dec_parseopts(char *optstr, jpc_dec_importopts_t *opts);
static jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id);
/******************************************************************************\
* Global data.
\******************************************************************************/
jpc_dec_mstabent_t jpc_dec_mstab[] = {
{JPC_MS_SOC, JPC_MHSOC, jpc_dec_process_soc},
{JPC_MS_SOT, JPC_MH | JPC_TPHSOT, jpc_dec_process_sot},
{JPC_MS_SOD, JPC_TPH, jpc_dec_process_sod},
{JPC_MS_EOC, JPC_TPHSOT, jpc_dec_process_eoc},
{JPC_MS_SIZ, JPC_MHSIZ, jpc_dec_process_siz},
{JPC_MS_COD, JPC_MH | JPC_TPH, jpc_dec_process_cod},
{JPC_MS_COC, JPC_MH | JPC_TPH, jpc_dec_process_coc},
{JPC_MS_RGN, JPC_MH | JPC_TPH, jpc_dec_process_rgn},
{JPC_MS_QCD, JPC_MH | JPC_TPH, jpc_dec_process_qcd},
{JPC_MS_QCC, JPC_MH | JPC_TPH, jpc_dec_process_qcc},
{JPC_MS_POC, JPC_MH | JPC_TPH, jpc_dec_process_poc},
{JPC_MS_TLM, JPC_MH, 0},
{JPC_MS_PLM, JPC_MH, 0},
{JPC_MS_PLT, JPC_TPH, 0},
{JPC_MS_PPM, JPC_MH, jpc_dec_process_ppm},
{JPC_MS_PPT, JPC_TPH, jpc_dec_process_ppt},
{JPC_MS_SOP, 0, 0},
{JPC_MS_CRG, JPC_MH, jpc_dec_process_crg},
{JPC_MS_COM, JPC_MH | JPC_TPH, jpc_dec_process_com},
{0, JPC_MH | JPC_TPH, jpc_dec_process_unk}
};
/******************************************************************************\
* The main entry point for the JPEG-2000 decoder.
\******************************************************************************/
jas_image_t *jpc_decode(jas_stream_t *in, char *optstr)
{
jpc_dec_importopts_t opts;
jpc_dec_t *dec;
jas_image_t *image;
dec = 0;
if (jpc_dec_parseopts(optstr, &opts)) {
goto error;
}
jpc_initluts();
if (!(dec = jpc_dec_create(&opts, in))) {
goto error;
}
/* Do most of the work. */
if (jpc_dec_decode(dec)) {
goto error;
}
if (jas_image_numcmpts(dec->image) >= 3) {
jas_image_setclrspc(dec->image, JAS_CLRSPC_SRGB);
jas_image_setcmpttype(dec->image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
jas_image_setcmpttype(dec->image, 1,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
jas_image_setcmpttype(dec->image, 2,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
} else {
jas_image_setclrspc(dec->image, JAS_CLRSPC_SGRAY);
jas_image_setcmpttype(dec->image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
}
/* Save the return value. */
image = dec->image;
/* Stop the image from being discarded. */
dec->image = 0;
/* Destroy decoder. */
jpc_dec_destroy(dec);
return image;
error:
if (dec) {
jpc_dec_destroy(dec);
}
return 0;
}
typedef enum {
OPT_MAXLYRS,
OPT_MAXPKTS,
OPT_DEBUG
} optid_t;
jas_taginfo_t decopts[] = {
{OPT_MAXLYRS, "maxlyrs"},
{OPT_MAXPKTS, "maxpkts"},
{OPT_DEBUG, "debug"},
{-1, 0}
};
static int jpc_dec_parseopts(char *optstr, jpc_dec_importopts_t *opts)
{
jas_tvparser_t *tvp;
opts->debug = 0;
opts->maxlyrs = JPC_MAXLYRS;
opts->maxpkts = -1;
if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) {
return -1;
}
while (!jas_tvparser_next(tvp)) {
switch (jas_taginfo_nonull(jas_taginfos_lookup(decopts,
jas_tvparser_gettag(tvp)))->id) {
case OPT_MAXLYRS:
opts->maxlyrs = atoi(jas_tvparser_getval(tvp));
break;
case OPT_DEBUG:
opts->debug = atoi(jas_tvparser_getval(tvp));
break;
case OPT_MAXPKTS:
opts->maxpkts = atoi(jas_tvparser_getval(tvp));
break;
default:
jas_eprintf("warning: ignoring invalid option %s\n",
jas_tvparser_gettag(tvp));
break;
}
}
jas_tvparser_destroy(tvp);
return 0;
}
/******************************************************************************\
* Code for table-driven code stream decoder.
\******************************************************************************/
static jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id)
{
jpc_dec_mstabent_t *mstabent;
for (mstabent = jpc_dec_mstab; mstabent->id != 0; ++mstabent) {
if (mstabent->id == id) {
break;
}
}
return mstabent;
}
static int jpc_dec_decode(jpc_dec_t *dec)
{
jpc_ms_t *ms;
jpc_dec_mstabent_t *mstabent;
int ret;
jpc_cstate_t *cstate;
if (!(cstate = jpc_cstate_create())) {
return -1;
}
dec->cstate = cstate;
/* Initially, we should expect to encounter a SOC marker segment. */
dec->state = JPC_MHSOC;
for (;;) {
/* Get the next marker segment in the code stream. */
if (!(ms = jpc_getms(dec->in, cstate))) {
jas_eprintf("cannot get marker segment\n");
return -1;
}
mstabent = jpc_dec_mstab_lookup(ms->id);
assert(mstabent);
/* Ensure that this type of marker segment is permitted
at this point in the code stream. */
if (!(dec->state & mstabent->validstates)) {
jas_eprintf("unexpected marker segment type\n");
jpc_ms_destroy(ms);
return -1;
}
/* Process the marker segment. */
if (mstabent->action) {
ret = (*mstabent->action)(dec, ms);
} else {
/* No explicit action is required. */
ret = 0;
}
/* Destroy the marker segment. */
jpc_ms_destroy(ms);
if (ret < 0) {
return -1;
} else if (ret > 0) {
break;
}
}
return 0;
}
static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms)
{
int cmptno;
jpc_dec_cmpt_t *cmpt;
jpc_crg_t *crg;
crg = &ms->parms.crg;
for (cmptno = 0, cmpt = dec->cmpts; cmptno < dec->numcomps; ++cmptno,
++cmpt) {
/* Ignore the information in the CRG marker segment for now.
This information serves no useful purpose for decoding anyhow.
Some other parts of the code need to be changed if these lines
are uncommented.
cmpt->hsubstep = crg->comps[cmptno].hoff;
cmpt->vsubstep = crg->comps[cmptno].voff;
*/
}
return 0;
}
static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms)
{
/* Eliminate warnings about unused variables. */
ms = 0;
/* We should expect to encounter a SIZ marker segment next. */
dec->state = JPC_MHSIZ;
return 0;
}
static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_dec_tile_t *tile;
jpc_sot_t *sot = &ms->parms.sot;
jas_image_cmptparm_t *compinfos;
jas_image_cmptparm_t *compinfo;
jpc_dec_cmpt_t *cmpt;
int cmptno;
if (dec->state == JPC_MH) {
if (!(compinfos = jas_alloc2(dec->numcomps,
sizeof(jas_image_cmptparm_t)))) {
abort();
}
for (cmptno = 0, cmpt = dec->cmpts, compinfo = compinfos;
cmptno < dec->numcomps; ++cmptno, ++cmpt, ++compinfo) {
compinfo->tlx = 0;
compinfo->tly = 0;
compinfo->prec = cmpt->prec;
compinfo->sgnd = cmpt->sgnd;
compinfo->width = cmpt->width;
compinfo->height = cmpt->height;
compinfo->hstep = cmpt->hstep;
compinfo->vstep = cmpt->vstep;
}
if (!(dec->image = jas_image_create(dec->numcomps, compinfos,
JAS_CLRSPC_UNKNOWN))) {
jas_free(compinfos);
return -1;
}
jas_free(compinfos);
/* Is the packet header information stored in PPM marker segments in
the main header? */
if (dec->ppmstab) {
/* Convert the PPM marker segment data into a collection of streams
(one stream per tile-part). */
if (!(dec->pkthdrstreams = jpc_ppmstabtostreams(dec->ppmstab))) {
abort();
}
jpc_ppxstab_destroy(dec->ppmstab);
dec->ppmstab = 0;
}
}
if (sot->len > 0) {
dec->curtileendoff = jas_stream_getrwcount(dec->in) - ms->len -
4 + sot->len;
} else {
dec->curtileendoff = 0;
}
if (JAS_CAST(int, sot->tileno) >= dec->numtiles) {
jas_eprintf("invalid tile number in SOT marker segment\n");
return -1;
}
/* Set the current tile. */
dec->curtile = &dec->tiles[sot->tileno];
tile = dec->curtile;
/* Ensure that this is the expected part number. */
if (sot->partno != tile->partno) {
return -1;
}
if (tile->numparts > 0 && sot->partno >= tile->numparts) {
return -1;
}
if (!tile->numparts && sot->numparts > 0) {
tile->numparts = sot->numparts;
}
tile->pptstab = 0;
switch (tile->state) {
case JPC_TILE_INIT:
/* This is the first tile-part for this tile. */
tile->state = JPC_TILE_ACTIVE;
assert(!tile->cp);
if (!(tile->cp = jpc_dec_cp_copy(dec->cp))) {
return -1;
}
jpc_dec_cp_resetflags(dec->cp);
break;
default:
if (sot->numparts == sot->partno - 1) {
tile->state = JPC_TILE_ACTIVELAST;
}
break;
}
/* Note: We do not increment the expected tile-part number until
all processing for this tile-part is complete. */
/* We should expect to encounter other tile-part header marker
segments next. */
dec->state = JPC_TPH;
return 0;
}
static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_dec_tile_t *tile;
int pos;
/* Eliminate compiler warnings about unused variables. */
ms = 0;
if (!(tile = dec->curtile)) {
return -1;
}
if (!tile->partno) {
if (!jpc_dec_cp_isvalid(tile->cp)) {
return -1;
}
jpc_dec_cp_prepare(tile->cp);
if (jpc_dec_tileinit(dec, tile)) {
return -1;
}
}
/* Are packet headers stored in the main header or tile-part header? */
if (dec->pkthdrstreams) {
/* Get the stream containing the packet header data for this
tile-part. */
if (!(tile->pkthdrstream = jpc_streamlist_remove(dec->pkthdrstreams, 0))) {
return -1;
}
}
if (tile->pptstab) {
if (!tile->pkthdrstream) {
if (!(tile->pkthdrstream = jas_stream_memopen(0, 0))) {
return -1;
}
}
pos = jas_stream_tell(tile->pkthdrstream);
jas_stream_seek(tile->pkthdrstream, 0, SEEK_END);
if (jpc_pptstabwrite(tile->pkthdrstream, tile->pptstab)) {
return -1;
}
jas_stream_seek(tile->pkthdrstream, pos, SEEK_SET);
jpc_ppxstab_destroy(tile->pptstab);
tile->pptstab = 0;
}
if (jas_getdbglevel() >= 10) {
jpc_dec_dump(dec, stderr);
}
if (jpc_dec_decodepkts(dec, (tile->pkthdrstream) ? tile->pkthdrstream :
dec->in, dec->in)) {
jas_eprintf("jpc_dec_decodepkts failed\n");
return -1;
}
/* Gobble any unconsumed tile data. */
if (dec->curtileendoff > 0) {
long curoff;
uint_fast32_t n;
curoff = jas_stream_getrwcount(dec->in);
if (curoff < dec->curtileendoff) {
n = dec->curtileendoff - curoff;
jas_eprintf("warning: ignoring trailing garbage (%lu bytes)\n",
(unsigned long) n);
while (n-- > 0) {
if (jas_stream_getc(dec->in) == EOF) {
jas_eprintf("read error\n");
return -1;
}
}
} else if (curoff > dec->curtileendoff) {
jas_eprintf("warning: not enough tile data (%lu bytes)\n",
(unsigned long) curoff - dec->curtileendoff);
}
}
if (tile->numparts > 0 && tile->partno == tile->numparts - 1) {
if (jpc_dec_tiledecode(dec, tile)) {
return -1;
}
jpc_dec_tilefini(dec, tile);
}
dec->curtile = 0;
/* Increment the expected tile-part number. */
++tile->partno;
/* We should expect to encounter a SOT marker segment next. */
dec->state = JPC_TPHSOT;
return 0;
}
static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile)
{
jpc_dec_tcomp_t *tcomp;
int compno;
int rlvlno;
jpc_dec_rlvl_t *rlvl;
jpc_dec_band_t *band;
jpc_dec_prc_t *prc;
int bndno;
jpc_tsfb_band_t *bnd;
int bandno;
jpc_dec_ccp_t *ccp;
int prccnt;
jpc_dec_cblk_t *cblk;
int cblkcnt;
uint_fast32_t tlprcxstart;
uint_fast32_t tlprcystart;
uint_fast32_t brprcxend;
uint_fast32_t brprcyend;
uint_fast32_t tlcbgxstart;
uint_fast32_t tlcbgystart;
uint_fast32_t brcbgxend;
uint_fast32_t brcbgyend;
uint_fast32_t cbgxstart;
uint_fast32_t cbgystart;
uint_fast32_t cbgxend;
uint_fast32_t cbgyend;
uint_fast32_t tlcblkxstart;
uint_fast32_t tlcblkystart;
uint_fast32_t brcblkxend;
uint_fast32_t brcblkyend;
uint_fast32_t cblkxstart;
uint_fast32_t cblkystart;
uint_fast32_t cblkxend;
uint_fast32_t cblkyend;
uint_fast32_t tmpxstart;
uint_fast32_t tmpystart;
uint_fast32_t tmpxend;
uint_fast32_t tmpyend;
jpc_dec_cp_t *cp;
jpc_tsfb_band_t bnds[64];
jpc_pchg_t *pchg;
int pchgno;
jpc_dec_cmpt_t *cmpt;
cp = tile->cp;
tile->realmode = 0;
if (cp->mctid == JPC_MCT_ICT) {
tile->realmode = 1;
}
for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
dec->numcomps; ++compno, ++tcomp, ++cmpt) {
ccp = &tile->cp->ccps[compno];
if (ccp->qmfbid == JPC_COX_INS) {
tile->realmode = 1;
}
tcomp->numrlvls = ccp->numrlvls;
if (!(tcomp->rlvls = jas_alloc2(tcomp->numrlvls,
sizeof(jpc_dec_rlvl_t)))) {
return -1;
}
if (!(tcomp->data = jas_seq2d_create(JPC_CEILDIV(tile->xstart,
cmpt->hstep), JPC_CEILDIV(tile->ystart, cmpt->vstep),
JPC_CEILDIV(tile->xend, cmpt->hstep), JPC_CEILDIV(tile->yend,
cmpt->vstep)))) {
return -1;
}
if (!(tcomp->tsfb = jpc_cod_gettsfb(ccp->qmfbid,
tcomp->numrlvls - 1))) {
return -1;
}
{
jpc_tsfb_getbands(tcomp->tsfb, jas_seq2d_xstart(tcomp->data),
jas_seq2d_ystart(tcomp->data), jas_seq2d_xend(tcomp->data),
jas_seq2d_yend(tcomp->data), bnds);
}
for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
++rlvlno, ++rlvl) {
rlvl->bands = 0;
rlvl->xstart = JPC_CEILDIVPOW2(tcomp->xstart,
tcomp->numrlvls - 1 - rlvlno);
rlvl->ystart = JPC_CEILDIVPOW2(tcomp->ystart,
tcomp->numrlvls - 1 - rlvlno);
rlvl->xend = JPC_CEILDIVPOW2(tcomp->xend,
tcomp->numrlvls - 1 - rlvlno);
rlvl->yend = JPC_CEILDIVPOW2(tcomp->yend,
tcomp->numrlvls - 1 - rlvlno);
rlvl->prcwidthexpn = ccp->prcwidthexpns[rlvlno];
rlvl->prcheightexpn = ccp->prcheightexpns[rlvlno];
tlprcxstart = JPC_FLOORDIVPOW2(rlvl->xstart,
rlvl->prcwidthexpn) << rlvl->prcwidthexpn;
tlprcystart = JPC_FLOORDIVPOW2(rlvl->ystart,
rlvl->prcheightexpn) << rlvl->prcheightexpn;
brprcxend = JPC_CEILDIVPOW2(rlvl->xend,
rlvl->prcwidthexpn) << rlvl->prcwidthexpn;
brprcyend = JPC_CEILDIVPOW2(rlvl->yend,
rlvl->prcheightexpn) << rlvl->prcheightexpn;
rlvl->numhprcs = (brprcxend - tlprcxstart) >>
rlvl->prcwidthexpn;
rlvl->numvprcs = (brprcyend - tlprcystart) >>
rlvl->prcheightexpn;
rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs;
if (rlvl->xstart >= rlvl->xend || rlvl->ystart >= rlvl->yend) {
rlvl->bands = 0;
rlvl->numprcs = 0;
rlvl->numhprcs = 0;
rlvl->numvprcs = 0;
continue;
}
if (!rlvlno) {
tlcbgxstart = tlprcxstart;
tlcbgystart = tlprcystart;
brcbgxend = brprcxend;
brcbgyend = brprcyend;
rlvl->cbgwidthexpn = rlvl->prcwidthexpn;
rlvl->cbgheightexpn = rlvl->prcheightexpn;
} else {
tlcbgxstart = JPC_CEILDIVPOW2(tlprcxstart, 1);
tlcbgystart = JPC_CEILDIVPOW2(tlprcystart, 1);
brcbgxend = JPC_CEILDIVPOW2(brprcxend, 1);
brcbgyend = JPC_CEILDIVPOW2(brprcyend, 1);
rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1;
rlvl->cbgheightexpn = rlvl->prcheightexpn - 1;
}
rlvl->cblkwidthexpn = JAS_MIN(ccp->cblkwidthexpn,
rlvl->cbgwidthexpn);
rlvl->cblkheightexpn = JAS_MIN(ccp->cblkheightexpn,
rlvl->cbgheightexpn);
rlvl->numbands = (!rlvlno) ? 1 : 3;
if (!(rlvl->bands = jas_alloc2(rlvl->numbands,
sizeof(jpc_dec_band_t)))) {
return -1;
}
for (bandno = 0, band = rlvl->bands;
bandno < rlvl->numbands; ++bandno, ++band) {
bndno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) +
bandno + 1);
bnd = &bnds[bndno];
band->orient = bnd->orient;
band->stepsize = ccp->stepsizes[bndno];
band->analgain = JPC_NOMINALGAIN(ccp->qmfbid,
tcomp->numrlvls - 1, rlvlno, band->orient);
band->absstepsize = jpc_calcabsstepsize(band->stepsize,
cmpt->prec + band->analgain);
band->numbps = ccp->numguardbits +
JPC_QCX_GETEXPN(band->stepsize) - 1;
band->roishift = (ccp->roishift + band->numbps >= JPC_PREC) ?
(JPC_PREC - 1 - band->numbps) : ccp->roishift;
band->data = 0;
band->prcs = 0;
if (bnd->xstart == bnd->xend || bnd->ystart == bnd->yend) {
continue;
}
if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) {
return -1;
}
jas_seq2d_bindsub(band->data, tcomp->data, bnd->locxstart,
bnd->locystart, bnd->locxend, bnd->locyend);
jas_seq2d_setshift(band->data, bnd->xstart, bnd->ystart);
assert(rlvl->numprcs);
if (!(band->prcs = jas_alloc2(rlvl->numprcs,
sizeof(jpc_dec_prc_t)))) {
return -1;
}
/************************************************/
cbgxstart = tlcbgxstart;
cbgystart = tlcbgystart;
for (prccnt = rlvl->numprcs, prc = band->prcs;
prccnt > 0; --prccnt, ++prc) {
cbgxend = cbgxstart + (1 << rlvl->cbgwidthexpn);
cbgyend = cbgystart + (1 << rlvl->cbgheightexpn);
prc->xstart = JAS_MAX(cbgxstart, JAS_CAST(uint_fast32_t,
jas_seq2d_xstart(band->data)));
prc->ystart = JAS_MAX(cbgystart, JAS_CAST(uint_fast32_t,
jas_seq2d_ystart(band->data)));
prc->xend = JAS_MIN(cbgxend, JAS_CAST(uint_fast32_t,
jas_seq2d_xend(band->data)));
prc->yend = JAS_MIN(cbgyend, JAS_CAST(uint_fast32_t,
jas_seq2d_yend(band->data)));
if (prc->xend > prc->xstart && prc->yend > prc->ystart) {
tlcblkxstart = JPC_FLOORDIVPOW2(prc->xstart,
rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn;
tlcblkystart = JPC_FLOORDIVPOW2(prc->ystart,
rlvl->cblkheightexpn) << rlvl->cblkheightexpn;
brcblkxend = JPC_CEILDIVPOW2(prc->xend,
rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn;
brcblkyend = JPC_CEILDIVPOW2(prc->yend,
rlvl->cblkheightexpn) << rlvl->cblkheightexpn;
prc->numhcblks = (brcblkxend - tlcblkxstart) >>
rlvl->cblkwidthexpn;
prc->numvcblks = (brcblkyend - tlcblkystart) >>
rlvl->cblkheightexpn;
prc->numcblks = prc->numhcblks * prc->numvcblks;
assert(prc->numcblks > 0);
if (!(prc->incltagtree = jpc_tagtree_create(
prc->numhcblks, prc->numvcblks))) {
return -1;
}
if (!(prc->numimsbstagtree = jpc_tagtree_create(
prc->numhcblks, prc->numvcblks))) {
return -1;
}
if (!(prc->cblks = jas_alloc2(prc->numcblks,
sizeof(jpc_dec_cblk_t)))) {
return -1;
}
cblkxstart = cbgxstart;
cblkystart = cbgystart;
for (cblkcnt = prc->numcblks, cblk = prc->cblks;
cblkcnt > 0;) {
cblkxend = cblkxstart + (1 << rlvl->cblkwidthexpn);
cblkyend = cblkystart + (1 << rlvl->cblkheightexpn);
tmpxstart = JAS_MAX(cblkxstart, prc->xstart);
tmpystart = JAS_MAX(cblkystart, prc->ystart);
tmpxend = JAS_MIN(cblkxend, prc->xend);
tmpyend = JAS_MIN(cblkyend, prc->yend);
if (tmpxend > tmpxstart && tmpyend > tmpystart) {
cblk->firstpassno = -1;
cblk->mqdec = 0;
cblk->nulldec = 0;
cblk->flags = 0;
cblk->numpasses = 0;
cblk->segs.head = 0;
cblk->segs.tail = 0;
cblk->curseg = 0;
cblk->numimsbs = 0;
cblk->numlenbits = 3;
cblk->flags = 0;
if (!(cblk->data = jas_seq2d_create(0, 0, 0,
0))) {
return -1;
}
jas_seq2d_bindsub(cblk->data, band->data,
tmpxstart, tmpystart, tmpxend, tmpyend);
++cblk;
--cblkcnt;
}
cblkxstart += 1 << rlvl->cblkwidthexpn;
if (cblkxstart >= cbgxend) {
cblkxstart = cbgxstart;
cblkystart += 1 << rlvl->cblkheightexpn;
}
}
} else {
prc->cblks = 0;
prc->incltagtree = 0;
prc->numimsbstagtree = 0;
}
cbgxstart += 1 << rlvl->cbgwidthexpn;
if (cbgxstart >= brcbgxend) {
cbgxstart = tlcbgxstart;
cbgystart += 1 << rlvl->cbgheightexpn;
}
}
/********************************************/
}
}
}
if (!(tile->pi = jpc_dec_pi_create(dec, tile))) {
return -1;
}
for (pchgno = 0; pchgno < jpc_pchglist_numpchgs(tile->cp->pchglist);
++pchgno) {
pchg = jpc_pchg_copy(jpc_pchglist_get(tile->cp->pchglist, pchgno));
assert(pchg);
jpc_pi_addpchg(tile->pi, pchg);
}
jpc_pi_init(tile->pi);
return 0;
}
static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile)
{
jpc_dec_tcomp_t *tcomp;
int compno;
int bandno;
int rlvlno;
jpc_dec_band_t *band;
jpc_dec_rlvl_t *rlvl;
int prcno;
jpc_dec_prc_t *prc;
jpc_dec_seg_t *seg;
jpc_dec_cblk_t *cblk;
int cblkno;
if (tile->tcomps) {
for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
++compno, ++tcomp) {
for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
++rlvlno, ++rlvl) {
if (!rlvl->bands) {
continue;
}
for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
++bandno, ++band) {
if (band->prcs) {
for (prcno = 0, prc = band->prcs; prcno <
rlvl->numprcs; ++prcno, ++prc) {
if (!prc->cblks) {
continue;
}
for (cblkno = 0, cblk = prc->cblks; cblkno <
prc->numcblks; ++cblkno, ++cblk) {
while (cblk->segs.head) {
seg = cblk->segs.head;
jpc_seglist_remove(&cblk->segs, seg);
jpc_seg_destroy(seg);
}
jas_matrix_destroy(cblk->data);
if (cblk->mqdec) {
jpc_mqdec_destroy(cblk->mqdec);
}
if (cblk->nulldec) {
jpc_bitstream_close(cblk->nulldec);
}
if (cblk->flags) {
jas_matrix_destroy(cblk->flags);
}
}
if (prc->incltagtree) {
jpc_tagtree_destroy(prc->incltagtree);
}
if (prc->numimsbstagtree) {
jpc_tagtree_destroy(prc->numimsbstagtree);
}
if (prc->cblks) {
jas_free(prc->cblks);
}
}
}
if (band->data) {
jas_matrix_destroy(band->data);
}
if (band->prcs) {
jas_free(band->prcs);
}
}
if (rlvl->bands) {
jas_free(rlvl->bands);
}
}
if (tcomp->rlvls) {
jas_free(tcomp->rlvls);
}
if (tcomp->data) {
jas_matrix_destroy(tcomp->data);
}
if (tcomp->tsfb) {
jpc_tsfb_destroy(tcomp->tsfb);
}
}
}
if (tile->cp) {
jpc_dec_cp_destroy(tile->cp);
//tile->cp = 0;
}
if (tile->tcomps) {
jas_free(tile->tcomps);
//tile->tcomps = 0;
}
if (tile->pi) {
jpc_pi_destroy(tile->pi);
//tile->pi = 0;
}
if (tile->pkthdrstream) {
jas_stream_close(tile->pkthdrstream);
//tile->pkthdrstream = 0;
}
if (tile->pptstab) {
jpc_ppxstab_destroy(tile->pptstab);
//tile->pptstab = 0;
}
tile->state = JPC_TILE_DONE;
return 0;
}
static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile)
{
int i;
int j;
jpc_dec_tcomp_t *tcomp;
jpc_dec_rlvl_t *rlvl;
jpc_dec_band_t *band;
int compno;
int rlvlno;
int bandno;
int adjust;
int v;
jpc_dec_ccp_t *ccp;
jpc_dec_cmpt_t *cmpt;
if (jpc_dec_decodecblks(dec, tile)) {
jas_eprintf("jpc_dec_decodecblks failed\n");
return -1;
}
/* Perform dequantization. */
for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
++compno, ++tcomp) {
ccp = &tile->cp->ccps[compno];
for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
++rlvlno, ++rlvl) {
if (!rlvl->bands) {
continue;
}
for (bandno = 0, band = rlvl->bands;
bandno < rlvl->numbands; ++bandno, ++band) {
if (!band->data) {
continue;
}
jpc_undo_roi(band->data, band->roishift, ccp->roishift -
band->roishift, band->numbps);
if (tile->realmode) {
jas_matrix_asl(band->data, JPC_FIX_FRACBITS);
jpc_dequantize(band->data, band->absstepsize);
}
}
}
}
/* Apply an inverse wavelet transform if necessary. */
for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
++compno, ++tcomp) {
ccp = &tile->cp->ccps[compno];
jpc_tsfb_synthesize(tcomp->tsfb, tcomp->data);
}
/* Apply an inverse intercomponent transform if necessary. */
switch (tile->cp->mctid) {
case JPC_MCT_RCT:
if (dec->numcomps < 3) {
jas_eprintf("RCT requires at least three components\n");
return -1;
}
if (!jas_image_cmpt_domains_same(dec->image)) {
jas_eprintf("RCT requires all components have the same domain\n");
return -1;
}
jpc_irct(tile->tcomps[0].data, tile->tcomps[1].data,
tile->tcomps[2].data);
break;
case JPC_MCT_ICT:
if (dec->numcomps < 3) {
jas_eprintf("ICT requires at least three components\n");
return -1;
}
if (!jas_image_cmpt_domains_same(dec->image)) {
jas_eprintf("RCT requires all components have the same domain\n");
return -1;
}
jpc_iict(tile->tcomps[0].data, tile->tcomps[1].data,
tile->tcomps[2].data);
break;
}
/* Perform rounding and convert to integer values. */
if (tile->realmode) {
for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
++compno, ++tcomp) {
for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) {
for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) {
v = jas_matrix_get(tcomp->data, i, j);
v = jpc_fix_round(v);
jas_matrix_set(tcomp->data, i, j, jpc_fixtoint(v));
}
}
}
}
/* Perform level shift. */
for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
dec->numcomps; ++compno, ++tcomp, ++cmpt) {
adjust = cmpt->sgnd ? 0 : (1 << (cmpt->prec - 1));
for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) {
for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) {
*jas_matrix_getref(tcomp->data, i, j) += adjust;
}
}
}
/* Perform clipping. */
for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
dec->numcomps; ++compno, ++tcomp, ++cmpt) {
jpc_fix_t mn;
jpc_fix_t mx;
mn = cmpt->sgnd ? (-(1 << (cmpt->prec - 1))) : (0);
mx = cmpt->sgnd ? ((1 << (cmpt->prec - 1)) - 1) : ((1 <<
cmpt->prec) - 1);
jas_matrix_clip(tcomp->data, mn, mx);
}
/* XXX need to free tsfb struct */
/* Write the data for each component of the image. */
for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
dec->numcomps; ++compno, ++tcomp, ++cmpt) {
if (jas_image_writecmpt(dec->image, compno, tcomp->xstart -
JPC_CEILDIV(dec->xstart, cmpt->hstep), tcomp->ystart -
JPC_CEILDIV(dec->ystart, cmpt->vstep), jas_matrix_numcols(
tcomp->data), jas_matrix_numrows(tcomp->data), tcomp->data)) {
jas_eprintf("write component failed\n");
return -1;
}
}
return 0;
}
static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms)
{
int tileno;
jpc_dec_tile_t *tile;
/* Eliminate compiler warnings about unused variables. */
ms = 0;
for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
++tile) {
if (tile->state == JPC_TILE_ACTIVE) {
if (jpc_dec_tiledecode(dec, tile)) {
return -1;
}
}
/* If the tile has not yet been finalized, finalize it. */
// OLD CODE: jpc_dec_tilefini(dec, tile);
if (tile->state != JPC_TILE_DONE) {
jpc_dec_tilefini(dec, tile);
}
}
/* We are done processing the code stream. */
dec->state = JPC_MT;
return 1;
}
static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_siz_t *siz = &ms->parms.siz;
int compno;
int tileno;
jpc_dec_tile_t *tile;
jpc_dec_tcomp_t *tcomp;
int htileno;
int vtileno;
jpc_dec_cmpt_t *cmpt;
size_t size;
dec->xstart = siz->xoff;
dec->ystart = siz->yoff;
dec->xend = siz->width;
dec->yend = siz->height;
dec->tilewidth = siz->tilewidth;
dec->tileheight = siz->tileheight;
dec->tilexoff = siz->tilexoff;
dec->tileyoff = siz->tileyoff;
dec->numcomps = siz->numcomps;
if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {
return -1;
}
if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,
++cmpt) {
cmpt->prec = siz->comps[compno].prec;
cmpt->sgnd = siz->comps[compno].sgnd;
cmpt->hstep = siz->comps[compno].hsamp;
cmpt->vstep = siz->comps[compno].vsamp;
cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -
JPC_CEILDIV(dec->xstart, cmpt->hstep);
cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -
JPC_CEILDIV(dec->ystart, cmpt->vstep);
cmpt->hsubstep = 0;
cmpt->vsubstep = 0;
}
dec->image = 0;
dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);
dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);
if (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size)) {
return -1;
}
dec->numtiles = size;
JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n",
dec->numtiles, dec->numhtiles, dec->numvtiles));
if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {
return -1;
}
for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
++tile) {
htileno = tileno % dec->numhtiles;
vtileno = tileno / dec->numhtiles;
tile->realmode = 0;
tile->state = JPC_TILE_INIT;
tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,
dec->xstart);
tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,
dec->ystart);
tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *
dec->tilewidth, dec->xend);
tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *
dec->tileheight, dec->yend);
tile->numparts = 0;
tile->partno = 0;
tile->pkthdrstream = 0;
tile->pkthdrstreampos = 0;
tile->pptstab = 0;
tile->cp = 0;
tile->pi = 0;
if (!(tile->tcomps = jas_alloc2(dec->numcomps,
sizeof(jpc_dec_tcomp_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;
compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {
tcomp->rlvls = 0;
tcomp->numrlvls = 0;
tcomp->data = 0;
tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);
tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);
tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);
tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);
tcomp->tsfb = 0;
}
}
dec->pkthdrstreams = 0;
/* We should expect to encounter other main header marker segments
or an SOT marker segment next. */
dec->state = JPC_MH;
return 0;
}
static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_cod_t *cod = &ms->parms.cod;
jpc_dec_tile_t *tile;
switch (dec->state) {
case JPC_MH:
jpc_dec_cp_setfromcod(dec->cp, cod);
break;
case JPC_TPH:
if (!(tile = dec->curtile)) {
return -1;
}
if (tile->partno != 0) {
return -1;
}
jpc_dec_cp_setfromcod(tile->cp, cod);
break;
}
return 0;
}
static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_coc_t *coc = &ms->parms.coc;
jpc_dec_tile_t *tile;
if (JAS_CAST(int, coc->compno) >= dec->numcomps) {
jas_eprintf("invalid component number in COC marker segment\n");
return -1;
}
switch (dec->state) {
case JPC_MH:
jpc_dec_cp_setfromcoc(dec->cp, coc);
break;
case JPC_TPH:
if (!(tile = dec->curtile)) {
return -1;
}
if (tile->partno > 0) {
return -1;
}
jpc_dec_cp_setfromcoc(tile->cp, coc);
break;
}
return 0;
}
static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_rgn_t *rgn = &ms->parms.rgn;
jpc_dec_tile_t *tile;
if (JAS_CAST(int, rgn->compno) >= dec->numcomps) {
jas_eprintf("invalid component number in RGN marker segment\n");
return -1;
}
switch (dec->state) {
case JPC_MH:
jpc_dec_cp_setfromrgn(dec->cp, rgn);
break;
case JPC_TPH:
if (!(tile = dec->curtile)) {
return -1;
}
if (tile->partno > 0) {
return -1;
}
jpc_dec_cp_setfromrgn(tile->cp, rgn);
break;
}
return 0;
}
static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_qcd_t *qcd = &ms->parms.qcd;
jpc_dec_tile_t *tile;
switch (dec->state) {
case JPC_MH:
jpc_dec_cp_setfromqcd(dec->cp, qcd);
break;
case JPC_TPH:
if (!(tile = dec->curtile)) {
return -1;
}
if (tile->partno > 0) {
return -1;
}
jpc_dec_cp_setfromqcd(tile->cp, qcd);
break;
}
return 0;
}
static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_qcc_t *qcc = &ms->parms.qcc;
jpc_dec_tile_t *tile;
if (JAS_CAST(int, qcc->compno) >= dec->numcomps) {
jas_eprintf("invalid component number in QCC marker segment\n");
return -1;
}
switch (dec->state) {
case JPC_MH:
jpc_dec_cp_setfromqcc(dec->cp, qcc);
break;
case JPC_TPH:
if (!(tile = dec->curtile)) {
return -1;
}
if (tile->partno > 0) {
return -1;
}
jpc_dec_cp_setfromqcc(tile->cp, qcc);
break;
}
return 0;
}
static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_poc_t *poc = &ms->parms.poc;
jpc_dec_tile_t *tile;
switch (dec->state) {
case JPC_MH:
if (jpc_dec_cp_setfrompoc(dec->cp, poc, 1)) {
return -1;
}
break;
case JPC_TPH:
if (!(tile = dec->curtile)) {
return -1;
}
if (!tile->partno) {
if (jpc_dec_cp_setfrompoc(tile->cp, poc, (!tile->partno))) {
return -1;
}
} else {
jpc_pi_addpchgfrompoc(tile->pi, poc);
}
break;
}
return 0;
}
static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_ppm_t *ppm = &ms->parms.ppm;
jpc_ppxstabent_t *ppmstabent;
if (!dec->ppmstab) {
if (!(dec->ppmstab = jpc_ppxstab_create())) {
return -1;
}
}
if (!(ppmstabent = jpc_ppxstabent_create())) {
return -1;
}
ppmstabent->ind = ppm->ind;
ppmstabent->data = ppm->data;
ppm->data = 0;
ppmstabent->len = ppm->len;
if (jpc_ppxstab_insert(dec->ppmstab, ppmstabent)) {
return -1;
}
return 0;
}
static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_ppt_t *ppt = &ms->parms.ppt;
jpc_dec_tile_t *tile;
jpc_ppxstabent_t *pptstabent;
tile = dec->curtile;
if (!tile->pptstab) {
if (!(tile->pptstab = jpc_ppxstab_create())) {
return -1;
}
}
if (!(pptstabent = jpc_ppxstabent_create())) {
return -1;
}
pptstabent->ind = ppt->ind;
pptstabent->data = ppt->data;
ppt->data = 0;
pptstabent->len = ppt->len;
if (jpc_ppxstab_insert(tile->pptstab, pptstabent)) {
return -1;
}
return 0;
}
static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms)
{
/* Eliminate compiler warnings about unused variables. */
dec = 0;
ms = 0;
return 0;
}
static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms)
{
/* Eliminate compiler warnings about unused variables. */
dec = 0;
jas_eprintf("warning: ignoring unknown marker segment\n");
jpc_ms_dump(ms, stderr);
return 0;
}
/******************************************************************************\
*
\******************************************************************************/
static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps)
{
jpc_dec_cp_t *cp;
jpc_dec_ccp_t *ccp;
int compno;
if (!(cp = jas_malloc(sizeof(jpc_dec_cp_t)))) {
return 0;
}
cp->flags = 0;
cp->numcomps = numcomps;
cp->prgord = 0;
cp->numlyrs = 0;
cp->mctid = 0;
cp->csty = 0;
if (!(cp->ccps = jas_alloc2(cp->numcomps, sizeof(jpc_dec_ccp_t)))) {
goto error;
}
if (!(cp->pchglist = jpc_pchglist_create())) {
goto error;
}
for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
++compno, ++ccp) {
ccp->flags = 0;
ccp->numrlvls = 0;
ccp->cblkwidthexpn = 0;
ccp->cblkheightexpn = 0;
ccp->qmfbid = 0;
ccp->numstepsizes = 0;
ccp->numguardbits = 0;
ccp->roishift = 0;
ccp->cblkctx = 0;
}
return cp;
error:
if (cp) {
jpc_dec_cp_destroy(cp);
}
return 0;
}
static jpc_dec_cp_t *jpc_dec_cp_copy(jpc_dec_cp_t *cp)
{
jpc_dec_cp_t *newcp;
jpc_dec_ccp_t *newccp;
jpc_dec_ccp_t *ccp;
int compno;
if (!(newcp = jpc_dec_cp_create(cp->numcomps))) {
return 0;
}
newcp->flags = cp->flags;
newcp->prgord = cp->prgord;
newcp->numlyrs = cp->numlyrs;
newcp->mctid = cp->mctid;
newcp->csty = cp->csty;
jpc_pchglist_destroy(newcp->pchglist);
newcp->pchglist = 0;
if (!(newcp->pchglist = jpc_pchglist_copy(cp->pchglist))) {
jas_free(newcp);
return 0;
}
for (compno = 0, newccp = newcp->ccps, ccp = cp->ccps;
compno < cp->numcomps;
++compno, ++newccp, ++ccp) {
*newccp = *ccp;
}
return newcp;
}
static void jpc_dec_cp_resetflags(jpc_dec_cp_t *cp)
{
int compno;
jpc_dec_ccp_t *ccp;
cp->flags &= (JPC_CSET | JPC_QSET);
for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
++compno, ++ccp) {
ccp->flags = 0;
}
}
static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp)
{
if (cp->ccps) {
jas_free(cp->ccps);
}
if (cp->pchglist) {
jpc_pchglist_destroy(cp->pchglist);
}
jas_free(cp);
}
static int jpc_dec_cp_isvalid(jpc_dec_cp_t *cp)
{
uint_fast16_t compcnt;
jpc_dec_ccp_t *ccp;
if (!(cp->flags & JPC_CSET) || !(cp->flags & JPC_QSET)) {
return 0;
}
for (compcnt = cp->numcomps, ccp = cp->ccps; compcnt > 0; --compcnt,
++ccp) {
/* Is there enough step sizes for the number of bands? */
if ((ccp->qsty != JPC_QCX_SIQNT && JAS_CAST(int, ccp->numstepsizes) < 3 *
ccp->numrlvls - 2) || (ccp->qsty == JPC_QCX_SIQNT &&
ccp->numstepsizes != 1)) {
return 0;
}
}
return 1;
}
static void calcstepsizes(uint_fast16_t refstepsize, int numrlvls,
uint_fast16_t *stepsizes)
{
int bandno;
int numbands;
uint_fast16_t expn;
uint_fast16_t mant;
expn = JPC_QCX_GETEXPN(refstepsize);
mant = JPC_QCX_GETMANT(refstepsize);
numbands = 3 * numrlvls - 2;
for (bandno = 0; bandno < numbands; ++bandno) {
//jas_eprintf("DEBUG %d %d %d %d %d\n", bandno, expn, numrlvls, bandno, ((numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))));
stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn +
(numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0))));
}
}
static int jpc_dec_cp_prepare(jpc_dec_cp_t *cp)
{
jpc_dec_ccp_t *ccp;
int compno;
int i;
for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
++compno, ++ccp) {
if (!(ccp->csty & JPC_COX_PRT)) {
for (i = 0; i < JPC_MAXRLVLS; ++i) {
ccp->prcwidthexpns[i] = 15;
ccp->prcheightexpns[i] = 15;
}
}
if (ccp->qsty == JPC_QCX_SIQNT) {
calcstepsizes(ccp->stepsizes[0], ccp->numrlvls, ccp->stepsizes);
}
}
return 0;
}
static int jpc_dec_cp_setfromcod(jpc_dec_cp_t *cp, jpc_cod_t *cod)
{
jpc_dec_ccp_t *ccp;
int compno;
cp->flags |= JPC_CSET;
cp->prgord = cod->prg;
if (cod->mctrans) {
cp->mctid = (cod->compparms.qmfbid == JPC_COX_INS) ? (JPC_MCT_ICT) : (JPC_MCT_RCT);
} else {
cp->mctid = JPC_MCT_NONE;
}
cp->numlyrs = cod->numlyrs;
cp->csty = cod->csty & (JPC_COD_SOP | JPC_COD_EPH);
for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
++compno, ++ccp) {
jpc_dec_cp_setfromcox(cp, ccp, &cod->compparms, 0);
}
cp->flags |= JPC_CSET;
return 0;
}
static int jpc_dec_cp_setfromcoc(jpc_dec_cp_t *cp, jpc_coc_t *coc)
{
jpc_dec_cp_setfromcox(cp, &cp->ccps[coc->compno], &coc->compparms, JPC_COC);
return 0;
}
static int jpc_dec_cp_setfromcox(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp,
jpc_coxcp_t *compparms, int flags)
{
int rlvlno;
/* Eliminate compiler warnings about unused variables. */
cp = 0;
if ((flags & JPC_COC) || !(ccp->flags & JPC_COC)) {
ccp->numrlvls = compparms->numdlvls + 1;
ccp->cblkwidthexpn = JPC_COX_GETCBLKSIZEEXPN(
compparms->cblkwidthval);
ccp->cblkheightexpn = JPC_COX_GETCBLKSIZEEXPN(
compparms->cblkheightval);
ccp->qmfbid = compparms->qmfbid;
ccp->cblkctx = compparms->cblksty;
ccp->csty = compparms->csty & JPC_COX_PRT;
for (rlvlno = 0; rlvlno < compparms->numrlvls; ++rlvlno) {
ccp->prcwidthexpns[rlvlno] =
compparms->rlvls[rlvlno].parwidthval;
ccp->prcheightexpns[rlvlno] =
compparms->rlvls[rlvlno].parheightval;
}
ccp->flags |= flags | JPC_CSET;
}
return 0;
}
static int jpc_dec_cp_setfromqcd(jpc_dec_cp_t *cp, jpc_qcd_t *qcd)
{
int compno;
jpc_dec_ccp_t *ccp;
for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
++compno, ++ccp) {
jpc_dec_cp_setfromqcx(cp, ccp, &qcd->compparms, 0);
}
cp->flags |= JPC_QSET;
return 0;
}
static int jpc_dec_cp_setfromqcc(jpc_dec_cp_t *cp, jpc_qcc_t *qcc)
{
return jpc_dec_cp_setfromqcx(cp, &cp->ccps[qcc->compno], &qcc->compparms, JPC_QCC);
}
static int jpc_dec_cp_setfromqcx(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp,
jpc_qcxcp_t *compparms, int flags)
{
int bandno;
/* Eliminate compiler warnings about unused variables. */
cp = 0;
if ((flags & JPC_QCC) || !(ccp->flags & JPC_QCC)) {
ccp->flags |= flags | JPC_QSET;
for (bandno = 0; bandno < compparms->numstepsizes; ++bandno) {
ccp->stepsizes[bandno] = compparms->stepsizes[bandno];
}
ccp->numstepsizes = compparms->numstepsizes;
ccp->numguardbits = compparms->numguard;
ccp->qsty = compparms->qntsty;
}
return 0;
}
static int jpc_dec_cp_setfromrgn(jpc_dec_cp_t *cp, jpc_rgn_t *rgn)
{
jpc_dec_ccp_t *ccp;
ccp = &cp->ccps[rgn->compno];
ccp->roishift = rgn->roishift;
return 0;
}
static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, jpc_poc_t *poc)
{
int pchgno;
jpc_pchg_t *pchg;
for (pchgno = 0; pchgno < poc->numpchgs; ++pchgno) {
if (!(pchg = jpc_pchg_copy(&poc->pchgs[pchgno]))) {
return -1;
}
if (jpc_pchglist_insert(pi->pchglist, -1, pchg)) {
return -1;
}
}
return 0;
}
static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, jpc_poc_t *poc, int reset)
{
int pchgno;
jpc_pchg_t *pchg;
if (reset) {
while (jpc_pchglist_numpchgs(cp->pchglist) > 0) {
pchg = jpc_pchglist_remove(cp->pchglist, 0);
jpc_pchg_destroy(pchg);
}
}
for (pchgno = 0; pchgno < poc->numpchgs; ++pchgno) {
if (!(pchg = jpc_pchg_copy(&poc->pchgs[pchgno]))) {
return -1;
}
if (jpc_pchglist_insert(cp->pchglist, -1, pchg)) {
return -1;
}
}
return 0;
}
static jpc_fix_t jpc_calcabsstepsize(int stepsize, int numbits)
{
jpc_fix_t absstepsize;
int n;
absstepsize = jpc_inttofix(1);
n = JPC_FIX_FRACBITS - 11;
absstepsize |= (n >= 0) ? (JPC_QCX_GETMANT(stepsize) << n) :
(JPC_QCX_GETMANT(stepsize) >> (-n));
n = numbits - JPC_QCX_GETEXPN(stepsize);
absstepsize = (n >= 0) ? (absstepsize << n) : (absstepsize >> (-n));
return absstepsize;
}
static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize)
{
int i;
int j;
int t;
assert(absstepsize >= 0);
if (absstepsize == jpc_inttofix(1)) {
return;
}
for (i = 0; i < jas_matrix_numrows(x); ++i) {
for (j = 0; j < jas_matrix_numcols(x); ++j) {
t = jas_matrix_get(x, i, j);
if (t) {
t = jpc_fix_mul(t, absstepsize);
} else {
t = 0;
}
jas_matrix_set(x, i, j, t);
}
}
}
static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps)
{
int i;
int j;
int thresh;
jpc_fix_t val;
jpc_fix_t mag;
bool warn;
uint_fast32_t mask;
if (roishift < 0) {
/* We could instead return an error here. */
/* I do not think it matters much. */
jas_eprintf("warning: forcing negative ROI shift to zero "
"(bitstream is probably corrupt)\n");
roishift = 0;
}
if (roishift == 0 && bgshift == 0) {
return;
}
thresh = 1 << roishift;
warn = false;
for (i = 0; i < jas_matrix_numrows(x); ++i) {
for (j = 0; j < jas_matrix_numcols(x); ++j) {
val = jas_matrix_get(x, i, j);
mag = JAS_ABS(val);
if (mag >= thresh) {
/* We are dealing with ROI data. */
mag >>= roishift;
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
} else {
/* We are dealing with non-ROI (i.e., background) data. */
mag <<= bgshift;
mask = (JAS_CAST(uint_fast32_t, 1) << numbps) - 1;
/* Perform a basic sanity check on the sample value. */
/* Some implementations write garbage in the unused
most-significant bit planes introduced by ROI shifting.
Here we ensure that any such bits are masked off. */
if (mag & (~mask)) {
if (!warn) {
jas_eprintf("warning: possibly corrupt code stream\n");
warn = true;
}
mag &= mask;
}
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
}
}
}
}
static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in)
{
jpc_dec_t *dec;
if (!(dec = jas_malloc(sizeof(jpc_dec_t)))) {
return 0;
}
dec->image = 0;
dec->xstart = 0;
dec->ystart = 0;
dec->xend = 0;
dec->yend = 0;
dec->tilewidth = 0;
dec->tileheight = 0;
dec->tilexoff = 0;
dec->tileyoff = 0;
dec->numhtiles = 0;
dec->numvtiles = 0;
dec->numtiles = 0;
dec->tiles = 0;
dec->curtile = 0;
dec->numcomps = 0;
dec->in = in;
dec->cp = 0;
dec->maxlyrs = impopts->maxlyrs;
dec->maxpkts = impopts->maxpkts;
dec->numpkts = 0;
dec->ppmseqno = 0;
dec->state = 0;
dec->cmpts = 0;
dec->pkthdrstreams = 0;
dec->ppmstab = 0;
dec->curtileendoff = 0;
return dec;
}
static void jpc_dec_destroy(jpc_dec_t *dec)
{
if (dec->cstate) {
jpc_cstate_destroy(dec->cstate);
}
if (dec->pkthdrstreams) {
jpc_streamlist_destroy(dec->pkthdrstreams);
}
if (dec->image) {
jas_image_destroy(dec->image);
}
if (dec->cp) {
jpc_dec_cp_destroy(dec->cp);
}
if (dec->cmpts) {
jas_free(dec->cmpts);
}
if (dec->tiles) {
jas_free(dec->tiles);
}
jas_free(dec);
}
/******************************************************************************\
*
\******************************************************************************/
void jpc_seglist_insert(jpc_dec_seglist_t *list, jpc_dec_seg_t *ins, jpc_dec_seg_t *node)
{
jpc_dec_seg_t *prev;
jpc_dec_seg_t *next;
prev = ins;
node->prev = prev;
next = prev ? (prev->next) : 0;
node->prev = prev;
node->next = next;
if (prev) {
prev->next = node;
} else {
list->head = node;
}
if (next) {
next->prev = node;
} else {
list->tail = node;
}
}
void jpc_seglist_remove(jpc_dec_seglist_t *list, jpc_dec_seg_t *seg)
{
jpc_dec_seg_t *prev;
jpc_dec_seg_t *next;
prev = seg->prev;
next = seg->next;
if (prev) {
prev->next = next;
} else {
list->head = next;
}
if (next) {
next->prev = prev;
} else {
list->tail = prev;
}
seg->prev = 0;
seg->next = 0;
}
jpc_dec_seg_t *jpc_seg_alloc()
{
jpc_dec_seg_t *seg;
if (!(seg = jas_malloc(sizeof(jpc_dec_seg_t)))) {
return 0;
}
seg->prev = 0;
seg->next = 0;
seg->passno = -1;
seg->numpasses = 0;
seg->maxpasses = 0;
seg->type = JPC_SEG_INVALID;
seg->stream = 0;
seg->cnt = 0;
seg->complete = 0;
seg->lyrno = -1;
return seg;
}
void jpc_seg_destroy(jpc_dec_seg_t *seg)
{
if (seg->stream) {
jas_stream_close(seg->stream);
}
jas_free(seg);
}
static int jpc_dec_dump(jpc_dec_t *dec, FILE *out)
{
jpc_dec_tile_t *tile;
int tileno;
jpc_dec_tcomp_t *tcomp;
int compno;
jpc_dec_rlvl_t *rlvl;
int rlvlno;
jpc_dec_band_t *band;
int bandno;
jpc_dec_prc_t *prc;
int prcno;
jpc_dec_cblk_t *cblk;
int cblkno;
assert(!dec->numtiles || dec->tiles);
for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles;
++tileno, ++tile) {
assert(!dec->numcomps || tile->tcomps);
for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
++compno, ++tcomp) {
for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno <
tcomp->numrlvls; ++rlvlno, ++rlvl) {
fprintf(out, "RESOLUTION LEVEL %d\n", rlvlno);
fprintf(out, "xs = %"PRIuFAST32", ys = %"PRIuFAST32", xe = %"PRIuFAST32", ye = %"PRIuFAST32", w = %"PRIuFAST32", h = %"PRIuFAST32"\n",
rlvl->xstart, rlvl->ystart, rlvl->xend, rlvl->yend,
rlvl->xend - rlvl->xstart, rlvl->yend - rlvl->ystart);
assert(!rlvl->numbands || rlvl->bands);
for (bandno = 0, band = rlvl->bands;
bandno < rlvl->numbands; ++bandno, ++band) {
fprintf(out, "BAND %d\n", bandno);
if (!band->data) {
fprintf(out, "band has no data (null pointer)\n");
assert(!band->prcs);
continue;
}
fprintf(out, "xs = %"PRIiFAST32", ys = %"PRIiFAST32", xe = %"PRIiFAST32", ye = %"PRIiFAST32", w = %"PRIiFAST32", h = %"PRIiFAST32"\n",
jas_seq2d_xstart(band->data),
jas_seq2d_ystart(band->data),
jas_seq2d_xend(band->data),
jas_seq2d_yend(band->data),
jas_seq2d_xend(band->data) -
jas_seq2d_xstart(band->data),
jas_seq2d_yend(band->data) -
jas_seq2d_ystart(band->data));
assert(!rlvl->numprcs || band->prcs);
for (prcno = 0, prc = band->prcs;
prcno < rlvl->numprcs; ++prcno,
++prc) {
fprintf(out, "CODE BLOCK GROUP %d\n", prcno);
fprintf(out, "xs = %"PRIuFAST32", ys = %"PRIuFAST32", xe = %"PRIuFAST32", ye = %"PRIuFAST32", w = %"PRIuFAST32", h = %"PRIuFAST32"\n",
prc->xstart, prc->ystart, prc->xend, prc->yend,
prc->xend - prc->xstart, prc->yend - prc->ystart);
assert(!prc->numcblks || prc->cblks);
for (cblkno = 0, cblk =
prc->cblks; cblkno <
prc->numcblks; ++cblkno,
++cblk) {
fprintf(out, "CODE BLOCK %d\n", cblkno);
fprintf(out, "xs = %"PRIiFAST32", ys = %"PRIiFAST32", xe = %"PRIiFAST32", ye = %"PRIiFAST32", w = %"PRIiFAST32", h = %"PRIiFAST32"\n",
jas_seq2d_xstart(cblk->data),
jas_seq2d_ystart(cblk->data),
jas_seq2d_xend(cblk->data),
jas_seq2d_yend(cblk->data),
jas_seq2d_xend(cblk->data) -
jas_seq2d_xstart(cblk->data),
jas_seq2d_yend(cblk->data) -
jas_seq2d_ystart(cblk->data));
}
}
}
}
}
}
return 0;
}
jpc_streamlist_t *jpc_streamlist_create()
{
jpc_streamlist_t *streamlist;
int i;
if (!(streamlist = jas_malloc(sizeof(jpc_streamlist_t)))) {
return 0;
}
streamlist->numstreams = 0;
streamlist->maxstreams = 100;
if (!(streamlist->streams = jas_alloc2(streamlist->maxstreams,
sizeof(jas_stream_t *)))) {
jas_free(streamlist);
return 0;
}
for (i = 0; i < streamlist->maxstreams; ++i) {
streamlist->streams[i] = 0;
}
return streamlist;
}
int jpc_streamlist_insert(jpc_streamlist_t *streamlist, int streamno,
jas_stream_t *stream)
{
jas_stream_t **newstreams;
int newmaxstreams;
int i;
/* Grow the array of streams if necessary. */
if (streamlist->numstreams >= streamlist->maxstreams) {
newmaxstreams = streamlist->maxstreams + 1024;
if (!(newstreams = jas_realloc2(streamlist->streams,
(newmaxstreams + 1024), sizeof(jas_stream_t *)))) {
return -1;
}
for (i = streamlist->numstreams; i < streamlist->maxstreams; ++i) {
streamlist->streams[i] = 0;
}
streamlist->maxstreams = newmaxstreams;
streamlist->streams = newstreams;
}
if (streamno != streamlist->numstreams) {
/* Can only handle insertion at start of list. */
return -1;
}
streamlist->streams[streamno] = stream;
++streamlist->numstreams;
return 0;
}
jas_stream_t *jpc_streamlist_remove(jpc_streamlist_t *streamlist, int streamno)
{
jas_stream_t *stream;
int i;
if (streamno >= streamlist->numstreams) {
abort();
}
stream = streamlist->streams[streamno];
for (i = streamno + 1; i < streamlist->numstreams; ++i) {
streamlist->streams[i - 1] = streamlist->streams[i];
}
--streamlist->numstreams;
return stream;
}
void jpc_streamlist_destroy(jpc_streamlist_t *streamlist)
{
int streamno;
if (streamlist->streams) {
for (streamno = 0; streamno < streamlist->numstreams;
++streamno) {
jas_stream_close(streamlist->streams[streamno]);
}
jas_free(streamlist->streams);
}
jas_free(streamlist);
}
jas_stream_t *jpc_streamlist_get(jpc_streamlist_t *streamlist, int streamno)
{
assert(streamno < streamlist->numstreams);
return streamlist->streams[streamno];
}
int jpc_streamlist_numstreams(jpc_streamlist_t *streamlist)
{
return streamlist->numstreams;
}
jpc_ppxstab_t *jpc_ppxstab_create()
{
jpc_ppxstab_t *tab;
if (!(tab = jas_malloc(sizeof(jpc_ppxstab_t)))) {
return 0;
}
tab->numents = 0;
tab->maxents = 0;
tab->ents = 0;
return tab;
}
void jpc_ppxstab_destroy(jpc_ppxstab_t *tab)
{
int i;
for (i = 0; i < tab->numents; ++i) {
jpc_ppxstabent_destroy(tab->ents[i]);
}
if (tab->ents) {
jas_free(tab->ents);
}
jas_free(tab);
}
int jpc_ppxstab_grow(jpc_ppxstab_t *tab, int maxents)
{
jpc_ppxstabent_t **newents;
if (tab->maxents < maxents) {
newents = (tab->ents) ? jas_realloc2(tab->ents, maxents,
sizeof(jpc_ppxstabent_t *)) : jas_alloc2(maxents, sizeof(jpc_ppxstabent_t *));
if (!newents) {
return -1;
}
tab->ents = newents;
tab->maxents = maxents;
}
return 0;
}
int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent)
{
int inspt;
int i;
for (i = 0; i < tab->numents; ++i) {
if (tab->ents[i]->ind > ent->ind) {
break;
}
}
inspt = i;
if (tab->numents >= tab->maxents) {
if (jpc_ppxstab_grow(tab, tab->maxents + 128)) {
return -1;
}
}
for (i = tab->numents; i > inspt; --i) {
tab->ents[i] = tab->ents[i - 1];
}
tab->ents[i] = ent;
++tab->numents;
return 0;
}
jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab)
{
jpc_streamlist_t *streams;
uchar *dataptr;
uint_fast32_t datacnt;
uint_fast32_t tpcnt;
jpc_ppxstabent_t *ent;
int entno;
jas_stream_t *stream;
int n;
if (!(streams = jpc_streamlist_create())) {
goto error;
}
if (!tab->numents) {
return streams;
}
entno = 0;
ent = tab->ents[entno];
dataptr = ent->data;
datacnt = ent->len;
for (;;) {
/* Get the length of the packet header data for the current
tile-part. */
if (datacnt < 4) {
goto error;
}
if (!(stream = jas_stream_memopen(0, 0))) {
goto error;
}
if (jpc_streamlist_insert(streams, jpc_streamlist_numstreams(streams),
stream)) {
goto error;
}
tpcnt = (dataptr[0] << 24) | (dataptr[1] << 16) | (dataptr[2] << 8)
| dataptr[3];
datacnt -= 4;
dataptr += 4;
/* Get the packet header data for the current tile-part. */
while (tpcnt) {
if (!datacnt) {
if (++entno >= tab->numents) {
goto error;
}
ent = tab->ents[entno];
dataptr = ent->data;
datacnt = ent->len;
}
n = JAS_MIN(tpcnt, datacnt);
if (jas_stream_write(stream, dataptr, n) != n) {
goto error;
}
tpcnt -= n;
dataptr += n;
datacnt -= n;
}
jas_stream_rewind(stream);
if (!datacnt) {
if (++entno >= tab->numents) {
break;
}
ent = tab->ents[entno];
dataptr = ent->data;
datacnt = ent->len;
}
}
return streams;
error:
if (streams) {
jpc_streamlist_destroy(streams);
}
return 0;
}
int jpc_pptstabwrite(jas_stream_t *out, jpc_ppxstab_t *tab)
{
int i;
jpc_ppxstabent_t *ent;
for (i = 0; i < tab->numents; ++i) {
ent = tab->ents[i];
if (jas_stream_write(out, ent->data, ent->len) != JAS_CAST(int, ent->len)) {
return -1;
}
}
return 0;
}
jpc_ppxstabent_t *jpc_ppxstabent_create()
{
jpc_ppxstabent_t *ent;
if (!(ent = jas_malloc(sizeof(jpc_ppxstabent_t)))) {
return 0;
}
ent->data = 0;
ent->len = 0;
ent->ind = 0;
return ent;
}
void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent)
{
if (ent->data) {
jas_free(ent->data);
}
jas_free(ent);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5415_1 |
crossvul-cpp_data_good_1763_0 | /* Key garbage collector
*
* Copyright (C) 2009-2011 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/security.h>
#include <keys/keyring-type.h>
#include "internal.h"
/*
* Delay between key revocation/expiry in seconds
*/
unsigned key_gc_delay = 5 * 60;
/*
* Reaper for unused keys.
*/
static void key_garbage_collector(struct work_struct *work);
DECLARE_WORK(key_gc_work, key_garbage_collector);
/*
* Reaper for links from keyrings to dead keys.
*/
static void key_gc_timer_func(unsigned long);
static DEFINE_TIMER(key_gc_timer, key_gc_timer_func, 0, 0);
static time_t key_gc_next_run = LONG_MAX;
static struct key_type *key_gc_dead_keytype;
static unsigned long key_gc_flags;
#define KEY_GC_KEY_EXPIRED 0 /* A key expired and needs unlinking */
#define KEY_GC_REAP_KEYTYPE 1 /* A keytype is being unregistered */
#define KEY_GC_REAPING_KEYTYPE 2 /* Cleared when keytype reaped */
/*
* Any key whose type gets unregistered will be re-typed to this if it can't be
* immediately unlinked.
*/
struct key_type key_type_dead = {
.name = "dead",
};
/*
* Schedule a garbage collection run.
* - time precision isn't particularly important
*/
void key_schedule_gc(time_t gc_at)
{
unsigned long expires;
time_t now = current_kernel_time().tv_sec;
kenter("%ld", gc_at - now);
if (gc_at <= now || test_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags)) {
kdebug("IMMEDIATE");
schedule_work(&key_gc_work);
} else if (gc_at < key_gc_next_run) {
kdebug("DEFERRED");
key_gc_next_run = gc_at;
expires = jiffies + (gc_at - now) * HZ;
mod_timer(&key_gc_timer, expires);
}
}
/*
* Schedule a dead links collection run.
*/
void key_schedule_gc_links(void)
{
set_bit(KEY_GC_KEY_EXPIRED, &key_gc_flags);
schedule_work(&key_gc_work);
}
/*
* Some key's cleanup time was met after it expired, so we need to get the
* reaper to go through a cycle finding expired keys.
*/
static void key_gc_timer_func(unsigned long data)
{
kenter("");
key_gc_next_run = LONG_MAX;
key_schedule_gc_links();
}
/*
* Reap keys of dead type.
*
* We use three flags to make sure we see three complete cycles of the garbage
* collector: the first to mark keys of that type as being dead, the second to
* collect dead links and the third to clean up the dead keys. We have to be
* careful as there may already be a cycle in progress.
*
* The caller must be holding key_types_sem.
*/
void key_gc_keytype(struct key_type *ktype)
{
kenter("%s", ktype->name);
key_gc_dead_keytype = ktype;
set_bit(KEY_GC_REAPING_KEYTYPE, &key_gc_flags);
smp_mb();
set_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags);
kdebug("schedule");
schedule_work(&key_gc_work);
kdebug("sleep");
wait_on_bit(&key_gc_flags, KEY_GC_REAPING_KEYTYPE,
TASK_UNINTERRUPTIBLE);
key_gc_dead_keytype = NULL;
kleave("");
}
/*
* Garbage collect a list of unreferenced, detached keys
*/
static noinline void key_gc_unused_keys(struct list_head *keys)
{
while (!list_empty(keys)) {
struct key *key =
list_entry(keys->next, struct key, graveyard_link);
list_del(&key->graveyard_link);
kdebug("- %u", key->serial);
key_check(key);
/* Throw away the key data if the key is instantiated */
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags) &&
!test_bit(KEY_FLAG_NEGATIVE, &key->flags) &&
key->type->destroy)
key->type->destroy(key);
security_key_free(key);
/* deal with the user's key tracking and quota */
if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
spin_lock(&key->user->lock);
key->user->qnkeys--;
key->user->qnbytes -= key->quotalen;
spin_unlock(&key->user->lock);
}
atomic_dec(&key->user->nkeys);
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
atomic_dec(&key->user->nikeys);
key_user_put(key->user);
kfree(key->description);
#ifdef KEY_DEBUGGING
key->magic = KEY_DEBUG_MAGIC_X;
#endif
kmem_cache_free(key_jar, key);
}
}
/*
* Garbage collector for unused keys.
*
* This is done in process context so that we don't have to disable interrupts
* all over the place. key_put() schedules this rather than trying to do the
* cleanup itself, which means key_put() doesn't have to sleep.
*/
static void key_garbage_collector(struct work_struct *work)
{
static LIST_HEAD(graveyard);
static u8 gc_state; /* Internal persistent state */
#define KEY_GC_REAP_AGAIN 0x01 /* - Need another cycle */
#define KEY_GC_REAPING_LINKS 0x02 /* - We need to reap links */
#define KEY_GC_SET_TIMER 0x04 /* - We need to restart the timer */
#define KEY_GC_REAPING_DEAD_1 0x10 /* - We need to mark dead keys */
#define KEY_GC_REAPING_DEAD_2 0x20 /* - We need to reap dead key links */
#define KEY_GC_REAPING_DEAD_3 0x40 /* - We need to reap dead keys */
#define KEY_GC_FOUND_DEAD_KEY 0x80 /* - We found at least one dead key */
struct rb_node *cursor;
struct key *key;
time_t new_timer, limit;
kenter("[%lx,%x]", key_gc_flags, gc_state);
limit = current_kernel_time().tv_sec;
if (limit > key_gc_delay)
limit -= key_gc_delay;
else
limit = key_gc_delay;
/* Work out what we're going to be doing in this pass */
gc_state &= KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2;
gc_state <<= 1;
if (test_and_clear_bit(KEY_GC_KEY_EXPIRED, &key_gc_flags))
gc_state |= KEY_GC_REAPING_LINKS | KEY_GC_SET_TIMER;
if (test_and_clear_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags))
gc_state |= KEY_GC_REAPING_DEAD_1;
kdebug("new pass %x", gc_state);
new_timer = LONG_MAX;
/* As only this function is permitted to remove things from the key
* serial tree, if cursor is non-NULL then it will always point to a
* valid node in the tree - even if lock got dropped.
*/
spin_lock(&key_serial_lock);
cursor = rb_first(&key_serial_tree);
continue_scanning:
while (cursor) {
key = rb_entry(cursor, struct key, serial_node);
cursor = rb_next(cursor);
if (atomic_read(&key->usage) == 0)
goto found_unreferenced_key;
if (unlikely(gc_state & KEY_GC_REAPING_DEAD_1)) {
if (key->type == key_gc_dead_keytype) {
gc_state |= KEY_GC_FOUND_DEAD_KEY;
set_bit(KEY_FLAG_DEAD, &key->flags);
key->perm = 0;
goto skip_dead_key;
}
}
if (gc_state & KEY_GC_SET_TIMER) {
if (key->expiry > limit && key->expiry < new_timer) {
kdebug("will expire %x in %ld",
key_serial(key), key->expiry - limit);
new_timer = key->expiry;
}
}
if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2))
if (key->type == key_gc_dead_keytype)
gc_state |= KEY_GC_FOUND_DEAD_KEY;
if ((gc_state & KEY_GC_REAPING_LINKS) ||
unlikely(gc_state & KEY_GC_REAPING_DEAD_2)) {
if (key->type == &key_type_keyring)
goto found_keyring;
}
if (unlikely(gc_state & KEY_GC_REAPING_DEAD_3))
if (key->type == key_gc_dead_keytype)
goto destroy_dead_key;
skip_dead_key:
if (spin_is_contended(&key_serial_lock) || need_resched())
goto contended;
}
contended:
spin_unlock(&key_serial_lock);
maybe_resched:
if (cursor) {
cond_resched();
spin_lock(&key_serial_lock);
goto continue_scanning;
}
/* We've completed the pass. Set the timer if we need to and queue a
* new cycle if necessary. We keep executing cycles until we find one
* where we didn't reap any keys.
*/
kdebug("pass complete");
if (gc_state & KEY_GC_SET_TIMER && new_timer != (time_t)LONG_MAX) {
new_timer += key_gc_delay;
key_schedule_gc(new_timer);
}
if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2) ||
!list_empty(&graveyard)) {
/* Make sure that all pending keyring payload destructions are
* fulfilled and that people aren't now looking at dead or
* dying keys that they don't have a reference upon or a link
* to.
*/
kdebug("gc sync");
synchronize_rcu();
}
if (!list_empty(&graveyard)) {
kdebug("gc keys");
key_gc_unused_keys(&graveyard);
}
if (unlikely(gc_state & (KEY_GC_REAPING_DEAD_1 |
KEY_GC_REAPING_DEAD_2))) {
if (!(gc_state & KEY_GC_FOUND_DEAD_KEY)) {
/* No remaining dead keys: short circuit the remaining
* keytype reap cycles.
*/
kdebug("dead short");
gc_state &= ~(KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2);
gc_state |= KEY_GC_REAPING_DEAD_3;
} else {
gc_state |= KEY_GC_REAP_AGAIN;
}
}
if (unlikely(gc_state & KEY_GC_REAPING_DEAD_3)) {
kdebug("dead wake");
smp_mb();
clear_bit(KEY_GC_REAPING_KEYTYPE, &key_gc_flags);
wake_up_bit(&key_gc_flags, KEY_GC_REAPING_KEYTYPE);
}
if (gc_state & KEY_GC_REAP_AGAIN)
schedule_work(&key_gc_work);
kleave(" [end %x]", gc_state);
return;
/* We found an unreferenced key - once we've removed it from the tree,
* we can safely drop the lock.
*/
found_unreferenced_key:
kdebug("unrefd key %d", key->serial);
rb_erase(&key->serial_node, &key_serial_tree);
spin_unlock(&key_serial_lock);
list_add_tail(&key->graveyard_link, &graveyard);
gc_state |= KEY_GC_REAP_AGAIN;
goto maybe_resched;
/* We found a keyring and we need to check the payload for links to
* dead or expired keys. We don't flag another reap immediately as we
* have to wait for the old payload to be destroyed by RCU before we
* can reap the keys to which it refers.
*/
found_keyring:
spin_unlock(&key_serial_lock);
keyring_gc(key, limit);
goto maybe_resched;
/* We found a dead key that is still referenced. Reset its type and
* destroy its payload with its semaphore held.
*/
destroy_dead_key:
spin_unlock(&key_serial_lock);
kdebug("destroy key %d", key->serial);
down_write(&key->sem);
key->type = &key_type_dead;
if (key_gc_dead_keytype->destroy)
key_gc_dead_keytype->destroy(key);
memset(&key->payload, KEY_DESTROY, sizeof(key->payload));
up_write(&key->sem);
goto maybe_resched;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_1763_0 |
crossvul-cpp_data_bad_5544_1 | /*
* Network-device interface management.
*
* Copyright (c) 2004-2005, Keir Fraser
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation; or, when distributed
* separately from the Linux kernel or incorporated into other
* software packages, subject to the following license:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this source file (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "common.h"
#include <linux/ethtool.h>
#include <linux/rtnetlink.h>
#include <linux/if_vlan.h>
#include <xen/events.h>
#include <asm/xen/hypercall.h>
#define XENVIF_QUEUE_LENGTH 32
void xenvif_get(struct xenvif *vif)
{
atomic_inc(&vif->refcnt);
}
void xenvif_put(struct xenvif *vif)
{
if (atomic_dec_and_test(&vif->refcnt))
wake_up(&vif->waiting_to_free);
}
int xenvif_schedulable(struct xenvif *vif)
{
return netif_running(vif->dev) && netif_carrier_ok(vif->dev);
}
static int xenvif_rx_schedulable(struct xenvif *vif)
{
return xenvif_schedulable(vif) && !xen_netbk_rx_ring_full(vif);
}
static irqreturn_t xenvif_interrupt(int irq, void *dev_id)
{
struct xenvif *vif = dev_id;
if (vif->netbk == NULL)
return IRQ_NONE;
xen_netbk_schedule_xenvif(vif);
if (xenvif_rx_schedulable(vif))
netif_wake_queue(vif->dev);
return IRQ_HANDLED;
}
static int xenvif_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct xenvif *vif = netdev_priv(dev);
BUG_ON(skb->dev != dev);
if (vif->netbk == NULL)
goto drop;
/* Drop the packet if the target domain has no receive buffers. */
if (!xenvif_rx_schedulable(vif))
goto drop;
/* Reserve ring slots for the worst-case number of fragments. */
vif->rx_req_cons_peek += xen_netbk_count_skb_slots(vif, skb);
xenvif_get(vif);
if (vif->can_queue && xen_netbk_must_stop_queue(vif))
netif_stop_queue(dev);
xen_netbk_queue_tx_skb(vif, skb);
return NETDEV_TX_OK;
drop:
vif->dev->stats.tx_dropped++;
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
void xenvif_receive_skb(struct xenvif *vif, struct sk_buff *skb)
{
netif_rx_ni(skb);
}
void xenvif_notify_tx_completion(struct xenvif *vif)
{
if (netif_queue_stopped(vif->dev) && xenvif_rx_schedulable(vif))
netif_wake_queue(vif->dev);
}
static struct net_device_stats *xenvif_get_stats(struct net_device *dev)
{
struct xenvif *vif = netdev_priv(dev);
return &vif->dev->stats;
}
static void xenvif_up(struct xenvif *vif)
{
xen_netbk_add_xenvif(vif);
enable_irq(vif->irq);
xen_netbk_check_rx_xenvif(vif);
}
static void xenvif_down(struct xenvif *vif)
{
disable_irq(vif->irq);
xen_netbk_deschedule_xenvif(vif);
xen_netbk_remove_xenvif(vif);
}
static int xenvif_open(struct net_device *dev)
{
struct xenvif *vif = netdev_priv(dev);
if (netif_carrier_ok(dev))
xenvif_up(vif);
netif_start_queue(dev);
return 0;
}
static int xenvif_close(struct net_device *dev)
{
struct xenvif *vif = netdev_priv(dev);
if (netif_carrier_ok(dev))
xenvif_down(vif);
netif_stop_queue(dev);
return 0;
}
static int xenvif_change_mtu(struct net_device *dev, int mtu)
{
struct xenvif *vif = netdev_priv(dev);
int max = vif->can_sg ? 65535 - VLAN_ETH_HLEN : ETH_DATA_LEN;
if (mtu > max)
return -EINVAL;
dev->mtu = mtu;
return 0;
}
static netdev_features_t xenvif_fix_features(struct net_device *dev,
netdev_features_t features)
{
struct xenvif *vif = netdev_priv(dev);
if (!vif->can_sg)
features &= ~NETIF_F_SG;
if (!vif->gso && !vif->gso_prefix)
features &= ~NETIF_F_TSO;
if (!vif->csum)
features &= ~NETIF_F_IP_CSUM;
return features;
}
static const struct xenvif_stat {
char name[ETH_GSTRING_LEN];
u16 offset;
} xenvif_stats[] = {
{
"rx_gso_checksum_fixup",
offsetof(struct xenvif, rx_gso_checksum_fixup)
},
};
static int xenvif_get_sset_count(struct net_device *dev, int string_set)
{
switch (string_set) {
case ETH_SS_STATS:
return ARRAY_SIZE(xenvif_stats);
default:
return -EINVAL;
}
}
static void xenvif_get_ethtool_stats(struct net_device *dev,
struct ethtool_stats *stats, u64 * data)
{
void *vif = netdev_priv(dev);
int i;
for (i = 0; i < ARRAY_SIZE(xenvif_stats); i++)
data[i] = *(unsigned long *)(vif + xenvif_stats[i].offset);
}
static void xenvif_get_strings(struct net_device *dev, u32 stringset, u8 * data)
{
int i;
switch (stringset) {
case ETH_SS_STATS:
for (i = 0; i < ARRAY_SIZE(xenvif_stats); i++)
memcpy(data + i * ETH_GSTRING_LEN,
xenvif_stats[i].name, ETH_GSTRING_LEN);
break;
}
}
static const struct ethtool_ops xenvif_ethtool_ops = {
.get_link = ethtool_op_get_link,
.get_sset_count = xenvif_get_sset_count,
.get_ethtool_stats = xenvif_get_ethtool_stats,
.get_strings = xenvif_get_strings,
};
static const struct net_device_ops xenvif_netdev_ops = {
.ndo_start_xmit = xenvif_start_xmit,
.ndo_get_stats = xenvif_get_stats,
.ndo_open = xenvif_open,
.ndo_stop = xenvif_close,
.ndo_change_mtu = xenvif_change_mtu,
.ndo_fix_features = xenvif_fix_features,
};
struct xenvif *xenvif_alloc(struct device *parent, domid_t domid,
unsigned int handle)
{
int err;
struct net_device *dev;
struct xenvif *vif;
char name[IFNAMSIZ] = {};
snprintf(name, IFNAMSIZ - 1, "vif%u.%u", domid, handle);
dev = alloc_netdev(sizeof(struct xenvif), name, ether_setup);
if (dev == NULL) {
pr_warn("Could not allocate netdev\n");
return ERR_PTR(-ENOMEM);
}
SET_NETDEV_DEV(dev, parent);
vif = netdev_priv(dev);
vif->domid = domid;
vif->handle = handle;
vif->netbk = NULL;
vif->can_sg = 1;
vif->csum = 1;
atomic_set(&vif->refcnt, 1);
init_waitqueue_head(&vif->waiting_to_free);
vif->dev = dev;
INIT_LIST_HEAD(&vif->schedule_list);
INIT_LIST_HEAD(&vif->notify_list);
vif->credit_bytes = vif->remaining_credit = ~0UL;
vif->credit_usec = 0UL;
init_timer(&vif->credit_timeout);
/* Initialize 'expires' now: it's used to track the credit window. */
vif->credit_timeout.expires = jiffies;
dev->netdev_ops = &xenvif_netdev_ops;
dev->hw_features = NETIF_F_SG | NETIF_F_IP_CSUM | NETIF_F_TSO;
dev->features = dev->hw_features;
SET_ETHTOOL_OPS(dev, &xenvif_ethtool_ops);
dev->tx_queue_len = XENVIF_QUEUE_LENGTH;
/*
* Initialise a dummy MAC address. We choose the numerically
* largest non-broadcast address to prevent the address getting
* stolen by an Ethernet bridge for STP purposes.
* (FE:FF:FF:FF:FF:FF)
*/
memset(dev->dev_addr, 0xFF, ETH_ALEN);
dev->dev_addr[0] &= ~0x01;
netif_carrier_off(dev);
err = register_netdev(dev);
if (err) {
netdev_warn(dev, "Could not register device: err=%d\n", err);
free_netdev(dev);
return ERR_PTR(err);
}
netdev_dbg(dev, "Successfully created xenvif\n");
return vif;
}
int xenvif_connect(struct xenvif *vif, unsigned long tx_ring_ref,
unsigned long rx_ring_ref, unsigned int evtchn)
{
int err = -ENOMEM;
/* Already connected through? */
if (vif->irq)
return 0;
err = xen_netbk_map_frontend_rings(vif, tx_ring_ref, rx_ring_ref);
if (err < 0)
goto err;
err = bind_interdomain_evtchn_to_irqhandler(
vif->domid, evtchn, xenvif_interrupt, 0,
vif->dev->name, vif);
if (err < 0)
goto err_unmap;
vif->irq = err;
disable_irq(vif->irq);
xenvif_get(vif);
rtnl_lock();
if (!vif->can_sg && vif->dev->mtu > ETH_DATA_LEN)
dev_set_mtu(vif->dev, ETH_DATA_LEN);
netdev_update_features(vif->dev);
netif_carrier_on(vif->dev);
if (netif_running(vif->dev))
xenvif_up(vif);
rtnl_unlock();
return 0;
err_unmap:
xen_netbk_unmap_frontend_rings(vif);
err:
return err;
}
void xenvif_disconnect(struct xenvif *vif)
{
struct net_device *dev = vif->dev;
if (netif_carrier_ok(dev)) {
rtnl_lock();
netif_carrier_off(dev); /* discard queued packets */
if (netif_running(dev))
xenvif_down(vif);
rtnl_unlock();
xenvif_put(vif);
}
atomic_dec(&vif->refcnt);
wait_event(vif->waiting_to_free, atomic_read(&vif->refcnt) == 0);
del_timer_sync(&vif->credit_timeout);
if (vif->irq)
unbind_from_irqhandler(vif->irq, vif);
unregister_netdev(vif->dev);
xen_netbk_unmap_frontend_rings(vif);
free_netdev(vif->dev);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5544_1 |
crossvul-cpp_data_good_5544_2 | /*
* Back-end of the driver for virtual network devices. This portion of the
* driver exports a 'unified' network-device interface that can be accessed
* by any operating system that implements a compatible front end. A
* reference front-end implementation can be found in:
* drivers/net/xen-netfront.c
*
* Copyright (c) 2002-2005, K A Fraser
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation; or, when distributed
* separately from the Linux kernel or incorporated into other
* software packages, subject to the following license:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this source file (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "common.h"
#include <linux/kthread.h>
#include <linux/if_vlan.h>
#include <linux/udp.h>
#include <net/tcp.h>
#include <xen/xen.h>
#include <xen/events.h>
#include <xen/interface/memory.h>
#include <asm/xen/hypercall.h>
#include <asm/xen/page.h>
struct pending_tx_info {
struct xen_netif_tx_request req;
struct xenvif *vif;
};
typedef unsigned int pending_ring_idx_t;
struct netbk_rx_meta {
int id;
int size;
int gso_size;
};
#define MAX_PENDING_REQS 256
/* Discriminate from any valid pending_idx value. */
#define INVALID_PENDING_IDX 0xFFFF
#define MAX_BUFFER_OFFSET PAGE_SIZE
/* extra field used in struct page */
union page_ext {
struct {
#if BITS_PER_LONG < 64
#define IDX_WIDTH 8
#define GROUP_WIDTH (BITS_PER_LONG - IDX_WIDTH)
unsigned int group:GROUP_WIDTH;
unsigned int idx:IDX_WIDTH;
#else
unsigned int group, idx;
#endif
} e;
void *mapping;
};
struct xen_netbk {
wait_queue_head_t wq;
struct task_struct *task;
struct sk_buff_head rx_queue;
struct sk_buff_head tx_queue;
struct timer_list net_timer;
struct page *mmap_pages[MAX_PENDING_REQS];
pending_ring_idx_t pending_prod;
pending_ring_idx_t pending_cons;
struct list_head net_schedule_list;
/* Protect the net_schedule_list in netif. */
spinlock_t net_schedule_list_lock;
atomic_t netfront_count;
struct pending_tx_info pending_tx_info[MAX_PENDING_REQS];
struct gnttab_copy tx_copy_ops[MAX_PENDING_REQS];
u16 pending_ring[MAX_PENDING_REQS];
/*
* Given MAX_BUFFER_OFFSET of 4096 the worst case is that each
* head/fragment page uses 2 copy operations because it
* straddles two buffers in the frontend.
*/
struct gnttab_copy grant_copy_op[2*XEN_NETIF_RX_RING_SIZE];
struct netbk_rx_meta meta[2*XEN_NETIF_RX_RING_SIZE];
};
static struct xen_netbk *xen_netbk;
static int xen_netbk_group_nr;
void xen_netbk_add_xenvif(struct xenvif *vif)
{
int i;
int min_netfront_count;
int min_group = 0;
struct xen_netbk *netbk;
min_netfront_count = atomic_read(&xen_netbk[0].netfront_count);
for (i = 0; i < xen_netbk_group_nr; i++) {
int netfront_count = atomic_read(&xen_netbk[i].netfront_count);
if (netfront_count < min_netfront_count) {
min_group = i;
min_netfront_count = netfront_count;
}
}
netbk = &xen_netbk[min_group];
vif->netbk = netbk;
atomic_inc(&netbk->netfront_count);
}
void xen_netbk_remove_xenvif(struct xenvif *vif)
{
struct xen_netbk *netbk = vif->netbk;
vif->netbk = NULL;
atomic_dec(&netbk->netfront_count);
}
static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx);
static void make_tx_response(struct xenvif *vif,
struct xen_netif_tx_request *txp,
s8 st);
static struct xen_netif_rx_response *make_rx_response(struct xenvif *vif,
u16 id,
s8 st,
u16 offset,
u16 size,
u16 flags);
static inline unsigned long idx_to_pfn(struct xen_netbk *netbk,
u16 idx)
{
return page_to_pfn(netbk->mmap_pages[idx]);
}
static inline unsigned long idx_to_kaddr(struct xen_netbk *netbk,
u16 idx)
{
return (unsigned long)pfn_to_kaddr(idx_to_pfn(netbk, idx));
}
/* extra field used in struct page */
static inline void set_page_ext(struct page *pg, struct xen_netbk *netbk,
unsigned int idx)
{
unsigned int group = netbk - xen_netbk;
union page_ext ext = { .e = { .group = group + 1, .idx = idx } };
BUILD_BUG_ON(sizeof(ext) > sizeof(ext.mapping));
pg->mapping = ext.mapping;
}
static int get_page_ext(struct page *pg,
unsigned int *pgroup, unsigned int *pidx)
{
union page_ext ext = { .mapping = pg->mapping };
struct xen_netbk *netbk;
unsigned int group, idx;
group = ext.e.group - 1;
if (group < 0 || group >= xen_netbk_group_nr)
return 0;
netbk = &xen_netbk[group];
idx = ext.e.idx;
if ((idx < 0) || (idx >= MAX_PENDING_REQS))
return 0;
if (netbk->mmap_pages[idx] != pg)
return 0;
*pgroup = group;
*pidx = idx;
return 1;
}
/*
* This is the amount of packet we copy rather than map, so that the
* guest can't fiddle with the contents of the headers while we do
* packet processing on them (netfilter, routing, etc).
*/
#define PKT_PROT_LEN (ETH_HLEN + \
VLAN_HLEN + \
sizeof(struct iphdr) + MAX_IPOPTLEN + \
sizeof(struct tcphdr) + MAX_TCP_OPTION_SPACE)
static u16 frag_get_pending_idx(skb_frag_t *frag)
{
return (u16)frag->page_offset;
}
static void frag_set_pending_idx(skb_frag_t *frag, u16 pending_idx)
{
frag->page_offset = pending_idx;
}
static inline pending_ring_idx_t pending_index(unsigned i)
{
return i & (MAX_PENDING_REQS-1);
}
static inline pending_ring_idx_t nr_pending_reqs(struct xen_netbk *netbk)
{
return MAX_PENDING_REQS -
netbk->pending_prod + netbk->pending_cons;
}
static void xen_netbk_kick_thread(struct xen_netbk *netbk)
{
wake_up(&netbk->wq);
}
static int max_required_rx_slots(struct xenvif *vif)
{
int max = DIV_ROUND_UP(vif->dev->mtu, PAGE_SIZE);
if (vif->can_sg || vif->gso || vif->gso_prefix)
max += MAX_SKB_FRAGS + 1; /* extra_info + frags */
return max;
}
int xen_netbk_rx_ring_full(struct xenvif *vif)
{
RING_IDX peek = vif->rx_req_cons_peek;
RING_IDX needed = max_required_rx_slots(vif);
return ((vif->rx.sring->req_prod - peek) < needed) ||
((vif->rx.rsp_prod_pvt + XEN_NETIF_RX_RING_SIZE - peek) < needed);
}
int xen_netbk_must_stop_queue(struct xenvif *vif)
{
if (!xen_netbk_rx_ring_full(vif))
return 0;
vif->rx.sring->req_event = vif->rx_req_cons_peek +
max_required_rx_slots(vif);
mb(); /* request notification /then/ check the queue */
return xen_netbk_rx_ring_full(vif);
}
/*
* Returns true if we should start a new receive buffer instead of
* adding 'size' bytes to a buffer which currently contains 'offset'
* bytes.
*/
static bool start_new_rx_buffer(int offset, unsigned long size, int head)
{
/* simple case: we have completely filled the current buffer. */
if (offset == MAX_BUFFER_OFFSET)
return true;
/*
* complex case: start a fresh buffer if the current frag
* would overflow the current buffer but only if:
* (i) this frag would fit completely in the next buffer
* and (ii) there is already some data in the current buffer
* and (iii) this is not the head buffer.
*
* Where:
* - (i) stops us splitting a frag into two copies
* unless the frag is too large for a single buffer.
* - (ii) stops us from leaving a buffer pointlessly empty.
* - (iii) stops us leaving the first buffer
* empty. Strictly speaking this is already covered
* by (ii) but is explicitly checked because
* netfront relies on the first buffer being
* non-empty and can crash otherwise.
*
* This means we will effectively linearise small
* frags but do not needlessly split large buffers
* into multiple copies tend to give large frags their
* own buffers as before.
*/
if ((offset + size > MAX_BUFFER_OFFSET) &&
(size <= MAX_BUFFER_OFFSET) && offset && !head)
return true;
return false;
}
/*
* Figure out how many ring slots we're going to need to send @skb to
* the guest. This function is essentially a dry run of
* netbk_gop_frag_copy.
*/
unsigned int xen_netbk_count_skb_slots(struct xenvif *vif, struct sk_buff *skb)
{
unsigned int count;
int i, copy_off;
count = DIV_ROUND_UP(skb_headlen(skb), PAGE_SIZE);
copy_off = skb_headlen(skb) % PAGE_SIZE;
if (skb_shinfo(skb)->gso_size)
count++;
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
unsigned long size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
unsigned long offset = skb_shinfo(skb)->frags[i].page_offset;
unsigned long bytes;
offset &= ~PAGE_MASK;
while (size > 0) {
BUG_ON(offset >= PAGE_SIZE);
BUG_ON(copy_off > MAX_BUFFER_OFFSET);
bytes = PAGE_SIZE - offset;
if (bytes > size)
bytes = size;
if (start_new_rx_buffer(copy_off, bytes, 0)) {
count++;
copy_off = 0;
}
if (copy_off + bytes > MAX_BUFFER_OFFSET)
bytes = MAX_BUFFER_OFFSET - copy_off;
copy_off += bytes;
offset += bytes;
size -= bytes;
if (offset == PAGE_SIZE)
offset = 0;
}
}
return count;
}
struct netrx_pending_operations {
unsigned copy_prod, copy_cons;
unsigned meta_prod, meta_cons;
struct gnttab_copy *copy;
struct netbk_rx_meta *meta;
int copy_off;
grant_ref_t copy_gref;
};
static struct netbk_rx_meta *get_next_rx_buffer(struct xenvif *vif,
struct netrx_pending_operations *npo)
{
struct netbk_rx_meta *meta;
struct xen_netif_rx_request *req;
req = RING_GET_REQUEST(&vif->rx, vif->rx.req_cons++);
meta = npo->meta + npo->meta_prod++;
meta->gso_size = 0;
meta->size = 0;
meta->id = req->id;
npo->copy_off = 0;
npo->copy_gref = req->gref;
return meta;
}
/*
* Set up the grant operations for this fragment. If it's a flipping
* interface, we also set up the unmap request from here.
*/
static void netbk_gop_frag_copy(struct xenvif *vif, struct sk_buff *skb,
struct netrx_pending_operations *npo,
struct page *page, unsigned long size,
unsigned long offset, int *head)
{
struct gnttab_copy *copy_gop;
struct netbk_rx_meta *meta;
/*
* These variables are used iff get_page_ext returns true,
* in which case they are guaranteed to be initialized.
*/
unsigned int uninitialized_var(group), uninitialized_var(idx);
int foreign = get_page_ext(page, &group, &idx);
unsigned long bytes;
/* Data must not cross a page boundary. */
BUG_ON(size + offset > PAGE_SIZE<<compound_order(page));
meta = npo->meta + npo->meta_prod - 1;
/* Skip unused frames from start of page */
page += offset >> PAGE_SHIFT;
offset &= ~PAGE_MASK;
while (size > 0) {
BUG_ON(offset >= PAGE_SIZE);
BUG_ON(npo->copy_off > MAX_BUFFER_OFFSET);
bytes = PAGE_SIZE - offset;
if (bytes > size)
bytes = size;
if (start_new_rx_buffer(npo->copy_off, bytes, *head)) {
/*
* Netfront requires there to be some data in the head
* buffer.
*/
BUG_ON(*head);
meta = get_next_rx_buffer(vif, npo);
}
if (npo->copy_off + bytes > MAX_BUFFER_OFFSET)
bytes = MAX_BUFFER_OFFSET - npo->copy_off;
copy_gop = npo->copy + npo->copy_prod++;
copy_gop->flags = GNTCOPY_dest_gref;
if (foreign) {
struct xen_netbk *netbk = &xen_netbk[group];
struct pending_tx_info *src_pend;
src_pend = &netbk->pending_tx_info[idx];
copy_gop->source.domid = src_pend->vif->domid;
copy_gop->source.u.ref = src_pend->req.gref;
copy_gop->flags |= GNTCOPY_source_gref;
} else {
void *vaddr = page_address(page);
copy_gop->source.domid = DOMID_SELF;
copy_gop->source.u.gmfn = virt_to_mfn(vaddr);
}
copy_gop->source.offset = offset;
copy_gop->dest.domid = vif->domid;
copy_gop->dest.offset = npo->copy_off;
copy_gop->dest.u.ref = npo->copy_gref;
copy_gop->len = bytes;
npo->copy_off += bytes;
meta->size += bytes;
offset += bytes;
size -= bytes;
/* Next frame */
if (offset == PAGE_SIZE && size) {
BUG_ON(!PageCompound(page));
page++;
offset = 0;
}
/* Leave a gap for the GSO descriptor. */
if (*head && skb_shinfo(skb)->gso_size && !vif->gso_prefix)
vif->rx.req_cons++;
*head = 0; /* There must be something in this buffer now. */
}
}
/*
* Prepare an SKB to be transmitted to the frontend.
*
* This function is responsible for allocating grant operations, meta
* structures, etc.
*
* It returns the number of meta structures consumed. The number of
* ring slots used is always equal to the number of meta slots used
* plus the number of GSO descriptors used. Currently, we use either
* zero GSO descriptors (for non-GSO packets) or one descriptor (for
* frontend-side LRO).
*/
static int netbk_gop_skb(struct sk_buff *skb,
struct netrx_pending_operations *npo)
{
struct xenvif *vif = netdev_priv(skb->dev);
int nr_frags = skb_shinfo(skb)->nr_frags;
int i;
struct xen_netif_rx_request *req;
struct netbk_rx_meta *meta;
unsigned char *data;
int head = 1;
int old_meta_prod;
old_meta_prod = npo->meta_prod;
/* Set up a GSO prefix descriptor, if necessary */
if (skb_shinfo(skb)->gso_size && vif->gso_prefix) {
req = RING_GET_REQUEST(&vif->rx, vif->rx.req_cons++);
meta = npo->meta + npo->meta_prod++;
meta->gso_size = skb_shinfo(skb)->gso_size;
meta->size = 0;
meta->id = req->id;
}
req = RING_GET_REQUEST(&vif->rx, vif->rx.req_cons++);
meta = npo->meta + npo->meta_prod++;
if (!vif->gso_prefix)
meta->gso_size = skb_shinfo(skb)->gso_size;
else
meta->gso_size = 0;
meta->size = 0;
meta->id = req->id;
npo->copy_off = 0;
npo->copy_gref = req->gref;
data = skb->data;
while (data < skb_tail_pointer(skb)) {
unsigned int offset = offset_in_page(data);
unsigned int len = PAGE_SIZE - offset;
if (data + len > skb_tail_pointer(skb))
len = skb_tail_pointer(skb) - data;
netbk_gop_frag_copy(vif, skb, npo,
virt_to_page(data), len, offset, &head);
data += len;
}
for (i = 0; i < nr_frags; i++) {
netbk_gop_frag_copy(vif, skb, npo,
skb_frag_page(&skb_shinfo(skb)->frags[i]),
skb_frag_size(&skb_shinfo(skb)->frags[i]),
skb_shinfo(skb)->frags[i].page_offset,
&head);
}
return npo->meta_prod - old_meta_prod;
}
/*
* This is a twin to netbk_gop_skb. Assume that netbk_gop_skb was
* used to set up the operations on the top of
* netrx_pending_operations, which have since been done. Check that
* they didn't give any errors and advance over them.
*/
static int netbk_check_gop(struct xenvif *vif, int nr_meta_slots,
struct netrx_pending_operations *npo)
{
struct gnttab_copy *copy_op;
int status = XEN_NETIF_RSP_OKAY;
int i;
for (i = 0; i < nr_meta_slots; i++) {
copy_op = npo->copy + npo->copy_cons++;
if (copy_op->status != GNTST_okay) {
netdev_dbg(vif->dev,
"Bad status %d from copy to DOM%d.\n",
copy_op->status, vif->domid);
status = XEN_NETIF_RSP_ERROR;
}
}
return status;
}
static void netbk_add_frag_responses(struct xenvif *vif, int status,
struct netbk_rx_meta *meta,
int nr_meta_slots)
{
int i;
unsigned long offset;
/* No fragments used */
if (nr_meta_slots <= 1)
return;
nr_meta_slots--;
for (i = 0; i < nr_meta_slots; i++) {
int flags;
if (i == nr_meta_slots - 1)
flags = 0;
else
flags = XEN_NETRXF_more_data;
offset = 0;
make_rx_response(vif, meta[i].id, status, offset,
meta[i].size, flags);
}
}
struct skb_cb_overlay {
int meta_slots_used;
};
static void xen_netbk_rx_action(struct xen_netbk *netbk)
{
struct xenvif *vif = NULL, *tmp;
s8 status;
u16 irq, flags;
struct xen_netif_rx_response *resp;
struct sk_buff_head rxq;
struct sk_buff *skb;
LIST_HEAD(notify);
int ret;
int nr_frags;
int count;
unsigned long offset;
struct skb_cb_overlay *sco;
struct netrx_pending_operations npo = {
.copy = netbk->grant_copy_op,
.meta = netbk->meta,
};
skb_queue_head_init(&rxq);
count = 0;
while ((skb = skb_dequeue(&netbk->rx_queue)) != NULL) {
vif = netdev_priv(skb->dev);
nr_frags = skb_shinfo(skb)->nr_frags;
sco = (struct skb_cb_overlay *)skb->cb;
sco->meta_slots_used = netbk_gop_skb(skb, &npo);
count += nr_frags + 1;
__skb_queue_tail(&rxq, skb);
/* Filled the batch queue? */
if (count + MAX_SKB_FRAGS >= XEN_NETIF_RX_RING_SIZE)
break;
}
BUG_ON(npo.meta_prod > ARRAY_SIZE(netbk->meta));
if (!npo.copy_prod)
return;
BUG_ON(npo.copy_prod > ARRAY_SIZE(netbk->grant_copy_op));
gnttab_batch_copy(netbk->grant_copy_op, npo.copy_prod);
while ((skb = __skb_dequeue(&rxq)) != NULL) {
sco = (struct skb_cb_overlay *)skb->cb;
vif = netdev_priv(skb->dev);
if (netbk->meta[npo.meta_cons].gso_size && vif->gso_prefix) {
resp = RING_GET_RESPONSE(&vif->rx,
vif->rx.rsp_prod_pvt++);
resp->flags = XEN_NETRXF_gso_prefix | XEN_NETRXF_more_data;
resp->offset = netbk->meta[npo.meta_cons].gso_size;
resp->id = netbk->meta[npo.meta_cons].id;
resp->status = sco->meta_slots_used;
npo.meta_cons++;
sco->meta_slots_used--;
}
vif->dev->stats.tx_bytes += skb->len;
vif->dev->stats.tx_packets++;
status = netbk_check_gop(vif, sco->meta_slots_used, &npo);
if (sco->meta_slots_used == 1)
flags = 0;
else
flags = XEN_NETRXF_more_data;
if (skb->ip_summed == CHECKSUM_PARTIAL) /* local packet? */
flags |= XEN_NETRXF_csum_blank | XEN_NETRXF_data_validated;
else if (skb->ip_summed == CHECKSUM_UNNECESSARY)
/* remote but checksummed. */
flags |= XEN_NETRXF_data_validated;
offset = 0;
resp = make_rx_response(vif, netbk->meta[npo.meta_cons].id,
status, offset,
netbk->meta[npo.meta_cons].size,
flags);
if (netbk->meta[npo.meta_cons].gso_size && !vif->gso_prefix) {
struct xen_netif_extra_info *gso =
(struct xen_netif_extra_info *)
RING_GET_RESPONSE(&vif->rx,
vif->rx.rsp_prod_pvt++);
resp->flags |= XEN_NETRXF_extra_info;
gso->u.gso.size = netbk->meta[npo.meta_cons].gso_size;
gso->u.gso.type = XEN_NETIF_GSO_TYPE_TCPV4;
gso->u.gso.pad = 0;
gso->u.gso.features = 0;
gso->type = XEN_NETIF_EXTRA_TYPE_GSO;
gso->flags = 0;
}
netbk_add_frag_responses(vif, status,
netbk->meta + npo.meta_cons + 1,
sco->meta_slots_used);
RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&vif->rx, ret);
irq = vif->irq;
if (ret && list_empty(&vif->notify_list))
list_add_tail(&vif->notify_list, ¬ify);
xenvif_notify_tx_completion(vif);
xenvif_put(vif);
npo.meta_cons += sco->meta_slots_used;
dev_kfree_skb(skb);
}
list_for_each_entry_safe(vif, tmp, ¬ify, notify_list) {
notify_remote_via_irq(vif->irq);
list_del_init(&vif->notify_list);
}
/* More work to do? */
if (!skb_queue_empty(&netbk->rx_queue) &&
!timer_pending(&netbk->net_timer))
xen_netbk_kick_thread(netbk);
}
void xen_netbk_queue_tx_skb(struct xenvif *vif, struct sk_buff *skb)
{
struct xen_netbk *netbk = vif->netbk;
skb_queue_tail(&netbk->rx_queue, skb);
xen_netbk_kick_thread(netbk);
}
static void xen_netbk_alarm(unsigned long data)
{
struct xen_netbk *netbk = (struct xen_netbk *)data;
xen_netbk_kick_thread(netbk);
}
static int __on_net_schedule_list(struct xenvif *vif)
{
return !list_empty(&vif->schedule_list);
}
/* Must be called with net_schedule_list_lock held */
static void remove_from_net_schedule_list(struct xenvif *vif)
{
if (likely(__on_net_schedule_list(vif))) {
list_del_init(&vif->schedule_list);
xenvif_put(vif);
}
}
static struct xenvif *poll_net_schedule_list(struct xen_netbk *netbk)
{
struct xenvif *vif = NULL;
spin_lock_irq(&netbk->net_schedule_list_lock);
if (list_empty(&netbk->net_schedule_list))
goto out;
vif = list_first_entry(&netbk->net_schedule_list,
struct xenvif, schedule_list);
if (!vif)
goto out;
xenvif_get(vif);
remove_from_net_schedule_list(vif);
out:
spin_unlock_irq(&netbk->net_schedule_list_lock);
return vif;
}
void xen_netbk_schedule_xenvif(struct xenvif *vif)
{
unsigned long flags;
struct xen_netbk *netbk = vif->netbk;
if (__on_net_schedule_list(vif))
goto kick;
spin_lock_irqsave(&netbk->net_schedule_list_lock, flags);
if (!__on_net_schedule_list(vif) &&
likely(xenvif_schedulable(vif))) {
list_add_tail(&vif->schedule_list, &netbk->net_schedule_list);
xenvif_get(vif);
}
spin_unlock_irqrestore(&netbk->net_schedule_list_lock, flags);
kick:
smp_mb();
if ((nr_pending_reqs(netbk) < (MAX_PENDING_REQS/2)) &&
!list_empty(&netbk->net_schedule_list))
xen_netbk_kick_thread(netbk);
}
void xen_netbk_deschedule_xenvif(struct xenvif *vif)
{
struct xen_netbk *netbk = vif->netbk;
spin_lock_irq(&netbk->net_schedule_list_lock);
remove_from_net_schedule_list(vif);
spin_unlock_irq(&netbk->net_schedule_list_lock);
}
void xen_netbk_check_rx_xenvif(struct xenvif *vif)
{
int more_to_do;
RING_FINAL_CHECK_FOR_REQUESTS(&vif->tx, more_to_do);
if (more_to_do)
xen_netbk_schedule_xenvif(vif);
}
static void tx_add_credit(struct xenvif *vif)
{
unsigned long max_burst, max_credit;
/*
* Allow a burst big enough to transmit a jumbo packet of up to 128kB.
* Otherwise the interface can seize up due to insufficient credit.
*/
max_burst = RING_GET_REQUEST(&vif->tx, vif->tx.req_cons)->size;
max_burst = min(max_burst, 131072UL);
max_burst = max(max_burst, vif->credit_bytes);
/* Take care that adding a new chunk of credit doesn't wrap to zero. */
max_credit = vif->remaining_credit + vif->credit_bytes;
if (max_credit < vif->remaining_credit)
max_credit = ULONG_MAX; /* wrapped: clamp to ULONG_MAX */
vif->remaining_credit = min(max_credit, max_burst);
}
static void tx_credit_callback(unsigned long data)
{
struct xenvif *vif = (struct xenvif *)data;
tx_add_credit(vif);
xen_netbk_check_rx_xenvif(vif);
}
static void netbk_tx_err(struct xenvif *vif,
struct xen_netif_tx_request *txp, RING_IDX end)
{
RING_IDX cons = vif->tx.req_cons;
do {
make_tx_response(vif, txp, XEN_NETIF_RSP_ERROR);
if (cons >= end)
break;
txp = RING_GET_REQUEST(&vif->tx, cons++);
} while (1);
vif->tx.req_cons = cons;
xen_netbk_check_rx_xenvif(vif);
xenvif_put(vif);
}
static void netbk_fatal_tx_err(struct xenvif *vif)
{
netdev_err(vif->dev, "fatal error; disabling device\n");
xenvif_carrier_off(vif);
xenvif_put(vif);
}
static int netbk_count_requests(struct xenvif *vif,
struct xen_netif_tx_request *first,
struct xen_netif_tx_request *txp,
int work_to_do)
{
RING_IDX cons = vif->tx.req_cons;
int frags = 0;
if (!(first->flags & XEN_NETTXF_more_data))
return 0;
do {
if (frags >= work_to_do) {
netdev_err(vif->dev, "Need more frags\n");
netbk_fatal_tx_err(vif);
return -frags;
}
if (unlikely(frags >= MAX_SKB_FRAGS)) {
netdev_err(vif->dev, "Too many frags\n");
netbk_fatal_tx_err(vif);
return -frags;
}
memcpy(txp, RING_GET_REQUEST(&vif->tx, cons + frags),
sizeof(*txp));
if (txp->size > first->size) {
netdev_err(vif->dev, "Frag is bigger than frame.\n");
netbk_fatal_tx_err(vif);
return -frags;
}
first->size -= txp->size;
frags++;
if (unlikely((txp->offset + txp->size) > PAGE_SIZE)) {
netdev_err(vif->dev, "txp->offset: %x, size: %u\n",
txp->offset, txp->size);
netbk_fatal_tx_err(vif);
return -frags;
}
} while ((txp++)->flags & XEN_NETTXF_more_data);
return frags;
}
static struct page *xen_netbk_alloc_page(struct xen_netbk *netbk,
struct sk_buff *skb,
u16 pending_idx)
{
struct page *page;
page = alloc_page(GFP_KERNEL|__GFP_COLD);
if (!page)
return NULL;
set_page_ext(page, netbk, pending_idx);
netbk->mmap_pages[pending_idx] = page;
return page;
}
static struct gnttab_copy *xen_netbk_get_requests(struct xen_netbk *netbk,
struct xenvif *vif,
struct sk_buff *skb,
struct xen_netif_tx_request *txp,
struct gnttab_copy *gop)
{
struct skb_shared_info *shinfo = skb_shinfo(skb);
skb_frag_t *frags = shinfo->frags;
u16 pending_idx = *((u16 *)skb->data);
int i, start;
/* Skip first skb fragment if it is on same page as header fragment. */
start = (frag_get_pending_idx(&shinfo->frags[0]) == pending_idx);
for (i = start; i < shinfo->nr_frags; i++, txp++) {
struct page *page;
pending_ring_idx_t index;
struct pending_tx_info *pending_tx_info =
netbk->pending_tx_info;
index = pending_index(netbk->pending_cons++);
pending_idx = netbk->pending_ring[index];
page = xen_netbk_alloc_page(netbk, skb, pending_idx);
if (!page)
return NULL;
gop->source.u.ref = txp->gref;
gop->source.domid = vif->domid;
gop->source.offset = txp->offset;
gop->dest.u.gmfn = virt_to_mfn(page_address(page));
gop->dest.domid = DOMID_SELF;
gop->dest.offset = txp->offset;
gop->len = txp->size;
gop->flags = GNTCOPY_source_gref;
gop++;
memcpy(&pending_tx_info[pending_idx].req, txp, sizeof(*txp));
xenvif_get(vif);
pending_tx_info[pending_idx].vif = vif;
frag_set_pending_idx(&frags[i], pending_idx);
}
return gop;
}
static int xen_netbk_tx_check_gop(struct xen_netbk *netbk,
struct sk_buff *skb,
struct gnttab_copy **gopp)
{
struct gnttab_copy *gop = *gopp;
u16 pending_idx = *((u16 *)skb->data);
struct pending_tx_info *pending_tx_info = netbk->pending_tx_info;
struct xenvif *vif = pending_tx_info[pending_idx].vif;
struct xen_netif_tx_request *txp;
struct skb_shared_info *shinfo = skb_shinfo(skb);
int nr_frags = shinfo->nr_frags;
int i, err, start;
/* Check status of header. */
err = gop->status;
if (unlikely(err)) {
pending_ring_idx_t index;
index = pending_index(netbk->pending_prod++);
txp = &pending_tx_info[pending_idx].req;
make_tx_response(vif, txp, XEN_NETIF_RSP_ERROR);
netbk->pending_ring[index] = pending_idx;
xenvif_put(vif);
}
/* Skip first skb fragment if it is on same page as header fragment. */
start = (frag_get_pending_idx(&shinfo->frags[0]) == pending_idx);
for (i = start; i < nr_frags; i++) {
int j, newerr;
pending_ring_idx_t index;
pending_idx = frag_get_pending_idx(&shinfo->frags[i]);
/* Check error status: if okay then remember grant handle. */
newerr = (++gop)->status;
if (likely(!newerr)) {
/* Had a previous error? Invalidate this fragment. */
if (unlikely(err))
xen_netbk_idx_release(netbk, pending_idx);
continue;
}
/* Error on this fragment: respond to client with an error. */
txp = &netbk->pending_tx_info[pending_idx].req;
make_tx_response(vif, txp, XEN_NETIF_RSP_ERROR);
index = pending_index(netbk->pending_prod++);
netbk->pending_ring[index] = pending_idx;
xenvif_put(vif);
/* Not the first error? Preceding frags already invalidated. */
if (err)
continue;
/* First error: invalidate header and preceding fragments. */
pending_idx = *((u16 *)skb->data);
xen_netbk_idx_release(netbk, pending_idx);
for (j = start; j < i; j++) {
pending_idx = frag_get_pending_idx(&shinfo->frags[j]);
xen_netbk_idx_release(netbk, pending_idx);
}
/* Remember the error: invalidate all subsequent fragments. */
err = newerr;
}
*gopp = gop + 1;
return err;
}
static void xen_netbk_fill_frags(struct xen_netbk *netbk, struct sk_buff *skb)
{
struct skb_shared_info *shinfo = skb_shinfo(skb);
int nr_frags = shinfo->nr_frags;
int i;
for (i = 0; i < nr_frags; i++) {
skb_frag_t *frag = shinfo->frags + i;
struct xen_netif_tx_request *txp;
struct page *page;
u16 pending_idx;
pending_idx = frag_get_pending_idx(frag);
txp = &netbk->pending_tx_info[pending_idx].req;
page = virt_to_page(idx_to_kaddr(netbk, pending_idx));
__skb_fill_page_desc(skb, i, page, txp->offset, txp->size);
skb->len += txp->size;
skb->data_len += txp->size;
skb->truesize += txp->size;
/* Take an extra reference to offset xen_netbk_idx_release */
get_page(netbk->mmap_pages[pending_idx]);
xen_netbk_idx_release(netbk, pending_idx);
}
}
static int xen_netbk_get_extras(struct xenvif *vif,
struct xen_netif_extra_info *extras,
int work_to_do)
{
struct xen_netif_extra_info extra;
RING_IDX cons = vif->tx.req_cons;
do {
if (unlikely(work_to_do-- <= 0)) {
netdev_err(vif->dev, "Missing extra info\n");
netbk_fatal_tx_err(vif);
return -EBADR;
}
memcpy(&extra, RING_GET_REQUEST(&vif->tx, cons),
sizeof(extra));
if (unlikely(!extra.type ||
extra.type >= XEN_NETIF_EXTRA_TYPE_MAX)) {
vif->tx.req_cons = ++cons;
netdev_err(vif->dev,
"Invalid extra type: %d\n", extra.type);
netbk_fatal_tx_err(vif);
return -EINVAL;
}
memcpy(&extras[extra.type - 1], &extra, sizeof(extra));
vif->tx.req_cons = ++cons;
} while (extra.flags & XEN_NETIF_EXTRA_FLAG_MORE);
return work_to_do;
}
static int netbk_set_skb_gso(struct xenvif *vif,
struct sk_buff *skb,
struct xen_netif_extra_info *gso)
{
if (!gso->u.gso.size) {
netdev_err(vif->dev, "GSO size must not be zero.\n");
netbk_fatal_tx_err(vif);
return -EINVAL;
}
/* Currently only TCPv4 S.O. is supported. */
if (gso->u.gso.type != XEN_NETIF_GSO_TYPE_TCPV4) {
netdev_err(vif->dev, "Bad GSO type %d.\n", gso->u.gso.type);
netbk_fatal_tx_err(vif);
return -EINVAL;
}
skb_shinfo(skb)->gso_size = gso->u.gso.size;
skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
/* Header must be checked, and gso_segs computed. */
skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
skb_shinfo(skb)->gso_segs = 0;
return 0;
}
static int checksum_setup(struct xenvif *vif, struct sk_buff *skb)
{
struct iphdr *iph;
unsigned char *th;
int err = -EPROTO;
int recalculate_partial_csum = 0;
/*
* A GSO SKB must be CHECKSUM_PARTIAL. However some buggy
* peers can fail to set NETRXF_csum_blank when sending a GSO
* frame. In this case force the SKB to CHECKSUM_PARTIAL and
* recalculate the partial checksum.
*/
if (skb->ip_summed != CHECKSUM_PARTIAL && skb_is_gso(skb)) {
vif->rx_gso_checksum_fixup++;
skb->ip_summed = CHECKSUM_PARTIAL;
recalculate_partial_csum = 1;
}
/* A non-CHECKSUM_PARTIAL SKB does not require setup. */
if (skb->ip_summed != CHECKSUM_PARTIAL)
return 0;
if (skb->protocol != htons(ETH_P_IP))
goto out;
iph = (void *)skb->data;
th = skb->data + 4 * iph->ihl;
if (th >= skb_tail_pointer(skb))
goto out;
skb->csum_start = th - skb->head;
switch (iph->protocol) {
case IPPROTO_TCP:
skb->csum_offset = offsetof(struct tcphdr, check);
if (recalculate_partial_csum) {
struct tcphdr *tcph = (struct tcphdr *)th;
tcph->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr,
skb->len - iph->ihl*4,
IPPROTO_TCP, 0);
}
break;
case IPPROTO_UDP:
skb->csum_offset = offsetof(struct udphdr, check);
if (recalculate_partial_csum) {
struct udphdr *udph = (struct udphdr *)th;
udph->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr,
skb->len - iph->ihl*4,
IPPROTO_UDP, 0);
}
break;
default:
if (net_ratelimit())
netdev_err(vif->dev,
"Attempting to checksum a non-TCP/UDP packet, dropping a protocol %d packet\n",
iph->protocol);
goto out;
}
if ((th + skb->csum_offset + 2) > skb_tail_pointer(skb))
goto out;
err = 0;
out:
return err;
}
static bool tx_credit_exceeded(struct xenvif *vif, unsigned size)
{
unsigned long now = jiffies;
unsigned long next_credit =
vif->credit_timeout.expires +
msecs_to_jiffies(vif->credit_usec / 1000);
/* Timer could already be pending in rare cases. */
if (timer_pending(&vif->credit_timeout))
return true;
/* Passed the point where we can replenish credit? */
if (time_after_eq(now, next_credit)) {
vif->credit_timeout.expires = now;
tx_add_credit(vif);
}
/* Still too big to send right now? Set a callback. */
if (size > vif->remaining_credit) {
vif->credit_timeout.data =
(unsigned long)vif;
vif->credit_timeout.function =
tx_credit_callback;
mod_timer(&vif->credit_timeout,
next_credit);
return true;
}
return false;
}
static unsigned xen_netbk_tx_build_gops(struct xen_netbk *netbk)
{
struct gnttab_copy *gop = netbk->tx_copy_ops, *request_gop;
struct sk_buff *skb;
int ret;
while (((nr_pending_reqs(netbk) + MAX_SKB_FRAGS) < MAX_PENDING_REQS) &&
!list_empty(&netbk->net_schedule_list)) {
struct xenvif *vif;
struct xen_netif_tx_request txreq;
struct xen_netif_tx_request txfrags[MAX_SKB_FRAGS];
struct page *page;
struct xen_netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX-1];
u16 pending_idx;
RING_IDX idx;
int work_to_do;
unsigned int data_len;
pending_ring_idx_t index;
/* Get a netif from the list with work to do. */
vif = poll_net_schedule_list(netbk);
/* This can sometimes happen because the test of
* list_empty(net_schedule_list) at the top of the
* loop is unlocked. Just go back and have another
* look.
*/
if (!vif)
continue;
if (vif->tx.sring->req_prod - vif->tx.req_cons >
XEN_NETIF_TX_RING_SIZE) {
netdev_err(vif->dev,
"Impossible number of requests. "
"req_prod %d, req_cons %d, size %ld\n",
vif->tx.sring->req_prod, vif->tx.req_cons,
XEN_NETIF_TX_RING_SIZE);
netbk_fatal_tx_err(vif);
continue;
}
RING_FINAL_CHECK_FOR_REQUESTS(&vif->tx, work_to_do);
if (!work_to_do) {
xenvif_put(vif);
continue;
}
idx = vif->tx.req_cons;
rmb(); /* Ensure that we see the request before we copy it. */
memcpy(&txreq, RING_GET_REQUEST(&vif->tx, idx), sizeof(txreq));
/* Credit-based scheduling. */
if (txreq.size > vif->remaining_credit &&
tx_credit_exceeded(vif, txreq.size)) {
xenvif_put(vif);
continue;
}
vif->remaining_credit -= txreq.size;
work_to_do--;
vif->tx.req_cons = ++idx;
memset(extras, 0, sizeof(extras));
if (txreq.flags & XEN_NETTXF_extra_info) {
work_to_do = xen_netbk_get_extras(vif, extras,
work_to_do);
idx = vif->tx.req_cons;
if (unlikely(work_to_do < 0))
continue;
}
ret = netbk_count_requests(vif, &txreq, txfrags, work_to_do);
if (unlikely(ret < 0))
continue;
idx += ret;
if (unlikely(txreq.size < ETH_HLEN)) {
netdev_dbg(vif->dev,
"Bad packet size: %d\n", txreq.size);
netbk_tx_err(vif, &txreq, idx);
continue;
}
/* No crossing a page as the payload mustn't fragment. */
if (unlikely((txreq.offset + txreq.size) > PAGE_SIZE)) {
netdev_err(vif->dev,
"txreq.offset: %x, size: %u, end: %lu\n",
txreq.offset, txreq.size,
(txreq.offset&~PAGE_MASK) + txreq.size);
netbk_fatal_tx_err(vif);
continue;
}
index = pending_index(netbk->pending_cons);
pending_idx = netbk->pending_ring[index];
data_len = (txreq.size > PKT_PROT_LEN &&
ret < MAX_SKB_FRAGS) ?
PKT_PROT_LEN : txreq.size;
skb = alloc_skb(data_len + NET_SKB_PAD + NET_IP_ALIGN,
GFP_ATOMIC | __GFP_NOWARN);
if (unlikely(skb == NULL)) {
netdev_dbg(vif->dev,
"Can't allocate a skb in start_xmit.\n");
netbk_tx_err(vif, &txreq, idx);
break;
}
/* Packets passed to netif_rx() must have some headroom. */
skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
if (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) {
struct xen_netif_extra_info *gso;
gso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1];
if (netbk_set_skb_gso(vif, skb, gso)) {
/* Failure in netbk_set_skb_gso is fatal. */
kfree_skb(skb);
continue;
}
}
/* XXX could copy straight to head */
page = xen_netbk_alloc_page(netbk, skb, pending_idx);
if (!page) {
kfree_skb(skb);
netbk_tx_err(vif, &txreq, idx);
continue;
}
gop->source.u.ref = txreq.gref;
gop->source.domid = vif->domid;
gop->source.offset = txreq.offset;
gop->dest.u.gmfn = virt_to_mfn(page_address(page));
gop->dest.domid = DOMID_SELF;
gop->dest.offset = txreq.offset;
gop->len = txreq.size;
gop->flags = GNTCOPY_source_gref;
gop++;
memcpy(&netbk->pending_tx_info[pending_idx].req,
&txreq, sizeof(txreq));
netbk->pending_tx_info[pending_idx].vif = vif;
*((u16 *)skb->data) = pending_idx;
__skb_put(skb, data_len);
skb_shinfo(skb)->nr_frags = ret;
if (data_len < txreq.size) {
skb_shinfo(skb)->nr_frags++;
frag_set_pending_idx(&skb_shinfo(skb)->frags[0],
pending_idx);
} else {
frag_set_pending_idx(&skb_shinfo(skb)->frags[0],
INVALID_PENDING_IDX);
}
netbk->pending_cons++;
request_gop = xen_netbk_get_requests(netbk, vif,
skb, txfrags, gop);
if (request_gop == NULL) {
kfree_skb(skb);
netbk_tx_err(vif, &txreq, idx);
continue;
}
gop = request_gop;
__skb_queue_tail(&netbk->tx_queue, skb);
vif->tx.req_cons = idx;
xen_netbk_check_rx_xenvif(vif);
if ((gop-netbk->tx_copy_ops) >= ARRAY_SIZE(netbk->tx_copy_ops))
break;
}
return gop - netbk->tx_copy_ops;
}
static void xen_netbk_tx_submit(struct xen_netbk *netbk)
{
struct gnttab_copy *gop = netbk->tx_copy_ops;
struct sk_buff *skb;
while ((skb = __skb_dequeue(&netbk->tx_queue)) != NULL) {
struct xen_netif_tx_request *txp;
struct xenvif *vif;
u16 pending_idx;
unsigned data_len;
pending_idx = *((u16 *)skb->data);
vif = netbk->pending_tx_info[pending_idx].vif;
txp = &netbk->pending_tx_info[pending_idx].req;
/* Check the remap error code. */
if (unlikely(xen_netbk_tx_check_gop(netbk, skb, &gop))) {
netdev_dbg(vif->dev, "netback grant failed.\n");
skb_shinfo(skb)->nr_frags = 0;
kfree_skb(skb);
continue;
}
data_len = skb->len;
memcpy(skb->data,
(void *)(idx_to_kaddr(netbk, pending_idx)|txp->offset),
data_len);
if (data_len < txp->size) {
/* Append the packet payload as a fragment. */
txp->offset += data_len;
txp->size -= data_len;
} else {
/* Schedule a response immediately. */
xen_netbk_idx_release(netbk, pending_idx);
}
if (txp->flags & XEN_NETTXF_csum_blank)
skb->ip_summed = CHECKSUM_PARTIAL;
else if (txp->flags & XEN_NETTXF_data_validated)
skb->ip_summed = CHECKSUM_UNNECESSARY;
xen_netbk_fill_frags(netbk, skb);
/*
* If the initial fragment was < PKT_PROT_LEN then
* pull through some bytes from the other fragments to
* increase the linear region to PKT_PROT_LEN bytes.
*/
if (skb_headlen(skb) < PKT_PROT_LEN && skb_is_nonlinear(skb)) {
int target = min_t(int, skb->len, PKT_PROT_LEN);
__pskb_pull_tail(skb, target - skb_headlen(skb));
}
skb->dev = vif->dev;
skb->protocol = eth_type_trans(skb, skb->dev);
if (checksum_setup(vif, skb)) {
netdev_dbg(vif->dev,
"Can't setup checksum in net_tx_action\n");
kfree_skb(skb);
continue;
}
vif->dev->stats.rx_bytes += skb->len;
vif->dev->stats.rx_packets++;
xenvif_receive_skb(vif, skb);
}
}
/* Called after netfront has transmitted */
static void xen_netbk_tx_action(struct xen_netbk *netbk)
{
unsigned nr_gops;
nr_gops = xen_netbk_tx_build_gops(netbk);
if (nr_gops == 0)
return;
gnttab_batch_copy(netbk->tx_copy_ops, nr_gops);
xen_netbk_tx_submit(netbk);
}
static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx)
{
struct xenvif *vif;
struct pending_tx_info *pending_tx_info;
pending_ring_idx_t index;
/* Already complete? */
if (netbk->mmap_pages[pending_idx] == NULL)
return;
pending_tx_info = &netbk->pending_tx_info[pending_idx];
vif = pending_tx_info->vif;
make_tx_response(vif, &pending_tx_info->req, XEN_NETIF_RSP_OKAY);
index = pending_index(netbk->pending_prod++);
netbk->pending_ring[index] = pending_idx;
xenvif_put(vif);
netbk->mmap_pages[pending_idx]->mapping = 0;
put_page(netbk->mmap_pages[pending_idx]);
netbk->mmap_pages[pending_idx] = NULL;
}
static void make_tx_response(struct xenvif *vif,
struct xen_netif_tx_request *txp,
s8 st)
{
RING_IDX i = vif->tx.rsp_prod_pvt;
struct xen_netif_tx_response *resp;
int notify;
resp = RING_GET_RESPONSE(&vif->tx, i);
resp->id = txp->id;
resp->status = st;
if (txp->flags & XEN_NETTXF_extra_info)
RING_GET_RESPONSE(&vif->tx, ++i)->status = XEN_NETIF_RSP_NULL;
vif->tx.rsp_prod_pvt = ++i;
RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&vif->tx, notify);
if (notify)
notify_remote_via_irq(vif->irq);
}
static struct xen_netif_rx_response *make_rx_response(struct xenvif *vif,
u16 id,
s8 st,
u16 offset,
u16 size,
u16 flags)
{
RING_IDX i = vif->rx.rsp_prod_pvt;
struct xen_netif_rx_response *resp;
resp = RING_GET_RESPONSE(&vif->rx, i);
resp->offset = offset;
resp->flags = flags;
resp->id = id;
resp->status = (s16)size;
if (st < 0)
resp->status = (s16)st;
vif->rx.rsp_prod_pvt = ++i;
return resp;
}
static inline int rx_work_todo(struct xen_netbk *netbk)
{
return !skb_queue_empty(&netbk->rx_queue);
}
static inline int tx_work_todo(struct xen_netbk *netbk)
{
if (((nr_pending_reqs(netbk) + MAX_SKB_FRAGS) < MAX_PENDING_REQS) &&
!list_empty(&netbk->net_schedule_list))
return 1;
return 0;
}
static int xen_netbk_kthread(void *data)
{
struct xen_netbk *netbk = data;
while (!kthread_should_stop()) {
wait_event_interruptible(netbk->wq,
rx_work_todo(netbk) ||
tx_work_todo(netbk) ||
kthread_should_stop());
cond_resched();
if (kthread_should_stop())
break;
if (rx_work_todo(netbk))
xen_netbk_rx_action(netbk);
if (tx_work_todo(netbk))
xen_netbk_tx_action(netbk);
}
return 0;
}
void xen_netbk_unmap_frontend_rings(struct xenvif *vif)
{
if (vif->tx.sring)
xenbus_unmap_ring_vfree(xenvif_to_xenbus_device(vif),
vif->tx.sring);
if (vif->rx.sring)
xenbus_unmap_ring_vfree(xenvif_to_xenbus_device(vif),
vif->rx.sring);
}
int xen_netbk_map_frontend_rings(struct xenvif *vif,
grant_ref_t tx_ring_ref,
grant_ref_t rx_ring_ref)
{
void *addr;
struct xen_netif_tx_sring *txs;
struct xen_netif_rx_sring *rxs;
int err = -ENOMEM;
err = xenbus_map_ring_valloc(xenvif_to_xenbus_device(vif),
tx_ring_ref, &addr);
if (err)
goto err;
txs = (struct xen_netif_tx_sring *)addr;
BACK_RING_INIT(&vif->tx, txs, PAGE_SIZE);
err = xenbus_map_ring_valloc(xenvif_to_xenbus_device(vif),
rx_ring_ref, &addr);
if (err)
goto err;
rxs = (struct xen_netif_rx_sring *)addr;
BACK_RING_INIT(&vif->rx, rxs, PAGE_SIZE);
vif->rx_req_cons_peek = 0;
return 0;
err:
xen_netbk_unmap_frontend_rings(vif);
return err;
}
static int __init netback_init(void)
{
int i;
int rc = 0;
int group;
if (!xen_domain())
return -ENODEV;
xen_netbk_group_nr = num_online_cpus();
xen_netbk = vzalloc(sizeof(struct xen_netbk) * xen_netbk_group_nr);
if (!xen_netbk)
return -ENOMEM;
for (group = 0; group < xen_netbk_group_nr; group++) {
struct xen_netbk *netbk = &xen_netbk[group];
skb_queue_head_init(&netbk->rx_queue);
skb_queue_head_init(&netbk->tx_queue);
init_timer(&netbk->net_timer);
netbk->net_timer.data = (unsigned long)netbk;
netbk->net_timer.function = xen_netbk_alarm;
netbk->pending_cons = 0;
netbk->pending_prod = MAX_PENDING_REQS;
for (i = 0; i < MAX_PENDING_REQS; i++)
netbk->pending_ring[i] = i;
init_waitqueue_head(&netbk->wq);
netbk->task = kthread_create(xen_netbk_kthread,
(void *)netbk,
"netback/%u", group);
if (IS_ERR(netbk->task)) {
printk(KERN_ALERT "kthread_create() fails at netback\n");
del_timer(&netbk->net_timer);
rc = PTR_ERR(netbk->task);
goto failed_init;
}
kthread_bind(netbk->task, group);
INIT_LIST_HEAD(&netbk->net_schedule_list);
spin_lock_init(&netbk->net_schedule_list_lock);
atomic_set(&netbk->netfront_count, 0);
wake_up_process(netbk->task);
}
rc = xenvif_xenbus_init();
if (rc)
goto failed_init;
return 0;
failed_init:
while (--group >= 0) {
struct xen_netbk *netbk = &xen_netbk[group];
for (i = 0; i < MAX_PENDING_REQS; i++) {
if (netbk->mmap_pages[i])
__free_page(netbk->mmap_pages[i]);
}
del_timer(&netbk->net_timer);
kthread_stop(netbk->task);
}
vfree(xen_netbk);
return rc;
}
module_init(netback_init);
MODULE_LICENSE("Dual BSD/GPL");
MODULE_ALIAS("xen-backend:vif");
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5544_2 |
crossvul-cpp_data_good_3174_0 | /*
* llc_conn.c - Driver routines for connection component.
*
* Copyright (c) 1997 by Procom Technology, Inc.
* 2001-2003 by Arnaldo Carvalho de Melo <acme@conectiva.com.br>
*
* This program can be redistributed or modified under the terms of the
* GNU General Public License as published by the Free Software Foundation.
* This program is distributed without any warranty or implied warranty
* of merchantability or fitness for a particular purpose.
*
* See the GNU General Public License for more details.
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <net/llc_sap.h>
#include <net/llc_conn.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <net/llc_c_ev.h>
#include <net/llc_c_ac.h>
#include <net/llc_c_st.h>
#include <net/llc_pdu.h>
#if 0
#define dprintk(args...) printk(KERN_DEBUG args)
#else
#define dprintk(args...)
#endif
static int llc_find_offset(int state, int ev_type);
static void llc_conn_send_pdus(struct sock *sk);
static int llc_conn_service(struct sock *sk, struct sk_buff *skb);
static int llc_exec_conn_trans_actions(struct sock *sk,
struct llc_conn_state_trans *trans,
struct sk_buff *ev);
static struct llc_conn_state_trans *llc_qualify_conn_ev(struct sock *sk,
struct sk_buff *skb);
/* Offset table on connection states transition diagram */
static int llc_offset_table[NBR_CONN_STATES][NBR_CONN_EV];
int sysctl_llc2_ack_timeout = LLC2_ACK_TIME * HZ;
int sysctl_llc2_p_timeout = LLC2_P_TIME * HZ;
int sysctl_llc2_rej_timeout = LLC2_REJ_TIME * HZ;
int sysctl_llc2_busy_timeout = LLC2_BUSY_TIME * HZ;
/**
* llc_conn_state_process - sends event to connection state machine
* @sk: connection
* @skb: occurred event
*
* Sends an event to connection state machine. After processing event
* (executing it's actions and changing state), upper layer will be
* indicated or confirmed, if needed. Returns 0 for success, 1 for
* failure. The socket lock has to be held before calling this function.
*/
int llc_conn_state_process(struct sock *sk, struct sk_buff *skb)
{
int rc;
struct llc_sock *llc = llc_sk(skb->sk);
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
/*
* We have to hold the skb, because llc_conn_service will kfree it in
* the sending path and we need to look at the skb->cb, where we encode
* llc_conn_state_ev.
*/
skb_get(skb);
ev->ind_prim = ev->cfm_prim = 0;
/*
* Send event to state machine
*/
rc = llc_conn_service(skb->sk, skb);
if (unlikely(rc != 0)) {
printk(KERN_ERR "%s: llc_conn_service failed\n", __func__);
goto out_kfree_skb;
}
if (unlikely(!ev->ind_prim && !ev->cfm_prim)) {
/* indicate or confirm not required */
if (!skb->next)
goto out_kfree_skb;
goto out_skb_put;
}
if (unlikely(ev->ind_prim && ev->cfm_prim)) /* Paranoia */
skb_get(skb);
switch (ev->ind_prim) {
case LLC_DATA_PRIM:
llc_save_primitive(sk, skb, LLC_DATA_PRIM);
if (unlikely(sock_queue_rcv_skb(sk, skb))) {
/*
* shouldn't happen
*/
printk(KERN_ERR "%s: sock_queue_rcv_skb failed!\n",
__func__);
kfree_skb(skb);
}
break;
case LLC_CONN_PRIM:
/*
* Can't be sock_queue_rcv_skb, because we have to leave the
* skb->sk pointing to the newly created struct sock in
* llc_conn_handler. -acme
*/
skb_queue_tail(&sk->sk_receive_queue, skb);
sk->sk_state_change(sk);
break;
case LLC_DISC_PRIM:
sock_hold(sk);
if (sk->sk_type == SOCK_STREAM &&
sk->sk_state == TCP_ESTABLISHED) {
sk->sk_shutdown = SHUTDOWN_MASK;
sk->sk_socket->state = SS_UNCONNECTED;
sk->sk_state = TCP_CLOSE;
if (!sock_flag(sk, SOCK_DEAD)) {
sock_set_flag(sk, SOCK_DEAD);
sk->sk_state_change(sk);
}
}
kfree_skb(skb);
sock_put(sk);
break;
case LLC_RESET_PRIM:
/*
* FIXME:
* RESET is not being notified to upper layers for now
*/
printk(KERN_INFO "%s: received a reset ind!\n", __func__);
kfree_skb(skb);
break;
default:
if (ev->ind_prim) {
printk(KERN_INFO "%s: received unknown %d prim!\n",
__func__, ev->ind_prim);
kfree_skb(skb);
}
/* No indication */
break;
}
switch (ev->cfm_prim) {
case LLC_DATA_PRIM:
if (!llc_data_accept_state(llc->state))
sk->sk_write_space(sk);
else
rc = llc->failed_data_req = 1;
break;
case LLC_CONN_PRIM:
if (sk->sk_type == SOCK_STREAM &&
sk->sk_state == TCP_SYN_SENT) {
if (ev->status) {
sk->sk_socket->state = SS_UNCONNECTED;
sk->sk_state = TCP_CLOSE;
} else {
sk->sk_socket->state = SS_CONNECTED;
sk->sk_state = TCP_ESTABLISHED;
}
sk->sk_state_change(sk);
}
break;
case LLC_DISC_PRIM:
sock_hold(sk);
if (sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_CLOSING) {
sk->sk_socket->state = SS_UNCONNECTED;
sk->sk_state = TCP_CLOSE;
sk->sk_state_change(sk);
}
sock_put(sk);
break;
case LLC_RESET_PRIM:
/*
* FIXME:
* RESET is not being notified to upper layers for now
*/
printk(KERN_INFO "%s: received a reset conf!\n", __func__);
break;
default:
if (ev->cfm_prim) {
printk(KERN_INFO "%s: received unknown %d prim!\n",
__func__, ev->cfm_prim);
break;
}
goto out_skb_put; /* No confirmation */
}
out_kfree_skb:
kfree_skb(skb);
out_skb_put:
kfree_skb(skb);
return rc;
}
void llc_conn_send_pdu(struct sock *sk, struct sk_buff *skb)
{
/* queue PDU to send to MAC layer */
skb_queue_tail(&sk->sk_write_queue, skb);
llc_conn_send_pdus(sk);
}
/**
* llc_conn_rtn_pdu - sends received data pdu to upper layer
* @sk: Active connection
* @skb: Received data frame
*
* Sends received data pdu to upper layer (by using indicate function).
* Prepares service parameters (prim and prim_data). calling indication
* function will be done in llc_conn_state_process.
*/
void llc_conn_rtn_pdu(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->ind_prim = LLC_DATA_PRIM;
}
/**
* llc_conn_resend_i_pdu_as_cmd - resend all all unacknowledged I PDUs
* @sk: active connection
* @nr: NR
* @first_p_bit: p_bit value of first pdu
*
* Resend all unacknowledged I PDUs, starting with the NR; send first as
* command PDU with P bit equal first_p_bit; if more than one send
* subsequent as command PDUs with P bit equal zero (0).
*/
void llc_conn_resend_i_pdu_as_cmd(struct sock *sk, u8 nr, u8 first_p_bit)
{
struct sk_buff *skb;
struct llc_pdu_sn *pdu;
u16 nbr_unack_pdus;
struct llc_sock *llc;
u8 howmany_resend = 0;
llc_conn_remove_acked_pdus(sk, nr, &nbr_unack_pdus);
if (!nbr_unack_pdus)
goto out;
/*
* Process unack PDUs only if unack queue is not empty; remove
* appropriate PDUs, fix them up, and put them on mac_pdu_q.
*/
llc = llc_sk(sk);
while ((skb = skb_dequeue(&llc->pdu_unack_q)) != NULL) {
pdu = llc_pdu_sn_hdr(skb);
llc_pdu_set_cmd_rsp(skb, LLC_PDU_CMD);
llc_pdu_set_pf_bit(skb, first_p_bit);
skb_queue_tail(&sk->sk_write_queue, skb);
first_p_bit = 0;
llc->vS = LLC_I_GET_NS(pdu);
howmany_resend++;
}
if (howmany_resend > 0)
llc->vS = (llc->vS + 1) % LLC_2_SEQ_NBR_MODULO;
/* any PDUs to re-send are queued up; start sending to MAC */
llc_conn_send_pdus(sk);
out:;
}
/**
* llc_conn_resend_i_pdu_as_rsp - Resend all unacknowledged I PDUs
* @sk: active connection.
* @nr: NR
* @first_f_bit: f_bit value of first pdu.
*
* Resend all unacknowledged I PDUs, starting with the NR; send first as
* response PDU with F bit equal first_f_bit; if more than one send
* subsequent as response PDUs with F bit equal zero (0).
*/
void llc_conn_resend_i_pdu_as_rsp(struct sock *sk, u8 nr, u8 first_f_bit)
{
struct sk_buff *skb;
u16 nbr_unack_pdus;
struct llc_sock *llc = llc_sk(sk);
u8 howmany_resend = 0;
llc_conn_remove_acked_pdus(sk, nr, &nbr_unack_pdus);
if (!nbr_unack_pdus)
goto out;
/*
* Process unack PDUs only if unack queue is not empty; remove
* appropriate PDUs, fix them up, and put them on mac_pdu_q
*/
while ((skb = skb_dequeue(&llc->pdu_unack_q)) != NULL) {
struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
llc_pdu_set_cmd_rsp(skb, LLC_PDU_RSP);
llc_pdu_set_pf_bit(skb, first_f_bit);
skb_queue_tail(&sk->sk_write_queue, skb);
first_f_bit = 0;
llc->vS = LLC_I_GET_NS(pdu);
howmany_resend++;
}
if (howmany_resend > 0)
llc->vS = (llc->vS + 1) % LLC_2_SEQ_NBR_MODULO;
/* any PDUs to re-send are queued up; start sending to MAC */
llc_conn_send_pdus(sk);
out:;
}
/**
* llc_conn_remove_acked_pdus - Removes acknowledged pdus from tx queue
* @sk: active connection
* nr: NR
* how_many_unacked: size of pdu_unack_q after removing acked pdus
*
* Removes acknowledged pdus from transmit queue (pdu_unack_q). Returns
* the number of pdus that removed from queue.
*/
int llc_conn_remove_acked_pdus(struct sock *sk, u8 nr, u16 *how_many_unacked)
{
int pdu_pos, i;
struct sk_buff *skb;
struct llc_pdu_sn *pdu;
int nbr_acked = 0;
struct llc_sock *llc = llc_sk(sk);
int q_len = skb_queue_len(&llc->pdu_unack_q);
if (!q_len)
goto out;
skb = skb_peek(&llc->pdu_unack_q);
pdu = llc_pdu_sn_hdr(skb);
/* finding position of last acked pdu in queue */
pdu_pos = ((int)LLC_2_SEQ_NBR_MODULO + (int)nr -
(int)LLC_I_GET_NS(pdu)) % LLC_2_SEQ_NBR_MODULO;
for (i = 0; i < pdu_pos && i < q_len; i++) {
skb = skb_dequeue(&llc->pdu_unack_q);
kfree_skb(skb);
nbr_acked++;
}
out:
*how_many_unacked = skb_queue_len(&llc->pdu_unack_q);
return nbr_acked;
}
/**
* llc_conn_send_pdus - Sends queued PDUs
* @sk: active connection
*
* Sends queued pdus to MAC layer for transmission.
*/
static void llc_conn_send_pdus(struct sock *sk)
{
struct sk_buff *skb;
while ((skb = skb_dequeue(&sk->sk_write_queue)) != NULL) {
struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
if (LLC_PDU_TYPE_IS_I(pdu) &&
!(skb->dev->flags & IFF_LOOPBACK)) {
struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
skb_queue_tail(&llc_sk(sk)->pdu_unack_q, skb);
if (!skb2)
break;
skb = skb2;
}
dev_queue_xmit(skb);
}
}
/**
* llc_conn_service - finds transition and changes state of connection
* @sk: connection
* @skb: happened event
*
* This function finds transition that matches with happened event, then
* executes related actions and finally changes state of connection.
* Returns 0 for success, 1 for failure.
*/
static int llc_conn_service(struct sock *sk, struct sk_buff *skb)
{
int rc = 1;
struct llc_sock *llc = llc_sk(sk);
struct llc_conn_state_trans *trans;
if (llc->state > NBR_CONN_STATES)
goto out;
rc = 0;
trans = llc_qualify_conn_ev(sk, skb);
if (trans) {
rc = llc_exec_conn_trans_actions(sk, trans, skb);
if (!rc && trans->next_state != NO_STATE_CHANGE) {
llc->state = trans->next_state;
if (!llc_data_accept_state(llc->state))
sk->sk_state_change(sk);
}
}
out:
return rc;
}
/**
* llc_qualify_conn_ev - finds transition for event
* @sk: connection
* @skb: happened event
*
* This function finds transition that matches with happened event.
* Returns pointer to found transition on success, %NULL otherwise.
*/
static struct llc_conn_state_trans *llc_qualify_conn_ev(struct sock *sk,
struct sk_buff *skb)
{
struct llc_conn_state_trans **next_trans;
const llc_conn_ev_qfyr_t *next_qualifier;
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
struct llc_sock *llc = llc_sk(sk);
struct llc_conn_state *curr_state =
&llc_conn_state_table[llc->state - 1];
/* search thru events for this state until
* list exhausted or until no more
*/
for (next_trans = curr_state->transitions +
llc_find_offset(llc->state - 1, ev->type);
(*next_trans)->ev; next_trans++) {
if (!((*next_trans)->ev)(sk, skb)) {
/* got POSSIBLE event match; the event may require
* qualification based on the values of a number of
* state flags; if all qualifications are met (i.e.,
* if all qualifying functions return success, or 0,
* then this is THE event we're looking for
*/
for (next_qualifier = (*next_trans)->ev_qualifiers;
next_qualifier && *next_qualifier &&
!(*next_qualifier)(sk, skb); next_qualifier++)
/* nothing */;
if (!next_qualifier || !*next_qualifier)
/* all qualifiers executed successfully; this is
* our transition; return it so we can perform
* the associated actions & change the state
*/
return *next_trans;
}
}
return NULL;
}
/**
* llc_exec_conn_trans_actions - executes related actions
* @sk: connection
* @trans: transition that it's actions must be performed
* @skb: event
*
* Executes actions that is related to happened event. Returns 0 for
* success, 1 to indicate failure of at least one action.
*/
static int llc_exec_conn_trans_actions(struct sock *sk,
struct llc_conn_state_trans *trans,
struct sk_buff *skb)
{
int rc = 0;
const llc_conn_action_t *next_action;
for (next_action = trans->ev_actions;
next_action && *next_action; next_action++) {
int rc2 = (*next_action)(sk, skb);
if (rc2 == 2) {
rc = rc2;
break;
} else if (rc2)
rc = 1;
}
return rc;
}
static inline bool llc_estab_match(const struct llc_sap *sap,
const struct llc_addr *daddr,
const struct llc_addr *laddr,
const struct sock *sk)
{
struct llc_sock *llc = llc_sk(sk);
return llc->laddr.lsap == laddr->lsap &&
llc->daddr.lsap == daddr->lsap &&
ether_addr_equal(llc->laddr.mac, laddr->mac) &&
ether_addr_equal(llc->daddr.mac, daddr->mac);
}
/**
* __llc_lookup_established - Finds connection for the remote/local sap/mac
* @sap: SAP
* @daddr: address of remote LLC (MAC + SAP)
* @laddr: address of local LLC (MAC + SAP)
*
* Search connection list of the SAP and finds connection using the remote
* mac, remote sap, local mac, and local sap. Returns pointer for
* connection found, %NULL otherwise.
* Caller has to make sure local_bh is disabled.
*/
static struct sock *__llc_lookup_established(struct llc_sap *sap,
struct llc_addr *daddr,
struct llc_addr *laddr)
{
struct sock *rc;
struct hlist_nulls_node *node;
int slot = llc_sk_laddr_hashfn(sap, laddr);
struct hlist_nulls_head *laddr_hb = &sap->sk_laddr_hash[slot];
rcu_read_lock();
again:
sk_nulls_for_each_rcu(rc, node, laddr_hb) {
if (llc_estab_match(sap, daddr, laddr, rc)) {
/* Extra checks required by SLAB_DESTROY_BY_RCU */
if (unlikely(!atomic_inc_not_zero(&rc->sk_refcnt)))
goto again;
if (unlikely(llc_sk(rc)->sap != sap ||
!llc_estab_match(sap, daddr, laddr, rc))) {
sock_put(rc);
continue;
}
goto found;
}
}
rc = NULL;
/*
* if the nulls value we got at the end of this lookup is
* not the expected one, we must restart lookup.
* We probably met an item that was moved to another chain.
*/
if (unlikely(get_nulls_value(node) != slot))
goto again;
found:
rcu_read_unlock();
return rc;
}
struct sock *llc_lookup_established(struct llc_sap *sap,
struct llc_addr *daddr,
struct llc_addr *laddr)
{
struct sock *sk;
local_bh_disable();
sk = __llc_lookup_established(sap, daddr, laddr);
local_bh_enable();
return sk;
}
static inline bool llc_listener_match(const struct llc_sap *sap,
const struct llc_addr *laddr,
const struct sock *sk)
{
struct llc_sock *llc = llc_sk(sk);
return sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_LISTEN &&
llc->laddr.lsap == laddr->lsap &&
ether_addr_equal(llc->laddr.mac, laddr->mac);
}
static struct sock *__llc_lookup_listener(struct llc_sap *sap,
struct llc_addr *laddr)
{
struct sock *rc;
struct hlist_nulls_node *node;
int slot = llc_sk_laddr_hashfn(sap, laddr);
struct hlist_nulls_head *laddr_hb = &sap->sk_laddr_hash[slot];
rcu_read_lock();
again:
sk_nulls_for_each_rcu(rc, node, laddr_hb) {
if (llc_listener_match(sap, laddr, rc)) {
/* Extra checks required by SLAB_DESTROY_BY_RCU */
if (unlikely(!atomic_inc_not_zero(&rc->sk_refcnt)))
goto again;
if (unlikely(llc_sk(rc)->sap != sap ||
!llc_listener_match(sap, laddr, rc))) {
sock_put(rc);
continue;
}
goto found;
}
}
rc = NULL;
/*
* if the nulls value we got at the end of this lookup is
* not the expected one, we must restart lookup.
* We probably met an item that was moved to another chain.
*/
if (unlikely(get_nulls_value(node) != slot))
goto again;
found:
rcu_read_unlock();
return rc;
}
/**
* llc_lookup_listener - Finds listener for local MAC + SAP
* @sap: SAP
* @laddr: address of local LLC (MAC + SAP)
*
* Search connection list of the SAP and finds connection listening on
* local mac, and local sap. Returns pointer for parent socket found,
* %NULL otherwise.
* Caller has to make sure local_bh is disabled.
*/
static struct sock *llc_lookup_listener(struct llc_sap *sap,
struct llc_addr *laddr)
{
static struct llc_addr null_addr;
struct sock *rc = __llc_lookup_listener(sap, laddr);
if (!rc)
rc = __llc_lookup_listener(sap, &null_addr);
return rc;
}
static struct sock *__llc_lookup(struct llc_sap *sap,
struct llc_addr *daddr,
struct llc_addr *laddr)
{
struct sock *sk = __llc_lookup_established(sap, daddr, laddr);
return sk ? : llc_lookup_listener(sap, laddr);
}
/**
* llc_data_accept_state - designates if in this state data can be sent.
* @state: state of connection.
*
* Returns 0 if data can be sent, 1 otherwise.
*/
u8 llc_data_accept_state(u8 state)
{
return state != LLC_CONN_STATE_NORMAL && state != LLC_CONN_STATE_BUSY &&
state != LLC_CONN_STATE_REJ;
}
/**
* llc_find_next_offset - finds offset for next category of transitions
* @state: state table.
* @offset: start offset.
*
* Finds offset of next category of transitions in transition table.
* Returns the start index of next category.
*/
static u16 __init llc_find_next_offset(struct llc_conn_state *state, u16 offset)
{
u16 cnt = 0;
struct llc_conn_state_trans **next_trans;
for (next_trans = state->transitions + offset;
(*next_trans)->ev; next_trans++)
++cnt;
return cnt;
}
/**
* llc_build_offset_table - builds offset table of connection
*
* Fills offset table of connection state transition table
* (llc_offset_table).
*/
void __init llc_build_offset_table(void)
{
struct llc_conn_state *curr_state;
int state, ev_type, next_offset;
for (state = 0; state < NBR_CONN_STATES; state++) {
curr_state = &llc_conn_state_table[state];
next_offset = 0;
for (ev_type = 0; ev_type < NBR_CONN_EV; ev_type++) {
llc_offset_table[state][ev_type] = next_offset;
next_offset += llc_find_next_offset(curr_state,
next_offset) + 1;
}
}
}
/**
* llc_find_offset - finds start offset of category of transitions
* @state: state of connection
* @ev_type: type of happened event
*
* Finds start offset of desired category of transitions. Returns the
* desired start offset.
*/
static int llc_find_offset(int state, int ev_type)
{
int rc = 0;
/* at this stage, llc_offset_table[..][2] is not important. it is for
* init_pf_cycle and I don't know what is it.
*/
switch (ev_type) {
case LLC_CONN_EV_TYPE_PRIM:
rc = llc_offset_table[state][0]; break;
case LLC_CONN_EV_TYPE_PDU:
rc = llc_offset_table[state][4]; break;
case LLC_CONN_EV_TYPE_SIMPLE:
rc = llc_offset_table[state][1]; break;
case LLC_CONN_EV_TYPE_P_TMR:
case LLC_CONN_EV_TYPE_ACK_TMR:
case LLC_CONN_EV_TYPE_REJ_TMR:
case LLC_CONN_EV_TYPE_BUSY_TMR:
rc = llc_offset_table[state][3]; break;
}
return rc;
}
/**
* llc_sap_add_socket - adds a socket to a SAP
* @sap: SAP
* @sk: socket
*
* This function adds a socket to the hash tables of a SAP.
*/
void llc_sap_add_socket(struct llc_sap *sap, struct sock *sk)
{
struct llc_sock *llc = llc_sk(sk);
struct hlist_head *dev_hb = llc_sk_dev_hash(sap, llc->dev->ifindex);
struct hlist_nulls_head *laddr_hb = llc_sk_laddr_hash(sap, &llc->laddr);
llc_sap_hold(sap);
llc_sk(sk)->sap = sap;
spin_lock_bh(&sap->sk_lock);
sap->sk_count++;
sk_nulls_add_node_rcu(sk, laddr_hb);
hlist_add_head(&llc->dev_hash_node, dev_hb);
spin_unlock_bh(&sap->sk_lock);
}
/**
* llc_sap_remove_socket - removes a socket from SAP
* @sap: SAP
* @sk: socket
*
* This function removes a connection from the hash tables of a SAP if
* the connection was in this list.
*/
void llc_sap_remove_socket(struct llc_sap *sap, struct sock *sk)
{
struct llc_sock *llc = llc_sk(sk);
spin_lock_bh(&sap->sk_lock);
sk_nulls_del_node_init_rcu(sk);
hlist_del(&llc->dev_hash_node);
sap->sk_count--;
spin_unlock_bh(&sap->sk_lock);
llc_sap_put(sap);
}
/**
* llc_conn_rcv - sends received pdus to the connection state machine
* @sk: current connection structure.
* @skb: received frame.
*
* Sends received pdus to the connection state machine.
*/
static int llc_conn_rcv(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->type = LLC_CONN_EV_TYPE_PDU;
ev->reason = 0;
return llc_conn_state_process(sk, skb);
}
static struct sock *llc_create_incoming_sock(struct sock *sk,
struct net_device *dev,
struct llc_addr *saddr,
struct llc_addr *daddr)
{
struct sock *newsk = llc_sk_alloc(sock_net(sk), sk->sk_family, GFP_ATOMIC,
sk->sk_prot, 0);
struct llc_sock *newllc, *llc = llc_sk(sk);
if (!newsk)
goto out;
newllc = llc_sk(newsk);
memcpy(&newllc->laddr, daddr, sizeof(newllc->laddr));
memcpy(&newllc->daddr, saddr, sizeof(newllc->daddr));
newllc->dev = dev;
dev_hold(dev);
llc_sap_add_socket(llc->sap, newsk);
llc_sap_hold(llc->sap);
out:
return newsk;
}
void llc_conn_handler(struct llc_sap *sap, struct sk_buff *skb)
{
struct llc_addr saddr, daddr;
struct sock *sk;
llc_pdu_decode_sa(skb, saddr.mac);
llc_pdu_decode_ssap(skb, &saddr.lsap);
llc_pdu_decode_da(skb, daddr.mac);
llc_pdu_decode_dsap(skb, &daddr.lsap);
sk = __llc_lookup(sap, &saddr, &daddr);
if (!sk)
goto drop;
bh_lock_sock(sk);
/*
* This has to be done here and not at the upper layer ->accept
* method because of the way the PROCOM state machine works:
* it needs to set several state variables (see, for instance,
* llc_adm_actions_2 in net/llc/llc_c_st.c) and send a packet to
* the originator of the new connection, and this state has to be
* in the newly created struct sock private area. -acme
*/
if (unlikely(sk->sk_state == TCP_LISTEN)) {
struct sock *newsk = llc_create_incoming_sock(sk, skb->dev,
&saddr, &daddr);
if (!newsk)
goto drop_unlock;
skb_set_owner_r(skb, newsk);
} else {
/*
* Can't be skb_set_owner_r, this will be done at the
* llc_conn_state_process function, later on, when we will use
* skb_queue_rcv_skb to send it to upper layers, this is
* another trick required to cope with how the PROCOM state
* machine works. -acme
*/
skb_orphan(skb);
sock_hold(sk);
skb->sk = sk;
skb->destructor = sock_efree;
}
if (!sock_owned_by_user(sk))
llc_conn_rcv(sk, skb);
else {
dprintk("%s: adding to backlog...\n", __func__);
llc_set_backlog_type(skb, LLC_PACKET);
if (sk_add_backlog(sk, skb, sk->sk_rcvbuf))
goto drop_unlock;
}
out:
bh_unlock_sock(sk);
sock_put(sk);
return;
drop:
kfree_skb(skb);
return;
drop_unlock:
kfree_skb(skb);
goto out;
}
#undef LLC_REFCNT_DEBUG
#ifdef LLC_REFCNT_DEBUG
static atomic_t llc_sock_nr;
#endif
/**
* llc_backlog_rcv - Processes rx frames and expired timers.
* @sk: LLC sock (p8022 connection)
* @skb: queued rx frame or event
*
* This function processes frames that has received and timers that has
* expired during sending an I pdu (refer to data_req_handler). frames
* queue by llc_rcv function (llc_mac.c) and timers queue by timer
* callback functions(llc_c_ac.c).
*/
static int llc_backlog_rcv(struct sock *sk, struct sk_buff *skb)
{
int rc = 0;
struct llc_sock *llc = llc_sk(sk);
if (likely(llc_backlog_type(skb) == LLC_PACKET)) {
if (likely(llc->state > 1)) /* not closed */
rc = llc_conn_rcv(sk, skb);
else
goto out_kfree_skb;
} else if (llc_backlog_type(skb) == LLC_EVENT) {
/* timer expiration event */
if (likely(llc->state > 1)) /* not closed */
rc = llc_conn_state_process(sk, skb);
else
goto out_kfree_skb;
} else {
printk(KERN_ERR "%s: invalid skb in backlog\n", __func__);
goto out_kfree_skb;
}
out:
return rc;
out_kfree_skb:
kfree_skb(skb);
goto out;
}
/**
* llc_sk_init - Initializes a socket with default llc values.
* @sk: socket to initialize.
*
* Initializes a socket with default llc values.
*/
static void llc_sk_init(struct sock *sk)
{
struct llc_sock *llc = llc_sk(sk);
llc->state = LLC_CONN_STATE_ADM;
llc->inc_cntr = llc->dec_cntr = 2;
llc->dec_step = llc->connect_step = 1;
setup_timer(&llc->ack_timer.timer, llc_conn_ack_tmr_cb,
(unsigned long)sk);
llc->ack_timer.expire = sysctl_llc2_ack_timeout;
setup_timer(&llc->pf_cycle_timer.timer, llc_conn_pf_cycle_tmr_cb,
(unsigned long)sk);
llc->pf_cycle_timer.expire = sysctl_llc2_p_timeout;
setup_timer(&llc->rej_sent_timer.timer, llc_conn_rej_tmr_cb,
(unsigned long)sk);
llc->rej_sent_timer.expire = sysctl_llc2_rej_timeout;
setup_timer(&llc->busy_state_timer.timer, llc_conn_busy_tmr_cb,
(unsigned long)sk);
llc->busy_state_timer.expire = sysctl_llc2_busy_timeout;
llc->n2 = 2; /* max retransmit */
llc->k = 2; /* tx win size, will adjust dynam */
llc->rw = 128; /* rx win size (opt and equal to
* tx_win of remote LLC) */
skb_queue_head_init(&llc->pdu_unack_q);
sk->sk_backlog_rcv = llc_backlog_rcv;
}
/**
* llc_sk_alloc - Allocates LLC sock
* @family: upper layer protocol family
* @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
*
* Allocates a LLC sock and initializes it. Returns the new LLC sock
* or %NULL if there's no memory available for one
*/
struct sock *llc_sk_alloc(struct net *net, int family, gfp_t priority, struct proto *prot, int kern)
{
struct sock *sk = sk_alloc(net, family, priority, prot, kern);
if (!sk)
goto out;
llc_sk_init(sk);
sock_init_data(NULL, sk);
#ifdef LLC_REFCNT_DEBUG
atomic_inc(&llc_sock_nr);
printk(KERN_DEBUG "LLC socket %p created in %s, now we have %d alive\n", sk,
__func__, atomic_read(&llc_sock_nr));
#endif
out:
return sk;
}
/**
* llc_sk_free - Frees a LLC socket
* @sk - socket to free
*
* Frees a LLC socket
*/
void llc_sk_free(struct sock *sk)
{
struct llc_sock *llc = llc_sk(sk);
llc->state = LLC_CONN_OUT_OF_SVC;
/* Stop all (possibly) running timers */
llc_conn_ac_stop_all_timers(sk, NULL);
#ifdef DEBUG_LLC_CONN_ALLOC
printk(KERN_INFO "%s: unackq=%d, txq=%d\n", __func__,
skb_queue_len(&llc->pdu_unack_q),
skb_queue_len(&sk->sk_write_queue));
#endif
skb_queue_purge(&sk->sk_receive_queue);
skb_queue_purge(&sk->sk_write_queue);
skb_queue_purge(&llc->pdu_unack_q);
#ifdef LLC_REFCNT_DEBUG
if (atomic_read(&sk->sk_refcnt) != 1) {
printk(KERN_DEBUG "Destruction of LLC sock %p delayed in %s, cnt=%d\n",
sk, __func__, atomic_read(&sk->sk_refcnt));
printk(KERN_DEBUG "%d LLC sockets are still alive\n",
atomic_read(&llc_sock_nr));
} else {
atomic_dec(&llc_sock_nr);
printk(KERN_DEBUG "LLC socket %p released in %s, %d are still alive\n", sk,
__func__, atomic_read(&llc_sock_nr));
}
#endif
sock_put(sk);
}
/**
* llc_sk_reset - resets a connection
* @sk: LLC socket to reset
*
* Resets a connection to the out of service state. Stops its timers
* and frees any frames in the queues of the connection.
*/
void llc_sk_reset(struct sock *sk)
{
struct llc_sock *llc = llc_sk(sk);
llc_conn_ac_stop_all_timers(sk, NULL);
skb_queue_purge(&sk->sk_write_queue);
skb_queue_purge(&llc->pdu_unack_q);
llc->remote_busy_flag = 0;
llc->cause_flag = 0;
llc->retry_count = 0;
llc_conn_set_p_flag(sk, 0);
llc->f_flag = 0;
llc->s_flag = 0;
llc->ack_pf = 0;
llc->first_pdu_Ns = 0;
llc->ack_must_be_send = 0;
llc->dec_step = 1;
llc->inc_cntr = 2;
llc->dec_cntr = 2;
llc->X = 0;
llc->failed_data_req = 0 ;
llc->last_nr = 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3174_0 |
crossvul-cpp_data_good_5115_2 | /* packet-rpcap.c
*
* Routines for RPCAP message formats.
*
* Copyright 2008, Stig Bjorlykke <stig@bjorlykke.org>, Thales Norway AS
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* Copyright 1998 Gerald Combs
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include <epan/packet.h>
#include <epan/aftypes.h>
#include <epan/prefs.h>
#include <epan/to_str.h>
#include <epan/expert.h>
#include <wiretap/wtap.h>
#include "packet-frame.h"
#include "packet-tcp.h"
#define PNAME "Remote Packet Capture"
#define PSNAME "RPCAP"
#define PFNAME "rpcap"
#define RPCAP_MSG_ERROR 1
#define RPCAP_MSG_FINDALLIF_REQ 2
#define RPCAP_MSG_OPEN_REQ 3
#define RPCAP_MSG_STARTCAP_REQ 4
#define RPCAP_MSG_UPDATEFILTER_REQ 5
#define RPCAP_MSG_CLOSE 6
#define RPCAP_MSG_PACKET 7
#define RPCAP_MSG_AUTH_REQ 8
#define RPCAP_MSG_STATS_REQ 9
#define RPCAP_MSG_ENDCAP_REQ 10
#define RPCAP_MSG_SETSAMPLING_REQ 11
#define RPCAP_MSG_FINDALLIF_REPLY (128+RPCAP_MSG_FINDALLIF_REQ)
#define RPCAP_MSG_OPEN_REPLY (128+RPCAP_MSG_OPEN_REQ)
#define RPCAP_MSG_STARTCAP_REPLY (128+RPCAP_MSG_STARTCAP_REQ)
#define RPCAP_MSG_UPDATEFILTER_REPLY (128+RPCAP_MSG_UPDATEFILTER_REQ)
#define RPCAP_MSG_AUTH_REPLY (128+RPCAP_MSG_AUTH_REQ)
#define RPCAP_MSG_STATS_REPLY (128+RPCAP_MSG_STATS_REQ)
#define RPCAP_MSG_ENDCAP_REPLY (128+RPCAP_MSG_ENDCAP_REQ)
#define RPCAP_MSG_SETSAMPLING_REPLY (128+RPCAP_MSG_SETSAMPLING_REQ)
#define RPCAP_ERR_NETW 1
#define RPCAP_ERR_INITTIMEOUT 2
#define RPCAP_ERR_AUTH 3
#define RPCAP_ERR_FINDALLIF 4
#define RPCAP_ERR_NOREMOTEIF 5
#define RPCAP_ERR_OPEN 6
#define RPCAP_ERR_UPDATEFILTER 7
#define RPCAP_ERR_GETSTATS 8
#define RPCAP_ERR_READEX 9
#define RPCAP_ERR_HOSTNOAUTH 10
#define RPCAP_ERR_REMOTEACCEPT 11
#define RPCAP_ERR_STARTCAPTURE 12
#define RPCAP_ERR_ENDCAPTURE 13
#define RPCAP_ERR_RUNTIMETIMEOUT 14
#define RPCAP_ERR_SETSAMPLING 15
#define RPCAP_ERR_WRONGMSG 16
#define RPCAP_ERR_WRONGVER 17
#define RPCAP_SAMP_NOSAMP 0
#define RPCAP_SAMP_1_EVERY_N 1
#define RPCAP_SAMP_FIRST_AFTER_N_MS 2
#define RPCAP_RMTAUTH_NULL 0
#define RPCAP_RMTAUTH_PWD 1
#define FLAG_PROMISC 0x0001
#define FLAG_DGRAM 0x0002
#define FLAG_SERVEROPEN 0x0004
#define FLAG_INBOUND 0x0008
#define FLAG_OUTBOUND 0x0010
void proto_register_rpcap (void);
void proto_reg_handoff_rpcap (void);
static int proto_rpcap = -1;
static int hf_version = -1;
static int hf_type = -1;
static int hf_value = -1;
static int hf_plen = -1;
static int hf_error = -1;
static int hf_error_value = -1;
static int hf_packet = -1;
static int hf_timestamp = -1;
static int hf_caplen = -1;
static int hf_len = -1;
static int hf_npkt = -1;
static int hf_auth_request = -1;
static int hf_auth_type = -1;
static int hf_auth_slen1 = -1;
static int hf_auth_slen2 = -1;
static int hf_auth_username = -1;
static int hf_auth_password = -1;
static int hf_open_request = -1;
static int hf_open_reply = -1;
static int hf_linktype = -1;
static int hf_tzoff = -1;
static int hf_startcap_request = -1;
static int hf_snaplen = -1;
static int hf_read_timeout = -1;
static int hf_flags = -1;
static int hf_flags_promisc = -1;
static int hf_flags_dgram = -1;
static int hf_flags_serveropen = -1;
static int hf_flags_inbound = -1;
static int hf_flags_outbound = -1;
static int hf_client_port = -1;
static int hf_startcap_reply = -1;
static int hf_bufsize = -1;
static int hf_server_port = -1;
static int hf_dummy = -1;
static int hf_filter = -1;
static int hf_filtertype = -1;
static int hf_nitems = -1;
static int hf_filterbpf_insn = -1;
static int hf_code = -1;
static int hf_code_class = -1;
static int hf_code_fields = -1;
static int hf_code_ld_size = -1;
static int hf_code_ld_mode = -1;
static int hf_code_alu_op = -1;
static int hf_code_jmp_op = -1;
static int hf_code_src = -1;
static int hf_code_rval = -1;
static int hf_code_misc_op = -1;
static int hf_jt = -1;
static int hf_jf = -1;
static int hf_instr_value = -1;
static int hf_stats_reply = -1;
static int hf_ifrecv = -1;
static int hf_ifdrop = -1;
static int hf_krnldrop = -1;
static int hf_srvcapt = -1;
static int hf_findalldevs_reply = -1;
static int hf_findalldevs_if = -1;
static int hf_namelen = -1;
static int hf_desclen = -1;
static int hf_if_flags = -1;
static int hf_naddr = -1;
static int hf_if_name = -1;
static int hf_if_desc = -1;
static int hf_findalldevs_ifaddr = -1;
static int hf_if_addr = -1;
static int hf_if_netmask = -1;
static int hf_if_broadaddr = -1;
static int hf_if_dstaddr = -1;
static int hf_if_af = -1;
static int hf_if_port = -1;
static int hf_if_ip = -1;
static int hf_if_padding = -1;
static int hf_if_unknown = -1;
static int hf_sampling_request = -1;
static int hf_sampling_method = -1;
static int hf_sampling_dummy1 = -1;
static int hf_sampling_dummy2 = -1;
static int hf_sampling_value = -1;
static gint ett_rpcap = -1;
static gint ett_error = -1;
static gint ett_packet = -1;
static gint ett_auth_request = -1;
static gint ett_open_reply = -1;
static gint ett_startcap_request = -1;
static gint ett_startcap_reply = -1;
static gint ett_startcap_flags = -1;
static gint ett_filter = -1;
static gint ett_filterbpf_insn = -1;
static gint ett_filterbpf_insn_code = -1;
static gint ett_stats_reply = -1;
static gint ett_findalldevs_reply = -1;
static gint ett_findalldevs_if = -1;
static gint ett_findalldevs_ifaddr = -1;
static gint ett_ifaddr = -1;
static gint ett_sampling_request = -1;
static expert_field ei_error = EI_INIT;
static expert_field ei_if_unknown = EI_INIT;
static expert_field ei_no_more_data = EI_INIT;
static expert_field ei_caplen_too_big = EI_INIT;
static dissector_handle_t data_handle;
/* User definable values */
static gboolean rpcap_desegment = TRUE;
static gboolean decode_content = TRUE;
static guint32 global_linktype = WTAP_ENCAP_UNKNOWN;
/* Global variables */
static guint32 linktype = WTAP_ENCAP_UNKNOWN;
static gboolean info_added = FALSE;
static const true_false_string open_closed = {
"Open", "Closed"
};
static const value_string message_type[] = {
{ RPCAP_MSG_ERROR, "Error" },
{ RPCAP_MSG_FINDALLIF_REQ, "Find all interfaces request" },
{ RPCAP_MSG_OPEN_REQ, "Open request" },
{ RPCAP_MSG_STARTCAP_REQ, "Start capture request" },
{ RPCAP_MSG_UPDATEFILTER_REQ, "Update filter request" },
{ RPCAP_MSG_CLOSE, "Close" },
{ RPCAP_MSG_PACKET, "Packet" },
{ RPCAP_MSG_AUTH_REQ, "Authentication request" },
{ RPCAP_MSG_STATS_REQ, "Statistics request" },
{ RPCAP_MSG_ENDCAP_REQ, "End capture request" },
{ RPCAP_MSG_SETSAMPLING_REQ, "Set sampling request" },
{ RPCAP_MSG_FINDALLIF_REPLY, "Find all interfaces reply" },
{ RPCAP_MSG_OPEN_REPLY, "Open reply" },
{ RPCAP_MSG_STARTCAP_REPLY, "Start capture reply" },
{ RPCAP_MSG_UPDATEFILTER_REPLY, "Update filter reply" },
{ RPCAP_MSG_AUTH_REPLY, "Authentication reply" },
{ RPCAP_MSG_STATS_REPLY, "Statistics reply" },
{ RPCAP_MSG_ENDCAP_REPLY, "End capture reply" },
{ RPCAP_MSG_SETSAMPLING_REPLY, "Set sampling reply" },
{ 0, NULL }
};
static const value_string error_codes[] = {
{ RPCAP_ERR_NETW, "Network error" },
{ RPCAP_ERR_INITTIMEOUT, "Initial timeout has expired" },
{ RPCAP_ERR_AUTH, "Authentication error" },
{ RPCAP_ERR_FINDALLIF, "Generic findalldevs error" },
{ RPCAP_ERR_NOREMOTEIF, "No remote interfaces" },
{ RPCAP_ERR_OPEN, "Generic pcap_open error" },
{ RPCAP_ERR_UPDATEFILTER, "Generic updatefilter error" },
{ RPCAP_ERR_GETSTATS, "Generic pcap_stats error" },
{ RPCAP_ERR_READEX, "Generic pcap_next_ex error" },
{ RPCAP_ERR_HOSTNOAUTH, "The host is not authorized" },
{ RPCAP_ERR_REMOTEACCEPT, "Generic pcap_remoteaccept error" },
{ RPCAP_ERR_STARTCAPTURE, "Generic pcap_startcapture error" },
{ RPCAP_ERR_ENDCAPTURE, "Generic pcap_endcapture error" },
{ RPCAP_ERR_RUNTIMETIMEOUT, "Runtime timeout has expired" },
{ RPCAP_ERR_SETSAMPLING, "Error in setting sampling parameters" },
{ RPCAP_ERR_WRONGMSG, "Unrecognized message" },
{ RPCAP_ERR_WRONGVER, "Incompatible version" },
{ 0, NULL }
};
static const value_string sampling_method[] = {
{ RPCAP_SAMP_NOSAMP, "No sampling" },
{ RPCAP_SAMP_1_EVERY_N, "1 every N" },
{ RPCAP_SAMP_FIRST_AFTER_N_MS, "First after N ms" },
{ 0, NULL }
};
static const value_string auth_type[] = {
{ RPCAP_RMTAUTH_NULL, "None" },
{ RPCAP_RMTAUTH_PWD, "Password" },
{ 0, NULL }
};
static const value_string address_family[] = {
{ COMMON_AF_UNSPEC, "AF_UNSPEC" },
{ COMMON_AF_INET, "AF_INET" },
{ 0, NULL }
};
static const value_string bpf_class[] = {
{ 0x00, "ld" },
{ 0x01, "ldx" },
{ 0x02, "st" },
{ 0x03, "stx" },
{ 0x04, "alu" },
{ 0x05, "jmp" },
{ 0x06, "ret" },
{ 0x07, "misc" },
{ 0, NULL }
};
static const value_string bpf_size[] = {
{ 0x00, "w" },
{ 0x01, "h" },
{ 0x02, "b" },
{ 0, NULL }
};
static const value_string bpf_mode[] = {
{ 0x00, "imm" },
{ 0x01, "abs" },
{ 0x02, "ind" },
{ 0x03, "mem" },
{ 0x04, "len" },
{ 0x05, "msh" },
{ 0, NULL }
};
static const value_string bpf_alu_op[] = {
{ 0x00, "add" },
{ 0x01, "sub" },
{ 0x02, "mul" },
{ 0x03, "div" },
{ 0x04, "or" },
{ 0x05, "and" },
{ 0x06, "lsh" },
{ 0x07, "rsh" },
{ 0x08, "neg" },
{ 0, NULL }
};
static const value_string bpf_jmp_op[] = {
{ 0x00, "ja" },
{ 0x01, "jeq" },
{ 0x02, "jgt" },
{ 0x03, "jge" },
{ 0x04, "jset" },
{ 0, NULL }
};
static const value_string bpf_src[] = {
{ 0x00, "k" },
{ 0x01, "x" },
{ 0, NULL }
};
static const value_string bpf_rval[] = {
{ 0x00, "k" },
{ 0x01, "x" },
{ 0x02, "a" },
{ 0, NULL }
};
static const value_string bpf_misc_op[] = {
{ 0x00, "tax" },
{ 0x10, "txa" },
{ 0, NULL }
};
static void rpcap_frame_end (void)
{
info_added = FALSE;
}
static void
dissect_rpcap_error (tvbuff_t *tvb, packet_info *pinfo,
proto_tree *parent_tree, gint offset)
{
proto_item *ti;
gint len;
len = tvb_captured_length_remaining (tvb, offset);
if (len <= 0)
return;
col_append_fstr (pinfo->cinfo, COL_INFO, ": %s",
tvb_format_text_wsp (tvb, offset, len));
ti = proto_tree_add_item (parent_tree, hf_error, tvb, offset, len, ENC_ASCII|ENC_NA);
expert_add_info_format(pinfo, ti, &ei_error,
"Error: %s", tvb_format_text_wsp (tvb, offset, len));
}
static gint
dissect_rpcap_ifaddr (tvbuff_t *tvb, packet_info *pinfo,
proto_tree *parent_tree, gint offset, int hf_id,
proto_item *parent_item)
{
proto_tree *tree;
proto_item *ti;
gchar ipaddr[MAX_ADDR_STR_LEN];
guint32 ipv4;
guint16 af;
ti = proto_tree_add_item (parent_tree, hf_id, tvb, offset, 128, ENC_BIG_ENDIAN);
tree = proto_item_add_subtree (ti, ett_ifaddr);
af = tvb_get_ntohs (tvb, offset);
proto_tree_add_item (tree, hf_if_af, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
if (af == COMMON_AF_INET) {
proto_tree_add_item (tree, hf_if_port, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
ipv4 = tvb_get_ipv4 (tvb, offset);
ip_to_str_buf((guint8 *)&ipv4, ipaddr, MAX_ADDR_STR_LEN);
proto_item_append_text (ti, ": %s", ipaddr);
if (parent_item) {
proto_item_append_text (parent_item, ": %s", ipaddr);
}
proto_tree_add_item (tree, hf_if_ip, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
proto_tree_add_item (tree, hf_if_padding, tvb, offset, 120, ENC_NA);
offset += 120;
} else {
ti = proto_tree_add_item (tree, hf_if_unknown, tvb, offset, 126, ENC_NA);
if (af != COMMON_AF_UNSPEC) {
expert_add_info_format(pinfo, ti, &ei_if_unknown,
"Unknown address family: %d", af);
}
offset += 126;
}
return offset;
}
static gint
dissect_rpcap_findalldevs_ifaddr (tvbuff_t *tvb, packet_info *pinfo _U_,
proto_tree *parent_tree, gint offset)
{
proto_tree *tree;
proto_item *ti;
gint boffset = offset;
ti = proto_tree_add_item (parent_tree, hf_findalldevs_ifaddr, tvb, offset, -1, ENC_NA);
tree = proto_item_add_subtree (ti, ett_findalldevs_ifaddr);
offset = dissect_rpcap_ifaddr (tvb, pinfo, tree, offset, hf_if_addr, ti);
offset = dissect_rpcap_ifaddr (tvb, pinfo, tree, offset, hf_if_netmask, NULL);
offset = dissect_rpcap_ifaddr (tvb, pinfo, tree, offset, hf_if_broadaddr, NULL);
offset = dissect_rpcap_ifaddr (tvb, pinfo, tree, offset, hf_if_dstaddr, NULL);
proto_item_set_len (ti, offset - boffset);
return offset;
}
static gint
dissect_rpcap_findalldevs_if (tvbuff_t *tvb, packet_info *pinfo _U_,
proto_tree *parent_tree, gint offset)
{
proto_tree *tree;
proto_item *ti;
guint16 namelen, desclen, naddr, i;
gint boffset = offset;
ti = proto_tree_add_item (parent_tree, hf_findalldevs_if, tvb, offset, -1, ENC_NA);
tree = proto_item_add_subtree (ti, ett_findalldevs_if);
namelen = tvb_get_ntohs (tvb, offset);
proto_tree_add_item (tree, hf_namelen, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
desclen = tvb_get_ntohs (tvb, offset);
proto_tree_add_item (tree, hf_desclen, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
proto_tree_add_item (tree, hf_if_flags, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
naddr = tvb_get_ntohs (tvb, offset);
proto_tree_add_item (tree, hf_naddr, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
proto_tree_add_item (tree, hf_dummy, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
if (namelen) {
proto_item_append_text (ti, ": %s", tvb_get_string_enc(wmem_packet_scope(), tvb, offset, namelen, ENC_ASCII));
proto_tree_add_item (tree, hf_if_name, tvb, offset, namelen, ENC_ASCII|ENC_NA);
offset += namelen;
}
if (desclen) {
proto_tree_add_item (tree, hf_if_desc, tvb, offset, desclen, ENC_ASCII|ENC_NA);
offset += desclen;
}
for (i = 0; i < naddr; i++) {
offset = dissect_rpcap_findalldevs_ifaddr (tvb, pinfo, tree, offset);
if (tvb_reported_length_remaining (tvb, offset) < 0) {
/* No more data in packet */
expert_add_info(pinfo, ti, &ei_no_more_data);
break;
}
}
proto_item_set_len (ti, offset - boffset);
return offset;
}
static void
dissect_rpcap_findalldevs_reply (tvbuff_t *tvb, packet_info *pinfo _U_,
proto_tree *parent_tree, gint offset, guint16 no_devs)
{
proto_tree *tree;
proto_item *ti;
guint16 i;
ti = proto_tree_add_item (parent_tree, hf_findalldevs_reply, tvb, offset, -1, ENC_NA);
tree = proto_item_add_subtree (ti, ett_findalldevs_reply);
for (i = 0; i < no_devs; i++) {
offset = dissect_rpcap_findalldevs_if (tvb, pinfo, tree, offset);
if (tvb_reported_length_remaining (tvb, offset) < 0) {
/* No more data in packet */
expert_add_info(pinfo, ti, &ei_no_more_data);
break;
}
}
proto_item_append_text (ti, ", %d item%s", no_devs, plurality (no_devs, "", "s"));
}
static gint
dissect_rpcap_filterbpf_insn (tvbuff_t *tvb, packet_info *pinfo _U_,
proto_tree *parent_tree, gint offset)
{
proto_tree *tree, *code_tree;
proto_item *ti, *code_ti;
guint8 inst_class;
ti = proto_tree_add_item (parent_tree, hf_filterbpf_insn, tvb, offset, 8, ENC_NA);
tree = proto_item_add_subtree (ti, ett_filterbpf_insn);
code_ti = proto_tree_add_item (tree, hf_code, tvb, offset, 2, ENC_BIG_ENDIAN);
code_tree = proto_item_add_subtree (code_ti, ett_filterbpf_insn_code);
proto_tree_add_item (code_tree, hf_code_class, tvb, offset, 2, ENC_BIG_ENDIAN);
inst_class = tvb_get_guint8 (tvb, offset + 1) & 0x07;
proto_item_append_text (ti, ": %s", val_to_str_const (inst_class, bpf_class, ""));
switch (inst_class) {
case 0x00: /* ld */
case 0x01: /* ldx */
proto_tree_add_item (code_tree, hf_code_ld_size, tvb, offset, 2, ENC_BIG_ENDIAN);
proto_tree_add_item (code_tree, hf_code_ld_mode, tvb, offset, 2, ENC_BIG_ENDIAN);
break;
case 0x04: /* alu */
proto_tree_add_item (code_tree, hf_code_src, tvb, offset, 2, ENC_BIG_ENDIAN);
proto_tree_add_item (code_tree, hf_code_alu_op, tvb, offset, 2, ENC_BIG_ENDIAN);
break;
case 0x05: /* jmp */
proto_tree_add_item (code_tree, hf_code_src, tvb, offset, 2, ENC_BIG_ENDIAN);
proto_tree_add_item (code_tree, hf_code_jmp_op, tvb, offset, 2, ENC_BIG_ENDIAN);
break;
case 0x06: /* ret */
proto_tree_add_item (code_tree, hf_code_rval, tvb, offset, 2, ENC_BIG_ENDIAN);
break;
case 0x07: /* misc */
proto_tree_add_item (code_tree, hf_code_misc_op, tvb, offset, 2, ENC_BIG_ENDIAN);
break;
default:
proto_tree_add_item (code_tree, hf_code_fields, tvb, offset, 2, ENC_BIG_ENDIAN);
break;
}
offset += 2;
proto_tree_add_item (tree, hf_jt, tvb, offset, 1, ENC_BIG_ENDIAN);
offset += 1;
proto_tree_add_item (tree, hf_jf, tvb, offset, 1, ENC_BIG_ENDIAN);
offset += 1;
proto_tree_add_item (tree, hf_instr_value, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
return offset;
}
static void
dissect_rpcap_filter (tvbuff_t *tvb, packet_info *pinfo,
proto_tree *parent_tree, gint offset)
{
proto_tree *tree;
proto_item *ti;
guint32 nitems, i;
ti = proto_tree_add_item (parent_tree, hf_filter, tvb, offset, -1, ENC_NA);
tree = proto_item_add_subtree (ti, ett_filter);
proto_tree_add_item (tree, hf_filtertype, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
proto_tree_add_item (tree, hf_dummy, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
nitems = tvb_get_ntohl (tvb, offset);
proto_tree_add_item (tree, hf_nitems, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
for (i = 0; i < nitems; i++) {
offset = dissect_rpcap_filterbpf_insn (tvb, pinfo, tree, offset);
if (tvb_reported_length_remaining (tvb, offset) < 0) {
/* No more data in packet */
expert_add_info(pinfo, ti, &ei_no_more_data);
break;
}
}
}
static int
dissect_rpcap_auth_request (tvbuff_t *tvb, packet_info *pinfo _U_,
proto_tree *parent_tree, gint offset)
{
proto_tree *tree;
proto_item *ti;
guint16 type, slen1, slen2;
ti = proto_tree_add_item (parent_tree, hf_auth_request, tvb, offset, -1, ENC_NA);
tree = proto_item_add_subtree (ti, ett_auth_request);
type = tvb_get_ntohs (tvb, offset);
proto_tree_add_item (tree, hf_auth_type, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
proto_tree_add_item (tree, hf_dummy, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
slen1 = tvb_get_ntohs (tvb, offset);
proto_tree_add_item (tree, hf_auth_slen1, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
slen2 = tvb_get_ntohs (tvb, offset);
proto_tree_add_item (tree, hf_auth_slen2, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
if (type == RPCAP_RMTAUTH_NULL) {
proto_item_append_text (ti, " (none)");
} else if (type == RPCAP_RMTAUTH_PWD) {
guint8 *username, *password;
username = tvb_get_string_enc(wmem_packet_scope(), tvb, offset, slen1, ENC_ASCII);
proto_tree_add_item (tree, hf_auth_username, tvb, offset, slen1, ENC_ASCII|ENC_NA);
offset += slen1;
password = tvb_get_string_enc(wmem_packet_scope(), tvb, offset, slen2, ENC_ASCII);
proto_tree_add_item (tree, hf_auth_password, tvb, offset, slen2, ENC_ASCII|ENC_NA);
offset += slen2;
proto_item_append_text (ti, " (%s/%s)", username, password);
}
return offset;
}
static void
dissect_rpcap_open_request (tvbuff_t *tvb, packet_info *pinfo _U_,
proto_tree *parent_tree, gint offset)
{
gint len;
len = tvb_captured_length_remaining (tvb, offset);
proto_tree_add_item (parent_tree, hf_open_request, tvb, offset, len, ENC_ASCII|ENC_NA);
}
static void
dissect_rpcap_open_reply (tvbuff_t *tvb, packet_info *pinfo _U_,
proto_tree *parent_tree, gint offset)
{
proto_tree *tree;
proto_item *ti;
ti = proto_tree_add_item (parent_tree, hf_open_reply, tvb, offset, -1, ENC_NA);
tree = proto_item_add_subtree (ti, ett_open_reply);
linktype = tvb_get_ntohl (tvb, offset);
proto_tree_add_item (tree, hf_linktype, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
proto_tree_add_item (tree, hf_tzoff, tvb, offset, 4, ENC_BIG_ENDIAN);
}
static void
dissect_rpcap_startcap_request (tvbuff_t *tvb, packet_info *pinfo,
proto_tree *parent_tree, gint offset)
{
proto_tree *tree, *field_tree;
proto_item *ti, *field_ti;
guint16 flags;
ti = proto_tree_add_item (parent_tree, hf_startcap_request, tvb, offset, -1, ENC_NA);
tree = proto_item_add_subtree (ti, ett_startcap_request);
proto_tree_add_item (tree, hf_snaplen, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
proto_tree_add_item (tree, hf_read_timeout, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
flags = tvb_get_ntohs (tvb, offset);
field_ti = proto_tree_add_uint_format (tree, hf_flags, tvb, offset, 2, flags, "Flags");
field_tree = proto_item_add_subtree (field_ti, ett_startcap_flags);
proto_tree_add_item (field_tree, hf_flags_promisc, tvb, offset, 2, ENC_BIG_ENDIAN);
proto_tree_add_item (field_tree, hf_flags_dgram, tvb, offset, 2, ENC_BIG_ENDIAN);
proto_tree_add_item (field_tree, hf_flags_serveropen, tvb, offset, 2, ENC_BIG_ENDIAN);
proto_tree_add_item (field_tree, hf_flags_inbound, tvb, offset, 2, ENC_BIG_ENDIAN);
proto_tree_add_item (field_tree, hf_flags_outbound, tvb, offset, 2, ENC_BIG_ENDIAN);
if (flags & 0x1F) {
gchar *flagstr = wmem_strdup_printf (wmem_packet_scope(), "%s%s%s%s%s",
(flags & FLAG_PROMISC) ? ", Promiscuous" : "",
(flags & FLAG_DGRAM) ? ", Datagram" : "",
(flags & FLAG_SERVEROPEN) ? ", ServerOpen" : "",
(flags & FLAG_INBOUND) ? ", Inbound" : "",
(flags & FLAG_OUTBOUND) ? ", Outbound" : "");
proto_item_append_text (field_ti, ":%s", &flagstr[1]);
} else {
proto_item_append_text (field_ti, " (none)");
}
offset += 2;
proto_tree_add_item (tree, hf_client_port, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
dissect_rpcap_filter (tvb, pinfo, tree, offset);
}
static void
dissect_rpcap_startcap_reply (tvbuff_t *tvb, packet_info *pinfo _U_,
proto_tree *parent_tree, gint offset)
{
proto_tree *tree;
proto_item *ti;
ti = proto_tree_add_item (parent_tree, hf_startcap_reply, tvb, offset, -1, ENC_NA);
tree = proto_item_add_subtree (ti, ett_startcap_reply);
proto_tree_add_item (tree, hf_bufsize, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
proto_tree_add_item (tree, hf_server_port, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
proto_tree_add_item (tree, hf_dummy, tvb, offset, 2, ENC_BIG_ENDIAN);
}
static void
dissect_rpcap_stats_reply (tvbuff_t *tvb, packet_info *pinfo _U_,
proto_tree *parent_tree, gint offset)
{
proto_tree *tree;
proto_item *ti;
ti = proto_tree_add_item (parent_tree, hf_stats_reply, tvb, offset, 16, ENC_NA);
tree = proto_item_add_subtree (ti, ett_stats_reply);
proto_tree_add_item (tree, hf_ifrecv, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
proto_tree_add_item (tree, hf_ifdrop, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
proto_tree_add_item (tree, hf_krnldrop, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
proto_tree_add_item (tree, hf_srvcapt, tvb, offset, 4, ENC_BIG_ENDIAN);
}
static int
dissect_rpcap_sampling_request (tvbuff_t *tvb, packet_info *pinfo _U_,
proto_tree *parent_tree, gint offset)
{
proto_tree *tree;
proto_item *ti;
guint32 value;
guint8 method;
ti = proto_tree_add_item (parent_tree, hf_sampling_request, tvb, offset, -1, ENC_NA);
tree = proto_item_add_subtree (ti, ett_sampling_request);
method = tvb_get_guint8 (tvb, offset);
proto_tree_add_item (tree, hf_sampling_method, tvb, offset, 1, ENC_BIG_ENDIAN);
offset += 1;
proto_tree_add_item (tree, hf_sampling_dummy1, tvb, offset, 1, ENC_BIG_ENDIAN);
offset += 1;
proto_tree_add_item (tree, hf_sampling_dummy2, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
value = tvb_get_ntohl (tvb, offset);
proto_tree_add_item (tree, hf_sampling_value, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
switch (method) {
case RPCAP_SAMP_NOSAMP:
proto_item_append_text (ti, ": None");
break;
case RPCAP_SAMP_1_EVERY_N:
proto_item_append_text (ti, ": 1 every %d", value);
break;
case RPCAP_SAMP_FIRST_AFTER_N_MS:
proto_item_append_text (ti, ": First after %d ms", value);
break;
default:
break;
}
return offset;
}
static void
dissect_rpcap_packet (tvbuff_t *tvb, packet_info *pinfo, proto_tree *top_tree,
proto_tree *parent_tree, gint offset, proto_item *top_item)
{
proto_tree *tree;
proto_item *ti;
nstime_t ts;
tvbuff_t *new_tvb;
guint caplen, len, frame_no;
gint reported_length_remaining;
struct eth_phdr eth;
void *phdr;
ti = proto_tree_add_item (parent_tree, hf_packet, tvb, offset, 20, ENC_NA);
tree = proto_item_add_subtree (ti, ett_packet);
ts.secs = tvb_get_ntohl (tvb, offset);
ts.nsecs = tvb_get_ntohl (tvb, offset + 4) * 1000;
proto_tree_add_time(tree, hf_timestamp, tvb, offset, 8, &ts);
offset += 8;
caplen = tvb_get_ntohl (tvb, offset);
ti = proto_tree_add_item (tree, hf_caplen, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
len = tvb_get_ntohl (tvb, offset);
proto_tree_add_item (tree, hf_len, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
frame_no = tvb_get_ntohl (tvb, offset);
proto_tree_add_item (tree, hf_npkt, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
proto_item_append_text (ti, ", Frame %u", frame_no);
proto_item_append_text (top_item, " Frame %u", frame_no);
/*
* reported_length_remaining should not be -1, as offset is at
* most right past the end of the available data in the packet.
*/
reported_length_remaining = tvb_reported_length_remaining (tvb, offset);
if (caplen > (guint)reported_length_remaining) {
expert_add_info(pinfo, ti, &ei_caplen_too_big);
return;
}
new_tvb = tvb_new_subset (tvb, offset, caplen, len);
if (decode_content && linktype != WTAP_ENCAP_UNKNOWN) {
switch (linktype) {
case WTAP_ENCAP_ETHERNET:
eth.fcs_len = -1; /* Unknown whether we have an FCS */
phdr = ð
break;
default:
phdr = NULL;
break;
}
dissector_try_uint_new(wtap_encap_dissector_table, linktype, new_tvb, pinfo, top_tree, TRUE, phdr);
if (!info_added) {
/* Only indicate when not added before */
/* Indicate RPCAP in the protocol column */
col_prepend_fence_fstr(pinfo->cinfo, COL_PROTOCOL, "R|");
/* Indicate RPCAP in the info column */
col_prepend_fence_fstr (pinfo->cinfo, COL_INFO, "Remote | ");
info_added = TRUE;
register_frame_end_routine(pinfo, rpcap_frame_end);
}
} else {
if (linktype == WTAP_ENCAP_UNKNOWN) {
proto_item_append_text (ti, ", Unknown link-layer type");
}
call_dissector (data_handle, new_tvb, pinfo, top_tree);
}
}
static int
dissect_rpcap (tvbuff_t *tvb, packet_info *pinfo, proto_tree *top_tree, void* data _U_)
{
proto_tree *tree;
proto_item *ti;
tvbuff_t *new_tvb;
gint len, offset = 0;
guint8 msg_type;
guint16 msg_value;
col_set_str (pinfo->cinfo, COL_PROTOCOL, PSNAME);
col_clear(pinfo->cinfo, COL_INFO);
ti = proto_tree_add_item (top_tree, proto_rpcap, tvb, offset, -1, ENC_NA);
tree = proto_item_add_subtree (ti, ett_rpcap);
proto_tree_add_item (tree, hf_version, tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
msg_type = tvb_get_guint8 (tvb, offset);
proto_tree_add_item (tree, hf_type, tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
col_append_fstr (pinfo->cinfo, COL_INFO, "%s",
val_to_str (msg_type, message_type, "Unknown: %d"));
proto_item_append_text (ti, ", %s", val_to_str (msg_type, message_type, "Unknown: %d"));
msg_value = tvb_get_ntohs (tvb, offset);
if (msg_type == RPCAP_MSG_ERROR) {
proto_tree_add_item (tree, hf_error_value, tvb, offset, 2, ENC_BIG_ENDIAN);
} else {
proto_tree_add_item (tree, hf_value, tvb, offset, 2, ENC_BIG_ENDIAN);
}
offset += 2;
proto_tree_add_item (tree, hf_plen, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
switch (msg_type) {
case RPCAP_MSG_ERROR:
dissect_rpcap_error (tvb, pinfo, tree, offset);
break;
case RPCAP_MSG_OPEN_REQ:
dissect_rpcap_open_request (tvb, pinfo, tree, offset);
break;
case RPCAP_MSG_STARTCAP_REQ:
dissect_rpcap_startcap_request (tvb, pinfo, tree, offset);
break;
case RPCAP_MSG_UPDATEFILTER_REQ:
dissect_rpcap_filter (tvb, pinfo, tree, offset);
break;
case RPCAP_MSG_PACKET:
proto_item_set_len (ti, 28);
dissect_rpcap_packet (tvb, pinfo, top_tree, tree, offset, ti);
break;
case RPCAP_MSG_AUTH_REQ:
dissect_rpcap_auth_request (tvb, pinfo, tree, offset);
break;
case RPCAP_MSG_SETSAMPLING_REQ:
dissect_rpcap_sampling_request (tvb, pinfo, tree, offset);
break;
case RPCAP_MSG_FINDALLIF_REPLY:
dissect_rpcap_findalldevs_reply (tvb, pinfo, tree, offset, msg_value);
break;
case RPCAP_MSG_OPEN_REPLY:
dissect_rpcap_open_reply (tvb, pinfo, tree, offset);
break;
case RPCAP_MSG_STARTCAP_REPLY:
dissect_rpcap_startcap_reply (tvb, pinfo, tree, offset);
break;
case RPCAP_MSG_STATS_REPLY:
dissect_rpcap_stats_reply (tvb, pinfo, tree, offset);
break;
default:
len = tvb_reported_length_remaining (tvb, offset);
if (len) {
/* Yet unknown, dump as data */
proto_item_set_len (ti, 8);
new_tvb = tvb_new_subset_remaining (tvb, offset);
call_dissector (data_handle, new_tvb, pinfo, top_tree);
}
break;
}
return tvb_captured_length(tvb);
}
static gboolean
check_rpcap_heur (tvbuff_t *tvb, gboolean tcp)
{
gint offset = 0;
guint8 version, msg_type;
guint16 msg_value;
guint32 plen, len, caplen;
if (tvb_captured_length (tvb) < 8)
/* Too short */
return FALSE;
version = tvb_get_guint8 (tvb, offset);
if (version != 0)
/* Incorrect version */
return FALSE;
offset++;
msg_type = tvb_get_guint8 (tvb, offset);
if (!tcp && msg_type != 7) {
/* UDP is only used for packets */
return FALSE;
}
if (try_val_to_str(msg_type, message_type) == NULL)
/* Unknown message type */
return FALSE;
offset++;
msg_value = tvb_get_ntohs (tvb, offset);
if (msg_value > 0) {
if (msg_type == RPCAP_MSG_ERROR) {
/* Must have a valid error code */
if (try_val_to_str(msg_value, error_codes) == NULL)
return FALSE;
} else if (msg_type != RPCAP_MSG_FINDALLIF_REPLY) {
return FALSE;
}
}
offset += 2;
plen = tvb_get_ntohl (tvb, offset);
offset += 4;
len = (guint32) tvb_reported_length_remaining (tvb, offset);
switch (msg_type) {
case RPCAP_MSG_FINDALLIF_REQ:
case RPCAP_MSG_UPDATEFILTER_REPLY:
case RPCAP_MSG_AUTH_REPLY:
case RPCAP_MSG_STATS_REQ:
case RPCAP_MSG_CLOSE:
case RPCAP_MSG_SETSAMPLING_REPLY:
case RPCAP_MSG_ENDCAP_REQ:
case RPCAP_MSG_ENDCAP_REPLY:
/* Empty payload */
if (plen != 0 || len != 0)
return FALSE;
break;
case RPCAP_MSG_OPEN_REPLY:
case RPCAP_MSG_STARTCAP_REPLY:
case RPCAP_MSG_SETSAMPLING_REQ:
/* Always 8 bytes */
if (plen != 8 || len != 8)
return FALSE;
break;
case RPCAP_MSG_STATS_REPLY:
/* Always 16 bytes */
if (plen != 16 || len != 16)
return FALSE;
break;
case RPCAP_MSG_PACKET:
/* Must have the frame header */
if (plen < 20)
return FALSE;
/* Check if capture length is valid */
caplen = tvb_get_ntohl (tvb, offset+8);
/* Always 20 bytes less than packet length */
if (caplen != (plen - 20) || caplen > 65535)
return FALSE;
break;
case RPCAP_MSG_FINDALLIF_REPLY:
case RPCAP_MSG_ERROR:
case RPCAP_MSG_OPEN_REQ:
case RPCAP_MSG_STARTCAP_REQ:
case RPCAP_MSG_UPDATEFILTER_REQ:
case RPCAP_MSG_AUTH_REQ:
/* Variable length */
if (plen != len)
return FALSE;
break;
default:
/* Unknown message type */
return FALSE;
}
return TRUE;
}
static guint
get_rpcap_pdu_len (packet_info *pinfo _U_, tvbuff_t *tvb, int offset, void *data _U_)
{
return tvb_get_ntohl (tvb, offset + 4) + 8;
}
static gboolean
dissect_rpcap_heur_tcp (tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
if (check_rpcap_heur (tvb, TRUE)) {
/* This is probably a rpcap tcp package */
tcp_dissect_pdus (tvb, pinfo, tree, rpcap_desegment, 8,
get_rpcap_pdu_len, dissect_rpcap, data);
return TRUE;
}
return FALSE;
}
static gboolean
dissect_rpcap_heur_udp (tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
if (check_rpcap_heur (tvb, FALSE)) {
/* This is probably a rpcap udp package */
dissect_rpcap (tvb, pinfo, tree, data);
return TRUE;
}
return FALSE;
}
void
proto_register_rpcap (void)
{
static hf_register_info hf[] = {
/* Common header for all messages */
{ &hf_version,
{ "Version", "rpcap.version", FT_UINT8, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_type,
{ "Message type", "rpcap.type", FT_UINT8, BASE_DEC,
VALS(message_type), 0x0, NULL, HFILL } },
{ &hf_value,
{ "Message value", "rpcap.value", FT_UINT16, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_plen,
{ "Payload length", "rpcap.len", FT_UINT32, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
/* Error */
{ &hf_error,
{ "Error", "rpcap.error", FT_STRING, BASE_NONE,
NULL, 0x0, "Error text", HFILL } },
{ &hf_error_value,
{ "Error value", "rpcap.error_value", FT_UINT16, BASE_DEC,
VALS(error_codes), 0x0, NULL, HFILL } },
/* Packet header */
{ &hf_packet,
{ "Packet", "rpcap.packet", FT_NONE, BASE_NONE,
NULL, 0x0, "Packet data", HFILL } },
{ &hf_timestamp,
{ "Arrival time", "rpcap.time", FT_ABSOLUTE_TIME, ABSOLUTE_TIME_LOCAL,
NULL, 0x0, NULL, HFILL } },
{ &hf_caplen,
{ "Capture length", "rpcap.cap_len", FT_UINT32, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_len,
{ "Frame length", "rpcap.len", FT_UINT32, BASE_DEC,
NULL, 0x0, "Frame length (off wire)", HFILL } },
{ &hf_npkt,
{ "Frame number", "rpcap.number", FT_UINT32, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
/* Authentication request */
{ &hf_auth_request,
{ "Authentication", "rpcap.auth", FT_NONE, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
{ &hf_auth_type,
{ "Authentication type", "rpcap.auth_type", FT_UINT16, BASE_DEC,
VALS(auth_type), 0x0, NULL, HFILL } },
{ &hf_auth_slen1,
{ "Authentication item length 1", "rpcap.auth_len1", FT_UINT16, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_auth_slen2,
{ "Authentication item length 2", "rpcap.auth_len2", FT_UINT16, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_auth_username,
{ "Username", "rpcap.username", FT_STRING, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
{ &hf_auth_password,
{ "Password", "rpcap.password", FT_STRING, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
/* Open request */
{ &hf_open_request,
{ "Open request", "rpcap.open_request", FT_STRING, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
/* Open reply */
{ &hf_open_reply,
{ "Open reply", "rpcap.open_reply", FT_NONE, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
{ &hf_linktype,
{ "Link type", "rpcap.linktype", FT_UINT32, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_tzoff,
{ "Timezone offset", "rpcap.tzoff", FT_UINT32, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
/* Start capture request */
{ &hf_startcap_request,
{ "Start capture request", "rpcap.startcap_request", FT_NONE, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
{ &hf_snaplen,
{ "Snap length", "rpcap.snaplen", FT_UINT32, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_read_timeout,
{ "Read timeout", "rpcap.read_timeout", FT_UINT32, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_flags,
{ "Flags", "rpcap.flags", FT_UINT16, BASE_DEC,
NULL, 0x0, "Capture flags", HFILL } },
{ &hf_flags_promisc,
{ "Promiscuous mode", "rpcap.flags.promisc", FT_BOOLEAN, 16,
TFS(&tfs_enabled_disabled), FLAG_PROMISC, NULL, HFILL } },
{ &hf_flags_dgram,
{ "Use Datagram", "rpcap.flags.dgram", FT_BOOLEAN, 16,
TFS(&tfs_yes_no), FLAG_DGRAM, NULL, HFILL } },
{ &hf_flags_serveropen,
{ "Server open", "rpcap.flags.serveropen", FT_BOOLEAN, 16,
TFS(&open_closed), FLAG_SERVEROPEN, NULL, HFILL } },
{ &hf_flags_inbound,
{ "Inbound", "rpcap.flags.inbound", FT_BOOLEAN, 16,
TFS(&tfs_yes_no), FLAG_INBOUND, NULL, HFILL } },
{ &hf_flags_outbound,
{ "Outbound", "rpcap.flags.outbound", FT_BOOLEAN, 16,
TFS(&tfs_yes_no), FLAG_OUTBOUND, NULL, HFILL } },
{ &hf_client_port,
{ "Client Port", "rpcap.client_port", FT_UINT16, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
/* Start capture reply */
{ &hf_startcap_reply,
{ "Start capture reply", "rpcap.startcap_reply", FT_NONE, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
{ &hf_bufsize,
{ "Buffer size", "rpcap.bufsize", FT_UINT32, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_server_port,
{ "Server port", "rpcap.server_port", FT_UINT16, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_dummy,
{ "Dummy", "rpcap.dummy", FT_UINT16, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
/* Filter */
{ &hf_filter,
{ "Filter", "rpcap.filter", FT_NONE, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
{ &hf_filtertype,
{ "Filter type", "rpcap.filtertype", FT_UINT16, BASE_DEC,
NULL, 0x0, "Filter type (BPF)", HFILL } },
{ &hf_nitems,
{ "Number of items", "rpcap.nitems", FT_UINT32, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
/* Filter BPF instruction */
{ &hf_filterbpf_insn,
{ "Filter BPF instruction", "rpcap.filterbpf_insn", FT_NONE, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
{ &hf_code,
{ "Op code", "rpcap.opcode", FT_UINT16, BASE_HEX,
NULL, 0x0, "Operation code", HFILL } },
{ &hf_code_class,
{ "Class", "rpcap.opcode.class", FT_UINT16, BASE_HEX,
VALS(bpf_class), 0x07, "Instruction Class", HFILL } },
{ &hf_code_fields,
{ "Fields", "rpcap.opcode.fields", FT_UINT16, BASE_HEX,
NULL, 0xF8, "Class Fields", HFILL } },
{ &hf_code_ld_size,
{ "Size", "rpcap.opcode.size", FT_UINT16, BASE_HEX,
VALS(bpf_size), 0x18, NULL, HFILL } },
{ &hf_code_ld_mode,
{ "Mode", "rpcap.opcode.mode", FT_UINT16, BASE_HEX,
VALS(bpf_mode), 0xE0, NULL, HFILL } },
{ &hf_code_alu_op,
{ "Op", "rpcap.opcode.aluop", FT_UINT16, BASE_HEX,
VALS(bpf_alu_op), 0xF0, NULL, HFILL } },
{ &hf_code_jmp_op,
{ "Op", "rpcap.opcode.jmpop", FT_UINT16, BASE_HEX,
VALS(bpf_jmp_op), 0xF0, NULL, HFILL } },
{ &hf_code_src,
{ "Src", "rpcap.opcode.src", FT_UINT16, BASE_HEX,
VALS(bpf_src), 0x08, NULL, HFILL } },
{ &hf_code_rval,
{ "Rval", "rpcap.opcode.rval", FT_UINT16, BASE_HEX,
VALS(bpf_rval), 0x18, NULL, HFILL } },
{ &hf_code_misc_op,
{ "Op", "rpcap.opcode.miscop", FT_UINT16, BASE_HEX,
VALS(bpf_misc_op), 0xF8, NULL, HFILL } },
{ &hf_jt,
{ "JT", "rpcap.jt", FT_UINT8, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_jf,
{ "JF", "rpcap.jf", FT_UINT8, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_instr_value,
{ "Instruction value", "rpcap.instr_value", FT_UINT32, BASE_DEC,
NULL, 0x0, "Instruction-Dependent value", HFILL } },
/* Statistics reply */
{ &hf_stats_reply,
{ "Statistics", "rpcap.stats_reply", FT_NONE, BASE_NONE,
NULL, 0x0, "Statistics reply data", HFILL } },
{ &hf_ifrecv,
{ "Received by kernel filter", "rpcap.ifrecv", FT_UINT32, BASE_DEC,
NULL, 0x0, "Received by kernel", HFILL } },
{ &hf_ifdrop,
{ "Dropped by network interface", "rpcap.ifdrop", FT_UINT32, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_krnldrop,
{ "Dropped by kernel filter", "rpcap.krnldrop", FT_UINT32, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_srvcapt,
{ "Captured by rpcapd", "rpcap.srvcapt", FT_UINT32, BASE_DEC,
NULL, 0x0, "Captured by RPCAP daemon", HFILL } },
/* Find all devices reply */
{ &hf_findalldevs_reply,
{ "Find all devices", "rpcap.findalldevs_reply", FT_NONE, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
{ &hf_findalldevs_if,
{ "Interface", "rpcap.if", FT_NONE, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
{ &hf_namelen,
{ "Name length", "rpcap.namelen", FT_UINT16, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_desclen,
{ "Description length", "rpcap.desclen", FT_UINT32, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_if_flags,
{ "Interface flags", "rpcap.if.flags", FT_UINT32, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_naddr,
{ "Number of addresses", "rpcap.naddr", FT_UINT32, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_if_name,
{ "Name", "rpcap.ifname", FT_STRING, BASE_NONE,
NULL, 0x0, "Interface name", HFILL } },
{ &hf_if_desc,
{ "Description", "rpcap.ifdesc", FT_STRING, BASE_NONE,
NULL, 0x0, "Interface description", HFILL } },
/* Find all devices / Interface addresses */
{ &hf_findalldevs_ifaddr,
{ "Interface address", "rpcap.ifaddr", FT_NONE, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
{ &hf_if_addr,
{ "Address", "rpcap.addr", FT_NONE, BASE_NONE,
NULL, 0x0, "Network address", HFILL } },
{ &hf_if_netmask,
{ "Netmask", "rpcap.netmask", FT_NONE, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
{ &hf_if_broadaddr,
{ "Broadcast", "rpcap.broadaddr", FT_NONE, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
{ &hf_if_dstaddr,
{ "P2P destination address", "rpcap.dstaddr", FT_NONE, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
{ &hf_if_af,
{ "Address family", "rpcap.if.af", FT_UINT16, BASE_HEX,
VALS(address_family), 0x0, NULL, HFILL } },
{ &hf_if_port,
{ "Port", "rpcap.if.port", FT_UINT16, BASE_DEC,
NULL, 0x0, "Port number", HFILL } },
{ &hf_if_ip,
{ "IP address", "rpcap.if.ip", FT_IPv4, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
{ &hf_if_padding,
{ "Padding", "rpcap.if.padding", FT_BYTES, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
{ &hf_if_unknown,
{ "Unknown address", "rpcap.if.unknown", FT_BYTES, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
/* Sampling request */
{ &hf_sampling_request,
{ "Sampling", "rpcap.sampling_request", FT_NONE, BASE_NONE,
NULL, 0x0, NULL, HFILL } },
{ &hf_sampling_method,
{ "Method", "rpcap.sampling_method", FT_UINT8, BASE_DEC,
VALS(sampling_method), 0x0, "Sampling method", HFILL } },
{ &hf_sampling_dummy1,
{ "Dummy1", "rpcap.dummy", FT_UINT8, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_sampling_dummy2,
{ "Dummy2", "rpcap.dummy", FT_UINT16, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
{ &hf_sampling_value,
{ "Value", "rpcap.sampling_value", FT_UINT32, BASE_DEC,
NULL, 0x0, NULL, HFILL } },
};
static gint *ett[] = {
&ett_rpcap,
&ett_error,
&ett_packet,
&ett_auth_request,
&ett_open_reply,
&ett_startcap_request,
&ett_startcap_reply,
&ett_startcap_flags,
&ett_filter,
&ett_filterbpf_insn,
&ett_filterbpf_insn_code,
&ett_stats_reply,
&ett_findalldevs_reply,
&ett_findalldevs_if,
&ett_findalldevs_ifaddr,
&ett_ifaddr,
&ett_sampling_request
};
static ei_register_info ei[] = {
{ &ei_error, { "rpcap.error.expert", PI_SEQUENCE, PI_NOTE, "Error", EXPFILL }},
{ &ei_if_unknown, { "rpcap.if_unknown", PI_SEQUENCE, PI_NOTE, "Unknown address family", EXPFILL }},
{ &ei_no_more_data, { "rpcap.no_more_data", PI_MALFORMED, PI_ERROR, "No more data in packet", EXPFILL }},
{ &ei_caplen_too_big, { "rpcap.caplen_too_big", PI_MALFORMED, PI_ERROR, "Caplen is bigger than the remaining message length", EXPFILL }},
};
module_t *rpcap_module;
expert_module_t* expert_rpcap;
proto_rpcap = proto_register_protocol (PNAME, PSNAME, PFNAME);
new_register_dissector (PFNAME, dissect_rpcap, proto_rpcap);
expert_rpcap = expert_register_protocol(proto_rpcap);
expert_register_field_array(expert_rpcap, ei, array_length(ei));
proto_register_field_array (proto_rpcap, hf, array_length (hf));
proto_register_subtree_array (ett, array_length (ett));
/* Register our configuration options */
rpcap_module = prefs_register_protocol (proto_rpcap, proto_reg_handoff_rpcap);
prefs_register_bool_preference (rpcap_module, "desegment_pdus",
"Reassemble PDUs spanning multiple TCP segments",
"Whether the RPCAP dissector should reassemble PDUs"
" spanning multiple TCP segments."
" To use this option, you must also enable \"Allow subdissectors"
" to reassemble TCP streams\" in the TCP protocol settings.",
&rpcap_desegment);
prefs_register_bool_preference (rpcap_module, "decode_content",
"Decode content according to link-layer type",
"Whether the packets should be decoded according to"
" the link-layer type.",
&decode_content);
prefs_register_uint_preference (rpcap_module, "linktype",
"Default link-layer type",
"Default link-layer type to use if an Open Reply packet"
" has not been received.",
10, &global_linktype);
}
void
proto_reg_handoff_rpcap (void)
{
static gboolean rpcap_prefs_initialized = FALSE;
if (!rpcap_prefs_initialized) {
data_handle = find_dissector ("data");
rpcap_prefs_initialized = TRUE;
heur_dissector_add ("tcp", dissect_rpcap_heur_tcp, "RPCAP over TCP", "rpcap_tcp", proto_rpcap, HEURISTIC_ENABLE);
heur_dissector_add ("udp", dissect_rpcap_heur_udp, "RPCAP over UDP", "rpcap_udp", proto_rpcap, HEURISTIC_ENABLE);
}
info_added = FALSE;
linktype = global_linktype;
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local Variables:
* c-basic-offset: 2
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* ex: set shiftwidth=2 tabstop=8 expandtab:
* :indentSize=2:tabSize=8:noTabs=true:
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5115_2 |
crossvul-cpp_data_bad_1762_0 | /* Key garbage collector
*
* Copyright (C) 2009-2011 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/security.h>
#include <keys/keyring-type.h>
#include "internal.h"
/*
* Delay between key revocation/expiry in seconds
*/
unsigned key_gc_delay = 5 * 60;
/*
* Reaper for unused keys.
*/
static void key_garbage_collector(struct work_struct *work);
DECLARE_WORK(key_gc_work, key_garbage_collector);
/*
* Reaper for links from keyrings to dead keys.
*/
static void key_gc_timer_func(unsigned long);
static DEFINE_TIMER(key_gc_timer, key_gc_timer_func, 0, 0);
static time_t key_gc_next_run = LONG_MAX;
static struct key_type *key_gc_dead_keytype;
static unsigned long key_gc_flags;
#define KEY_GC_KEY_EXPIRED 0 /* A key expired and needs unlinking */
#define KEY_GC_REAP_KEYTYPE 1 /* A keytype is being unregistered */
#define KEY_GC_REAPING_KEYTYPE 2 /* Cleared when keytype reaped */
/*
* Any key whose type gets unregistered will be re-typed to this if it can't be
* immediately unlinked.
*/
struct key_type key_type_dead = {
.name = "dead",
};
/*
* Schedule a garbage collection run.
* - time precision isn't particularly important
*/
void key_schedule_gc(time_t gc_at)
{
unsigned long expires;
time_t now = current_kernel_time().tv_sec;
kenter("%ld", gc_at - now);
if (gc_at <= now || test_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags)) {
kdebug("IMMEDIATE");
schedule_work(&key_gc_work);
} else if (gc_at < key_gc_next_run) {
kdebug("DEFERRED");
key_gc_next_run = gc_at;
expires = jiffies + (gc_at - now) * HZ;
mod_timer(&key_gc_timer, expires);
}
}
/*
* Schedule a dead links collection run.
*/
void key_schedule_gc_links(void)
{
set_bit(KEY_GC_KEY_EXPIRED, &key_gc_flags);
schedule_work(&key_gc_work);
}
/*
* Some key's cleanup time was met after it expired, so we need to get the
* reaper to go through a cycle finding expired keys.
*/
static void key_gc_timer_func(unsigned long data)
{
kenter("");
key_gc_next_run = LONG_MAX;
key_schedule_gc_links();
}
/*
* Reap keys of dead type.
*
* We use three flags to make sure we see three complete cycles of the garbage
* collector: the first to mark keys of that type as being dead, the second to
* collect dead links and the third to clean up the dead keys. We have to be
* careful as there may already be a cycle in progress.
*
* The caller must be holding key_types_sem.
*/
void key_gc_keytype(struct key_type *ktype)
{
kenter("%s", ktype->name);
key_gc_dead_keytype = ktype;
set_bit(KEY_GC_REAPING_KEYTYPE, &key_gc_flags);
smp_mb();
set_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags);
kdebug("schedule");
schedule_work(&key_gc_work);
kdebug("sleep");
wait_on_bit(&key_gc_flags, KEY_GC_REAPING_KEYTYPE,
TASK_UNINTERRUPTIBLE);
key_gc_dead_keytype = NULL;
kleave("");
}
/*
* Garbage collect a list of unreferenced, detached keys
*/
static noinline void key_gc_unused_keys(struct list_head *keys)
{
while (!list_empty(keys)) {
struct key *key =
list_entry(keys->next, struct key, graveyard_link);
list_del(&key->graveyard_link);
kdebug("- %u", key->serial);
key_check(key);
/* Throw away the key data */
if (key->type->destroy)
key->type->destroy(key);
security_key_free(key);
/* deal with the user's key tracking and quota */
if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
spin_lock(&key->user->lock);
key->user->qnkeys--;
key->user->qnbytes -= key->quotalen;
spin_unlock(&key->user->lock);
}
atomic_dec(&key->user->nkeys);
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
atomic_dec(&key->user->nikeys);
key_user_put(key->user);
kfree(key->description);
#ifdef KEY_DEBUGGING
key->magic = KEY_DEBUG_MAGIC_X;
#endif
kmem_cache_free(key_jar, key);
}
}
/*
* Garbage collector for unused keys.
*
* This is done in process context so that we don't have to disable interrupts
* all over the place. key_put() schedules this rather than trying to do the
* cleanup itself, which means key_put() doesn't have to sleep.
*/
static void key_garbage_collector(struct work_struct *work)
{
static LIST_HEAD(graveyard);
static u8 gc_state; /* Internal persistent state */
#define KEY_GC_REAP_AGAIN 0x01 /* - Need another cycle */
#define KEY_GC_REAPING_LINKS 0x02 /* - We need to reap links */
#define KEY_GC_SET_TIMER 0x04 /* - We need to restart the timer */
#define KEY_GC_REAPING_DEAD_1 0x10 /* - We need to mark dead keys */
#define KEY_GC_REAPING_DEAD_2 0x20 /* - We need to reap dead key links */
#define KEY_GC_REAPING_DEAD_3 0x40 /* - We need to reap dead keys */
#define KEY_GC_FOUND_DEAD_KEY 0x80 /* - We found at least one dead key */
struct rb_node *cursor;
struct key *key;
time_t new_timer, limit;
kenter("[%lx,%x]", key_gc_flags, gc_state);
limit = current_kernel_time().tv_sec;
if (limit > key_gc_delay)
limit -= key_gc_delay;
else
limit = key_gc_delay;
/* Work out what we're going to be doing in this pass */
gc_state &= KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2;
gc_state <<= 1;
if (test_and_clear_bit(KEY_GC_KEY_EXPIRED, &key_gc_flags))
gc_state |= KEY_GC_REAPING_LINKS | KEY_GC_SET_TIMER;
if (test_and_clear_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags))
gc_state |= KEY_GC_REAPING_DEAD_1;
kdebug("new pass %x", gc_state);
new_timer = LONG_MAX;
/* As only this function is permitted to remove things from the key
* serial tree, if cursor is non-NULL then it will always point to a
* valid node in the tree - even if lock got dropped.
*/
spin_lock(&key_serial_lock);
cursor = rb_first(&key_serial_tree);
continue_scanning:
while (cursor) {
key = rb_entry(cursor, struct key, serial_node);
cursor = rb_next(cursor);
if (atomic_read(&key->usage) == 0)
goto found_unreferenced_key;
if (unlikely(gc_state & KEY_GC_REAPING_DEAD_1)) {
if (key->type == key_gc_dead_keytype) {
gc_state |= KEY_GC_FOUND_DEAD_KEY;
set_bit(KEY_FLAG_DEAD, &key->flags);
key->perm = 0;
goto skip_dead_key;
}
}
if (gc_state & KEY_GC_SET_TIMER) {
if (key->expiry > limit && key->expiry < new_timer) {
kdebug("will expire %x in %ld",
key_serial(key), key->expiry - limit);
new_timer = key->expiry;
}
}
if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2))
if (key->type == key_gc_dead_keytype)
gc_state |= KEY_GC_FOUND_DEAD_KEY;
if ((gc_state & KEY_GC_REAPING_LINKS) ||
unlikely(gc_state & KEY_GC_REAPING_DEAD_2)) {
if (key->type == &key_type_keyring)
goto found_keyring;
}
if (unlikely(gc_state & KEY_GC_REAPING_DEAD_3))
if (key->type == key_gc_dead_keytype)
goto destroy_dead_key;
skip_dead_key:
if (spin_is_contended(&key_serial_lock) || need_resched())
goto contended;
}
contended:
spin_unlock(&key_serial_lock);
maybe_resched:
if (cursor) {
cond_resched();
spin_lock(&key_serial_lock);
goto continue_scanning;
}
/* We've completed the pass. Set the timer if we need to and queue a
* new cycle if necessary. We keep executing cycles until we find one
* where we didn't reap any keys.
*/
kdebug("pass complete");
if (gc_state & KEY_GC_SET_TIMER && new_timer != (time_t)LONG_MAX) {
new_timer += key_gc_delay;
key_schedule_gc(new_timer);
}
if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2) ||
!list_empty(&graveyard)) {
/* Make sure that all pending keyring payload destructions are
* fulfilled and that people aren't now looking at dead or
* dying keys that they don't have a reference upon or a link
* to.
*/
kdebug("gc sync");
synchronize_rcu();
}
if (!list_empty(&graveyard)) {
kdebug("gc keys");
key_gc_unused_keys(&graveyard);
}
if (unlikely(gc_state & (KEY_GC_REAPING_DEAD_1 |
KEY_GC_REAPING_DEAD_2))) {
if (!(gc_state & KEY_GC_FOUND_DEAD_KEY)) {
/* No remaining dead keys: short circuit the remaining
* keytype reap cycles.
*/
kdebug("dead short");
gc_state &= ~(KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2);
gc_state |= KEY_GC_REAPING_DEAD_3;
} else {
gc_state |= KEY_GC_REAP_AGAIN;
}
}
if (unlikely(gc_state & KEY_GC_REAPING_DEAD_3)) {
kdebug("dead wake");
smp_mb();
clear_bit(KEY_GC_REAPING_KEYTYPE, &key_gc_flags);
wake_up_bit(&key_gc_flags, KEY_GC_REAPING_KEYTYPE);
}
if (gc_state & KEY_GC_REAP_AGAIN)
schedule_work(&key_gc_work);
kleave(" [end %x]", gc_state);
return;
/* We found an unreferenced key - once we've removed it from the tree,
* we can safely drop the lock.
*/
found_unreferenced_key:
kdebug("unrefd key %d", key->serial);
rb_erase(&key->serial_node, &key_serial_tree);
spin_unlock(&key_serial_lock);
list_add_tail(&key->graveyard_link, &graveyard);
gc_state |= KEY_GC_REAP_AGAIN;
goto maybe_resched;
/* We found a keyring and we need to check the payload for links to
* dead or expired keys. We don't flag another reap immediately as we
* have to wait for the old payload to be destroyed by RCU before we
* can reap the keys to which it refers.
*/
found_keyring:
spin_unlock(&key_serial_lock);
keyring_gc(key, limit);
goto maybe_resched;
/* We found a dead key that is still referenced. Reset its type and
* destroy its payload with its semaphore held.
*/
destroy_dead_key:
spin_unlock(&key_serial_lock);
kdebug("destroy key %d", key->serial);
down_write(&key->sem);
key->type = &key_type_dead;
if (key_gc_dead_keytype->destroy)
key_gc_dead_keytype->destroy(key);
memset(&key->payload, KEY_DESTROY, sizeof(key->payload));
up_write(&key->sem);
goto maybe_resched;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1762_0 |
crossvul-cpp_data_bad_5711_2 | /* Generated by re2c 0.13.5 on Wed Mar 27 23:52:29 2013 */
#line 1 "Zend/zend_language_scanner.l"
/*
+----------------------------------------------------------------------+
| Zend Engine |
+----------------------------------------------------------------------+
| Copyright (c) 1998-2013 Zend Technologies Ltd. (http://www.zend.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 2.00 of the Zend license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.zend.com/license/2_00.txt. |
| If you did not receive a copy of the Zend license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@zend.com so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Marcus Boerger <helly@php.net> |
| Nuno Lopes <nlopess@php.net> |
| Scott MacVicar <scottmac@php.net> |
| Flex version authors: |
| Andi Gutmans <andi@zend.com> |
| Zeev Suraski <zeev@zend.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#if 0
# define YYDEBUG(s, c) printf("state: %d char: %c\n", s, c)
#else
# define YYDEBUG(s, c)
#endif
#include "zend_language_scanner_defs.h"
#include <errno.h>
#include "zend.h"
#ifdef PHP_WIN32
# include <Winuser.h>
#endif
#include "zend_alloc.h"
#include <zend_language_parser.h>
#include "zend_compile.h"
#include "zend_language_scanner.h"
#include "zend_highlight.h"
#include "zend_constants.h"
#include "zend_variables.h"
#include "zend_operators.h"
#include "zend_API.h"
#include "zend_strtod.h"
#include "zend_exceptions.h"
#include "tsrm_virtual_cwd.h"
#include "tsrm_config_common.h"
#define YYCTYPE unsigned char
#define YYFILL(n) { if ((YYCURSOR + n) >= (YYLIMIT + ZEND_MMAP_AHEAD)) { return 0; } }
#define YYCURSOR SCNG(yy_cursor)
#define YYLIMIT SCNG(yy_limit)
#define YYMARKER SCNG(yy_marker)
#define YYGETCONDITION() SCNG(yy_state)
#define YYSETCONDITION(s) SCNG(yy_state) = s
#define STATE(name) yyc##name
/* emulate flex constructs */
#define BEGIN(state) YYSETCONDITION(STATE(state))
#define YYSTATE YYGETCONDITION()
#define yytext ((char*)SCNG(yy_text))
#define yyleng SCNG(yy_leng)
#define yyless(x) do { YYCURSOR = (unsigned char*)yytext + x; \
yyleng = (unsigned int)x; } while(0)
#define yymore() goto yymore_restart
/* perform sanity check. If this message is triggered you should
increase the ZEND_MMAP_AHEAD value in the zend_streams.h file */
#define YYMAXFILL 16
#if ZEND_MMAP_AHEAD < YYMAXFILL
# error ZEND_MMAP_AHEAD should be greater than or equal to YYMAXFILL
#endif
#ifdef HAVE_STDARG_H
# include <stdarg.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
/* Globals Macros */
#define SCNG LANG_SCNG
#ifdef ZTS
ZEND_API ts_rsrc_id language_scanner_globals_id;
#else
ZEND_API zend_php_scanner_globals language_scanner_globals;
#endif
#define HANDLE_NEWLINES(s, l) \
do { \
char *p = (s), *boundary = p+(l); \
\
while (p<boundary) { \
if (*p == '\n' || (*p == '\r' && (*(p+1) != '\n'))) { \
CG(zend_lineno)++; \
} \
p++; \
} \
} while (0)
#define HANDLE_NEWLINE(c) \
{ \
if (c == '\n' || c == '\r') { \
CG(zend_lineno)++; \
} \
}
/* To save initial string length after scanning to first variable, CG(doc_comment_len) can be reused */
#define SET_DOUBLE_QUOTES_SCANNED_LENGTH(len) CG(doc_comment_len) = (len)
#define GET_DOUBLE_QUOTES_SCANNED_LENGTH() CG(doc_comment_len)
#define IS_LABEL_START(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z') || (c) == '_' || (c) >= 0x7F)
#define ZEND_IS_OCT(c) ((c)>='0' && (c)<='7')
#define ZEND_IS_HEX(c) (((c)>='0' && (c)<='9') || ((c)>='a' && (c)<='f') || ((c)>='A' && (c)<='F'))
BEGIN_EXTERN_C()
static size_t encoding_filter_script_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC)
{
const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C);
assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding));
return zend_multibyte_encoding_converter(to, to_length, from, from_length, internal_encoding, LANG_SCNG(script_encoding) TSRMLS_CC);
}
static size_t encoding_filter_script_to_intermediate(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC)
{
return zend_multibyte_encoding_converter(to, to_length, from, from_length, zend_multibyte_encoding_utf8, LANG_SCNG(script_encoding) TSRMLS_CC);
}
static size_t encoding_filter_intermediate_to_script(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC)
{
return zend_multibyte_encoding_converter(to, to_length, from, from_length,
LANG_SCNG(script_encoding), zend_multibyte_encoding_utf8 TSRMLS_CC);
}
static size_t encoding_filter_intermediate_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC)
{
const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C);
assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding));
return zend_multibyte_encoding_converter(to, to_length, from, from_length,
internal_encoding, zend_multibyte_encoding_utf8 TSRMLS_CC);
}
static void _yy_push_state(int new_state TSRMLS_DC)
{
zend_stack_push(&SCNG(state_stack), (void *) &YYGETCONDITION(), sizeof(int));
YYSETCONDITION(new_state);
}
#define yy_push_state(state_and_tsrm) _yy_push_state(yyc##state_and_tsrm)
static void yy_pop_state(TSRMLS_D)
{
int *stack_state;
zend_stack_top(&SCNG(state_stack), (void **) &stack_state);
YYSETCONDITION(*stack_state);
zend_stack_del_top(&SCNG(state_stack));
}
static void yy_scan_buffer(char *str, unsigned int len TSRMLS_DC)
{
YYCURSOR = (YYCTYPE*)str;
YYLIMIT = YYCURSOR + len;
if (!SCNG(yy_start)) {
SCNG(yy_start) = YYCURSOR;
}
}
void startup_scanner(TSRMLS_D)
{
CG(parse_error) = 0;
CG(heredoc) = NULL;
CG(heredoc_len) = 0;
CG(doc_comment) = NULL;
CG(doc_comment_len) = 0;
zend_stack_init(&SCNG(state_stack));
}
void shutdown_scanner(TSRMLS_D)
{
if (CG(heredoc)) {
efree(CG(heredoc));
CG(heredoc_len)=0;
}
CG(parse_error) = 0;
zend_stack_destroy(&SCNG(state_stack));
RESET_DOC_COMMENT();
}
ZEND_API void zend_save_lexical_state(zend_lex_state *lex_state TSRMLS_DC)
{
lex_state->yy_leng = SCNG(yy_leng);
lex_state->yy_start = SCNG(yy_start);
lex_state->yy_text = SCNG(yy_text);
lex_state->yy_cursor = SCNG(yy_cursor);
lex_state->yy_marker = SCNG(yy_marker);
lex_state->yy_limit = SCNG(yy_limit);
lex_state->state_stack = SCNG(state_stack);
zend_stack_init(&SCNG(state_stack));
lex_state->in = SCNG(yy_in);
lex_state->yy_state = YYSTATE;
lex_state->filename = zend_get_compiled_filename(TSRMLS_C);
lex_state->lineno = CG(zend_lineno);
lex_state->script_org = SCNG(script_org);
lex_state->script_org_size = SCNG(script_org_size);
lex_state->script_filtered = SCNG(script_filtered);
lex_state->script_filtered_size = SCNG(script_filtered_size);
lex_state->input_filter = SCNG(input_filter);
lex_state->output_filter = SCNG(output_filter);
lex_state->script_encoding = SCNG(script_encoding);
}
ZEND_API void zend_restore_lexical_state(zend_lex_state *lex_state TSRMLS_DC)
{
SCNG(yy_leng) = lex_state->yy_leng;
SCNG(yy_start) = lex_state->yy_start;
SCNG(yy_text) = lex_state->yy_text;
SCNG(yy_cursor) = lex_state->yy_cursor;
SCNG(yy_marker) = lex_state->yy_marker;
SCNG(yy_limit) = lex_state->yy_limit;
zend_stack_destroy(&SCNG(state_stack));
SCNG(state_stack) = lex_state->state_stack;
SCNG(yy_in) = lex_state->in;
YYSETCONDITION(lex_state->yy_state);
CG(zend_lineno) = lex_state->lineno;
zend_restore_compiled_filename(lex_state->filename TSRMLS_CC);
if (SCNG(script_filtered)) {
efree(SCNG(script_filtered));
SCNG(script_filtered) = NULL;
}
SCNG(script_org) = lex_state->script_org;
SCNG(script_org_size) = lex_state->script_org_size;
SCNG(script_filtered) = lex_state->script_filtered;
SCNG(script_filtered_size) = lex_state->script_filtered_size;
SCNG(input_filter) = lex_state->input_filter;
SCNG(output_filter) = lex_state->output_filter;
SCNG(script_encoding) = lex_state->script_encoding;
if (CG(heredoc)) {
efree(CG(heredoc));
CG(heredoc) = NULL;
CG(heredoc_len) = 0;
}
}
ZEND_API void zend_destroy_file_handle(zend_file_handle *file_handle TSRMLS_DC)
{
zend_llist_del_element(&CG(open_files), file_handle, (int (*)(void *, void *)) zend_compare_file_handles);
/* zend_file_handle_dtor() operates on the copy, so we have to NULLify the original here */
file_handle->opened_path = NULL;
if (file_handle->free_filename) {
file_handle->filename = NULL;
}
}
#define BOM_UTF32_BE "\x00\x00\xfe\xff"
#define BOM_UTF32_LE "\xff\xfe\x00\x00"
#define BOM_UTF16_BE "\xfe\xff"
#define BOM_UTF16_LE "\xff\xfe"
#define BOM_UTF8 "\xef\xbb\xbf"
static const zend_encoding *zend_multibyte_detect_utf_encoding(const unsigned char *script, size_t script_size TSRMLS_DC)
{
const unsigned char *p;
int wchar_size = 2;
int le = 0;
/* utf-16 or utf-32? */
p = script;
while ((p-script) < script_size) {
p = memchr(p, 0, script_size-(p-script)-2);
if (!p) {
break;
}
if (*(p+1) == '\0' && *(p+2) == '\0') {
wchar_size = 4;
break;
}
/* searching for UTF-32 specific byte orders, so this will do */
p += 4;
}
/* BE or LE? */
p = script;
while ((p-script) < script_size) {
if (*p == '\0' && *(p+wchar_size-1) != '\0') {
/* BE */
le = 0;
break;
} else if (*p != '\0' && *(p+wchar_size-1) == '\0') {
/* LE* */
le = 1;
break;
}
p += wchar_size;
}
if (wchar_size == 2) {
return le ? zend_multibyte_encoding_utf16le : zend_multibyte_encoding_utf16be;
} else {
return le ? zend_multibyte_encoding_utf32le : zend_multibyte_encoding_utf32be;
}
return NULL;
}
static const zend_encoding* zend_multibyte_detect_unicode(TSRMLS_D)
{
const zend_encoding *script_encoding = NULL;
int bom_size;
unsigned char *pos1, *pos2;
if (LANG_SCNG(script_org_size) < sizeof(BOM_UTF32_LE)-1) {
return NULL;
}
/* check out BOM */
if (!memcmp(LANG_SCNG(script_org), BOM_UTF32_BE, sizeof(BOM_UTF32_BE)-1)) {
script_encoding = zend_multibyte_encoding_utf32be;
bom_size = sizeof(BOM_UTF32_BE)-1;
} else if (!memcmp(LANG_SCNG(script_org), BOM_UTF32_LE, sizeof(BOM_UTF32_LE)-1)) {
script_encoding = zend_multibyte_encoding_utf32le;
bom_size = sizeof(BOM_UTF32_LE)-1;
} else if (!memcmp(LANG_SCNG(script_org), BOM_UTF16_BE, sizeof(BOM_UTF16_BE)-1)) {
script_encoding = zend_multibyte_encoding_utf16be;
bom_size = sizeof(BOM_UTF16_BE)-1;
} else if (!memcmp(LANG_SCNG(script_org), BOM_UTF16_LE, sizeof(BOM_UTF16_LE)-1)) {
script_encoding = zend_multibyte_encoding_utf16le;
bom_size = sizeof(BOM_UTF16_LE)-1;
} else if (!memcmp(LANG_SCNG(script_org), BOM_UTF8, sizeof(BOM_UTF8)-1)) {
script_encoding = zend_multibyte_encoding_utf8;
bom_size = sizeof(BOM_UTF8)-1;
}
if (script_encoding) {
/* remove BOM */
LANG_SCNG(script_org) += bom_size;
LANG_SCNG(script_org_size) -= bom_size;
return script_encoding;
}
/* script contains NULL bytes -> auto-detection */
if ((pos1 = memchr(LANG_SCNG(script_org), 0, LANG_SCNG(script_org_size)))) {
/* check if the NULL byte is after the __HALT_COMPILER(); */
pos2 = LANG_SCNG(script_org);
while (pos1 - pos2 >= sizeof("__HALT_COMPILER();")-1) {
pos2 = memchr(pos2, '_', pos1 - pos2);
if (!pos2) break;
pos2++;
if (strncasecmp((char*)pos2, "_HALT_COMPILER", sizeof("_HALT_COMPILER")-1) == 0) {
pos2 += sizeof("_HALT_COMPILER")-1;
while (*pos2 == ' ' ||
*pos2 == '\t' ||
*pos2 == '\r' ||
*pos2 == '\n') {
pos2++;
}
if (*pos2 == '(') {
pos2++;
while (*pos2 == ' ' ||
*pos2 == '\t' ||
*pos2 == '\r' ||
*pos2 == '\n') {
pos2++;
}
if (*pos2 == ')') {
pos2++;
while (*pos2 == ' ' ||
*pos2 == '\t' ||
*pos2 == '\r' ||
*pos2 == '\n') {
pos2++;
}
if (*pos2 == ';') {
return NULL;
}
}
}
}
}
/* make best effort if BOM is missing */
return zend_multibyte_detect_utf_encoding(LANG_SCNG(script_org), LANG_SCNG(script_org_size) TSRMLS_CC);
}
return NULL;
}
static const zend_encoding* zend_multibyte_find_script_encoding(TSRMLS_D)
{
const zend_encoding *script_encoding;
if (CG(detect_unicode)) {
/* check out bom(byte order mark) and see if containing wchars */
script_encoding = zend_multibyte_detect_unicode(TSRMLS_C);
if (script_encoding != NULL) {
/* bom or wchar detection is prior to 'script_encoding' option */
return script_encoding;
}
}
/* if no script_encoding specified, just leave alone */
if (!CG(script_encoding_list) || !CG(script_encoding_list_size)) {
return NULL;
}
/* if multiple encodings specified, detect automagically */
if (CG(script_encoding_list_size) > 1) {
return zend_multibyte_encoding_detector(LANG_SCNG(script_org), LANG_SCNG(script_org_size), CG(script_encoding_list), CG(script_encoding_list_size) TSRMLS_CC);
}
return CG(script_encoding_list)[0];
}
ZEND_API int zend_multibyte_set_filter(const zend_encoding *onetime_encoding TSRMLS_DC)
{
const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C);
const zend_encoding *script_encoding = onetime_encoding ? onetime_encoding: zend_multibyte_find_script_encoding(TSRMLS_C);
if (!script_encoding) {
return FAILURE;
}
/* judge input/output filter */
LANG_SCNG(script_encoding) = script_encoding;
LANG_SCNG(input_filter) = NULL;
LANG_SCNG(output_filter) = NULL;
if (!internal_encoding || LANG_SCNG(script_encoding) == internal_encoding) {
if (!zend_multibyte_check_lexer_compatibility(LANG_SCNG(script_encoding))) {
/* and if not, work around w/ script_encoding -> utf-8 -> script_encoding conversion */
LANG_SCNG(input_filter) = encoding_filter_script_to_intermediate;
LANG_SCNG(output_filter) = encoding_filter_intermediate_to_script;
} else {
LANG_SCNG(input_filter) = NULL;
LANG_SCNG(output_filter) = NULL;
}
return SUCCESS;
}
if (zend_multibyte_check_lexer_compatibility(internal_encoding)) {
LANG_SCNG(input_filter) = encoding_filter_script_to_internal;
LANG_SCNG(output_filter) = NULL;
} else if (zend_multibyte_check_lexer_compatibility(LANG_SCNG(script_encoding))) {
LANG_SCNG(input_filter) = NULL;
LANG_SCNG(output_filter) = encoding_filter_script_to_internal;
} else {
/* both script and internal encodings are incompatible w/ flex */
LANG_SCNG(input_filter) = encoding_filter_script_to_intermediate;
LANG_SCNG(output_filter) = encoding_filter_intermediate_to_internal;
}
return 0;
}
ZEND_API int open_file_for_scanning(zend_file_handle *file_handle TSRMLS_DC)
{
const char *file_path = NULL;
char *buf;
size_t size, offset = 0;
/* The shebang line was read, get the current position to obtain the buffer start */
if (CG(start_lineno) == 2 && file_handle->type == ZEND_HANDLE_FP && file_handle->handle.fp) {
if ((offset = ftell(file_handle->handle.fp)) == -1) {
offset = 0;
}
}
if (zend_stream_fixup(file_handle, &buf, &size TSRMLS_CC) == FAILURE) {
return FAILURE;
}
zend_llist_add_element(&CG(open_files), file_handle);
if (file_handle->handle.stream.handle >= (void*)file_handle && file_handle->handle.stream.handle <= (void*)(file_handle+1)) {
zend_file_handle *fh = (zend_file_handle*)zend_llist_get_last(&CG(open_files));
size_t diff = (char*)file_handle->handle.stream.handle - (char*)file_handle;
fh->handle.stream.handle = (void*)(((char*)fh) + diff);
file_handle->handle.stream.handle = fh->handle.stream.handle;
}
/* Reset the scanner for scanning the new file */
SCNG(yy_in) = file_handle;
SCNG(yy_start) = NULL;
if (size != -1) {
if (CG(multibyte)) {
SCNG(script_org) = (unsigned char*)buf;
SCNG(script_org_size) = size;
SCNG(script_filtered) = NULL;
zend_multibyte_set_filter(NULL TSRMLS_CC);
if (SCNG(input_filter)) {
if ((size_t)-1 == SCNG(input_filter)(&SCNG(script_filtered), &SCNG(script_filtered_size), SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) {
zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected "
"encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding)));
}
buf = (char*)SCNG(script_filtered);
size = SCNG(script_filtered_size);
}
}
SCNG(yy_start) = (unsigned char *)buf - offset;
yy_scan_buffer(buf, size TSRMLS_CC);
} else {
zend_error_noreturn(E_COMPILE_ERROR, "zend_stream_mmap() failed");
}
BEGIN(INITIAL);
if (file_handle->opened_path) {
file_path = file_handle->opened_path;
} else {
file_path = file_handle->filename;
}
zend_set_compiled_filename(file_path TSRMLS_CC);
if (CG(start_lineno)) {
CG(zend_lineno) = CG(start_lineno);
CG(start_lineno) = 0;
} else {
CG(zend_lineno) = 1;
}
CG(increment_lineno) = 0;
return SUCCESS;
}
END_EXTERN_C()
ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC)
{
zend_lex_state original_lex_state;
zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array));
zend_op_array *original_active_op_array = CG(active_op_array);
zend_op_array *retval=NULL;
int compiler_result;
zend_bool compilation_successful=0;
znode retval_znode;
zend_bool original_in_compilation = CG(in_compilation);
retval_znode.op_type = IS_CONST;
retval_znode.u.constant.type = IS_LONG;
retval_znode.u.constant.value.lval = 1;
Z_UNSET_ISREF(retval_znode.u.constant);
Z_SET_REFCOUNT(retval_znode.u.constant, 1);
zend_save_lexical_state(&original_lex_state TSRMLS_CC);
retval = op_array; /* success oriented */
if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) {
if (type==ZEND_REQUIRE) {
zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC);
zend_bailout();
} else {
zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC);
}
compilation_successful=0;
} else {
init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC);
CG(in_compilation) = 1;
CG(active_op_array) = op_array;
zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context)));
zend_init_compiler_context(TSRMLS_C);
compiler_result = zendparse(TSRMLS_C);
zend_do_return(&retval_znode, 0 TSRMLS_CC);
CG(in_compilation) = original_in_compilation;
if (compiler_result==1) { /* parser error */
zend_bailout();
}
compilation_successful=1;
}
if (retval) {
CG(active_op_array) = original_active_op_array;
if (compilation_successful) {
pass_two(op_array TSRMLS_CC);
zend_release_labels(0 TSRMLS_CC);
} else {
efree(op_array);
retval = NULL;
}
}
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
return retval;
}
zend_op_array *compile_filename(int type, zval *filename TSRMLS_DC)
{
zend_file_handle file_handle;
zval tmp;
zend_op_array *retval;
char *opened_path = NULL;
if (filename->type != IS_STRING) {
tmp = *filename;
zval_copy_ctor(&tmp);
convert_to_string(&tmp);
filename = &tmp;
}
file_handle.filename = filename->value.str.val;
file_handle.free_filename = 0;
file_handle.type = ZEND_HANDLE_FILENAME;
file_handle.opened_path = NULL;
file_handle.handle.fp = NULL;
retval = zend_compile_file(&file_handle, type TSRMLS_CC);
if (retval && file_handle.handle.stream.handle) {
int dummy = 1;
if (!file_handle.opened_path) {
file_handle.opened_path = opened_path = estrndup(filename->value.str.val, filename->value.str.len);
}
zend_hash_add(&EG(included_files), file_handle.opened_path, strlen(file_handle.opened_path)+1, (void *)&dummy, sizeof(int), NULL);
if (opened_path) {
efree(opened_path);
}
}
zend_destroy_file_handle(&file_handle TSRMLS_CC);
if (filename==&tmp) {
zval_dtor(&tmp);
}
return retval;
}
ZEND_API int zend_prepare_string_for_scanning(zval *str, char *filename TSRMLS_DC)
{
char *buf;
size_t size;
/* enforce two trailing NULLs for flex... */
if (IS_INTERNED(str->value.str.val)) {
char *tmp = safe_emalloc(1, str->value.str.len, ZEND_MMAP_AHEAD);
memcpy(tmp, str->value.str.val, str->value.str.len + ZEND_MMAP_AHEAD);
str->value.str.val = tmp;
} else {
str->value.str.val = safe_erealloc(str->value.str.val, 1, str->value.str.len, ZEND_MMAP_AHEAD);
}
memset(str->value.str.val + str->value.str.len, 0, ZEND_MMAP_AHEAD);
SCNG(yy_in) = NULL;
SCNG(yy_start) = NULL;
buf = str->value.str.val;
size = str->value.str.len;
if (CG(multibyte)) {
SCNG(script_org) = (unsigned char*)buf;
SCNG(script_org_size) = size;
SCNG(script_filtered) = NULL;
zend_multibyte_set_filter(zend_multibyte_get_internal_encoding(TSRMLS_C) TSRMLS_CC);
if (SCNG(input_filter)) {
if ((size_t)-1 == SCNG(input_filter)(&SCNG(script_filtered), &SCNG(script_filtered_size), SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) {
zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected "
"encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding)));
}
buf = (char*)SCNG(script_filtered);
size = SCNG(script_filtered_size);
}
}
yy_scan_buffer(buf, size TSRMLS_CC);
zend_set_compiled_filename(filename TSRMLS_CC);
CG(zend_lineno) = 1;
CG(increment_lineno) = 0;
return SUCCESS;
}
ZEND_API size_t zend_get_scanned_file_offset(TSRMLS_D)
{
size_t offset = SCNG(yy_cursor) - SCNG(yy_start);
if (SCNG(input_filter)) {
size_t original_offset = offset, length = 0;
do {
unsigned char *p = NULL;
if ((size_t)-1 == SCNG(input_filter)(&p, &length, SCNG(script_org), offset TSRMLS_CC)) {
return (size_t)-1;
}
efree(p);
if (length > original_offset) {
offset--;
} else if (length < original_offset) {
offset++;
}
} while (original_offset != length);
}
return offset;
}
zend_op_array *compile_string(zval *source_string, char *filename TSRMLS_DC)
{
zend_lex_state original_lex_state;
zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array));
zend_op_array *original_active_op_array = CG(active_op_array);
zend_op_array *retval;
zval tmp;
int compiler_result;
zend_bool original_in_compilation = CG(in_compilation);
if (source_string->value.str.len==0) {
efree(op_array);
return NULL;
}
CG(in_compilation) = 1;
tmp = *source_string;
zval_copy_ctor(&tmp);
convert_to_string(&tmp);
source_string = &tmp;
zend_save_lexical_state(&original_lex_state TSRMLS_CC);
if (zend_prepare_string_for_scanning(source_string, filename TSRMLS_CC)==FAILURE) {
efree(op_array);
retval = NULL;
} else {
zend_bool orig_interactive = CG(interactive);
CG(interactive) = 0;
init_op_array(op_array, ZEND_EVAL_CODE, INITIAL_OP_ARRAY_SIZE TSRMLS_CC);
CG(interactive) = orig_interactive;
CG(active_op_array) = op_array;
zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context)));
zend_init_compiler_context(TSRMLS_C);
BEGIN(ST_IN_SCRIPTING);
compiler_result = zendparse(TSRMLS_C);
if (SCNG(script_filtered)) {
efree(SCNG(script_filtered));
SCNG(script_filtered) = NULL;
}
if (compiler_result==1) {
CG(active_op_array) = original_active_op_array;
CG(unclean_shutdown)=1;
destroy_op_array(op_array TSRMLS_CC);
efree(op_array);
retval = NULL;
} else {
zend_do_return(NULL, 0 TSRMLS_CC);
CG(active_op_array) = original_active_op_array;
pass_two(op_array TSRMLS_CC);
zend_release_labels(0 TSRMLS_CC);
retval = op_array;
}
}
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
zval_dtor(&tmp);
CG(in_compilation) = original_in_compilation;
return retval;
}
BEGIN_EXTERN_C()
int highlight_file(char *filename, zend_syntax_highlighter_ini *syntax_highlighter_ini TSRMLS_DC)
{
zend_lex_state original_lex_state;
zend_file_handle file_handle;
file_handle.type = ZEND_HANDLE_FILENAME;
file_handle.filename = filename;
file_handle.free_filename = 0;
file_handle.opened_path = NULL;
zend_save_lexical_state(&original_lex_state TSRMLS_CC);
if (open_file_for_scanning(&file_handle TSRMLS_CC)==FAILURE) {
zend_message_dispatcher(ZMSG_FAILED_HIGHLIGHT_FOPEN, filename TSRMLS_CC);
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
return FAILURE;
}
zend_highlight(syntax_highlighter_ini TSRMLS_CC);
if (SCNG(script_filtered)) {
efree(SCNG(script_filtered));
SCNG(script_filtered) = NULL;
}
zend_destroy_file_handle(&file_handle TSRMLS_CC);
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
return SUCCESS;
}
int highlight_string(zval *str, zend_syntax_highlighter_ini *syntax_highlighter_ini, char *str_name TSRMLS_DC)
{
zend_lex_state original_lex_state;
zval tmp = *str;
str = &tmp;
zval_copy_ctor(str);
zend_save_lexical_state(&original_lex_state TSRMLS_CC);
if (zend_prepare_string_for_scanning(str, str_name TSRMLS_CC)==FAILURE) {
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
return FAILURE;
}
BEGIN(INITIAL);
zend_highlight(syntax_highlighter_ini TSRMLS_CC);
if (SCNG(script_filtered)) {
efree(SCNG(script_filtered));
SCNG(script_filtered) = NULL;
}
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
zval_dtor(str);
return SUCCESS;
}
ZEND_API void zend_multibyte_yyinput_again(zend_encoding_filter old_input_filter, const zend_encoding *old_encoding TSRMLS_DC)
{
size_t length;
unsigned char *new_yy_start;
/* convert and set */
if (!SCNG(input_filter)) {
if (SCNG(script_filtered)) {
efree(SCNG(script_filtered));
SCNG(script_filtered) = NULL;
}
SCNG(script_filtered_size) = 0;
length = SCNG(script_org_size);
new_yy_start = SCNG(script_org);
} else {
if ((size_t)-1 == SCNG(input_filter)(&new_yy_start, &length, SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) {
zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected "
"encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding)));
}
SCNG(script_filtered) = new_yy_start;
SCNG(script_filtered_size) = length;
}
SCNG(yy_cursor) = new_yy_start + (SCNG(yy_cursor) - SCNG(yy_start));
SCNG(yy_marker) = new_yy_start + (SCNG(yy_marker) - SCNG(yy_start));
SCNG(yy_text) = new_yy_start + (SCNG(yy_text) - SCNG(yy_start));
SCNG(yy_limit) = new_yy_start + (SCNG(yy_limit) - SCNG(yy_start));
SCNG(yy_start) = new_yy_start;
}
# define zend_copy_value(zendlval, yytext, yyleng) \
if (SCNG(output_filter)) { \
size_t sz = 0; \
SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)yytext, (size_t)yyleng TSRMLS_CC); \
zendlval->value.str.len = sz; \
} else { \
zendlval->value.str.val = (char *) estrndup(yytext, yyleng); \
zendlval->value.str.len = yyleng; \
}
static void zend_scan_escape_string(zval *zendlval, char *str, int len, char quote_type TSRMLS_DC)
{
register char *s, *t;
char *end;
ZVAL_STRINGL(zendlval, str, len, 1);
/* convert escape sequences */
s = t = zendlval->value.str.val;
end = s+zendlval->value.str.len;
while (s<end) {
if (*s=='\\') {
s++;
if (s >= end) {
*t++ = '\\';
break;
}
switch(*s) {
case 'n':
*t++ = '\n';
zendlval->value.str.len--;
break;
case 'r':
*t++ = '\r';
zendlval->value.str.len--;
break;
case 't':
*t++ = '\t';
zendlval->value.str.len--;
break;
case 'f':
*t++ = '\f';
zendlval->value.str.len--;
break;
case 'v':
*t++ = '\v';
zendlval->value.str.len--;
break;
case 'e':
#ifdef PHP_WIN32
*t++ = VK_ESCAPE;
#else
*t++ = '\e';
#endif
zendlval->value.str.len--;
break;
case '"':
case '`':
if (*s != quote_type) {
*t++ = '\\';
*t++ = *s;
break;
}
case '\\':
case '$':
*t++ = *s;
zendlval->value.str.len--;
break;
case 'x':
case 'X':
if (ZEND_IS_HEX(*(s+1))) {
char hex_buf[3] = { 0, 0, 0 };
zendlval->value.str.len--; /* for the 'x' */
hex_buf[0] = *(++s);
zendlval->value.str.len--;
if (ZEND_IS_HEX(*(s+1))) {
hex_buf[1] = *(++s);
zendlval->value.str.len--;
}
*t++ = (char) strtol(hex_buf, NULL, 16);
} else {
*t++ = '\\';
*t++ = *s;
}
break;
default:
/* check for an octal */
if (ZEND_IS_OCT(*s)) {
char octal_buf[4] = { 0, 0, 0, 0 };
octal_buf[0] = *s;
zendlval->value.str.len--;
if (ZEND_IS_OCT(*(s+1))) {
octal_buf[1] = *(++s);
zendlval->value.str.len--;
if (ZEND_IS_OCT(*(s+1))) {
octal_buf[2] = *(++s);
zendlval->value.str.len--;
}
}
*t++ = (char) strtol(octal_buf, NULL, 8);
} else {
*t++ = '\\';
*t++ = *s;
}
break;
}
} else {
*t++ = *s;
}
if (*s == '\n' || (*s == '\r' && (*(s+1) != '\n'))) {
CG(zend_lineno)++;
}
s++;
}
*t = 0;
if (SCNG(output_filter)) {
size_t sz = 0;
s = zendlval->value.str.val;
SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)s, (size_t)zendlval->value.str.len TSRMLS_CC);
zendlval->value.str.len = sz;
efree(s);
}
}
int lex_scan(zval *zendlval TSRMLS_DC)
{
restart:
SCNG(yy_text) = YYCURSOR;
yymore_restart:
#line 1004 "Zend/zend_language_scanner.c"
{
YYCTYPE yych;
unsigned int yyaccept = 0;
if (YYGETCONDITION() < 5) {
if (YYGETCONDITION() < 2) {
if (YYGETCONDITION() < 1) {
goto yyc_ST_IN_SCRIPTING;
} else {
goto yyc_ST_LOOKING_FOR_PROPERTY;
}
} else {
if (YYGETCONDITION() < 3) {
goto yyc_ST_BACKQUOTE;
} else {
if (YYGETCONDITION() < 4) {
goto yyc_ST_DOUBLE_QUOTES;
} else {
goto yyc_ST_HEREDOC;
}
}
}
} else {
if (YYGETCONDITION() < 7) {
if (YYGETCONDITION() < 6) {
goto yyc_ST_LOOKING_FOR_VARNAME;
} else {
goto yyc_ST_VAR_OFFSET;
}
} else {
if (YYGETCONDITION() < 8) {
goto yyc_INITIAL;
} else {
if (YYGETCONDITION() < 9) {
goto yyc_ST_END_HEREDOC;
} else {
goto yyc_ST_NOWDOC;
}
}
}
}
/* *********************************** */
yyc_INITIAL:
{
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 128, 128, 0, 0, 128, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
YYDEBUG(0, *YYCURSOR);
YYFILL(8);
yych = *YYCURSOR;
if (yych != '<') goto yy4;
YYDEBUG(2, *YYCURSOR);
yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= '?') {
if (yych == '%') goto yy7;
if (yych >= '?') goto yy5;
} else {
if (yych <= 'S') {
if (yych >= 'S') goto yy9;
} else {
if (yych == 's') goto yy9;
}
}
yy3:
YYDEBUG(3, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1792 "Zend/zend_language_scanner.l"
{
if (YYCURSOR > YYLIMIT) {
return 0;
}
inline_char_handler:
while (1) {
YYCTYPE *ptr = memchr(YYCURSOR, '<', YYLIMIT - YYCURSOR);
YYCURSOR = ptr ? ptr + 1 : YYLIMIT;
if (YYCURSOR < YYLIMIT) {
switch (*YYCURSOR) {
case '?':
if (CG(short_tags) || !strncasecmp((char*)YYCURSOR + 1, "php", 3) || (*(YYCURSOR + 1) == '=')) { /* Assume [ \t\n\r] follows "php" */
break;
}
continue;
case '%':
if (CG(asp_tags)) {
break;
}
continue;
case 's':
case 'S':
/* Probably NOT an opening PHP <script> tag, so don't end the HTML chunk yet
* If it is, the PHP <script> tag rule checks for any HTML scanned before it */
YYCURSOR--;
yymore();
default:
continue;
}
YYCURSOR--;
}
break;
}
inline_html:
yyleng = YYCURSOR - SCNG(yy_text);
if (SCNG(output_filter)) {
int readsize;
size_t sz = 0;
readsize = SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)yytext, (size_t)yyleng TSRMLS_CC);
zendlval->value.str.len = sz;
if (readsize < yyleng) {
yyless(readsize);
}
} else {
zendlval->value.str.val = (char *) estrndup(yytext, yyleng);
zendlval->value.str.len = yyleng;
}
zendlval->type = IS_STRING;
HANDLE_NEWLINES(yytext, yyleng);
return T_INLINE_HTML;
}
#line 1163 "Zend/zend_language_scanner.c"
yy4:
YYDEBUG(4, *YYCURSOR);
yych = *++YYCURSOR;
goto yy3;
yy5:
YYDEBUG(5, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= 'O') {
if (yych == '=') goto yy45;
} else {
if (yych <= 'P') goto yy47;
if (yych == 'p') goto yy47;
}
yy6:
YYDEBUG(6, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1780 "Zend/zend_language_scanner.l"
{
if (CG(short_tags)) {
zendlval->value.str.val = yytext; /* no copying - intentional */
zendlval->value.str.len = yyleng;
zendlval->type = IS_STRING;
BEGIN(ST_IN_SCRIPTING);
return T_OPEN_TAG;
} else {
goto inline_char_handler;
}
}
#line 1193 "Zend/zend_language_scanner.c"
yy7:
YYDEBUG(7, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) == '=') goto yy43;
YYDEBUG(8, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1757 "Zend/zend_language_scanner.l"
{
if (CG(asp_tags)) {
zendlval->value.str.val = yytext; /* no copying - intentional */
zendlval->value.str.len = yyleng;
zendlval->type = IS_STRING;
BEGIN(ST_IN_SCRIPTING);
return T_OPEN_TAG;
} else {
goto inline_char_handler;
}
}
#line 1212 "Zend/zend_language_scanner.c"
yy9:
YYDEBUG(9, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy11;
if (yych == 'c') goto yy11;
yy10:
YYDEBUG(10, *YYCURSOR);
YYCURSOR = YYMARKER;
if (yyaccept <= 0) {
goto yy3;
} else {
goto yy6;
}
yy11:
YYDEBUG(11, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy12;
if (yych != 'r') goto yy10;
yy12:
YYDEBUG(12, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy13;
if (yych != 'i') goto yy10;
yy13:
YYDEBUG(13, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'P') goto yy14;
if (yych != 'p') goto yy10;
yy14:
YYDEBUG(14, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy15;
if (yych != 't') goto yy10;
yy15:
YYDEBUG(15, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy10;
if (yych == 'l') goto yy10;
goto yy17;
yy16:
YYDEBUG(16, *YYCURSOR);
++YYCURSOR;
YYFILL(8);
yych = *YYCURSOR;
yy17:
YYDEBUG(17, *YYCURSOR);
if (yybm[0+yych] & 128) {
goto yy16;
}
if (yych == 'L') goto yy18;
if (yych != 'l') goto yy10;
yy18:
YYDEBUG(18, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy19;
if (yych != 'a') goto yy10;
yy19:
YYDEBUG(19, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy20;
if (yych != 'n') goto yy10;
yy20:
YYDEBUG(20, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'G') goto yy21;
if (yych != 'g') goto yy10;
yy21:
YYDEBUG(21, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'U') goto yy22;
if (yych != 'u') goto yy10;
yy22:
YYDEBUG(22, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy23;
if (yych != 'a') goto yy10;
yy23:
YYDEBUG(23, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'G') goto yy24;
if (yych != 'g') goto yy10;
yy24:
YYDEBUG(24, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy25;
if (yych != 'e') goto yy10;
yy25:
YYDEBUG(25, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(26, *YYCURSOR);
if (yych <= '\r') {
if (yych <= 0x08) goto yy10;
if (yych <= '\n') goto yy25;
if (yych <= '\f') goto yy10;
goto yy25;
} else {
if (yych <= ' ') {
if (yych <= 0x1F) goto yy10;
goto yy25;
} else {
if (yych != '=') goto yy10;
}
}
yy27:
YYDEBUG(27, *YYCURSOR);
++YYCURSOR;
YYFILL(5);
yych = *YYCURSOR;
YYDEBUG(28, *YYCURSOR);
if (yych <= '!') {
if (yych <= '\f') {
if (yych <= 0x08) goto yy10;
if (yych <= '\n') goto yy27;
goto yy10;
} else {
if (yych <= '\r') goto yy27;
if (yych == ' ') goto yy27;
goto yy10;
}
} else {
if (yych <= 'O') {
if (yych <= '"') goto yy30;
if (yych == '\'') goto yy31;
goto yy10;
} else {
if (yych <= 'P') goto yy29;
if (yych != 'p') goto yy10;
}
}
yy29:
YYDEBUG(29, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'H') goto yy42;
if (yych == 'h') goto yy42;
goto yy10;
yy30:
YYDEBUG(30, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'P') goto yy39;
if (yych == 'p') goto yy39;
goto yy10;
yy31:
YYDEBUG(31, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'P') goto yy32;
if (yych != 'p') goto yy10;
yy32:
YYDEBUG(32, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'H') goto yy33;
if (yych != 'h') goto yy10;
yy33:
YYDEBUG(33, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'P') goto yy34;
if (yych != 'p') goto yy10;
yy34:
YYDEBUG(34, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '\'') goto yy10;
yy35:
YYDEBUG(35, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(36, *YYCURSOR);
if (yych <= '\r') {
if (yych <= 0x08) goto yy10;
if (yych <= '\n') goto yy35;
if (yych <= '\f') goto yy10;
goto yy35;
} else {
if (yych <= ' ') {
if (yych <= 0x1F) goto yy10;
goto yy35;
} else {
if (yych != '>') goto yy10;
}
}
YYDEBUG(37, *YYCURSOR);
++YYCURSOR;
YYDEBUG(38, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1717 "Zend/zend_language_scanner.l"
{
YYCTYPE *bracket = (YYCTYPE*)zend_memrchr(yytext, '<', yyleng - (sizeof("script language=php>") - 1));
if (bracket != SCNG(yy_text)) {
/* Handle previously scanned HTML, as possible <script> tags found are assumed to not be PHP's */
YYCURSOR = bracket;
goto inline_html;
}
HANDLE_NEWLINES(yytext, yyleng);
zendlval->value.str.val = yytext; /* no copying - intentional */
zendlval->value.str.len = yyleng;
zendlval->type = IS_STRING;
BEGIN(ST_IN_SCRIPTING);
return T_OPEN_TAG;
}
#line 1415 "Zend/zend_language_scanner.c"
yy39:
YYDEBUG(39, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'H') goto yy40;
if (yych != 'h') goto yy10;
yy40:
YYDEBUG(40, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'P') goto yy41;
if (yych != 'p') goto yy10;
yy41:
YYDEBUG(41, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '"') goto yy35;
goto yy10;
yy42:
YYDEBUG(42, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'P') goto yy35;
if (yych == 'p') goto yy35;
goto yy10;
yy43:
YYDEBUG(43, *YYCURSOR);
++YYCURSOR;
YYDEBUG(44, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1735 "Zend/zend_language_scanner.l"
{
if (CG(asp_tags)) {
zendlval->value.str.val = yytext; /* no copying - intentional */
zendlval->value.str.len = yyleng;
zendlval->type = IS_STRING;
BEGIN(ST_IN_SCRIPTING);
return T_OPEN_TAG_WITH_ECHO;
} else {
goto inline_char_handler;
}
}
#line 1454 "Zend/zend_language_scanner.c"
yy45:
YYDEBUG(45, *YYCURSOR);
++YYCURSOR;
YYDEBUG(46, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1748 "Zend/zend_language_scanner.l"
{
zendlval->value.str.val = yytext; /* no copying - intentional */
zendlval->value.str.len = yyleng;
zendlval->type = IS_STRING;
BEGIN(ST_IN_SCRIPTING);
return T_OPEN_TAG_WITH_ECHO;
}
#line 1468 "Zend/zend_language_scanner.c"
yy47:
YYDEBUG(47, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'H') goto yy48;
if (yych != 'h') goto yy10;
yy48:
YYDEBUG(48, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'P') goto yy49;
if (yych != 'p') goto yy10;
yy49:
YYDEBUG(49, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '\f') {
if (yych <= 0x08) goto yy10;
if (yych >= '\v') goto yy10;
} else {
if (yych <= '\r') goto yy52;
if (yych != ' ') goto yy10;
}
yy50:
YYDEBUG(50, *YYCURSOR);
++YYCURSOR;
yy51:
YYDEBUG(51, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1770 "Zend/zend_language_scanner.l"
{
zendlval->value.str.val = yytext; /* no copying - intentional */
zendlval->value.str.len = yyleng;
zendlval->type = IS_STRING;
HANDLE_NEWLINE(yytext[yyleng-1]);
BEGIN(ST_IN_SCRIPTING);
return T_OPEN_TAG;
}
#line 1504 "Zend/zend_language_scanner.c"
yy52:
YYDEBUG(52, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) == '\n') goto yy50;
goto yy51;
}
/* *********************************** */
yyc_ST_BACKQUOTE:
{
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 0, 0, 0, 0, 0, 0,
0, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 0, 0, 0, 0, 128,
0, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 0, 0, 0, 0, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
};
YYDEBUG(53, *YYCURSOR);
YYFILL(2);
yych = *YYCURSOR;
if (yych <= '_') {
if (yych != '$') goto yy60;
} else {
if (yych <= '`') goto yy58;
if (yych == '{') goto yy57;
goto yy60;
}
YYDEBUG(55, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) <= '_') {
if (yych <= '@') goto yy56;
if (yych <= 'Z') goto yy63;
if (yych >= '_') goto yy63;
} else {
if (yych <= 'z') {
if (yych >= 'a') goto yy63;
} else {
if (yych <= '{') goto yy66;
if (yych >= 0x7F) goto yy63;
}
}
yy56:
YYDEBUG(56, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 2243 "Zend/zend_language_scanner.l"
{
if (YYCURSOR > YYLIMIT) {
return 0;
}
if (yytext[0] == '\\' && YYCURSOR < YYLIMIT) {
YYCURSOR++;
}
while (YYCURSOR < YYLIMIT) {
switch (*YYCURSOR++) {
case '`':
break;
case '$':
if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') {
break;
}
continue;
case '{':
if (*YYCURSOR == '$') {
break;
}
continue;
case '\\':
if (YYCURSOR < YYLIMIT) {
YYCURSOR++;
}
/* fall through */
default:
continue;
}
YYCURSOR--;
break;
}
yyleng = YYCURSOR - SCNG(yy_text);
zend_scan_escape_string(zendlval, yytext, yyleng, '`' TSRMLS_CC);
return T_ENCAPSED_AND_WHITESPACE;
}
#line 1616 "Zend/zend_language_scanner.c"
yy57:
YYDEBUG(57, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '$') goto yy61;
goto yy56;
yy58:
YYDEBUG(58, *YYCURSOR);
++YYCURSOR;
YYDEBUG(59, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 2187 "Zend/zend_language_scanner.l"
{
BEGIN(ST_IN_SCRIPTING);
return '`';
}
#line 1632 "Zend/zend_language_scanner.c"
yy60:
YYDEBUG(60, *YYCURSOR);
yych = *++YYCURSOR;
goto yy56;
yy61:
YYDEBUG(61, *YYCURSOR);
++YYCURSOR;
YYDEBUG(62, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 2174 "Zend/zend_language_scanner.l"
{
zendlval->value.lval = (long) '{';
yy_push_state(ST_IN_SCRIPTING TSRMLS_CC);
yyless(1);
return T_CURLY_OPEN;
}
#line 1649 "Zend/zend_language_scanner.c"
yy63:
YYDEBUG(63, *YYCURSOR);
yyaccept = 0;
YYMARKER = ++YYCURSOR;
YYFILL(3);
yych = *YYCURSOR;
YYDEBUG(64, *YYCURSOR);
if (yybm[0+yych] & 128) {
goto yy63;
}
if (yych == '-') goto yy68;
if (yych == '[') goto yy70;
yy65:
YYDEBUG(65, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1874 "Zend/zend_language_scanner.l"
{
zend_copy_value(zendlval, (yytext+1), (yyleng-1));
zendlval->type = IS_STRING;
return T_VARIABLE;
}
#line 1671 "Zend/zend_language_scanner.c"
yy66:
YYDEBUG(66, *YYCURSOR);
++YYCURSOR;
YYDEBUG(67, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1451 "Zend/zend_language_scanner.l"
{
yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC);
return T_DOLLAR_OPEN_CURLY_BRACES;
}
#line 1682 "Zend/zend_language_scanner.c"
yy68:
YYDEBUG(68, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '>') goto yy72;
yy69:
YYDEBUG(69, *YYCURSOR);
YYCURSOR = YYMARKER;
goto yy65;
yy70:
YYDEBUG(70, *YYCURSOR);
++YYCURSOR;
YYDEBUG(71, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1866 "Zend/zend_language_scanner.l"
{
yyless(yyleng - 1);
yy_push_state(ST_VAR_OFFSET TSRMLS_CC);
zend_copy_value(zendlval, (yytext+1), (yyleng-1));
zendlval->type = IS_STRING;
return T_VARIABLE;
}
#line 1704 "Zend/zend_language_scanner.c"
yy72:
YYDEBUG(72, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '_') {
if (yych <= '@') goto yy69;
if (yych <= 'Z') goto yy73;
if (yych <= '^') goto yy69;
} else {
if (yych <= '`') goto yy69;
if (yych <= 'z') goto yy73;
if (yych <= '~') goto yy69;
}
yy73:
YYDEBUG(73, *YYCURSOR);
++YYCURSOR;
YYDEBUG(74, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1856 "Zend/zend_language_scanner.l"
{
yyless(yyleng - 3);
yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC);
zend_copy_value(zendlval, (yytext+1), (yyleng-1));
zendlval->type = IS_STRING;
return T_VARIABLE;
}
#line 1730 "Zend/zend_language_scanner.c"
}
/* *********************************** */
yyc_ST_DOUBLE_QUOTES:
{
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 0, 0, 0, 0, 0, 0,
0, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 0, 0, 0, 0, 128,
0, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 0, 0, 0, 0, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
};
YYDEBUG(75, *YYCURSOR);
YYFILL(2);
yych = *YYCURSOR;
if (yych <= '#') {
if (yych == '"') goto yy80;
goto yy82;
} else {
if (yych <= '$') goto yy77;
if (yych == '{') goto yy79;
goto yy82;
}
yy77:
YYDEBUG(77, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) <= '_') {
if (yych <= '@') goto yy78;
if (yych <= 'Z') goto yy85;
if (yych >= '_') goto yy85;
} else {
if (yych <= 'z') {
if (yych >= 'a') goto yy85;
} else {
if (yych <= '{') goto yy88;
if (yych >= 0x7F) goto yy85;
}
}
yy78:
YYDEBUG(78, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 2193 "Zend/zend_language_scanner.l"
{
if (GET_DOUBLE_QUOTES_SCANNED_LENGTH()) {
YYCURSOR += GET_DOUBLE_QUOTES_SCANNED_LENGTH() - 1;
SET_DOUBLE_QUOTES_SCANNED_LENGTH(0);
goto double_quotes_scan_done;
}
if (YYCURSOR > YYLIMIT) {
return 0;
}
if (yytext[0] == '\\' && YYCURSOR < YYLIMIT) {
YYCURSOR++;
}
while (YYCURSOR < YYLIMIT) {
switch (*YYCURSOR++) {
case '"':
break;
case '$':
if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') {
break;
}
continue;
case '{':
if (*YYCURSOR == '$') {
break;
}
continue;
case '\\':
if (YYCURSOR < YYLIMIT) {
YYCURSOR++;
}
/* fall through */
default:
continue;
}
YYCURSOR--;
break;
}
double_quotes_scan_done:
yyleng = YYCURSOR - SCNG(yy_text);
zend_scan_escape_string(zendlval, yytext, yyleng, '"' TSRMLS_CC);
return T_ENCAPSED_AND_WHITESPACE;
}
#line 1847 "Zend/zend_language_scanner.c"
yy79:
YYDEBUG(79, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '$') goto yy83;
goto yy78;
yy80:
YYDEBUG(80, *YYCURSOR);
++YYCURSOR;
YYDEBUG(81, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 2182 "Zend/zend_language_scanner.l"
{
BEGIN(ST_IN_SCRIPTING);
return '"';
}
#line 1863 "Zend/zend_language_scanner.c"
yy82:
YYDEBUG(82, *YYCURSOR);
yych = *++YYCURSOR;
goto yy78;
yy83:
YYDEBUG(83, *YYCURSOR);
++YYCURSOR;
YYDEBUG(84, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 2174 "Zend/zend_language_scanner.l"
{
zendlval->value.lval = (long) '{';
yy_push_state(ST_IN_SCRIPTING TSRMLS_CC);
yyless(1);
return T_CURLY_OPEN;
}
#line 1880 "Zend/zend_language_scanner.c"
yy85:
YYDEBUG(85, *YYCURSOR);
yyaccept = 0;
YYMARKER = ++YYCURSOR;
YYFILL(3);
yych = *YYCURSOR;
YYDEBUG(86, *YYCURSOR);
if (yybm[0+yych] & 128) {
goto yy85;
}
if (yych == '-') goto yy90;
if (yych == '[') goto yy92;
yy87:
YYDEBUG(87, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1874 "Zend/zend_language_scanner.l"
{
zend_copy_value(zendlval, (yytext+1), (yyleng-1));
zendlval->type = IS_STRING;
return T_VARIABLE;
}
#line 1902 "Zend/zend_language_scanner.c"
yy88:
YYDEBUG(88, *YYCURSOR);
++YYCURSOR;
YYDEBUG(89, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1451 "Zend/zend_language_scanner.l"
{
yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC);
return T_DOLLAR_OPEN_CURLY_BRACES;
}
#line 1913 "Zend/zend_language_scanner.c"
yy90:
YYDEBUG(90, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '>') goto yy94;
yy91:
YYDEBUG(91, *YYCURSOR);
YYCURSOR = YYMARKER;
goto yy87;
yy92:
YYDEBUG(92, *YYCURSOR);
++YYCURSOR;
YYDEBUG(93, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1866 "Zend/zend_language_scanner.l"
{
yyless(yyleng - 1);
yy_push_state(ST_VAR_OFFSET TSRMLS_CC);
zend_copy_value(zendlval, (yytext+1), (yyleng-1));
zendlval->type = IS_STRING;
return T_VARIABLE;
}
#line 1935 "Zend/zend_language_scanner.c"
yy94:
YYDEBUG(94, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '_') {
if (yych <= '@') goto yy91;
if (yych <= 'Z') goto yy95;
if (yych <= '^') goto yy91;
} else {
if (yych <= '`') goto yy91;
if (yych <= 'z') goto yy95;
if (yych <= '~') goto yy91;
}
yy95:
YYDEBUG(95, *YYCURSOR);
++YYCURSOR;
YYDEBUG(96, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1856 "Zend/zend_language_scanner.l"
{
yyless(yyleng - 3);
yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC);
zend_copy_value(zendlval, (yytext+1), (yyleng-1));
zendlval->type = IS_STRING;
return T_VARIABLE;
}
#line 1961 "Zend/zend_language_scanner.c"
}
/* *********************************** */
yyc_ST_END_HEREDOC:
YYDEBUG(97, *YYCURSOR);
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(99, *YYCURSOR);
++YYCURSOR;
YYDEBUG(100, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 2161 "Zend/zend_language_scanner.l"
{
YYCURSOR += CG(heredoc_len) - 1;
yyleng = CG(heredoc_len);
Z_STRVAL_P(zendlval) = CG(heredoc);
Z_STRLEN_P(zendlval) = CG(heredoc_len);
CG(heredoc) = NULL;
CG(heredoc_len) = 0;
BEGIN(ST_IN_SCRIPTING);
return T_END_HEREDOC;
}
#line 1984 "Zend/zend_language_scanner.c"
/* *********************************** */
yyc_ST_HEREDOC:
{
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 0, 0, 0, 0, 0, 0,
0, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 0, 0, 0, 0, 128,
0, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 0, 0, 0, 0, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
};
YYDEBUG(101, *YYCURSOR);
YYFILL(2);
yych = *YYCURSOR;
if (yych == '$') goto yy103;
if (yych == '{') goto yy105;
goto yy106;
yy103:
YYDEBUG(103, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) <= '_') {
if (yych <= '@') goto yy104;
if (yych <= 'Z') goto yy109;
if (yych >= '_') goto yy109;
} else {
if (yych <= 'z') {
if (yych >= 'a') goto yy109;
} else {
if (yych <= '{') goto yy112;
if (yych >= 0x7F) goto yy109;
}
}
yy104:
YYDEBUG(104, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 2285 "Zend/zend_language_scanner.l"
{
int newline = 0;
if (YYCURSOR > YYLIMIT) {
return 0;
}
YYCURSOR--;
while (YYCURSOR < YYLIMIT) {
switch (*YYCURSOR++) {
case '\r':
if (*YYCURSOR == '\n') {
YYCURSOR++;
}
/* fall through */
case '\n':
/* Check for ending label on the next line */
if (IS_LABEL_START(*YYCURSOR) && CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, CG(heredoc), CG(heredoc_len))) {
YYCTYPE *end = YYCURSOR + CG(heredoc_len);
if (*end == ';') {
end++;
}
if (*end == '\n' || *end == '\r') {
/* newline before label will be subtracted from returned text, but
* yyleng/yytext will include it, for zend_highlight/strip, tokenizer, etc. */
if (YYCURSOR[-2] == '\r' && YYCURSOR[-1] == '\n') {
newline = 2; /* Windows newline */
} else {
newline = 1;
}
CG(increment_lineno) = 1; /* For newline before label */
BEGIN(ST_END_HEREDOC);
goto heredoc_scan_done;
}
}
continue;
case '$':
if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') {
break;
}
continue;
case '{':
if (*YYCURSOR == '$') {
break;
}
continue;
case '\\':
if (YYCURSOR < YYLIMIT && *YYCURSOR != '\n' && *YYCURSOR != '\r') {
YYCURSOR++;
}
/* fall through */
default:
continue;
}
YYCURSOR--;
break;
}
heredoc_scan_done:
yyleng = YYCURSOR - SCNG(yy_text);
zend_scan_escape_string(zendlval, yytext, yyleng - newline, 0 TSRMLS_CC);
return T_ENCAPSED_AND_WHITESPACE;
}
#line 2117 "Zend/zend_language_scanner.c"
yy105:
YYDEBUG(105, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '$') goto yy107;
goto yy104;
yy106:
YYDEBUG(106, *YYCURSOR);
yych = *++YYCURSOR;
goto yy104;
yy107:
YYDEBUG(107, *YYCURSOR);
++YYCURSOR;
YYDEBUG(108, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 2174 "Zend/zend_language_scanner.l"
{
zendlval->value.lval = (long) '{';
yy_push_state(ST_IN_SCRIPTING TSRMLS_CC);
yyless(1);
return T_CURLY_OPEN;
}
#line 2139 "Zend/zend_language_scanner.c"
yy109:
YYDEBUG(109, *YYCURSOR);
yyaccept = 0;
YYMARKER = ++YYCURSOR;
YYFILL(3);
yych = *YYCURSOR;
YYDEBUG(110, *YYCURSOR);
if (yybm[0+yych] & 128) {
goto yy109;
}
if (yych == '-') goto yy114;
if (yych == '[') goto yy116;
yy111:
YYDEBUG(111, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1874 "Zend/zend_language_scanner.l"
{
zend_copy_value(zendlval, (yytext+1), (yyleng-1));
zendlval->type = IS_STRING;
return T_VARIABLE;
}
#line 2161 "Zend/zend_language_scanner.c"
yy112:
YYDEBUG(112, *YYCURSOR);
++YYCURSOR;
YYDEBUG(113, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1451 "Zend/zend_language_scanner.l"
{
yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC);
return T_DOLLAR_OPEN_CURLY_BRACES;
}
#line 2172 "Zend/zend_language_scanner.c"
yy114:
YYDEBUG(114, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '>') goto yy118;
yy115:
YYDEBUG(115, *YYCURSOR);
YYCURSOR = YYMARKER;
goto yy111;
yy116:
YYDEBUG(116, *YYCURSOR);
++YYCURSOR;
YYDEBUG(117, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1866 "Zend/zend_language_scanner.l"
{
yyless(yyleng - 1);
yy_push_state(ST_VAR_OFFSET TSRMLS_CC);
zend_copy_value(zendlval, (yytext+1), (yyleng-1));
zendlval->type = IS_STRING;
return T_VARIABLE;
}
#line 2194 "Zend/zend_language_scanner.c"
yy118:
YYDEBUG(118, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '_') {
if (yych <= '@') goto yy115;
if (yych <= 'Z') goto yy119;
if (yych <= '^') goto yy115;
} else {
if (yych <= '`') goto yy115;
if (yych <= 'z') goto yy119;
if (yych <= '~') goto yy115;
}
yy119:
YYDEBUG(119, *YYCURSOR);
++YYCURSOR;
YYDEBUG(120, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1856 "Zend/zend_language_scanner.l"
{
yyless(yyleng - 3);
yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC);
zend_copy_value(zendlval, (yytext+1), (yyleng-1));
zendlval->type = IS_STRING;
return T_VARIABLE;
}
#line 2220 "Zend/zend_language_scanner.c"
}
/* *********************************** */
yyc_ST_IN_SCRIPTING:
{
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 192, 64, 0, 0, 64, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
192, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
60, 60, 44, 44, 44, 44, 44, 44,
44, 44, 0, 0, 0, 0, 0, 0,
0, 36, 36, 36, 36, 36, 36, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 0, 0, 0, 0, 4,
0, 36, 36, 36, 36, 36, 36, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 0, 0, 0, 0, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
};
YYDEBUG(121, *YYCURSOR);
YYFILL(16);
yych = *YYCURSOR;
YYDEBUG(-1, yych);
switch (yych) {
case 0x00:
case 0x01:
case 0x02:
case 0x03:
case 0x04:
case 0x05:
case 0x06:
case 0x07:
case 0x08:
case '\v':
case '\f':
case 0x0E:
case 0x0F:
case 0x10:
case 0x11:
case 0x12:
case 0x13:
case 0x14:
case 0x15:
case 0x16:
case 0x17:
case 0x18:
case 0x19:
case 0x1A:
case 0x1B:
case 0x1C:
case 0x1D:
case 0x1E:
case 0x1F: goto yy183;
case '\t':
case '\n':
case '\r':
case ' ': goto yy139;
case '!': goto yy152;
case '"': goto yy179;
case '#': goto yy175;
case '$': goto yy164;
case '%': goto yy158;
case '&': goto yy159;
case '\'': goto yy177;
case '(': goto yy146;
case ')':
case ',':
case ';':
case '@':
case '[':
case ']':
case '~': goto yy165;
case '*': goto yy155;
case '+': goto yy151;
case '-': goto yy137;
case '.': goto yy157;
case '/': goto yy156;
case '0': goto yy171;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy173;
case ':': goto yy141;
case '<': goto yy153;
case '=': goto yy149;
case '>': goto yy154;
case '?': goto yy166;
case 'A':
case 'a': goto yy132;
case 'B':
case 'b': goto yy134;
case 'C':
case 'c': goto yy127;
case 'D':
case 'd': goto yy125;
case 'E':
case 'e': goto yy123;
case 'F':
case 'f': goto yy126;
case 'G':
case 'g': goto yy135;
case 'I':
case 'i': goto yy130;
case 'L':
case 'l': goto yy150;
case 'N':
case 'n': goto yy144;
case 'O':
case 'o': goto yy162;
case 'P':
case 'p': goto yy136;
case 'R':
case 'r': goto yy128;
case 'S':
case 's': goto yy133;
case 'T':
case 't': goto yy129;
case 'U':
case 'u': goto yy147;
case 'V':
case 'v': goto yy145;
case 'W':
case 'w': goto yy131;
case 'X':
case 'x': goto yy163;
case '\\': goto yy142;
case '^': goto yy161;
case '_': goto yy148;
case '`': goto yy181;
case '{': goto yy167;
case '|': goto yy160;
case '}': goto yy169;
default: goto yy174;
}
yy123:
YYDEBUG(123, *YYCURSOR);
++YYCURSOR;
YYDEBUG(-1, yych);
switch ((yych = *YYCURSOR)) {
case 'C':
case 'c': goto yy726;
case 'L':
case 'l': goto yy727;
case 'M':
case 'm': goto yy728;
case 'N':
case 'n': goto yy729;
case 'V':
case 'v': goto yy730;
case 'X':
case 'x': goto yy731;
default: goto yy186;
}
yy124:
YYDEBUG(124, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1897 "Zend/zend_language_scanner.l"
{
zend_copy_value(zendlval, yytext, yyleng);
zendlval->type = IS_STRING;
return T_STRING;
}
#line 2407 "Zend/zend_language_scanner.c"
yy125:
YYDEBUG(125, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'O') {
if (yych <= 'H') {
if (yych == 'E') goto yy708;
goto yy186;
} else {
if (yych <= 'I') goto yy709;
if (yych <= 'N') goto yy186;
goto yy710;
}
} else {
if (yych <= 'h') {
if (yych == 'e') goto yy708;
goto yy186;
} else {
if (yych <= 'i') goto yy709;
if (yych == 'o') goto yy710;
goto yy186;
}
}
yy126:
YYDEBUG(126, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'U') {
if (yych <= 'N') {
if (yych == 'I') goto yy687;
goto yy186;
} else {
if (yych <= 'O') goto yy688;
if (yych <= 'T') goto yy186;
goto yy689;
}
} else {
if (yych <= 'n') {
if (yych == 'i') goto yy687;
goto yy186;
} else {
if (yych <= 'o') goto yy688;
if (yych == 'u') goto yy689;
goto yy186;
}
}
yy127:
YYDEBUG(127, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'O') {
if (yych <= 'K') {
if (yych == 'A') goto yy652;
goto yy186;
} else {
if (yych <= 'L') goto yy653;
if (yych <= 'N') goto yy186;
goto yy654;
}
} else {
if (yych <= 'k') {
if (yych == 'a') goto yy652;
goto yy186;
} else {
if (yych <= 'l') goto yy653;
if (yych == 'o') goto yy654;
goto yy186;
}
}
yy128:
YYDEBUG(128, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy634;
if (yych == 'e') goto yy634;
goto yy186;
yy129:
YYDEBUG(129, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'R') {
if (yych == 'H') goto yy622;
if (yych <= 'Q') goto yy186;
goto yy623;
} else {
if (yych <= 'h') {
if (yych <= 'g') goto yy186;
goto yy622;
} else {
if (yych == 'r') goto yy623;
goto yy186;
}
}
yy130:
YYDEBUG(130, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'S') {
if (yych <= 'L') {
if (yych == 'F') goto yy569;
goto yy186;
} else {
if (yych <= 'M') goto yy571;
if (yych <= 'N') goto yy572;
if (yych <= 'R') goto yy186;
goto yy573;
}
} else {
if (yych <= 'm') {
if (yych == 'f') goto yy569;
if (yych <= 'l') goto yy186;
goto yy571;
} else {
if (yych <= 'n') goto yy572;
if (yych == 's') goto yy573;
goto yy186;
}
}
yy131:
YYDEBUG(131, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'H') goto yy564;
if (yych == 'h') goto yy564;
goto yy186;
yy132:
YYDEBUG(132, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'S') {
if (yych <= 'M') {
if (yych == 'B') goto yy546;
goto yy186;
} else {
if (yych <= 'N') goto yy547;
if (yych <= 'Q') goto yy186;
if (yych <= 'R') goto yy548;
goto yy549;
}
} else {
if (yych <= 'n') {
if (yych == 'b') goto yy546;
if (yych <= 'm') goto yy186;
goto yy547;
} else {
if (yych <= 'q') goto yy186;
if (yych <= 'r') goto yy548;
if (yych <= 's') goto yy549;
goto yy186;
}
}
yy133:
YYDEBUG(133, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'W') {
if (yych == 'T') goto yy534;
if (yych <= 'V') goto yy186;
goto yy535;
} else {
if (yych <= 't') {
if (yych <= 's') goto yy186;
goto yy534;
} else {
if (yych == 'w') goto yy535;
goto yy186;
}
}
yy134:
YYDEBUG(134, *YYCURSOR);
yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= ';') {
if (yych <= '"') {
if (yych <= '!') goto yy186;
goto yy526;
} else {
if (yych == '\'') goto yy527;
goto yy186;
}
} else {
if (yych <= 'R') {
if (yych <= '<') goto yy525;
if (yych <= 'Q') goto yy186;
goto yy528;
} else {
if (yych == 'r') goto yy528;
goto yy186;
}
}
yy135:
YYDEBUG(135, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'O') {
if (yych == 'L') goto yy515;
if (yych <= 'N') goto yy186;
goto yy516;
} else {
if (yych <= 'l') {
if (yych <= 'k') goto yy186;
goto yy515;
} else {
if (yych == 'o') goto yy516;
goto yy186;
}
}
yy136:
YYDEBUG(136, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'U') {
if (yych == 'R') goto yy491;
if (yych <= 'T') goto yy186;
goto yy492;
} else {
if (yych <= 'r') {
if (yych <= 'q') goto yy186;
goto yy491;
} else {
if (yych == 'u') goto yy492;
goto yy186;
}
}
yy137:
YYDEBUG(137, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) <= '<') {
if (yych == '-') goto yy487;
} else {
if (yych <= '=') goto yy485;
if (yych <= '>') goto yy489;
}
yy138:
YYDEBUG(138, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1440 "Zend/zend_language_scanner.l"
{
return yytext[0];
}
#line 2637 "Zend/zend_language_scanner.c"
yy139:
YYDEBUG(139, *YYCURSOR);
++YYCURSOR;
yych = *YYCURSOR;
goto yy484;
yy140:
YYDEBUG(140, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1171 "Zend/zend_language_scanner.l"
{
zendlval->value.str.val = yytext; /* no copying - intentional */
zendlval->value.str.len = yyleng;
zendlval->type = IS_STRING;
HANDLE_NEWLINES(yytext, yyleng);
return T_WHITESPACE;
}
#line 2654 "Zend/zend_language_scanner.c"
yy141:
YYDEBUG(141, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == ':') goto yy481;
goto yy138;
yy142:
YYDEBUG(142, *YYCURSOR);
++YYCURSOR;
YYDEBUG(143, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1200 "Zend/zend_language_scanner.l"
{
return T_NS_SEPARATOR;
}
#line 2669 "Zend/zend_language_scanner.c"
yy144:
YYDEBUG(144, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'E') {
if (yych == 'A') goto yy469;
if (yych <= 'D') goto yy186;
goto yy470;
} else {
if (yych <= 'a') {
if (yych <= '`') goto yy186;
goto yy469;
} else {
if (yych == 'e') goto yy470;
goto yy186;
}
}
yy145:
YYDEBUG(145, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy466;
if (yych == 'a') goto yy466;
goto yy186;
yy146:
YYDEBUG(146, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= 'S') {
if (yych <= 'D') {
if (yych <= ' ') {
if (yych == '\t') goto yy391;
if (yych <= 0x1F) goto yy138;
goto yy391;
} else {
if (yych <= '@') goto yy138;
if (yych == 'C') goto yy138;
goto yy391;
}
} else {
if (yych <= 'I') {
if (yych == 'F') goto yy391;
if (yych <= 'H') goto yy138;
goto yy391;
} else {
if (yych == 'O') goto yy391;
if (yych <= 'Q') goto yy138;
goto yy391;
}
}
} else {
if (yych <= 'f') {
if (yych <= 'b') {
if (yych == 'U') goto yy391;
if (yych <= '`') goto yy138;
goto yy391;
} else {
if (yych == 'd') goto yy391;
if (yych <= 'e') goto yy138;
goto yy391;
}
} else {
if (yych <= 'o') {
if (yych == 'i') goto yy391;
if (yych <= 'n') goto yy138;
goto yy391;
} else {
if (yych <= 's') {
if (yych <= 'q') goto yy138;
goto yy391;
} else {
if (yych == 'u') goto yy391;
goto yy138;
}
}
}
}
yy147:
YYDEBUG(147, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'S') {
if (yych == 'N') goto yy382;
if (yych <= 'R') goto yy186;
goto yy383;
} else {
if (yych <= 'n') {
if (yych <= 'm') goto yy186;
goto yy382;
} else {
if (yych == 's') goto yy383;
goto yy186;
}
}
yy148:
YYDEBUG(148, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '_') goto yy300;
goto yy186;
yy149:
YYDEBUG(149, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '<') goto yy138;
if (yych <= '=') goto yy294;
if (yych <= '>') goto yy296;
goto yy138;
yy150:
YYDEBUG(150, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy290;
if (yych == 'i') goto yy290;
goto yy186;
yy151:
YYDEBUG(151, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '+') goto yy288;
if (yych == '=') goto yy286;
goto yy138;
yy152:
YYDEBUG(152, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '=') goto yy283;
goto yy138;
yy153:
YYDEBUG(153, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= ';') {
if (yych == '/') goto yy255;
goto yy138;
} else {
if (yych <= '<') goto yy253;
if (yych <= '=') goto yy256;
if (yych <= '>') goto yy258;
goto yy138;
}
yy154:
YYDEBUG(154, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '<') goto yy138;
if (yych <= '=') goto yy249;
if (yych <= '>') goto yy247;
goto yy138;
yy155:
YYDEBUG(155, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '=') goto yy245;
goto yy138;
yy156:
YYDEBUG(156, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '.') {
if (yych == '*') goto yy237;
goto yy138;
} else {
if (yych <= '/') goto yy239;
if (yych == '=') goto yy240;
goto yy138;
}
yy157:
YYDEBUG(157, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy138;
if (yych <= '9') goto yy233;
if (yych == '=') goto yy235;
goto yy138;
yy158:
YYDEBUG(158, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '<') goto yy138;
if (yych <= '=') goto yy229;
if (yych <= '>') goto yy227;
goto yy138;
yy159:
YYDEBUG(159, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '&') goto yy223;
if (yych == '=') goto yy225;
goto yy138;
yy160:
YYDEBUG(160, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '=') goto yy221;
if (yych == '|') goto yy219;
goto yy138;
yy161:
YYDEBUG(161, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '=') goto yy217;
goto yy138;
yy162:
YYDEBUG(162, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy215;
if (yych == 'r') goto yy215;
goto yy186;
yy163:
YYDEBUG(163, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy212;
if (yych == 'o') goto yy212;
goto yy186;
yy164:
YYDEBUG(164, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '_') {
if (yych <= '@') goto yy138;
if (yych <= 'Z') goto yy209;
if (yych <= '^') goto yy138;
goto yy209;
} else {
if (yych <= '`') goto yy138;
if (yych <= 'z') goto yy209;
if (yych <= '~') goto yy138;
goto yy209;
}
yy165:
YYDEBUG(165, *YYCURSOR);
yych = *++YYCURSOR;
goto yy138;
yy166:
YYDEBUG(166, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '>') goto yy205;
goto yy138;
yy167:
YYDEBUG(167, *YYCURSOR);
++YYCURSOR;
YYDEBUG(168, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1445 "Zend/zend_language_scanner.l"
{
yy_push_state(ST_IN_SCRIPTING TSRMLS_CC);
return '{';
}
#line 2902 "Zend/zend_language_scanner.c"
yy169:
YYDEBUG(169, *YYCURSOR);
++YYCURSOR;
YYDEBUG(170, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1457 "Zend/zend_language_scanner.l"
{
RESET_DOC_COMMENT();
if (!zend_stack_is_empty(&SCNG(state_stack))) {
yy_pop_state(TSRMLS_C);
}
return '}';
}
#line 2916 "Zend/zend_language_scanner.c"
yy171:
YYDEBUG(171, *YYCURSOR);
yyaccept = 2;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= 'E') {
if (yych <= '9') {
if (yych == '.') goto yy187;
if (yych >= '0') goto yy190;
} else {
if (yych == 'B') goto yy198;
if (yych >= 'E') goto yy192;
}
} else {
if (yych <= 'b') {
if (yych == 'X') goto yy197;
if (yych >= 'b') goto yy198;
} else {
if (yych <= 'e') {
if (yych >= 'e') goto yy192;
} else {
if (yych == 'x') goto yy197;
}
}
}
yy172:
YYDEBUG(172, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1507 "Zend/zend_language_scanner.l"
{
if (yyleng < MAX_LENGTH_OF_LONG - 1) { /* Won't overflow */
zendlval->value.lval = strtol(yytext, NULL, 0);
} else {
errno = 0;
zendlval->value.lval = strtol(yytext, NULL, 0);
if (errno == ERANGE) { /* Overflow */
if (yytext[0] == '0') { /* octal overflow */
zendlval->value.dval = zend_oct_strtod(yytext, NULL);
} else {
zendlval->value.dval = zend_strtod(yytext, NULL);
}
zendlval->type = IS_DOUBLE;
return T_DNUMBER;
}
}
zendlval->type = IS_LONG;
return T_LNUMBER;
}
#line 2965 "Zend/zend_language_scanner.c"
yy173:
YYDEBUG(173, *YYCURSOR);
yyaccept = 2;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= '9') {
if (yych == '.') goto yy187;
if (yych <= '/') goto yy172;
goto yy190;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy172;
goto yy192;
} else {
if (yych == 'e') goto yy192;
goto yy172;
}
}
yy174:
YYDEBUG(174, *YYCURSOR);
yych = *++YYCURSOR;
goto yy186;
yy175:
YYDEBUG(175, *YYCURSOR);
++YYCURSOR;
yy176:
YYDEBUG(176, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1904 "Zend/zend_language_scanner.l"
{
while (YYCURSOR < YYLIMIT) {
switch (*YYCURSOR++) {
case '\r':
if (*YYCURSOR == '\n') {
YYCURSOR++;
}
/* fall through */
case '\n':
CG(zend_lineno)++;
break;
case '%':
if (!CG(asp_tags)) {
continue;
}
/* fall through */
case '?':
if (*YYCURSOR == '>') {
YYCURSOR--;
break;
}
/* fall through */
default:
continue;
}
break;
}
yyleng = YYCURSOR - SCNG(yy_text);
return T_COMMENT;
}
#line 3027 "Zend/zend_language_scanner.c"
yy177:
YYDEBUG(177, *YYCURSOR);
++YYCURSOR;
yy178:
YYDEBUG(178, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1995 "Zend/zend_language_scanner.l"
{
register char *s, *t;
char *end;
int bprefix = (yytext[0] != '\'') ? 1 : 0;
while (1) {
if (YYCURSOR < YYLIMIT) {
if (*YYCURSOR == '\'') {
YYCURSOR++;
yyleng = YYCURSOR - SCNG(yy_text);
break;
} else if (*YYCURSOR++ == '\\' && YYCURSOR < YYLIMIT) {
YYCURSOR++;
}
} else {
yyleng = YYLIMIT - SCNG(yy_text);
/* Unclosed single quotes; treat similar to double quotes, but without a separate token
* for ' (unrecognized by parser), instead of old flex fallback to "Unexpected character..."
* rule, which continued in ST_IN_SCRIPTING state after the quote */
return T_ENCAPSED_AND_WHITESPACE;
}
}
zendlval->value.str.val = estrndup(yytext+bprefix+1, yyleng-bprefix-2);
zendlval->value.str.len = yyleng-bprefix-2;
zendlval->type = IS_STRING;
/* convert escape sequences */
s = t = zendlval->value.str.val;
end = s+zendlval->value.str.len;
while (s<end) {
if (*s=='\\') {
s++;
switch(*s) {
case '\\':
case '\'':
*t++ = *s;
zendlval->value.str.len--;
break;
default:
*t++ = '\\';
*t++ = *s;
break;
}
} else {
*t++ = *s;
}
if (*s == '\n' || (*s == '\r' && (*(s+1) != '\n'))) {
CG(zend_lineno)++;
}
s++;
}
*t = 0;
if (SCNG(output_filter)) {
size_t sz = 0;
s = zendlval->value.str.val;
SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)s, (size_t)zendlval->value.str.len TSRMLS_CC);
zendlval->value.str.len = sz;
efree(s);
}
return T_CONSTANT_ENCAPSED_STRING;
}
#line 3102 "Zend/zend_language_scanner.c"
yy179:
YYDEBUG(179, *YYCURSOR);
++YYCURSOR;
yy180:
YYDEBUG(180, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 2064 "Zend/zend_language_scanner.l"
{
int bprefix = (yytext[0] != '"') ? 1 : 0;
while (YYCURSOR < YYLIMIT) {
switch (*YYCURSOR++) {
case '"':
yyleng = YYCURSOR - SCNG(yy_text);
zend_scan_escape_string(zendlval, yytext+bprefix+1, yyleng-bprefix-2, '"' TSRMLS_CC);
return T_CONSTANT_ENCAPSED_STRING;
case '$':
if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') {
break;
}
continue;
case '{':
if (*YYCURSOR == '$') {
break;
}
continue;
case '\\':
if (YYCURSOR < YYLIMIT) {
YYCURSOR++;
}
/* fall through */
default:
continue;
}
YYCURSOR--;
break;
}
/* Remember how much was scanned to save rescanning */
SET_DOUBLE_QUOTES_SCANNED_LENGTH(YYCURSOR - SCNG(yy_text) - yyleng);
YYCURSOR = SCNG(yy_text) + yyleng;
BEGIN(ST_DOUBLE_QUOTES);
return '"';
}
#line 3150 "Zend/zend_language_scanner.c"
yy181:
YYDEBUG(181, *YYCURSOR);
++YYCURSOR;
YYDEBUG(182, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 2155 "Zend/zend_language_scanner.l"
{
BEGIN(ST_BACKQUOTE);
return '`';
}
#line 3161 "Zend/zend_language_scanner.c"
yy183:
YYDEBUG(183, *YYCURSOR);
++YYCURSOR;
YYDEBUG(184, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 2413 "Zend/zend_language_scanner.l"
{
if (YYCURSOR > YYLIMIT) {
return 0;
}
zend_error(E_COMPILE_WARNING,"Unexpected character in input: '%c' (ASCII=%d) state=%d", yytext[0], yytext[0], YYSTATE);
goto restart;
}
#line 3176 "Zend/zend_language_scanner.c"
yy185:
YYDEBUG(185, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
yy186:
YYDEBUG(186, *YYCURSOR);
if (yybm[0+yych] & 4) {
goto yy185;
}
goto yy124;
yy187:
YYDEBUG(187, *YYCURSOR);
yyaccept = 3;
YYMARKER = ++YYCURSOR;
YYFILL(3);
yych = *YYCURSOR;
YYDEBUG(188, *YYCURSOR);
if (yybm[0+yych] & 8) {
goto yy187;
}
if (yych == 'E') goto yy192;
if (yych == 'e') goto yy192;
yy189:
YYDEBUG(189, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1572 "Zend/zend_language_scanner.l"
{
zendlval->value.dval = zend_strtod(yytext, NULL);
zendlval->type = IS_DOUBLE;
return T_DNUMBER;
}
#line 3209 "Zend/zend_language_scanner.c"
yy190:
YYDEBUG(190, *YYCURSOR);
yyaccept = 2;
YYMARKER = ++YYCURSOR;
YYFILL(3);
yych = *YYCURSOR;
YYDEBUG(191, *YYCURSOR);
if (yych <= '9') {
if (yych == '.') goto yy187;
if (yych <= '/') goto yy172;
goto yy190;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy172;
} else {
if (yych != 'e') goto yy172;
}
}
yy192:
YYDEBUG(192, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych == '+') goto yy194;
} else {
if (yych <= '-') goto yy194;
if (yych <= '/') goto yy193;
if (yych <= '9') goto yy195;
}
yy193:
YYDEBUG(193, *YYCURSOR);
YYCURSOR = YYMARKER;
if (yyaccept <= 2) {
if (yyaccept <= 1) {
if (yyaccept <= 0) {
goto yy124;
} else {
goto yy138;
}
} else {
goto yy172;
}
} else {
if (yyaccept <= 4) {
if (yyaccept <= 3) {
goto yy189;
} else {
goto yy238;
}
} else {
goto yy254;
}
}
yy194:
YYDEBUG(194, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy193;
if (yych >= ':') goto yy193;
yy195:
YYDEBUG(195, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(196, *YYCURSOR);
if (yych <= '/') goto yy189;
if (yych <= '9') goto yy195;
goto yy189;
yy197:
YYDEBUG(197, *YYCURSOR);
yych = *++YYCURSOR;
if (yybm[0+yych] & 32) {
goto yy202;
}
goto yy193;
yy198:
YYDEBUG(198, *YYCURSOR);
yych = *++YYCURSOR;
if (yybm[0+yych] & 16) {
goto yy199;
}
goto yy193;
yy199:
YYDEBUG(199, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(200, *YYCURSOR);
if (yybm[0+yych] & 16) {
goto yy199;
}
YYDEBUG(201, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1482 "Zend/zend_language_scanner.l"
{
char *bin = yytext + 2; /* Skip "0b" */
int len = yyleng - 2;
/* Skip any leading 0s */
while (*bin == '0') {
++bin;
--len;
}
if (len < SIZEOF_LONG * 8) {
if (len == 0) {
zendlval->value.lval = 0;
} else {
zendlval->value.lval = strtol(bin, NULL, 2);
}
zendlval->type = IS_LONG;
return T_LNUMBER;
} else {
zendlval->value.dval = zend_bin_strtod(bin, NULL);
zendlval->type = IS_DOUBLE;
return T_DNUMBER;
}
}
#line 3326 "Zend/zend_language_scanner.c"
yy202:
YYDEBUG(202, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(203, *YYCURSOR);
if (yybm[0+yych] & 32) {
goto yy202;
}
YYDEBUG(204, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1528 "Zend/zend_language_scanner.l"
{
char *hex = yytext + 2; /* Skip "0x" */
int len = yyleng - 2;
/* Skip any leading 0s */
while (*hex == '0') {
hex++;
len--;
}
if (len < SIZEOF_LONG * 2 || (len == SIZEOF_LONG * 2 && *hex <= '7')) {
if (len == 0) {
zendlval->value.lval = 0;
} else {
zendlval->value.lval = strtol(hex, NULL, 16);
}
zendlval->type = IS_LONG;
return T_LNUMBER;
} else {
zendlval->value.dval = zend_hex_strtod(hex, NULL);
zendlval->type = IS_DOUBLE;
return T_DNUMBER;
}
}
#line 3363 "Zend/zend_language_scanner.c"
yy205:
YYDEBUG(205, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) == '\n') goto yy207;
if (yych == '\r') goto yy208;
yy206:
YYDEBUG(206, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1972 "Zend/zend_language_scanner.l"
{
zendlval->value.str.val = yytext; /* no copying - intentional */
zendlval->value.str.len = yyleng;
zendlval->type = IS_STRING;
BEGIN(INITIAL);
return T_CLOSE_TAG; /* implicit ';' at php-end tag */
}
#line 3380 "Zend/zend_language_scanner.c"
yy207:
YYDEBUG(207, *YYCURSOR);
yych = *++YYCURSOR;
goto yy206;
yy208:
YYDEBUG(208, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '\n') goto yy207;
goto yy206;
yy209:
YYDEBUG(209, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(210, *YYCURSOR);
if (yych <= '^') {
if (yych <= '9') {
if (yych >= '0') goto yy209;
} else {
if (yych <= '@') goto yy211;
if (yych <= 'Z') goto yy209;
}
} else {
if (yych <= '`') {
if (yych <= '_') goto yy209;
} else {
if (yych <= 'z') goto yy209;
if (yych >= 0x7F) goto yy209;
}
}
yy211:
YYDEBUG(211, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1874 "Zend/zend_language_scanner.l"
{
zend_copy_value(zendlval, (yytext+1), (yyleng-1));
zendlval->type = IS_STRING;
return T_VARIABLE;
}
#line 3420 "Zend/zend_language_scanner.c"
yy212:
YYDEBUG(212, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy213;
if (yych != 'r') goto yy186;
yy213:
YYDEBUG(213, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(214, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1428 "Zend/zend_language_scanner.l"
{
return T_LOGICAL_XOR;
}
#line 3438 "Zend/zend_language_scanner.c"
yy215:
YYDEBUG(215, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(216, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1420 "Zend/zend_language_scanner.l"
{
return T_LOGICAL_OR;
}
#line 3451 "Zend/zend_language_scanner.c"
yy217:
YYDEBUG(217, *YYCURSOR);
++YYCURSOR;
YYDEBUG(218, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1408 "Zend/zend_language_scanner.l"
{
return T_XOR_EQUAL;
}
#line 3461 "Zend/zend_language_scanner.c"
yy219:
YYDEBUG(219, *YYCURSOR);
++YYCURSOR;
YYDEBUG(220, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1412 "Zend/zend_language_scanner.l"
{
return T_BOOLEAN_OR;
}
#line 3471 "Zend/zend_language_scanner.c"
yy221:
YYDEBUG(221, *YYCURSOR);
++YYCURSOR;
YYDEBUG(222, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1404 "Zend/zend_language_scanner.l"
{
return T_OR_EQUAL;
}
#line 3481 "Zend/zend_language_scanner.c"
yy223:
YYDEBUG(223, *YYCURSOR);
++YYCURSOR;
YYDEBUG(224, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1416 "Zend/zend_language_scanner.l"
{
return T_BOOLEAN_AND;
}
#line 3491 "Zend/zend_language_scanner.c"
yy225:
YYDEBUG(225, *YYCURSOR);
++YYCURSOR;
YYDEBUG(226, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1400 "Zend/zend_language_scanner.l"
{
return T_AND_EQUAL;
}
#line 3501 "Zend/zend_language_scanner.c"
yy227:
YYDEBUG(227, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) == '\n') goto yy231;
if (yych == '\r') goto yy232;
yy228:
YYDEBUG(228, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1981 "Zend/zend_language_scanner.l"
{
if (CG(asp_tags)) {
BEGIN(INITIAL);
zendlval->value.str.len = yyleng;
zendlval->type = IS_STRING;
zendlval->value.str.val = yytext; /* no copying - intentional */
return T_CLOSE_TAG; /* implicit ';' at php-end tag */
} else {
yyless(1);
return yytext[0];
}
}
#line 3523 "Zend/zend_language_scanner.c"
yy229:
YYDEBUG(229, *YYCURSOR);
++YYCURSOR;
YYDEBUG(230, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1388 "Zend/zend_language_scanner.l"
{
return T_MOD_EQUAL;
}
#line 3533 "Zend/zend_language_scanner.c"
yy231:
YYDEBUG(231, *YYCURSOR);
yych = *++YYCURSOR;
goto yy228;
yy232:
YYDEBUG(232, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '\n') goto yy231;
goto yy228;
yy233:
YYDEBUG(233, *YYCURSOR);
yyaccept = 3;
YYMARKER = ++YYCURSOR;
YYFILL(3);
yych = *YYCURSOR;
YYDEBUG(234, *YYCURSOR);
if (yych <= 'D') {
if (yych <= '/') goto yy189;
if (yych <= '9') goto yy233;
goto yy189;
} else {
if (yych <= 'E') goto yy192;
if (yych == 'e') goto yy192;
goto yy189;
}
yy235:
YYDEBUG(235, *YYCURSOR);
++YYCURSOR;
YYDEBUG(236, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1384 "Zend/zend_language_scanner.l"
{
return T_CONCAT_EQUAL;
}
#line 3568 "Zend/zend_language_scanner.c"
yy237:
YYDEBUG(237, *YYCURSOR);
yyaccept = 4;
yych = *(YYMARKER = ++YYCURSOR);
if (yych == '*') goto yy242;
yy238:
YYDEBUG(238, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1938 "Zend/zend_language_scanner.l"
{
int doc_com;
if (yyleng > 2) {
doc_com = 1;
RESET_DOC_COMMENT();
} else {
doc_com = 0;
}
while (YYCURSOR < YYLIMIT) {
if (*YYCURSOR++ == '*' && *YYCURSOR == '/') {
break;
}
}
if (YYCURSOR < YYLIMIT) {
YYCURSOR++;
} else {
zend_error(E_COMPILE_WARNING, "Unterminated comment starting line %d", CG(zend_lineno));
}
yyleng = YYCURSOR - SCNG(yy_text);
HANDLE_NEWLINES(yytext, yyleng);
if (doc_com) {
CG(doc_comment) = estrndup(yytext, yyleng);
CG(doc_comment_len) = yyleng;
return T_DOC_COMMENT;
}
return T_COMMENT;
}
#line 3611 "Zend/zend_language_scanner.c"
yy239:
YYDEBUG(239, *YYCURSOR);
yych = *++YYCURSOR;
goto yy176;
yy240:
YYDEBUG(240, *YYCURSOR);
++YYCURSOR;
YYDEBUG(241, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1380 "Zend/zend_language_scanner.l"
{
return T_DIV_EQUAL;
}
#line 3625 "Zend/zend_language_scanner.c"
yy242:
YYDEBUG(242, *YYCURSOR);
yych = *++YYCURSOR;
if (yybm[0+yych] & 64) {
goto yy243;
}
goto yy193;
yy243:
YYDEBUG(243, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(244, *YYCURSOR);
if (yybm[0+yych] & 64) {
goto yy243;
}
goto yy238;
yy245:
YYDEBUG(245, *YYCURSOR);
++YYCURSOR;
YYDEBUG(246, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1376 "Zend/zend_language_scanner.l"
{
return T_MUL_EQUAL;
}
#line 3652 "Zend/zend_language_scanner.c"
yy247:
YYDEBUG(247, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) == '=') goto yy251;
YYDEBUG(248, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1436 "Zend/zend_language_scanner.l"
{
return T_SR;
}
#line 3663 "Zend/zend_language_scanner.c"
yy249:
YYDEBUG(249, *YYCURSOR);
++YYCURSOR;
YYDEBUG(250, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1364 "Zend/zend_language_scanner.l"
{
return T_IS_GREATER_OR_EQUAL;
}
#line 3673 "Zend/zend_language_scanner.c"
yy251:
YYDEBUG(251, *YYCURSOR);
++YYCURSOR;
YYDEBUG(252, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1396 "Zend/zend_language_scanner.l"
{
return T_SR_EQUAL;
}
#line 3683 "Zend/zend_language_scanner.c"
yy253:
YYDEBUG(253, *YYCURSOR);
yyaccept = 5;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= ';') goto yy254;
if (yych <= '<') goto yy269;
if (yych <= '=') goto yy267;
yy254:
YYDEBUG(254, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1432 "Zend/zend_language_scanner.l"
{
return T_SL;
}
#line 3698 "Zend/zend_language_scanner.c"
yy255:
YYDEBUG(255, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'S') goto yy260;
if (yych == 's') goto yy260;
goto yy193;
yy256:
YYDEBUG(256, *YYCURSOR);
++YYCURSOR;
YYDEBUG(257, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1360 "Zend/zend_language_scanner.l"
{
return T_IS_SMALLER_OR_EQUAL;
}
#line 3714 "Zend/zend_language_scanner.c"
yy258:
YYDEBUG(258, *YYCURSOR);
++YYCURSOR;
yy259:
YYDEBUG(259, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1356 "Zend/zend_language_scanner.l"
{
return T_IS_NOT_EQUAL;
}
#line 3725 "Zend/zend_language_scanner.c"
yy260:
YYDEBUG(260, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy261;
if (yych != 'c') goto yy193;
yy261:
YYDEBUG(261, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy262;
if (yych != 'r') goto yy193;
yy262:
YYDEBUG(262, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy263;
if (yych != 'i') goto yy193;
yy263:
YYDEBUG(263, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'P') goto yy264;
if (yych != 'p') goto yy193;
yy264:
YYDEBUG(264, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy265;
if (yych != 't') goto yy193;
yy265:
YYDEBUG(265, *YYCURSOR);
++YYCURSOR;
YYFILL(3);
yych = *YYCURSOR;
YYDEBUG(266, *YYCURSOR);
if (yych <= '\r') {
if (yych <= 0x08) goto yy193;
if (yych <= '\n') goto yy265;
if (yych <= '\f') goto yy193;
goto yy265;
} else {
if (yych <= ' ') {
if (yych <= 0x1F) goto yy193;
goto yy265;
} else {
if (yych == '>') goto yy205;
goto yy193;
}
}
yy267:
YYDEBUG(267, *YYCURSOR);
++YYCURSOR;
YYDEBUG(268, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1392 "Zend/zend_language_scanner.l"
{
return T_SL_EQUAL;
}
#line 3780 "Zend/zend_language_scanner.c"
yy269:
YYDEBUG(269, *YYCURSOR);
++YYCURSOR;
YYFILL(2);
yych = *YYCURSOR;
YYDEBUG(270, *YYCURSOR);
if (yybm[0+yych] & 128) {
goto yy269;
}
if (yych <= 'Z') {
if (yych <= '&') {
if (yych == '"') goto yy274;
goto yy193;
} else {
if (yych <= '\'') goto yy273;
if (yych <= '@') goto yy193;
}
} else {
if (yych <= '`') {
if (yych != '_') goto yy193;
} else {
if (yych <= 'z') goto yy271;
if (yych <= '~') goto yy193;
}
}
yy271:
YYDEBUG(271, *YYCURSOR);
++YYCURSOR;
YYFILL(2);
yych = *YYCURSOR;
YYDEBUG(272, *YYCURSOR);
if (yych <= '@') {
if (yych <= '\f') {
if (yych == '\n') goto yy278;
goto yy193;
} else {
if (yych <= '\r') goto yy280;
if (yych <= '/') goto yy193;
if (yych <= '9') goto yy271;
goto yy193;
}
} else {
if (yych <= '_') {
if (yych <= 'Z') goto yy271;
if (yych <= '^') goto yy193;
goto yy271;
} else {
if (yych <= '`') goto yy193;
if (yych <= 'z') goto yy271;
if (yych <= '~') goto yy193;
goto yy271;
}
}
yy273:
YYDEBUG(273, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '\'') goto yy193;
if (yych <= '/') goto yy282;
if (yych <= '9') goto yy193;
goto yy282;
yy274:
YYDEBUG(274, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '"') goto yy193;
if (yych <= '/') goto yy276;
if (yych <= '9') goto yy193;
goto yy276;
yy275:
YYDEBUG(275, *YYCURSOR);
++YYCURSOR;
YYFILL(3);
yych = *YYCURSOR;
yy276:
YYDEBUG(276, *YYCURSOR);
if (yych <= 'Z') {
if (yych <= '/') {
if (yych != '"') goto yy193;
} else {
if (yych <= '9') goto yy275;
if (yych <= '@') goto yy193;
goto yy275;
}
} else {
if (yych <= '`') {
if (yych == '_') goto yy275;
goto yy193;
} else {
if (yych <= 'z') goto yy275;
if (yych <= '~') goto yy193;
goto yy275;
}
}
yy277:
YYDEBUG(277, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '\n') goto yy278;
if (yych == '\r') goto yy280;
goto yy193;
yy278:
YYDEBUG(278, *YYCURSOR);
++YYCURSOR;
yy279:
YYDEBUG(279, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 2106 "Zend/zend_language_scanner.l"
{
char *s;
int bprefix = (yytext[0] != '<') ? 1 : 0;
/* save old heredoc label */
Z_STRVAL_P(zendlval) = CG(heredoc);
Z_STRLEN_P(zendlval) = CG(heredoc_len);
CG(zend_lineno)++;
CG(heredoc_len) = yyleng-bprefix-3-1-(yytext[yyleng-2]=='\r'?1:0);
s = yytext+bprefix+3;
while ((*s == ' ') || (*s == '\t')) {
s++;
CG(heredoc_len)--;
}
if (*s == '\'') {
s++;
CG(heredoc_len) -= 2;
BEGIN(ST_NOWDOC);
} else {
if (*s == '"') {
s++;
CG(heredoc_len) -= 2;
}
BEGIN(ST_HEREDOC);
}
CG(heredoc) = estrndup(s, CG(heredoc_len));
/* Check for ending label on the next line */
if (CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, s, CG(heredoc_len))) {
YYCTYPE *end = YYCURSOR + CG(heredoc_len);
if (*end == ';') {
end++;
}
if (*end == '\n' || *end == '\r') {
BEGIN(ST_END_HEREDOC);
}
}
return T_START_HEREDOC;
}
#line 3933 "Zend/zend_language_scanner.c"
yy280:
YYDEBUG(280, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '\n') goto yy278;
goto yy279;
yy281:
YYDEBUG(281, *YYCURSOR);
++YYCURSOR;
YYFILL(3);
yych = *YYCURSOR;
yy282:
YYDEBUG(282, *YYCURSOR);
if (yych <= 'Z') {
if (yych <= '/') {
if (yych == '\'') goto yy277;
goto yy193;
} else {
if (yych <= '9') goto yy281;
if (yych <= '@') goto yy193;
goto yy281;
}
} else {
if (yych <= '`') {
if (yych == '_') goto yy281;
goto yy193;
} else {
if (yych <= 'z') goto yy281;
if (yych <= '~') goto yy193;
goto yy281;
}
}
yy283:
YYDEBUG(283, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '=') goto yy259;
YYDEBUG(284, *YYCURSOR);
++YYCURSOR;
YYDEBUG(285, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1348 "Zend/zend_language_scanner.l"
{
return T_IS_NOT_IDENTICAL;
}
#line 3977 "Zend/zend_language_scanner.c"
yy286:
YYDEBUG(286, *YYCURSOR);
++YYCURSOR;
YYDEBUG(287, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1368 "Zend/zend_language_scanner.l"
{
return T_PLUS_EQUAL;
}
#line 3987 "Zend/zend_language_scanner.c"
yy288:
YYDEBUG(288, *YYCURSOR);
++YYCURSOR;
YYDEBUG(289, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1336 "Zend/zend_language_scanner.l"
{
return T_INC;
}
#line 3997 "Zend/zend_language_scanner.c"
yy290:
YYDEBUG(290, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'S') goto yy291;
if (yych != 's') goto yy186;
yy291:
YYDEBUG(291, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy292;
if (yych != 't') goto yy186;
yy292:
YYDEBUG(292, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(293, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1324 "Zend/zend_language_scanner.l"
{
return T_LIST;
}
#line 4020 "Zend/zend_language_scanner.c"
yy294:
YYDEBUG(294, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) == '=') goto yy298;
YYDEBUG(295, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1352 "Zend/zend_language_scanner.l"
{
return T_IS_EQUAL;
}
#line 4031 "Zend/zend_language_scanner.c"
yy296:
YYDEBUG(296, *YYCURSOR);
++YYCURSOR;
YYDEBUG(297, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1320 "Zend/zend_language_scanner.l"
{
return T_DOUBLE_ARROW;
}
#line 4041 "Zend/zend_language_scanner.c"
yy298:
YYDEBUG(298, *YYCURSOR);
++YYCURSOR;
YYDEBUG(299, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1344 "Zend/zend_language_scanner.l"
{
return T_IS_IDENTICAL;
}
#line 4051 "Zend/zend_language_scanner.c"
yy300:
YYDEBUG(300, *YYCURSOR);
yych = *++YYCURSOR;
YYDEBUG(-1, yych);
switch (yych) {
case 'C':
case 'c': goto yy302;
case 'D':
case 'd': goto yy307;
case 'F':
case 'f': goto yy304;
case 'H':
case 'h': goto yy301;
case 'L':
case 'l': goto yy306;
case 'M':
case 'm': goto yy305;
case 'N':
case 'n': goto yy308;
case 'T':
case 't': goto yy303;
default: goto yy186;
}
yy301:
YYDEBUG(301, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy369;
if (yych == 'a') goto yy369;
goto yy186;
yy302:
YYDEBUG(302, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy362;
if (yych == 'l') goto yy362;
goto yy186;
yy303:
YYDEBUG(303, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy355;
if (yych == 'r') goto yy355;
goto yy186;
yy304:
YYDEBUG(304, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'U') {
if (yych == 'I') goto yy339;
if (yych <= 'T') goto yy186;
goto yy340;
} else {
if (yych <= 'i') {
if (yych <= 'h') goto yy186;
goto yy339;
} else {
if (yych == 'u') goto yy340;
goto yy186;
}
}
yy305:
YYDEBUG(305, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy331;
if (yych == 'e') goto yy331;
goto yy186;
yy306:
YYDEBUG(306, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy325;
if (yych == 'i') goto yy325;
goto yy186;
yy307:
YYDEBUG(307, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy320;
if (yych == 'i') goto yy320;
goto yy186;
yy308:
YYDEBUG(308, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy309;
if (yych != 'a') goto yy186;
yy309:
YYDEBUG(309, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'M') goto yy310;
if (yych != 'm') goto yy186;
yy310:
YYDEBUG(310, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy311;
if (yych != 'e') goto yy186;
yy311:
YYDEBUG(311, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'S') goto yy312;
if (yych != 's') goto yy186;
yy312:
YYDEBUG(312, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'P') goto yy313;
if (yych != 'p') goto yy186;
yy313:
YYDEBUG(313, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy314;
if (yych != 'a') goto yy186;
yy314:
YYDEBUG(314, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy315;
if (yych != 'c') goto yy186;
yy315:
YYDEBUG(315, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy316;
if (yych != 'e') goto yy186;
yy316:
YYDEBUG(316, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(317, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(318, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(319, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1707 "Zend/zend_language_scanner.l"
{
if (CG(current_namespace)) {
*zendlval = *CG(current_namespace);
zval_copy_ctor(zendlval);
} else {
ZVAL_EMPTY_STRING(zendlval);
}
return T_NS_C;
}
#line 4191 "Zend/zend_language_scanner.c"
yy320:
YYDEBUG(320, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy321;
if (yych != 'r') goto yy186;
yy321:
YYDEBUG(321, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(322, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(323, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(324, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1680 "Zend/zend_language_scanner.l"
{
char *filename = zend_get_compiled_filename(TSRMLS_C);
const size_t filename_len = strlen(filename);
char *dirname;
if (!filename) {
filename = "";
}
dirname = estrndup(filename, filename_len);
zend_dirname(dirname, filename_len);
if (strcmp(dirname, ".") == 0) {
dirname = erealloc(dirname, MAXPATHLEN);
#if HAVE_GETCWD
VCWD_GETCWD(dirname, MAXPATHLEN);
#elif HAVE_GETWD
VCWD_GETWD(dirname);
#endif
}
zendlval->value.str.len = strlen(dirname);
zendlval->value.str.val = dirname;
zendlval->type = IS_STRING;
return T_DIR;
}
#line 4238 "Zend/zend_language_scanner.c"
yy325:
YYDEBUG(325, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy326;
if (yych != 'n') goto yy186;
yy326:
YYDEBUG(326, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy327;
if (yych != 'e') goto yy186;
yy327:
YYDEBUG(327, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(328, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(329, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(330, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1662 "Zend/zend_language_scanner.l"
{
zendlval->value.lval = CG(zend_lineno);
zendlval->type = IS_LONG;
return T_LINE;
}
#line 4269 "Zend/zend_language_scanner.c"
yy331:
YYDEBUG(331, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy332;
if (yych != 't') goto yy186;
yy332:
YYDEBUG(332, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'H') goto yy333;
if (yych != 'h') goto yy186;
yy333:
YYDEBUG(333, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy334;
if (yych != 'o') goto yy186;
yy334:
YYDEBUG(334, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'D') goto yy335;
if (yych != 'd') goto yy186;
yy335:
YYDEBUG(335, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(336, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(337, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(338, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1641 "Zend/zend_language_scanner.l"
{
const char *class_name = CG(active_class_entry) ? CG(active_class_entry)->name : NULL;
const char *func_name = CG(active_op_array)? CG(active_op_array)->function_name : NULL;
size_t len = 0;
if (class_name) {
len += strlen(class_name) + 2;
}
if (func_name) {
len += strlen(func_name);
}
zendlval->value.str.len = zend_spprintf(&zendlval->value.str.val, 0, "%s%s%s",
class_name ? class_name : "",
class_name && func_name ? "::" : "",
func_name ? func_name : ""
);
zendlval->type = IS_STRING;
return T_METHOD_C;
}
#line 4325 "Zend/zend_language_scanner.c"
yy339:
YYDEBUG(339, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy350;
if (yych == 'l') goto yy350;
goto yy186;
yy340:
YYDEBUG(340, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy341;
if (yych != 'n') goto yy186;
yy341:
YYDEBUG(341, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy342;
if (yych != 'c') goto yy186;
yy342:
YYDEBUG(342, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy343;
if (yych != 't') goto yy186;
yy343:
YYDEBUG(343, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy344;
if (yych != 'i') goto yy186;
yy344:
YYDEBUG(344, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy345;
if (yych != 'o') goto yy186;
yy345:
YYDEBUG(345, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy346;
if (yych != 'n') goto yy186;
yy346:
YYDEBUG(346, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(347, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(348, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(349, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1625 "Zend/zend_language_scanner.l"
{
const char *func_name = NULL;
if (CG(active_op_array)) {
func_name = CG(active_op_array)->function_name;
}
if (!func_name) {
func_name = "";
}
zendlval->value.str.len = strlen(func_name);
zendlval->value.str.val = estrndup(func_name, zendlval->value.str.len);
zendlval->type = IS_STRING;
return T_FUNC_C;
}
#line 4392 "Zend/zend_language_scanner.c"
yy350:
YYDEBUG(350, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy351;
if (yych != 'e') goto yy186;
yy351:
YYDEBUG(351, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(352, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(353, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(354, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1668 "Zend/zend_language_scanner.l"
{
char *filename = zend_get_compiled_filename(TSRMLS_C);
if (!filename) {
filename = "";
}
zendlval->value.str.len = strlen(filename);
zendlval->value.str.val = estrndup(filename, zendlval->value.str.len);
zendlval->type = IS_STRING;
return T_FILE;
}
#line 4424 "Zend/zend_language_scanner.c"
yy355:
YYDEBUG(355, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy356;
if (yych != 'a') goto yy186;
yy356:
YYDEBUG(356, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy357;
if (yych != 'i') goto yy186;
yy357:
YYDEBUG(357, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy358;
if (yych != 't') goto yy186;
yy358:
YYDEBUG(358, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(359, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(360, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(361, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1605 "Zend/zend_language_scanner.l"
{
const char *trait_name = NULL;
if (CG(active_class_entry)
&& (ZEND_ACC_TRAIT ==
(CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT))) {
trait_name = CG(active_class_entry)->name;
}
if (!trait_name) {
trait_name = "";
}
zendlval->value.str.len = strlen(trait_name);
zendlval->value.str.val = estrndup(trait_name, zendlval->value.str.len);
zendlval->type = IS_STRING;
return T_TRAIT_C;
}
#line 4474 "Zend/zend_language_scanner.c"
yy362:
YYDEBUG(362, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy363;
if (yych != 'a') goto yy186;
yy363:
YYDEBUG(363, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'S') goto yy364;
if (yych != 's') goto yy186;
yy364:
YYDEBUG(364, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'S') goto yy365;
if (yych != 's') goto yy186;
yy365:
YYDEBUG(365, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(366, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(367, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(368, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1578 "Zend/zend_language_scanner.l"
{
const char *class_name = NULL;
if (CG(active_class_entry)
&& (ZEND_ACC_TRAIT ==
(CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT))) {
/* We create a special __CLASS__ constant that is going to be resolved
at run-time */
zendlval->value.str.len = sizeof("__CLASS__")-1;
zendlval->value.str.val = estrndup("__CLASS__", zendlval->value.str.len);
zendlval->type = IS_CONSTANT;
} else {
if (CG(active_class_entry)) {
class_name = CG(active_class_entry)->name;
}
if (!class_name) {
class_name = "";
}
zendlval->value.str.len = strlen(class_name);
zendlval->value.str.val = estrndup(class_name, zendlval->value.str.len);
zendlval->type = IS_STRING;
}
return T_CLASS_C;
}
#line 4531 "Zend/zend_language_scanner.c"
yy369:
YYDEBUG(369, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy370;
if (yych != 'l') goto yy186;
yy370:
YYDEBUG(370, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy371;
if (yych != 't') goto yy186;
yy371:
YYDEBUG(371, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '_') goto yy186;
YYDEBUG(372, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy373;
if (yych != 'c') goto yy186;
yy373:
YYDEBUG(373, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy374;
if (yych != 'o') goto yy186;
yy374:
YYDEBUG(374, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'M') goto yy375;
if (yych != 'm') goto yy186;
yy375:
YYDEBUG(375, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'P') goto yy376;
if (yych != 'p') goto yy186;
yy376:
YYDEBUG(376, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy377;
if (yych != 'i') goto yy186;
yy377:
YYDEBUG(377, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy378;
if (yych != 'l') goto yy186;
yy378:
YYDEBUG(378, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy379;
if (yych != 'e') goto yy186;
yy379:
YYDEBUG(379, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy380;
if (yych != 'r') goto yy186;
yy380:
YYDEBUG(380, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(381, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1288 "Zend/zend_language_scanner.l"
{
return T_HALT_COMPILER;
}
#line 4597 "Zend/zend_language_scanner.c"
yy382:
YYDEBUG(382, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'S') goto yy386;
if (yych == 's') goto yy386;
goto yy186;
yy383:
YYDEBUG(383, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy384;
if (yych != 'e') goto yy186;
yy384:
YYDEBUG(384, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(385, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1268 "Zend/zend_language_scanner.l"
{
return T_USE;
}
#line 4621 "Zend/zend_language_scanner.c"
yy386:
YYDEBUG(386, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy387;
if (yych != 'e') goto yy186;
yy387:
YYDEBUG(387, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy388;
if (yych != 't') goto yy186;
yy388:
YYDEBUG(388, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(389, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1316 "Zend/zend_language_scanner.l"
{
return T_UNSET;
}
#line 4644 "Zend/zend_language_scanner.c"
yy390:
YYDEBUG(390, *YYCURSOR);
++YYCURSOR;
YYFILL(7);
yych = *YYCURSOR;
yy391:
YYDEBUG(391, *YYCURSOR);
if (yych <= 'S') {
if (yych <= 'D') {
if (yych <= ' ') {
if (yych == '\t') goto yy390;
if (yych <= 0x1F) goto yy193;
goto yy390;
} else {
if (yych <= 'A') {
if (yych <= '@') goto yy193;
goto yy395;
} else {
if (yych <= 'B') goto yy393;
if (yych <= 'C') goto yy193;
goto yy398;
}
}
} else {
if (yych <= 'I') {
if (yych == 'F') goto yy399;
if (yych <= 'H') goto yy193;
goto yy400;
} else {
if (yych <= 'O') {
if (yych <= 'N') goto yy193;
goto yy394;
} else {
if (yych <= 'Q') goto yy193;
if (yych <= 'R') goto yy397;
goto yy396;
}
}
}
} else {
if (yych <= 'f') {
if (yych <= 'a') {
if (yych == 'U') goto yy392;
if (yych <= '`') goto yy193;
goto yy395;
} else {
if (yych <= 'c') {
if (yych <= 'b') goto yy393;
goto yy193;
} else {
if (yych <= 'd') goto yy398;
if (yych <= 'e') goto yy193;
goto yy399;
}
}
} else {
if (yych <= 'q') {
if (yych <= 'i') {
if (yych <= 'h') goto yy193;
goto yy400;
} else {
if (yych == 'o') goto yy394;
goto yy193;
}
} else {
if (yych <= 's') {
if (yych <= 'r') goto yy397;
goto yy396;
} else {
if (yych != 'u') goto yy193;
}
}
}
}
yy392:
YYDEBUG(392, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy459;
if (yych == 'n') goto yy459;
goto yy193;
yy393:
YYDEBUG(393, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'O') {
if (yych == 'I') goto yy446;
if (yych <= 'N') goto yy193;
goto yy447;
} else {
if (yych <= 'i') {
if (yych <= 'h') goto yy193;
goto yy446;
} else {
if (yych == 'o') goto yy447;
goto yy193;
}
}
yy394:
YYDEBUG(394, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'B') goto yy438;
if (yych == 'b') goto yy438;
goto yy193;
yy395:
YYDEBUG(395, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy431;
if (yych == 'r') goto yy431;
goto yy193;
yy396:
YYDEBUG(396, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy423;
if (yych == 't') goto yy423;
goto yy193;
yy397:
YYDEBUG(397, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy421;
if (yych == 'e') goto yy421;
goto yy193;
yy398:
YYDEBUG(398, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy417;
if (yych == 'o') goto yy417;
goto yy193;
yy399:
YYDEBUG(399, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy410;
if (yych == 'l') goto yy410;
goto yy193;
yy400:
YYDEBUG(400, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy401;
if (yych != 'n') goto yy193;
yy401:
YYDEBUG(401, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy402;
if (yych != 't') goto yy193;
yy402:
YYDEBUG(402, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy403;
if (yych != 'e') goto yy405;
yy403:
YYDEBUG(403, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'G') goto yy408;
if (yych == 'g') goto yy408;
goto yy193;
yy404:
YYDEBUG(404, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
yy405:
YYDEBUG(405, *YYCURSOR);
if (yych <= 0x1F) {
if (yych == '\t') goto yy404;
goto yy193;
} else {
if (yych <= ' ') goto yy404;
if (yych != ')') goto yy193;
}
YYDEBUG(406, *YYCURSOR);
++YYCURSOR;
YYDEBUG(407, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1216 "Zend/zend_language_scanner.l"
{
return T_INT_CAST;
}
#line 4820 "Zend/zend_language_scanner.c"
yy408:
YYDEBUG(408, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy409;
if (yych != 'e') goto yy193;
yy409:
YYDEBUG(409, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy404;
if (yych == 'r') goto yy404;
goto yy193;
yy410:
YYDEBUG(410, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy411;
if (yych != 'o') goto yy193;
yy411:
YYDEBUG(411, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy412;
if (yych != 'a') goto yy193;
yy412:
YYDEBUG(412, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy413;
if (yych != 't') goto yy193;
yy413:
YYDEBUG(413, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(414, *YYCURSOR);
if (yych <= 0x1F) {
if (yych == '\t') goto yy413;
goto yy193;
} else {
if (yych <= ' ') goto yy413;
if (yych != ')') goto yy193;
}
YYDEBUG(415, *YYCURSOR);
++YYCURSOR;
YYDEBUG(416, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1220 "Zend/zend_language_scanner.l"
{
return T_DOUBLE_CAST;
}
#line 4868 "Zend/zend_language_scanner.c"
yy417:
YYDEBUG(417, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'U') goto yy418;
if (yych != 'u') goto yy193;
yy418:
YYDEBUG(418, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'B') goto yy419;
if (yych != 'b') goto yy193;
yy419:
YYDEBUG(419, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy420;
if (yych != 'l') goto yy193;
yy420:
YYDEBUG(420, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy413;
if (yych == 'e') goto yy413;
goto yy193;
yy421:
YYDEBUG(421, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy422;
if (yych != 'a') goto yy193;
yy422:
YYDEBUG(422, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy413;
if (yych == 'l') goto yy413;
goto yy193;
yy423:
YYDEBUG(423, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy424;
if (yych != 'r') goto yy193;
yy424:
YYDEBUG(424, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy425;
if (yych != 'i') goto yy193;
yy425:
YYDEBUG(425, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy426;
if (yych != 'n') goto yy193;
yy426:
YYDEBUG(426, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'G') goto yy427;
if (yych != 'g') goto yy193;
yy427:
YYDEBUG(427, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(428, *YYCURSOR);
if (yych <= 0x1F) {
if (yych == '\t') goto yy427;
goto yy193;
} else {
if (yych <= ' ') goto yy427;
if (yych != ')') goto yy193;
}
YYDEBUG(429, *YYCURSOR);
++YYCURSOR;
YYDEBUG(430, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1224 "Zend/zend_language_scanner.l"
{
return T_STRING_CAST;
}
#line 4942 "Zend/zend_language_scanner.c"
yy431:
YYDEBUG(431, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy432;
if (yych != 'r') goto yy193;
yy432:
YYDEBUG(432, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy433;
if (yych != 'a') goto yy193;
yy433:
YYDEBUG(433, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'Y') goto yy434;
if (yych != 'y') goto yy193;
yy434:
YYDEBUG(434, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(435, *YYCURSOR);
if (yych <= 0x1F) {
if (yych == '\t') goto yy434;
goto yy193;
} else {
if (yych <= ' ') goto yy434;
if (yych != ')') goto yy193;
}
YYDEBUG(436, *YYCURSOR);
++YYCURSOR;
YYDEBUG(437, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1228 "Zend/zend_language_scanner.l"
{
return T_ARRAY_CAST;
}
#line 4979 "Zend/zend_language_scanner.c"
yy438:
YYDEBUG(438, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'J') goto yy439;
if (yych != 'j') goto yy193;
yy439:
YYDEBUG(439, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy440;
if (yych != 'e') goto yy193;
yy440:
YYDEBUG(440, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy441;
if (yych != 'c') goto yy193;
yy441:
YYDEBUG(441, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy442;
if (yych != 't') goto yy193;
yy442:
YYDEBUG(442, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(443, *YYCURSOR);
if (yych <= 0x1F) {
if (yych == '\t') goto yy442;
goto yy193;
} else {
if (yych <= ' ') goto yy442;
if (yych != ')') goto yy193;
}
YYDEBUG(444, *YYCURSOR);
++YYCURSOR;
YYDEBUG(445, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1232 "Zend/zend_language_scanner.l"
{
return T_OBJECT_CAST;
}
#line 5021 "Zend/zend_language_scanner.c"
yy446:
YYDEBUG(446, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy456;
if (yych == 'n') goto yy456;
goto yy193;
yy447:
YYDEBUG(447, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy448;
if (yych != 'o') goto yy193;
yy448:
YYDEBUG(448, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy449;
if (yych != 'l') goto yy193;
yy449:
YYDEBUG(449, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy454;
if (yych == 'e') goto yy454;
goto yy451;
yy450:
YYDEBUG(450, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
yy451:
YYDEBUG(451, *YYCURSOR);
if (yych <= 0x1F) {
if (yych == '\t') goto yy450;
goto yy193;
} else {
if (yych <= ' ') goto yy450;
if (yych != ')') goto yy193;
}
YYDEBUG(452, *YYCURSOR);
++YYCURSOR;
YYDEBUG(453, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1236 "Zend/zend_language_scanner.l"
{
return T_BOOL_CAST;
}
#line 5066 "Zend/zend_language_scanner.c"
yy454:
YYDEBUG(454, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy455;
if (yych != 'a') goto yy193;
yy455:
YYDEBUG(455, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy450;
if (yych == 'n') goto yy450;
goto yy193;
yy456:
YYDEBUG(456, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy457;
if (yych != 'a') goto yy193;
yy457:
YYDEBUG(457, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy458;
if (yych != 'r') goto yy193;
yy458:
YYDEBUG(458, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'Y') goto yy427;
if (yych == 'y') goto yy427;
goto yy193;
yy459:
YYDEBUG(459, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'S') goto yy460;
if (yych != 's') goto yy193;
yy460:
YYDEBUG(460, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy461;
if (yych != 'e') goto yy193;
yy461:
YYDEBUG(461, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy462;
if (yych != 't') goto yy193;
yy462:
YYDEBUG(462, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(463, *YYCURSOR);
if (yych <= 0x1F) {
if (yych == '\t') goto yy462;
goto yy193;
} else {
if (yych <= ' ') goto yy462;
if (yych != ')') goto yy193;
}
YYDEBUG(464, *YYCURSOR);
++YYCURSOR;
YYDEBUG(465, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1240 "Zend/zend_language_scanner.l"
{
return T_UNSET_CAST;
}
#line 5130 "Zend/zend_language_scanner.c"
yy466:
YYDEBUG(466, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy467;
if (yych != 'r') goto yy186;
yy467:
YYDEBUG(467, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(468, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1212 "Zend/zend_language_scanner.l"
{
return T_VAR;
}
#line 5148 "Zend/zend_language_scanner.c"
yy469:
YYDEBUG(469, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'M') goto yy473;
if (yych == 'm') goto yy473;
goto yy186;
yy470:
YYDEBUG(470, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'W') goto yy471;
if (yych != 'w') goto yy186;
yy471:
YYDEBUG(471, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(472, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1204 "Zend/zend_language_scanner.l"
{
return T_NEW;
}
#line 5172 "Zend/zend_language_scanner.c"
yy473:
YYDEBUG(473, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy474;
if (yych != 'e') goto yy186;
yy474:
YYDEBUG(474, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'S') goto yy475;
if (yych != 's') goto yy186;
yy475:
YYDEBUG(475, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'P') goto yy476;
if (yych != 'p') goto yy186;
yy476:
YYDEBUG(476, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy477;
if (yych != 'a') goto yy186;
yy477:
YYDEBUG(477, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy478;
if (yych != 'c') goto yy186;
yy478:
YYDEBUG(478, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy479;
if (yych != 'e') goto yy186;
yy479:
YYDEBUG(479, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(480, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1264 "Zend/zend_language_scanner.l"
{
return T_NAMESPACE;
}
#line 5215 "Zend/zend_language_scanner.c"
yy481:
YYDEBUG(481, *YYCURSOR);
++YYCURSOR;
YYDEBUG(482, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1196 "Zend/zend_language_scanner.l"
{
return T_PAAMAYIM_NEKUDOTAYIM;
}
#line 5225 "Zend/zend_language_scanner.c"
yy483:
YYDEBUG(483, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
yy484:
YYDEBUG(484, *YYCURSOR);
if (yych <= '\f') {
if (yych <= 0x08) goto yy140;
if (yych <= '\n') goto yy483;
goto yy140;
} else {
if (yych <= '\r') goto yy483;
if (yych == ' ') goto yy483;
goto yy140;
}
yy485:
YYDEBUG(485, *YYCURSOR);
++YYCURSOR;
YYDEBUG(486, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1372 "Zend/zend_language_scanner.l"
{
return T_MINUS_EQUAL;
}
#line 5251 "Zend/zend_language_scanner.c"
yy487:
YYDEBUG(487, *YYCURSOR);
++YYCURSOR;
YYDEBUG(488, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1340 "Zend/zend_language_scanner.l"
{
return T_DEC;
}
#line 5261 "Zend/zend_language_scanner.c"
yy489:
YYDEBUG(489, *YYCURSOR);
++YYCURSOR;
YYDEBUG(490, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1166 "Zend/zend_language_scanner.l"
{
yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC);
return T_OBJECT_OPERATOR;
}
#line 5272 "Zend/zend_language_scanner.c"
yy491:
YYDEBUG(491, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'O') {
if (yych == 'I') goto yy498;
if (yych <= 'N') goto yy186;
goto yy499;
} else {
if (yych <= 'i') {
if (yych <= 'h') goto yy186;
goto yy498;
} else {
if (yych == 'o') goto yy499;
goto yy186;
}
}
yy492:
YYDEBUG(492, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'B') goto yy493;
if (yych != 'b') goto yy186;
yy493:
YYDEBUG(493, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy494;
if (yych != 'l') goto yy186;
yy494:
YYDEBUG(494, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy495;
if (yych != 'i') goto yy186;
yy495:
YYDEBUG(495, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy496;
if (yych != 'c') goto yy186;
yy496:
YYDEBUG(496, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(497, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1312 "Zend/zend_language_scanner.l"
{
return T_PUBLIC;
}
#line 5321 "Zend/zend_language_scanner.c"
yy498:
YYDEBUG(498, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'V') {
if (yych == 'N') goto yy507;
if (yych <= 'U') goto yy186;
goto yy508;
} else {
if (yych <= 'n') {
if (yych <= 'm') goto yy186;
goto yy507;
} else {
if (yych == 'v') goto yy508;
goto yy186;
}
}
yy499:
YYDEBUG(499, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy500;
if (yych != 't') goto yy186;
yy500:
YYDEBUG(500, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy501;
if (yych != 'e') goto yy186;
yy501:
YYDEBUG(501, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy502;
if (yych != 'c') goto yy186;
yy502:
YYDEBUG(502, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy503;
if (yych != 't') goto yy186;
yy503:
YYDEBUG(503, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy504;
if (yych != 'e') goto yy186;
yy504:
YYDEBUG(504, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'D') goto yy505;
if (yych != 'd') goto yy186;
yy505:
YYDEBUG(505, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(506, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1308 "Zend/zend_language_scanner.l"
{
return T_PROTECTED;
}
#line 5380 "Zend/zend_language_scanner.c"
yy507:
YYDEBUG(507, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy513;
if (yych == 't') goto yy513;
goto yy186;
yy508:
YYDEBUG(508, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy509;
if (yych != 'a') goto yy186;
yy509:
YYDEBUG(509, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy510;
if (yych != 't') goto yy186;
yy510:
YYDEBUG(510, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy511;
if (yych != 'e') goto yy186;
yy511:
YYDEBUG(511, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(512, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1304 "Zend/zend_language_scanner.l"
{
return T_PRIVATE;
}
#line 5414 "Zend/zend_language_scanner.c"
yy513:
YYDEBUG(513, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(514, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1142 "Zend/zend_language_scanner.l"
{
return T_PRINT;
}
#line 5427 "Zend/zend_language_scanner.c"
yy515:
YYDEBUG(515, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy520;
if (yych == 'o') goto yy520;
goto yy186;
yy516:
YYDEBUG(516, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy517;
if (yych != 't') goto yy186;
yy517:
YYDEBUG(517, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy518;
if (yych != 'o') goto yy186;
yy518:
YYDEBUG(518, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(519, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1134 "Zend/zend_language_scanner.l"
{
return T_GOTO;
}
#line 5456 "Zend/zend_language_scanner.c"
yy520:
YYDEBUG(520, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'B') goto yy521;
if (yych != 'b') goto yy186;
yy521:
YYDEBUG(521, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy522;
if (yych != 'a') goto yy186;
yy522:
YYDEBUG(522, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy523;
if (yych != 'l') goto yy186;
yy523:
YYDEBUG(523, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(524, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1276 "Zend/zend_language_scanner.l"
{
return T_GLOBAL;
}
#line 5484 "Zend/zend_language_scanner.c"
yy525:
YYDEBUG(525, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '<') goto yy533;
goto yy193;
yy526:
YYDEBUG(526, *YYCURSOR);
yych = *++YYCURSOR;
goto yy180;
yy527:
YYDEBUG(527, *YYCURSOR);
yych = *++YYCURSOR;
goto yy178;
yy528:
YYDEBUG(528, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy529;
if (yych != 'e') goto yy186;
yy529:
YYDEBUG(529, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy530;
if (yych != 'a') goto yy186;
yy530:
YYDEBUG(530, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'K') goto yy531;
if (yych != 'k') goto yy186;
yy531:
YYDEBUG(531, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(532, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1126 "Zend/zend_language_scanner.l"
{
return T_BREAK;
}
#line 5525 "Zend/zend_language_scanner.c"
yy533:
YYDEBUG(533, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == '<') goto yy269;
goto yy193;
yy534:
YYDEBUG(534, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy541;
if (yych == 'a') goto yy541;
goto yy186;
yy535:
YYDEBUG(535, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy536;
if (yych != 'i') goto yy186;
yy536:
YYDEBUG(536, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy537;
if (yych != 't') goto yy186;
yy537:
YYDEBUG(537, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy538;
if (yych != 'c') goto yy186;
yy538:
YYDEBUG(538, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'H') goto yy539;
if (yych != 'h') goto yy186;
yy539:
YYDEBUG(539, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(540, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1110 "Zend/zend_language_scanner.l"
{
return T_SWITCH;
}
#line 5569 "Zend/zend_language_scanner.c"
yy541:
YYDEBUG(541, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy542;
if (yych != 't') goto yy186;
yy542:
YYDEBUG(542, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy543;
if (yych != 'i') goto yy186;
yy543:
YYDEBUG(543, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy544;
if (yych != 'c') goto yy186;
yy544:
YYDEBUG(544, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(545, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1292 "Zend/zend_language_scanner.l"
{
return T_STATIC;
}
#line 5597 "Zend/zend_language_scanner.c"
yy546:
YYDEBUG(546, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'S') goto yy557;
if (yych == 's') goto yy557;
goto yy186;
yy547:
YYDEBUG(547, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'D') goto yy555;
if (yych == 'd') goto yy555;
goto yy186;
yy548:
YYDEBUG(548, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy551;
if (yych == 'r') goto yy551;
goto yy186;
yy549:
YYDEBUG(549, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(550, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1106 "Zend/zend_language_scanner.l"
{
return T_AS;
}
#line 5628 "Zend/zend_language_scanner.c"
yy551:
YYDEBUG(551, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy552;
if (yych != 'a') goto yy186;
yy552:
YYDEBUG(552, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'Y') goto yy553;
if (yych != 'y') goto yy186;
yy553:
YYDEBUG(553, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(554, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1328 "Zend/zend_language_scanner.l"
{
return T_ARRAY;
}
#line 5651 "Zend/zend_language_scanner.c"
yy555:
YYDEBUG(555, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(556, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1424 "Zend/zend_language_scanner.l"
{
return T_LOGICAL_AND;
}
#line 5664 "Zend/zend_language_scanner.c"
yy557:
YYDEBUG(557, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy558;
if (yych != 't') goto yy186;
yy558:
YYDEBUG(558, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy559;
if (yych != 'r') goto yy186;
yy559:
YYDEBUG(559, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy560;
if (yych != 'a') goto yy186;
yy560:
YYDEBUG(560, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy561;
if (yych != 'c') goto yy186;
yy561:
YYDEBUG(561, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy562;
if (yych != 't') goto yy186;
yy562:
YYDEBUG(562, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(563, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1296 "Zend/zend_language_scanner.l"
{
return T_ABSTRACT;
}
#line 5702 "Zend/zend_language_scanner.c"
yy564:
YYDEBUG(564, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy565;
if (yych != 'i') goto yy186;
yy565:
YYDEBUG(565, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy566;
if (yych != 'l') goto yy186;
yy566:
YYDEBUG(566, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy567;
if (yych != 'e') goto yy186;
yy567:
YYDEBUG(567, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(568, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1066 "Zend/zend_language_scanner.l"
{
return T_WHILE;
}
#line 5730 "Zend/zend_language_scanner.c"
yy569:
YYDEBUG(569, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(570, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1050 "Zend/zend_language_scanner.l"
{
return T_IF;
}
#line 5743 "Zend/zend_language_scanner.c"
yy571:
YYDEBUG(571, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'P') goto yy613;
if (yych == 'p') goto yy613;
goto yy186;
yy572:
YYDEBUG(572, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'T') {
if (yych <= 'C') {
if (yych <= 'B') goto yy186;
goto yy580;
} else {
if (yych <= 'R') goto yy186;
if (yych <= 'S') goto yy578;
goto yy579;
}
} else {
if (yych <= 'r') {
if (yych == 'c') goto yy580;
goto yy186;
} else {
if (yych <= 's') goto yy578;
if (yych <= 't') goto yy579;
goto yy186;
}
}
yy573:
YYDEBUG(573, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'S') goto yy574;
if (yych != 's') goto yy186;
yy574:
YYDEBUG(574, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy575;
if (yych != 'e') goto yy186;
yy575:
YYDEBUG(575, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy576;
if (yych != 't') goto yy186;
yy576:
YYDEBUG(576, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(577, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1280 "Zend/zend_language_scanner.l"
{
return T_ISSET;
}
#line 5799 "Zend/zend_language_scanner.c"
yy578:
YYDEBUG(578, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy599;
if (yych == 't') goto yy599;
goto yy186;
yy579:
YYDEBUG(579, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy592;
if (yych == 'e') goto yy592;
goto yy186;
yy580:
YYDEBUG(580, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy581;
if (yych != 'l') goto yy186;
yy581:
YYDEBUG(581, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'U') goto yy582;
if (yych != 'u') goto yy186;
yy582:
YYDEBUG(582, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'D') goto yy583;
if (yych != 'd') goto yy186;
yy583:
YYDEBUG(583, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy584;
if (yych != 'e') goto yy186;
yy584:
YYDEBUG(584, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) <= '^') {
if (yych <= '9') {
if (yych >= '0') goto yy185;
} else {
if (yych <= '@') goto yy585;
if (yych <= 'Z') goto yy185;
}
} else {
if (yych <= '`') {
if (yych <= '_') goto yy586;
} else {
if (yych <= 'z') goto yy185;
if (yych >= 0x7F) goto yy185;
}
}
yy585:
YYDEBUG(585, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1248 "Zend/zend_language_scanner.l"
{
return T_INCLUDE;
}
#line 5857 "Zend/zend_language_scanner.c"
yy586:
YYDEBUG(586, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy587;
if (yych != 'o') goto yy186;
yy587:
YYDEBUG(587, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy588;
if (yych != 'n') goto yy186;
yy588:
YYDEBUG(588, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy589;
if (yych != 'c') goto yy186;
yy589:
YYDEBUG(589, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy590;
if (yych != 'e') goto yy186;
yy590:
YYDEBUG(590, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(591, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1252 "Zend/zend_language_scanner.l"
{
return T_INCLUDE_ONCE;
}
#line 5890 "Zend/zend_language_scanner.c"
yy592:
YYDEBUG(592, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy593;
if (yych != 'r') goto yy186;
yy593:
YYDEBUG(593, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'F') goto yy594;
if (yych != 'f') goto yy186;
yy594:
YYDEBUG(594, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy595;
if (yych != 'a') goto yy186;
yy595:
YYDEBUG(595, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy596;
if (yych != 'c') goto yy186;
yy596:
YYDEBUG(596, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy597;
if (yych != 'e') goto yy186;
yy597:
YYDEBUG(597, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(598, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1150 "Zend/zend_language_scanner.l"
{
return T_INTERFACE;
}
#line 5928 "Zend/zend_language_scanner.c"
yy599:
YYDEBUG(599, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'E') {
if (yych == 'A') goto yy600;
if (yych <= 'D') goto yy186;
goto yy601;
} else {
if (yych <= 'a') {
if (yych <= '`') goto yy186;
} else {
if (yych == 'e') goto yy601;
goto yy186;
}
}
yy600:
YYDEBUG(600, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy607;
if (yych == 'n') goto yy607;
goto yy186;
yy601:
YYDEBUG(601, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy602;
if (yych != 'a') goto yy186;
yy602:
YYDEBUG(602, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'D') goto yy603;
if (yych != 'd') goto yy186;
yy603:
YYDEBUG(603, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy604;
if (yych != 'o') goto yy186;
yy604:
YYDEBUG(604, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'F') goto yy605;
if (yych != 'f') goto yy186;
yy605:
YYDEBUG(605, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(606, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1272 "Zend/zend_language_scanner.l"
{
return T_INSTEADOF;
}
#line 5982 "Zend/zend_language_scanner.c"
yy607:
YYDEBUG(607, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy608;
if (yych != 'c') goto yy186;
yy608:
YYDEBUG(608, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy609;
if (yych != 'e') goto yy186;
yy609:
YYDEBUG(609, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy610;
if (yych != 'o') goto yy186;
yy610:
YYDEBUG(610, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'F') goto yy611;
if (yych != 'f') goto yy186;
yy611:
YYDEBUG(611, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(612, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1102 "Zend/zend_language_scanner.l"
{
return T_INSTANCEOF;
}
#line 6015 "Zend/zend_language_scanner.c"
yy613:
YYDEBUG(613, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy614;
if (yych != 'l') goto yy186;
yy614:
YYDEBUG(614, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy615;
if (yych != 'e') goto yy186;
yy615:
YYDEBUG(615, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'M') goto yy616;
if (yych != 'm') goto yy186;
yy616:
YYDEBUG(616, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy617;
if (yych != 'e') goto yy186;
yy617:
YYDEBUG(617, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy618;
if (yych != 'n') goto yy186;
yy618:
YYDEBUG(618, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy619;
if (yych != 't') goto yy186;
yy619:
YYDEBUG(619, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'S') goto yy620;
if (yych != 's') goto yy186;
yy620:
YYDEBUG(620, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(621, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1162 "Zend/zend_language_scanner.l"
{
return T_IMPLEMENTS;
}
#line 6063 "Zend/zend_language_scanner.c"
yy622:
YYDEBUG(622, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy630;
if (yych == 'r') goto yy630;
goto yy186;
yy623:
YYDEBUG(623, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'Y') {
if (yych == 'A') goto yy626;
if (yych <= 'X') goto yy186;
} else {
if (yych <= 'a') {
if (yych <= '`') goto yy186;
goto yy626;
} else {
if (yych != 'y') goto yy186;
}
}
YYDEBUG(624, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(625, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1038 "Zend/zend_language_scanner.l"
{
return T_TRY;
}
#line 6095 "Zend/zend_language_scanner.c"
yy626:
YYDEBUG(626, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy627;
if (yych != 'i') goto yy186;
yy627:
YYDEBUG(627, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy628;
if (yych != 't') goto yy186;
yy628:
YYDEBUG(628, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(629, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1154 "Zend/zend_language_scanner.l"
{
return T_TRAIT;
}
#line 6118 "Zend/zend_language_scanner.c"
yy630:
YYDEBUG(630, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy631;
if (yych != 'o') goto yy186;
yy631:
YYDEBUG(631, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'W') goto yy632;
if (yych != 'w') goto yy186;
yy632:
YYDEBUG(632, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(633, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1046 "Zend/zend_language_scanner.l"
{
return T_THROW;
}
#line 6141 "Zend/zend_language_scanner.c"
yy634:
YYDEBUG(634, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'T') {
if (yych == 'Q') goto yy636;
if (yych <= 'S') goto yy186;
} else {
if (yych <= 'q') {
if (yych <= 'p') goto yy186;
goto yy636;
} else {
if (yych != 't') goto yy186;
}
}
YYDEBUG(635, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'U') goto yy648;
if (yych == 'u') goto yy648;
goto yy186;
yy636:
YYDEBUG(636, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'U') goto yy637;
if (yych != 'u') goto yy186;
yy637:
YYDEBUG(637, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy638;
if (yych != 'i') goto yy186;
yy638:
YYDEBUG(638, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy639;
if (yych != 'r') goto yy186;
yy639:
YYDEBUG(639, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy640;
if (yych != 'e') goto yy186;
yy640:
YYDEBUG(640, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) <= '^') {
if (yych <= '9') {
if (yych >= '0') goto yy185;
} else {
if (yych <= '@') goto yy641;
if (yych <= 'Z') goto yy185;
}
} else {
if (yych <= '`') {
if (yych <= '_') goto yy642;
} else {
if (yych <= 'z') goto yy185;
if (yych >= 0x7F) goto yy185;
}
}
yy641:
YYDEBUG(641, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1256 "Zend/zend_language_scanner.l"
{
return T_REQUIRE;
}
#line 6206 "Zend/zend_language_scanner.c"
yy642:
YYDEBUG(642, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy643;
if (yych != 'o') goto yy186;
yy643:
YYDEBUG(643, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy644;
if (yych != 'n') goto yy186;
yy644:
YYDEBUG(644, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy645;
if (yych != 'c') goto yy186;
yy645:
YYDEBUG(645, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy646;
if (yych != 'e') goto yy186;
yy646:
YYDEBUG(646, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(647, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1260 "Zend/zend_language_scanner.l"
{
return T_REQUIRE_ONCE;
}
#line 6239 "Zend/zend_language_scanner.c"
yy648:
YYDEBUG(648, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy649;
if (yych != 'r') goto yy186;
yy649:
YYDEBUG(649, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy650;
if (yych != 'n') goto yy186;
yy650:
YYDEBUG(650, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(651, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1034 "Zend/zend_language_scanner.l"
{
return T_RETURN;
}
#line 6262 "Zend/zend_language_scanner.c"
yy652:
YYDEBUG(652, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'T') {
if (yych <= 'L') {
if (yych <= 'K') goto yy186;
goto yy675;
} else {
if (yych <= 'R') goto yy186;
if (yych <= 'S') goto yy674;
goto yy673;
}
} else {
if (yych <= 'r') {
if (yych == 'l') goto yy675;
goto yy186;
} else {
if (yych <= 's') goto yy674;
if (yych <= 't') goto yy673;
goto yy186;
}
}
yy653:
YYDEBUG(653, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'O') {
if (yych == 'A') goto yy665;
if (yych <= 'N') goto yy186;
goto yy666;
} else {
if (yych <= 'a') {
if (yych <= '`') goto yy186;
goto yy665;
} else {
if (yych == 'o') goto yy666;
goto yy186;
}
}
yy654:
YYDEBUG(654, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy655;
if (yych != 'n') goto yy186;
yy655:
YYDEBUG(655, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'T') {
if (yych <= 'R') goto yy186;
if (yych >= 'T') goto yy657;
} else {
if (yych <= 'r') goto yy186;
if (yych <= 's') goto yy656;
if (yych <= 't') goto yy657;
goto yy186;
}
yy656:
YYDEBUG(656, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy663;
if (yych == 't') goto yy663;
goto yy186;
yy657:
YYDEBUG(657, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy658;
if (yych != 'i') goto yy186;
yy658:
YYDEBUG(658, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy659;
if (yych != 'n') goto yy186;
yy659:
YYDEBUG(659, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'U') goto yy660;
if (yych != 'u') goto yy186;
yy660:
YYDEBUG(660, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy661;
if (yych != 'e') goto yy186;
yy661:
YYDEBUG(661, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(662, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1130 "Zend/zend_language_scanner.l"
{
return T_CONTINUE;
}
#line 6356 "Zend/zend_language_scanner.c"
yy663:
YYDEBUG(663, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(664, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1030 "Zend/zend_language_scanner.l"
{
return T_CONST;
}
#line 6369 "Zend/zend_language_scanner.c"
yy665:
YYDEBUG(665, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'S') goto yy670;
if (yych == 's') goto yy670;
goto yy186;
yy666:
YYDEBUG(666, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy667;
if (yych != 'n') goto yy186;
yy667:
YYDEBUG(667, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy668;
if (yych != 'e') goto yy186;
yy668:
YYDEBUG(668, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(669, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1208 "Zend/zend_language_scanner.l"
{
return T_CLONE;
}
#line 6398 "Zend/zend_language_scanner.c"
yy670:
YYDEBUG(670, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'S') goto yy671;
if (yych != 's') goto yy186;
yy671:
YYDEBUG(671, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(672, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1146 "Zend/zend_language_scanner.l"
{
return T_CLASS;
}
#line 6416 "Zend/zend_language_scanner.c"
yy673:
YYDEBUG(673, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy684;
if (yych == 'c') goto yy684;
goto yy186;
yy674:
YYDEBUG(674, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy682;
if (yych == 'e') goto yy682;
goto yy186;
yy675:
YYDEBUG(675, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy676;
if (yych != 'l') goto yy186;
yy676:
YYDEBUG(676, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy677;
if (yych != 'a') goto yy186;
yy677:
YYDEBUG(677, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'B') goto yy678;
if (yych != 'b') goto yy186;
yy678:
YYDEBUG(678, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy679;
if (yych != 'l') goto yy186;
yy679:
YYDEBUG(679, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy680;
if (yych != 'e') goto yy186;
yy680:
YYDEBUG(680, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(681, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1332 "Zend/zend_language_scanner.l"
{
return T_CALLABLE;
}
#line 6466 "Zend/zend_language_scanner.c"
yy682:
YYDEBUG(682, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(683, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1118 "Zend/zend_language_scanner.l"
{
return T_CASE;
}
#line 6479 "Zend/zend_language_scanner.c"
yy684:
YYDEBUG(684, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'H') goto yy685;
if (yych != 'h') goto yy186;
yy685:
YYDEBUG(685, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(686, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1042 "Zend/zend_language_scanner.l"
{
return T_CATCH;
}
#line 6497 "Zend/zend_language_scanner.c"
yy687:
YYDEBUG(687, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy704;
if (yych == 'n') goto yy704;
goto yy186;
yy688:
YYDEBUG(688, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy697;
if (yych == 'r') goto yy697;
goto yy186;
yy689:
YYDEBUG(689, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy690;
if (yych != 'n') goto yy186;
yy690:
YYDEBUG(690, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy691;
if (yych != 'c') goto yy186;
yy691:
YYDEBUG(691, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy692;
if (yych != 't') goto yy186;
yy692:
YYDEBUG(692, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy693;
if (yych != 'i') goto yy186;
yy693:
YYDEBUG(693, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy694;
if (yych != 'o') goto yy186;
yy694:
YYDEBUG(694, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy695;
if (yych != 'n') goto yy186;
yy695:
YYDEBUG(695, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(696, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1026 "Zend/zend_language_scanner.l"
{
return T_FUNCTION;
}
#line 6552 "Zend/zend_language_scanner.c"
yy697:
YYDEBUG(697, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) <= '^') {
if (yych <= '@') {
if (yych <= '/') goto yy698;
if (yych <= '9') goto yy185;
} else {
if (yych == 'E') goto yy699;
if (yych <= 'Z') goto yy185;
}
} else {
if (yych <= 'd') {
if (yych != '`') goto yy185;
} else {
if (yych <= 'e') goto yy699;
if (yych <= 'z') goto yy185;
if (yych >= 0x7F) goto yy185;
}
}
yy698:
YYDEBUG(698, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1078 "Zend/zend_language_scanner.l"
{
return T_FOR;
}
#line 6580 "Zend/zend_language_scanner.c"
yy699:
YYDEBUG(699, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy700;
if (yych != 'a') goto yy186;
yy700:
YYDEBUG(700, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy701;
if (yych != 'c') goto yy186;
yy701:
YYDEBUG(701, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'H') goto yy702;
if (yych != 'h') goto yy186;
yy702:
YYDEBUG(702, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(703, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1086 "Zend/zend_language_scanner.l"
{
return T_FOREACH;
}
#line 6608 "Zend/zend_language_scanner.c"
yy704:
YYDEBUG(704, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy705;
if (yych != 'a') goto yy186;
yy705:
YYDEBUG(705, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy706;
if (yych != 'l') goto yy186;
yy706:
YYDEBUG(706, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(707, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1300 "Zend/zend_language_scanner.l"
{
return T_FINAL;
}
#line 6631 "Zend/zend_language_scanner.c"
yy708:
YYDEBUG(708, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'F') {
if (yych == 'C') goto yy714;
if (yych <= 'E') goto yy186;
goto yy715;
} else {
if (yych <= 'c') {
if (yych <= 'b') goto yy186;
goto yy714;
} else {
if (yych == 'f') goto yy715;
goto yy186;
}
}
yy709:
YYDEBUG(709, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy712;
if (yych == 'e') goto yy712;
goto yy186;
yy710:
YYDEBUG(710, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(711, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1074 "Zend/zend_language_scanner.l"
{
return T_DO;
}
#line 6666 "Zend/zend_language_scanner.c"
yy712:
YYDEBUG(712, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(713, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1022 "Zend/zend_language_scanner.l"
{
return T_EXIT;
}
#line 6679 "Zend/zend_language_scanner.c"
yy714:
YYDEBUG(714, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy721;
if (yych == 'l') goto yy721;
goto yy186;
yy715:
YYDEBUG(715, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy716;
if (yych != 'a') goto yy186;
yy716:
YYDEBUG(716, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'U') goto yy717;
if (yych != 'u') goto yy186;
yy717:
YYDEBUG(717, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy718;
if (yych != 'l') goto yy186;
yy718:
YYDEBUG(718, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy719;
if (yych != 't') goto yy186;
yy719:
YYDEBUG(719, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(720, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1122 "Zend/zend_language_scanner.l"
{
return T_DEFAULT;
}
#line 6718 "Zend/zend_language_scanner.c"
yy721:
YYDEBUG(721, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy722;
if (yych != 'a') goto yy186;
yy722:
YYDEBUG(722, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy723;
if (yych != 'r') goto yy186;
yy723:
YYDEBUG(723, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy724;
if (yych != 'e') goto yy186;
yy724:
YYDEBUG(724, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(725, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1094 "Zend/zend_language_scanner.l"
{
return T_DECLARE;
}
#line 6746 "Zend/zend_language_scanner.c"
yy726:
YYDEBUG(726, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'H') goto yy788;
if (yych == 'h') goto yy788;
goto yy186;
yy727:
YYDEBUG(727, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'S') goto yy782;
if (yych == 's') goto yy782;
goto yy186;
yy728:
YYDEBUG(728, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'P') goto yy778;
if (yych == 'p') goto yy778;
goto yy186;
yy729:
YYDEBUG(729, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'D') goto yy744;
if (yych == 'd') goto yy744;
goto yy186;
yy730:
YYDEBUG(730, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy741;
if (yych == 'a') goto yy741;
goto yy186;
yy731:
YYDEBUG(731, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'T') {
if (yych == 'I') goto yy732;
if (yych <= 'S') goto yy186;
goto yy733;
} else {
if (yych <= 'i') {
if (yych <= 'h') goto yy186;
} else {
if (yych == 't') goto yy733;
goto yy186;
}
}
yy732:
YYDEBUG(732, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy739;
if (yych == 't') goto yy739;
goto yy186;
yy733:
YYDEBUG(733, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy734;
if (yych != 'e') goto yy186;
yy734:
YYDEBUG(734, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'N') goto yy735;
if (yych != 'n') goto yy186;
yy735:
YYDEBUG(735, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'D') goto yy736;
if (yych != 'd') goto yy186;
yy736:
YYDEBUG(736, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'S') goto yy737;
if (yych != 's') goto yy186;
yy737:
YYDEBUG(737, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(738, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1158 "Zend/zend_language_scanner.l"
{
return T_EXTENDS;
}
#line 6830 "Zend/zend_language_scanner.c"
yy739:
YYDEBUG(739, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(740, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1018 "Zend/zend_language_scanner.l"
{
return T_EXIT;
}
#line 6843 "Zend/zend_language_scanner.c"
yy741:
YYDEBUG(741, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy742;
if (yych != 'l') goto yy186;
yy742:
YYDEBUG(742, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(743, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1244 "Zend/zend_language_scanner.l"
{
return T_EVAL;
}
#line 6861 "Zend/zend_language_scanner.c"
yy744:
YYDEBUG(744, *YYCURSOR);
yych = *++YYCURSOR;
YYDEBUG(-1, yych);
switch (yych) {
case 'D':
case 'd': goto yy745;
case 'F':
case 'f': goto yy746;
case 'I':
case 'i': goto yy747;
case 'S':
case 's': goto yy748;
case 'W':
case 'w': goto yy749;
default: goto yy186;
}
yy745:
YYDEBUG(745, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy771;
if (yych == 'e') goto yy771;
goto yy186;
yy746:
YYDEBUG(746, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy763;
if (yych == 'o') goto yy763;
goto yy186;
yy747:
YYDEBUG(747, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'F') goto yy761;
if (yych == 'f') goto yy761;
goto yy186;
yy748:
YYDEBUG(748, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'W') goto yy755;
if (yych == 'w') goto yy755;
goto yy186;
yy749:
YYDEBUG(749, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'H') goto yy750;
if (yych != 'h') goto yy186;
yy750:
YYDEBUG(750, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy751;
if (yych != 'i') goto yy186;
yy751:
YYDEBUG(751, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy752;
if (yych != 'l') goto yy186;
yy752:
YYDEBUG(752, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy753;
if (yych != 'e') goto yy186;
yy753:
YYDEBUG(753, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(754, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1070 "Zend/zend_language_scanner.l"
{
return T_ENDWHILE;
}
#line 6935 "Zend/zend_language_scanner.c"
yy755:
YYDEBUG(755, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'I') goto yy756;
if (yych != 'i') goto yy186;
yy756:
YYDEBUG(756, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy757;
if (yych != 't') goto yy186;
yy757:
YYDEBUG(757, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy758;
if (yych != 'c') goto yy186;
yy758:
YYDEBUG(758, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'H') goto yy759;
if (yych != 'h') goto yy186;
yy759:
YYDEBUG(759, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(760, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1114 "Zend/zend_language_scanner.l"
{
return T_ENDSWITCH;
}
#line 6968 "Zend/zend_language_scanner.c"
yy761:
YYDEBUG(761, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(762, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1058 "Zend/zend_language_scanner.l"
{
return T_ENDIF;
}
#line 6981 "Zend/zend_language_scanner.c"
yy763:
YYDEBUG(763, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy764;
if (yych != 'r') goto yy186;
yy764:
YYDEBUG(764, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) <= '^') {
if (yych <= '@') {
if (yych <= '/') goto yy765;
if (yych <= '9') goto yy185;
} else {
if (yych == 'E') goto yy766;
if (yych <= 'Z') goto yy185;
}
} else {
if (yych <= 'd') {
if (yych != '`') goto yy185;
} else {
if (yych <= 'e') goto yy766;
if (yych <= 'z') goto yy185;
if (yych >= 0x7F) goto yy185;
}
}
yy765:
YYDEBUG(765, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1082 "Zend/zend_language_scanner.l"
{
return T_ENDFOR;
}
#line 7014 "Zend/zend_language_scanner.c"
yy766:
YYDEBUG(766, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy767;
if (yych != 'a') goto yy186;
yy767:
YYDEBUG(767, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy768;
if (yych != 'c') goto yy186;
yy768:
YYDEBUG(768, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'H') goto yy769;
if (yych != 'h') goto yy186;
yy769:
YYDEBUG(769, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(770, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1090 "Zend/zend_language_scanner.l"
{
return T_ENDFOREACH;
}
#line 7042 "Zend/zend_language_scanner.c"
yy771:
YYDEBUG(771, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'C') goto yy772;
if (yych != 'c') goto yy186;
yy772:
YYDEBUG(772, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'L') goto yy773;
if (yych != 'l') goto yy186;
yy773:
YYDEBUG(773, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'A') goto yy774;
if (yych != 'a') goto yy186;
yy774:
YYDEBUG(774, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'R') goto yy775;
if (yych != 'r') goto yy186;
yy775:
YYDEBUG(775, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy776;
if (yych != 'e') goto yy186;
yy776:
YYDEBUG(776, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(777, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1098 "Zend/zend_language_scanner.l"
{
return T_ENDDECLARE;
}
#line 7080 "Zend/zend_language_scanner.c"
yy778:
YYDEBUG(778, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy779;
if (yych != 't') goto yy186;
yy779:
YYDEBUG(779, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'Y') goto yy780;
if (yych != 'y') goto yy186;
yy780:
YYDEBUG(780, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(781, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1284 "Zend/zend_language_scanner.l"
{
return T_EMPTY;
}
#line 7103 "Zend/zend_language_scanner.c"
yy782:
YYDEBUG(782, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'E') goto yy783;
if (yych != 'e') goto yy186;
yy783:
YYDEBUG(783, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) <= '^') {
if (yych <= '@') {
if (yych <= '/') goto yy784;
if (yych <= '9') goto yy185;
} else {
if (yych == 'I') goto yy785;
if (yych <= 'Z') goto yy185;
}
} else {
if (yych <= 'h') {
if (yych != '`') goto yy185;
} else {
if (yych <= 'i') goto yy785;
if (yych <= 'z') goto yy185;
if (yych >= 0x7F) goto yy185;
}
}
yy784:
YYDEBUG(784, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1062 "Zend/zend_language_scanner.l"
{
return T_ELSE;
}
#line 7136 "Zend/zend_language_scanner.c"
yy785:
YYDEBUG(785, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'F') goto yy786;
if (yych != 'f') goto yy186;
yy786:
YYDEBUG(786, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(787, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1054 "Zend/zend_language_scanner.l"
{
return T_ELSEIF;
}
#line 7154 "Zend/zend_language_scanner.c"
yy788:
YYDEBUG(788, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'O') goto yy789;
if (yych != 'o') goto yy186;
yy789:
YYDEBUG(789, *YYCURSOR);
++YYCURSOR;
if (yybm[0+(yych = *YYCURSOR)] & 4) {
goto yy185;
}
YYDEBUG(790, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1138 "Zend/zend_language_scanner.l"
{
return T_ECHO;
}
#line 7172 "Zend/zend_language_scanner.c"
}
/* *********************************** */
yyc_ST_LOOKING_FOR_PROPERTY:
{
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 128, 128, 0, 0, 128, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 0, 0, 0, 0, 0, 0,
0, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 0, 0, 0, 0, 64,
0, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 0, 0, 0, 0, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64,
};
YYDEBUG(791, *YYCURSOR);
YYFILL(2);
yych = *YYCURSOR;
if (yych <= '-') {
if (yych <= '\r') {
if (yych <= 0x08) goto yy799;
if (yych <= '\n') goto yy793;
if (yych <= '\f') goto yy799;
} else {
if (yych == ' ') goto yy793;
if (yych <= ',') goto yy799;
goto yy795;
}
} else {
if (yych <= '_') {
if (yych <= '@') goto yy799;
if (yych <= 'Z') goto yy797;
if (yych <= '^') goto yy799;
goto yy797;
} else {
if (yych <= '`') goto yy799;
if (yych <= 'z') goto yy797;
if (yych <= '~') goto yy799;
goto yy797;
}
}
yy793:
YYDEBUG(793, *YYCURSOR);
++YYCURSOR;
yych = *YYCURSOR;
goto yy805;
yy794:
YYDEBUG(794, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1171 "Zend/zend_language_scanner.l"
{
zendlval->value.str.val = yytext; /* no copying - intentional */
zendlval->value.str.len = yyleng;
zendlval->type = IS_STRING;
HANDLE_NEWLINES(yytext, yyleng);
return T_WHITESPACE;
}
#line 7253 "Zend/zend_language_scanner.c"
yy795:
YYDEBUG(795, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) == '>') goto yy802;
yy796:
YYDEBUG(796, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1190 "Zend/zend_language_scanner.l"
{
yyless(0);
yy_pop_state(TSRMLS_C);
goto restart;
}
#line 7267 "Zend/zend_language_scanner.c"
yy797:
YYDEBUG(797, *YYCURSOR);
++YYCURSOR;
yych = *YYCURSOR;
goto yy801;
yy798:
YYDEBUG(798, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1183 "Zend/zend_language_scanner.l"
{
yy_pop_state(TSRMLS_C);
zend_copy_value(zendlval, yytext, yyleng);
zendlval->type = IS_STRING;
return T_STRING;
}
#line 7283 "Zend/zend_language_scanner.c"
yy799:
YYDEBUG(799, *YYCURSOR);
yych = *++YYCURSOR;
goto yy796;
yy800:
YYDEBUG(800, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
yy801:
YYDEBUG(801, *YYCURSOR);
if (yybm[0+yych] & 64) {
goto yy800;
}
goto yy798;
yy802:
YYDEBUG(802, *YYCURSOR);
++YYCURSOR;
YYDEBUG(803, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1179 "Zend/zend_language_scanner.l"
{
return T_OBJECT_OPERATOR;
}
#line 7308 "Zend/zend_language_scanner.c"
yy804:
YYDEBUG(804, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
yy805:
YYDEBUG(805, *YYCURSOR);
if (yybm[0+yych] & 128) {
goto yy804;
}
goto yy794;
}
/* *********************************** */
yyc_ST_LOOKING_FOR_VARNAME:
{
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 0, 0, 0, 0, 0, 0,
0, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 0, 0, 0, 0, 128,
0, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 0, 0, 0, 0, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128,
};
YYDEBUG(806, *YYCURSOR);
YYFILL(2);
yych = *YYCURSOR;
if (yych <= '_') {
if (yych <= '@') goto yy810;
if (yych <= 'Z') goto yy808;
if (yych <= '^') goto yy810;
} else {
if (yych <= '`') goto yy810;
if (yych <= 'z') goto yy808;
if (yych <= '~') goto yy810;
}
yy808:
YYDEBUG(808, *YYCURSOR);
++YYCURSOR;
yych = *YYCURSOR;
goto yy813;
yy809:
YYDEBUG(809, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1466 "Zend/zend_language_scanner.l"
{
zend_copy_value(zendlval, yytext, yyleng);
zendlval->type = IS_STRING;
yy_pop_state(TSRMLS_C);
yy_push_state(ST_IN_SCRIPTING TSRMLS_CC);
return T_STRING_VARNAME;
}
#line 7386 "Zend/zend_language_scanner.c"
yy810:
YYDEBUG(810, *YYCURSOR);
++YYCURSOR;
YYDEBUG(811, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1475 "Zend/zend_language_scanner.l"
{
yyless(0);
yy_pop_state(TSRMLS_C);
yy_push_state(ST_IN_SCRIPTING TSRMLS_CC);
goto restart;
}
#line 7399 "Zend/zend_language_scanner.c"
yy812:
YYDEBUG(812, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
yy813:
YYDEBUG(813, *YYCURSOR);
if (yybm[0+yych] & 128) {
goto yy812;
}
goto yy809;
}
/* *********************************** */
yyc_ST_NOWDOC:
YYDEBUG(814, *YYCURSOR);
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(816, *YYCURSOR);
++YYCURSOR;
YYDEBUG(817, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 2357 "Zend/zend_language_scanner.l"
{
int newline = 0;
if (YYCURSOR > YYLIMIT) {
return 0;
}
YYCURSOR--;
while (YYCURSOR < YYLIMIT) {
switch (*YYCURSOR++) {
case '\r':
if (*YYCURSOR == '\n') {
YYCURSOR++;
}
/* fall through */
case '\n':
/* Check for ending label on the next line */
if (IS_LABEL_START(*YYCURSOR) && CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, CG(heredoc), CG(heredoc_len))) {
YYCTYPE *end = YYCURSOR + CG(heredoc_len);
if (*end == ';') {
end++;
}
if (*end == '\n' || *end == '\r') {
/* newline before label will be subtracted from returned text, but
* yyleng/yytext will include it, for zend_highlight/strip, tokenizer, etc. */
if (YYCURSOR[-2] == '\r' && YYCURSOR[-1] == '\n') {
newline = 2; /* Windows newline */
} else {
newline = 1;
}
CG(increment_lineno) = 1; /* For newline before label */
BEGIN(ST_END_HEREDOC);
goto nowdoc_scan_done;
}
}
/* fall through */
default:
continue;
}
}
nowdoc_scan_done:
yyleng = YYCURSOR - SCNG(yy_text);
zend_copy_value(zendlval, yytext, yyleng - newline);
zendlval->type = IS_STRING;
HANDLE_NEWLINES(yytext, yyleng - newline);
return T_ENCAPSED_AND_WHITESPACE;
}
#line 7476 "Zend/zend_language_scanner.c"
/* *********************************** */
yyc_ST_VAR_OFFSET:
{
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
240, 240, 112, 112, 112, 112, 112, 112,
112, 112, 0, 0, 0, 0, 0, 0,
0, 80, 80, 80, 80, 80, 80, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 0, 0, 0, 0, 16,
0, 80, 80, 80, 80, 80, 80, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 0, 0, 0, 0, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
};
YYDEBUG(818, *YYCURSOR);
YYFILL(3);
yych = *YYCURSOR;
if (yych <= '/') {
if (yych <= ' ') {
if (yych <= '\f') {
if (yych <= 0x08) goto yy832;
if (yych <= '\n') goto yy828;
goto yy832;
} else {
if (yych <= '\r') goto yy828;
if (yych <= 0x1F) goto yy832;
goto yy828;
}
} else {
if (yych <= '$') {
if (yych <= '"') goto yy827;
if (yych <= '#') goto yy828;
goto yy823;
} else {
if (yych == '\'') goto yy828;
goto yy827;
}
}
} else {
if (yych <= '\\') {
if (yych <= '@') {
if (yych <= '0') goto yy820;
if (yych <= '9') goto yy822;
goto yy827;
} else {
if (yych <= 'Z') goto yy830;
if (yych <= '[') goto yy827;
goto yy828;
}
} else {
if (yych <= '_') {
if (yych <= ']') goto yy825;
if (yych <= '^') goto yy827;
goto yy830;
} else {
if (yych <= '`') goto yy827;
if (yych <= 'z') goto yy830;
if (yych <= '~') goto yy827;
goto yy830;
}
}
}
yy820:
YYDEBUG(820, *YYCURSOR);
yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= 'W') {
if (yych <= '9') {
if (yych >= '0') goto yy844;
} else {
if (yych == 'B') goto yy841;
}
} else {
if (yych <= 'b') {
if (yych <= 'X') goto yy843;
if (yych >= 'b') goto yy841;
} else {
if (yych == 'x') goto yy843;
}
}
yy821:
YYDEBUG(821, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1553 "Zend/zend_language_scanner.l"
{ /* Offset could be treated as a long */
if (yyleng < MAX_LENGTH_OF_LONG - 1 || (yyleng == MAX_LENGTH_OF_LONG - 1 && strcmp(yytext, long_min_digits) < 0)) {
zendlval->value.lval = strtol(yytext, NULL, 10);
zendlval->type = IS_LONG;
} else {
zendlval->value.str.val = (char *)estrndup(yytext, yyleng);
zendlval->value.str.len = yyleng;
zendlval->type = IS_STRING;
}
return T_NUM_STRING;
}
#line 7595 "Zend/zend_language_scanner.c"
yy822:
YYDEBUG(822, *YYCURSOR);
yych = *++YYCURSOR;
goto yy840;
yy823:
YYDEBUG(823, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) <= '_') {
if (yych <= '@') goto yy824;
if (yych <= 'Z') goto yy836;
if (yych >= '_') goto yy836;
} else {
if (yych <= '`') goto yy824;
if (yych <= 'z') goto yy836;
if (yych >= 0x7F) goto yy836;
}
yy824:
YYDEBUG(824, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1885 "Zend/zend_language_scanner.l"
{
/* Only '[' can be valid, but returning other tokens will allow a more explicit parse error */
return yytext[0];
}
#line 7620 "Zend/zend_language_scanner.c"
yy825:
YYDEBUG(825, *YYCURSOR);
++YYCURSOR;
YYDEBUG(826, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1880 "Zend/zend_language_scanner.l"
{
yy_pop_state(TSRMLS_C);
return ']';
}
#line 7631 "Zend/zend_language_scanner.c"
yy827:
YYDEBUG(827, *YYCURSOR);
yych = *++YYCURSOR;
goto yy824;
yy828:
YYDEBUG(828, *YYCURSOR);
++YYCURSOR;
YYDEBUG(829, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1890 "Zend/zend_language_scanner.l"
{
/* Invalid rule to return a more explicit parse error with proper line number */
yyless(0);
yy_pop_state(TSRMLS_C);
return T_ENCAPSED_AND_WHITESPACE;
}
#line 7648 "Zend/zend_language_scanner.c"
yy830:
YYDEBUG(830, *YYCURSOR);
++YYCURSOR;
yych = *YYCURSOR;
goto yy835;
yy831:
YYDEBUG(831, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1897 "Zend/zend_language_scanner.l"
{
zend_copy_value(zendlval, yytext, yyleng);
zendlval->type = IS_STRING;
return T_STRING;
}
#line 7663 "Zend/zend_language_scanner.c"
yy832:
YYDEBUG(832, *YYCURSOR);
++YYCURSOR;
YYDEBUG(833, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 2413 "Zend/zend_language_scanner.l"
{
if (YYCURSOR > YYLIMIT) {
return 0;
}
zend_error(E_COMPILE_WARNING,"Unexpected character in input: '%c' (ASCII=%d) state=%d", yytext[0], yytext[0], YYSTATE);
goto restart;
}
#line 7678 "Zend/zend_language_scanner.c"
yy834:
YYDEBUG(834, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
yy835:
YYDEBUG(835, *YYCURSOR);
if (yybm[0+yych] & 16) {
goto yy834;
}
goto yy831;
yy836:
YYDEBUG(836, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(837, *YYCURSOR);
if (yych <= '^') {
if (yych <= '9') {
if (yych >= '0') goto yy836;
} else {
if (yych <= '@') goto yy838;
if (yych <= 'Z') goto yy836;
}
} else {
if (yych <= '`') {
if (yych <= '_') goto yy836;
} else {
if (yych <= 'z') goto yy836;
if (yych >= 0x7F) goto yy836;
}
}
yy838:
YYDEBUG(838, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1874 "Zend/zend_language_scanner.l"
{
zend_copy_value(zendlval, (yytext+1), (yyleng-1));
zendlval->type = IS_STRING;
return T_VARIABLE;
}
#line 7720 "Zend/zend_language_scanner.c"
yy839:
YYDEBUG(839, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
yy840:
YYDEBUG(840, *YYCURSOR);
if (yybm[0+yych] & 32) {
goto yy839;
}
goto yy821;
yy841:
YYDEBUG(841, *YYCURSOR);
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy849;
}
yy842:
YYDEBUG(842, *YYCURSOR);
YYCURSOR = YYMARKER;
goto yy821;
yy843:
YYDEBUG(843, *YYCURSOR);
yych = *++YYCURSOR;
if (yybm[0+yych] & 64) {
goto yy847;
}
goto yy842;
yy844:
YYDEBUG(844, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(845, *YYCURSOR);
if (yych <= '/') goto yy846;
if (yych <= '9') goto yy844;
yy846:
YYDEBUG(846, *YYCURSOR);
yyleng = YYCURSOR - SCNG(yy_text);
#line 1565 "Zend/zend_language_scanner.l"
{ /* Offset must be treated as a string */
zendlval->value.str.val = (char *)estrndup(yytext, yyleng);
zendlval->value.str.len = yyleng;
zendlval->type = IS_STRING;
return T_NUM_STRING;
}
#line 7767 "Zend/zend_language_scanner.c"
yy847:
YYDEBUG(847, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(848, *YYCURSOR);
if (yybm[0+yych] & 64) {
goto yy847;
}
goto yy846;
yy849:
YYDEBUG(849, *YYCURSOR);
++YYCURSOR;
YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(850, *YYCURSOR);
if (yybm[0+yych] & 128) {
goto yy849;
}
goto yy846;
}
}
#line 2422 "Zend/zend_language_scanner.l"
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5711_2 |
crossvul-cpp_data_bad_4965_0 | /*
* ALSA timer back-end using hrtimer
* Copyright (C) 2008 Takashi Iwai
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/hrtimer.h>
#include <sound/core.h>
#include <sound/timer.h>
MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>");
MODULE_DESCRIPTION("ALSA hrtimer backend");
MODULE_LICENSE("GPL");
MODULE_ALIAS("snd-timer-" __stringify(SNDRV_TIMER_GLOBAL_HRTIMER));
#define NANO_SEC 1000000000UL /* 10^9 in sec */
static unsigned int resolution;
struct snd_hrtimer {
struct snd_timer *timer;
struct hrtimer hrt;
atomic_t running;
};
static enum hrtimer_restart snd_hrtimer_callback(struct hrtimer *hrt)
{
struct snd_hrtimer *stime = container_of(hrt, struct snd_hrtimer, hrt);
struct snd_timer *t = stime->timer;
unsigned long oruns;
if (!atomic_read(&stime->running))
return HRTIMER_NORESTART;
oruns = hrtimer_forward_now(hrt, ns_to_ktime(t->sticks * resolution));
snd_timer_interrupt(stime->timer, t->sticks * oruns);
if (!atomic_read(&stime->running))
return HRTIMER_NORESTART;
return HRTIMER_RESTART;
}
static int snd_hrtimer_open(struct snd_timer *t)
{
struct snd_hrtimer *stime;
stime = kmalloc(sizeof(*stime), GFP_KERNEL);
if (!stime)
return -ENOMEM;
hrtimer_init(&stime->hrt, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
stime->timer = t;
stime->hrt.function = snd_hrtimer_callback;
atomic_set(&stime->running, 0);
t->private_data = stime;
return 0;
}
static int snd_hrtimer_close(struct snd_timer *t)
{
struct snd_hrtimer *stime = t->private_data;
if (stime) {
hrtimer_cancel(&stime->hrt);
kfree(stime);
t->private_data = NULL;
}
return 0;
}
static int snd_hrtimer_start(struct snd_timer *t)
{
struct snd_hrtimer *stime = t->private_data;
atomic_set(&stime->running, 0);
hrtimer_cancel(&stime->hrt);
hrtimer_start(&stime->hrt, ns_to_ktime(t->sticks * resolution),
HRTIMER_MODE_REL);
atomic_set(&stime->running, 1);
return 0;
}
static int snd_hrtimer_stop(struct snd_timer *t)
{
struct snd_hrtimer *stime = t->private_data;
atomic_set(&stime->running, 0);
return 0;
}
static struct snd_timer_hardware hrtimer_hw = {
.flags = SNDRV_TIMER_HW_AUTO | SNDRV_TIMER_HW_TASKLET,
.open = snd_hrtimer_open,
.close = snd_hrtimer_close,
.start = snd_hrtimer_start,
.stop = snd_hrtimer_stop,
};
/*
* entry functions
*/
static struct snd_timer *mytimer;
static int __init snd_hrtimer_init(void)
{
struct snd_timer *timer;
int err;
resolution = hrtimer_resolution;
/* Create a new timer and set up the fields */
err = snd_timer_global_new("hrtimer", SNDRV_TIMER_GLOBAL_HRTIMER,
&timer);
if (err < 0)
return err;
timer->module = THIS_MODULE;
strcpy(timer->name, "HR timer");
timer->hw = hrtimer_hw;
timer->hw.resolution = resolution;
timer->hw.ticks = NANO_SEC / resolution;
err = snd_timer_global_register(timer);
if (err < 0) {
snd_timer_global_free(timer);
return err;
}
mytimer = timer; /* remember this */
return 0;
}
static void __exit snd_hrtimer_exit(void)
{
if (mytimer) {
snd_timer_global_free(mytimer);
mytimer = NULL;
}
}
module_init(snd_hrtimer_init);
module_exit(snd_hrtimer_exit);
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_4965_0 |
crossvul-cpp_data_bad_2035_0 | /*
* linux/fs/namei.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
/*
* Some corrections by tytso.
*/
/* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname
* lookup logic.
*/
/* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/quotaops.h>
#include <linux/pagemap.h>
#include <linux/fsnotify.h>
#include <linux/personality.h>
#include <linux/security.h>
#include <linux/ima.h>
#include <linux/syscalls.h>
#include <linux/mount.h>
#include <linux/audit.h>
#include <linux/capability.h>
#include <linux/file.h>
#include <linux/fcntl.h>
#include <linux/device_cgroup.h>
#include <linux/fs_struct.h>
#include <asm/uaccess.h>
#include "internal.h"
/* [Feb-1997 T. Schoebel-Theuer]
* Fundamental changes in the pathname lookup mechanisms (namei)
* were necessary because of omirr. The reason is that omirr needs
* to know the _real_ pathname, not the user-supplied one, in case
* of symlinks (and also when transname replacements occur).
*
* The new code replaces the old recursive symlink resolution with
* an iterative one (in case of non-nested symlink chains). It does
* this with calls to <fs>_follow_link().
* As a side effect, dir_namei(), _namei() and follow_link() are now
* replaced with a single function lookup_dentry() that can handle all
* the special cases of the former code.
*
* With the new dcache, the pathname is stored at each inode, at least as
* long as the refcount of the inode is positive. As a side effect, the
* size of the dcache depends on the inode cache and thus is dynamic.
*
* [29-Apr-1998 C. Scott Ananian] Updated above description of symlink
* resolution to correspond with current state of the code.
*
* Note that the symlink resolution is not *completely* iterative.
* There is still a significant amount of tail- and mid- recursion in
* the algorithm. Also, note that <fs>_readlink() is not used in
* lookup_dentry(): lookup_dentry() on the result of <fs>_readlink()
* may return different results than <fs>_follow_link(). Many virtual
* filesystems (including /proc) exhibit this behavior.
*/
/* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation:
* New symlink semantics: when open() is called with flags O_CREAT | O_EXCL
* and the name already exists in form of a symlink, try to create the new
* name indicated by the symlink. The old code always complained that the
* name already exists, due to not following the symlink even if its target
* is nonexistent. The new semantics affects also mknod() and link() when
* the name is a symlink pointing to a non-existant name.
*
* I don't know which semantics is the right one, since I have no access
* to standards. But I found by trial that HP-UX 9.0 has the full "new"
* semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the
* "old" one. Personally, I think the new semantics is much more logical.
* Note that "ln old new" where "new" is a symlink pointing to a non-existing
* file does succeed in both HP-UX and SunOs, but not in Solaris
* and in the old Linux semantics.
*/
/* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink
* semantics. See the comments in "open_namei" and "do_link" below.
*
* [10-Sep-98 Alan Modra] Another symlink change.
*/
/* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks:
* inside the path - always follow.
* in the last component in creation/removal/renaming - never follow.
* if LOOKUP_FOLLOW passed - follow.
* if the pathname has trailing slashes - follow.
* otherwise - don't follow.
* (applied in that order).
*
* [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT
* restored for 2.4. This is the last surviving part of old 4.2BSD bug.
* During the 2.4 we need to fix the userland stuff depending on it -
* hopefully we will be able to get rid of that wart in 2.5. So far only
* XEmacs seems to be relying on it...
*/
/*
* [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland)
* implemented. Let's see if raised priority of ->s_vfs_rename_mutex gives
* any extra contention...
*/
/* In order to reduce some races, while at the same time doing additional
* checking and hopefully speeding things up, we copy filenames to the
* kernel data space before using them..
*
* POSIX.1 2.4: an empty pathname is invalid (ENOENT).
* PATH_MAX includes the nul terminator --RR.
*/
static int do_getname(const char __user *filename, char *page)
{
int retval;
unsigned long len = PATH_MAX;
if (!segment_eq(get_fs(), KERNEL_DS)) {
if ((unsigned long) filename >= TASK_SIZE)
return -EFAULT;
if (TASK_SIZE - (unsigned long) filename < PATH_MAX)
len = TASK_SIZE - (unsigned long) filename;
}
retval = strncpy_from_user(page, filename, len);
if (retval > 0) {
if (retval < len)
return 0;
return -ENAMETOOLONG;
} else if (!retval)
retval = -ENOENT;
return retval;
}
char * getname(const char __user * filename)
{
char *tmp, *result;
result = ERR_PTR(-ENOMEM);
tmp = __getname();
if (tmp) {
int retval = do_getname(filename, tmp);
result = tmp;
if (retval < 0) {
__putname(tmp);
result = ERR_PTR(retval);
}
}
audit_getname(result);
return result;
}
#ifdef CONFIG_AUDITSYSCALL
void putname(const char *name)
{
if (unlikely(!audit_dummy_context()))
audit_putname(name);
else
__putname(name);
}
EXPORT_SYMBOL(putname);
#endif
/*
* This does basic POSIX ACL permission checking
*/
static int acl_permission_check(struct inode *inode, int mask,
int (*check_acl)(struct inode *inode, int mask))
{
umode_t mode = inode->i_mode;
mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
if (current_fsuid() == inode->i_uid)
mode >>= 6;
else {
if (IS_POSIXACL(inode) && (mode & S_IRWXG) && check_acl) {
int error = check_acl(inode, mask);
if (error != -EAGAIN)
return error;
}
if (in_group_p(inode->i_gid))
mode >>= 3;
}
/*
* If the DACs are ok we don't need any capability check.
*/
if ((mask & ~mode) == 0)
return 0;
return -EACCES;
}
/**
* generic_permission - check for access rights on a Posix-like filesystem
* @inode: inode to check access rights for
* @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
* @check_acl: optional callback to check for Posix ACLs
*
* Used to check for read/write/execute permissions on a file.
* We use "fsuid" for this, letting us set arbitrary permissions
* for filesystem access without changing the "normal" uids which
* are used for other things..
*/
int generic_permission(struct inode *inode, int mask,
int (*check_acl)(struct inode *inode, int mask))
{
int ret;
/*
* Do the basic POSIX ACL permission checks.
*/
ret = acl_permission_check(inode, mask, check_acl);
if (ret != -EACCES)
return ret;
/*
* Read/write DACs are always overridable.
* Executable DACs are overridable if at least one exec bit is set.
*/
if (!(mask & MAY_EXEC) || execute_ok(inode))
if (capable(CAP_DAC_OVERRIDE))
return 0;
/*
* Searching includes executable on directories, else just read.
*/
mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
if (mask == MAY_READ || (S_ISDIR(inode->i_mode) && !(mask & MAY_WRITE)))
if (capable(CAP_DAC_READ_SEARCH))
return 0;
return -EACCES;
}
/**
* inode_permission - check for access rights to a given inode
* @inode: inode to check permission on
* @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
*
* Used to check for read/write/execute permissions on an inode.
* We use "fsuid" for this, letting us set arbitrary permissions
* for filesystem access without changing the "normal" uids which
* are used for other things.
*/
int inode_permission(struct inode *inode, int mask)
{
int retval;
if (mask & MAY_WRITE) {
umode_t mode = inode->i_mode;
/*
* Nobody gets write access to a read-only fs.
*/
if (IS_RDONLY(inode) &&
(S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
return -EROFS;
/*
* Nobody gets write access to an immutable file.
*/
if (IS_IMMUTABLE(inode))
return -EACCES;
}
if (inode->i_op->permission)
retval = inode->i_op->permission(inode, mask);
else
retval = generic_permission(inode, mask, inode->i_op->check_acl);
if (retval)
return retval;
retval = devcgroup_inode_permission(inode, mask);
if (retval)
return retval;
return security_inode_permission(inode,
mask & (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND));
}
/**
* file_permission - check for additional access rights to a given file
* @file: file to check access rights for
* @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
*
* Used to check for read/write/execute permissions on an already opened
* file.
*
* Note:
* Do not use this function in new code. All access checks should
* be done using inode_permission().
*/
int file_permission(struct file *file, int mask)
{
return inode_permission(file->f_path.dentry->d_inode, mask);
}
/*
* get_write_access() gets write permission for a file.
* put_write_access() releases this write permission.
* This is used for regular files.
* We cannot support write (and maybe mmap read-write shared) accesses and
* MAP_DENYWRITE mmappings simultaneously. The i_writecount field of an inode
* can have the following values:
* 0: no writers, no VM_DENYWRITE mappings
* < 0: (-i_writecount) vm_area_structs with VM_DENYWRITE set exist
* > 0: (i_writecount) users are writing to the file.
*
* Normally we operate on that counter with atomic_{inc,dec} and it's safe
* except for the cases where we don't hold i_writecount yet. Then we need to
* use {get,deny}_write_access() - these functions check the sign and refuse
* to do the change if sign is wrong. Exclusion between them is provided by
* the inode->i_lock spinlock.
*/
int get_write_access(struct inode * inode)
{
spin_lock(&inode->i_lock);
if (atomic_read(&inode->i_writecount) < 0) {
spin_unlock(&inode->i_lock);
return -ETXTBSY;
}
atomic_inc(&inode->i_writecount);
spin_unlock(&inode->i_lock);
return 0;
}
int deny_write_access(struct file * file)
{
struct inode *inode = file->f_path.dentry->d_inode;
spin_lock(&inode->i_lock);
if (atomic_read(&inode->i_writecount) > 0) {
spin_unlock(&inode->i_lock);
return -ETXTBSY;
}
atomic_dec(&inode->i_writecount);
spin_unlock(&inode->i_lock);
return 0;
}
/**
* path_get - get a reference to a path
* @path: path to get the reference to
*
* Given a path increment the reference count to the dentry and the vfsmount.
*/
void path_get(struct path *path)
{
mntget(path->mnt);
dget(path->dentry);
}
EXPORT_SYMBOL(path_get);
/**
* path_put - put a reference to a path
* @path: path to put the reference to
*
* Given a path decrement the reference count to the dentry and the vfsmount.
*/
void path_put(struct path *path)
{
dput(path->dentry);
mntput(path->mnt);
}
EXPORT_SYMBOL(path_put);
/**
* release_open_intent - free up open intent resources
* @nd: pointer to nameidata
*/
void release_open_intent(struct nameidata *nd)
{
if (nd->intent.open.file->f_path.dentry == NULL)
put_filp(nd->intent.open.file);
else
fput(nd->intent.open.file);
}
static inline struct dentry *
do_revalidate(struct dentry *dentry, struct nameidata *nd)
{
int status = dentry->d_op->d_revalidate(dentry, nd);
if (unlikely(status <= 0)) {
/*
* The dentry failed validation.
* If d_revalidate returned 0 attempt to invalidate
* the dentry otherwise d_revalidate is asking us
* to return a fail status.
*/
if (!status) {
if (!d_invalidate(dentry)) {
dput(dentry);
dentry = NULL;
}
} else {
dput(dentry);
dentry = ERR_PTR(status);
}
}
return dentry;
}
/*
* force_reval_path - force revalidation of a dentry
*
* In some situations the path walking code will trust dentries without
* revalidating them. This causes problems for filesystems that depend on
* d_revalidate to handle file opens (e.g. NFSv4). When FS_REVAL_DOT is set
* (which indicates that it's possible for the dentry to go stale), force
* a d_revalidate call before proceeding.
*
* Returns 0 if the revalidation was successful. If the revalidation fails,
* either return the error returned by d_revalidate or -ESTALE if the
* revalidation it just returned 0. If d_revalidate returns 0, we attempt to
* invalidate the dentry. It's up to the caller to handle putting references
* to the path if necessary.
*/
static int
force_reval_path(struct path *path, struct nameidata *nd)
{
int status;
struct dentry *dentry = path->dentry;
/*
* only check on filesystems where it's possible for the dentry to
* become stale. It's assumed that if this flag is set then the
* d_revalidate op will also be defined.
*/
if (!(dentry->d_sb->s_type->fs_flags & FS_REVAL_DOT))
return 0;
status = dentry->d_op->d_revalidate(dentry, nd);
if (status > 0)
return 0;
if (!status) {
d_invalidate(dentry);
status = -ESTALE;
}
return status;
}
/*
* Short-cut version of permission(), for calling on directories
* during pathname resolution. Combines parts of permission()
* and generic_permission(), and tests ONLY for MAY_EXEC permission.
*
* If appropriate, check DAC only. If not appropriate, or
* short-cut DAC fails, then call ->permission() to do more
* complete permission check.
*/
static int exec_permission(struct inode *inode)
{
int ret;
if (inode->i_op->permission) {
ret = inode->i_op->permission(inode, MAY_EXEC);
if (!ret)
goto ok;
return ret;
}
ret = acl_permission_check(inode, MAY_EXEC, inode->i_op->check_acl);
if (!ret)
goto ok;
if (capable(CAP_DAC_OVERRIDE) || capable(CAP_DAC_READ_SEARCH))
goto ok;
return ret;
ok:
return security_inode_permission(inode, MAY_EXEC);
}
static __always_inline void set_root(struct nameidata *nd)
{
if (!nd->root.mnt) {
struct fs_struct *fs = current->fs;
read_lock(&fs->lock);
nd->root = fs->root;
path_get(&nd->root);
read_unlock(&fs->lock);
}
}
static int link_path_walk(const char *, struct nameidata *);
static __always_inline int __vfs_follow_link(struct nameidata *nd, const char *link)
{
int res = 0;
char *name;
if (IS_ERR(link))
goto fail;
if (*link == '/') {
set_root(nd);
path_put(&nd->path);
nd->path = nd->root;
path_get(&nd->root);
}
res = link_path_walk(link, nd);
if (nd->depth || res || nd->last_type!=LAST_NORM)
return res;
/*
* If it is an iterative symlinks resolution in open_namei() we
* have to copy the last component. And all that crap because of
* bloody create() on broken symlinks. Furrfu...
*/
name = __getname();
if (unlikely(!name)) {
path_put(&nd->path);
return -ENOMEM;
}
strcpy(name, nd->last.name);
nd->last.name = name;
return 0;
fail:
path_put(&nd->path);
return PTR_ERR(link);
}
static void path_put_conditional(struct path *path, struct nameidata *nd)
{
dput(path->dentry);
if (path->mnt != nd->path.mnt)
mntput(path->mnt);
}
static inline void path_to_nameidata(struct path *path, struct nameidata *nd)
{
dput(nd->path.dentry);
if (nd->path.mnt != path->mnt)
mntput(nd->path.mnt);
nd->path.mnt = path->mnt;
nd->path.dentry = path->dentry;
}
static __always_inline int __do_follow_link(struct path *path, struct nameidata *nd)
{
int error;
void *cookie;
struct dentry *dentry = path->dentry;
touch_atime(path->mnt, dentry);
nd_set_link(nd, NULL);
if (path->mnt != nd->path.mnt) {
path_to_nameidata(path, nd);
dget(dentry);
}
mntget(path->mnt);
cookie = dentry->d_inode->i_op->follow_link(dentry, nd);
error = PTR_ERR(cookie);
if (!IS_ERR(cookie)) {
char *s = nd_get_link(nd);
error = 0;
if (s)
error = __vfs_follow_link(nd, s);
else if (nd->last_type == LAST_BIND) {
error = force_reval_path(&nd->path, nd);
if (error)
path_put(&nd->path);
}
if (dentry->d_inode->i_op->put_link)
dentry->d_inode->i_op->put_link(dentry, nd, cookie);
}
return error;
}
/*
* This limits recursive symlink follows to 8, while
* limiting consecutive symlinks to 40.
*
* Without that kind of total limit, nasty chains of consecutive
* symlinks can cause almost arbitrarily long lookups.
*/
static inline int do_follow_link(struct path *path, struct nameidata *nd)
{
int err = -ELOOP;
if (current->link_count >= MAX_NESTED_LINKS)
goto loop;
if (current->total_link_count >= 40)
goto loop;
BUG_ON(nd->depth >= MAX_NESTED_LINKS);
cond_resched();
err = security_inode_follow_link(path->dentry, nd);
if (err)
goto loop;
current->link_count++;
current->total_link_count++;
nd->depth++;
err = __do_follow_link(path, nd);
path_put(path);
current->link_count--;
nd->depth--;
return err;
loop:
path_put_conditional(path, nd);
path_put(&nd->path);
return err;
}
int follow_up(struct path *path)
{
struct vfsmount *parent;
struct dentry *mountpoint;
spin_lock(&vfsmount_lock);
parent = path->mnt->mnt_parent;
if (parent == path->mnt) {
spin_unlock(&vfsmount_lock);
return 0;
}
mntget(parent);
mountpoint = dget(path->mnt->mnt_mountpoint);
spin_unlock(&vfsmount_lock);
dput(path->dentry);
path->dentry = mountpoint;
mntput(path->mnt);
path->mnt = parent;
return 1;
}
/* no need for dcache_lock, as serialization is taken care in
* namespace.c
*/
static int __follow_mount(struct path *path)
{
int res = 0;
while (d_mountpoint(path->dentry)) {
struct vfsmount *mounted = lookup_mnt(path);
if (!mounted)
break;
dput(path->dentry);
if (res)
mntput(path->mnt);
path->mnt = mounted;
path->dentry = dget(mounted->mnt_root);
res = 1;
}
return res;
}
static void follow_mount(struct path *path)
{
while (d_mountpoint(path->dentry)) {
struct vfsmount *mounted = lookup_mnt(path);
if (!mounted)
break;
dput(path->dentry);
mntput(path->mnt);
path->mnt = mounted;
path->dentry = dget(mounted->mnt_root);
}
}
/* no need for dcache_lock, as serialization is taken care in
* namespace.c
*/
int follow_down(struct path *path)
{
struct vfsmount *mounted;
mounted = lookup_mnt(path);
if (mounted) {
dput(path->dentry);
mntput(path->mnt);
path->mnt = mounted;
path->dentry = dget(mounted->mnt_root);
return 1;
}
return 0;
}
static __always_inline void follow_dotdot(struct nameidata *nd)
{
set_root(nd);
while(1) {
struct vfsmount *parent;
struct dentry *old = nd->path.dentry;
if (nd->path.dentry == nd->root.dentry &&
nd->path.mnt == nd->root.mnt) {
break;
}
spin_lock(&dcache_lock);
if (nd->path.dentry != nd->path.mnt->mnt_root) {
nd->path.dentry = dget(nd->path.dentry->d_parent);
spin_unlock(&dcache_lock);
dput(old);
break;
}
spin_unlock(&dcache_lock);
spin_lock(&vfsmount_lock);
parent = nd->path.mnt->mnt_parent;
if (parent == nd->path.mnt) {
spin_unlock(&vfsmount_lock);
break;
}
mntget(parent);
nd->path.dentry = dget(nd->path.mnt->mnt_mountpoint);
spin_unlock(&vfsmount_lock);
dput(old);
mntput(nd->path.mnt);
nd->path.mnt = parent;
}
follow_mount(&nd->path);
}
/*
* It's more convoluted than I'd like it to be, but... it's still fairly
* small and for now I'd prefer to have fast path as straight as possible.
* It _is_ time-critical.
*/
static int do_lookup(struct nameidata *nd, struct qstr *name,
struct path *path)
{
struct vfsmount *mnt = nd->path.mnt;
struct dentry *dentry, *parent;
struct inode *dir;
/*
* See if the low-level filesystem might want
* to use its own hash..
*/
if (nd->path.dentry->d_op && nd->path.dentry->d_op->d_hash) {
int err = nd->path.dentry->d_op->d_hash(nd->path.dentry, name);
if (err < 0)
return err;
}
dentry = __d_lookup(nd->path.dentry, name);
if (!dentry)
goto need_lookup;
if (dentry->d_op && dentry->d_op->d_revalidate)
goto need_revalidate;
done:
path->mnt = mnt;
path->dentry = dentry;
__follow_mount(path);
return 0;
need_lookup:
parent = nd->path.dentry;
dir = parent->d_inode;
mutex_lock(&dir->i_mutex);
/*
* First re-do the cached lookup just in case it was created
* while we waited for the directory semaphore..
*
* FIXME! This could use version numbering or similar to
* avoid unnecessary cache lookups.
*
* The "dcache_lock" is purely to protect the RCU list walker
* from concurrent renames at this point (we mustn't get false
* negatives from the RCU list walk here, unlike the optimistic
* fast walk).
*
* so doing d_lookup() (with seqlock), instead of lockfree __d_lookup
*/
dentry = d_lookup(parent, name);
if (!dentry) {
struct dentry *new;
/* Don't create child dentry for a dead directory. */
dentry = ERR_PTR(-ENOENT);
if (IS_DEADDIR(dir))
goto out_unlock;
new = d_alloc(parent, name);
dentry = ERR_PTR(-ENOMEM);
if (new) {
dentry = dir->i_op->lookup(dir, new, nd);
if (dentry)
dput(new);
else
dentry = new;
}
out_unlock:
mutex_unlock(&dir->i_mutex);
if (IS_ERR(dentry))
goto fail;
goto done;
}
/*
* Uhhuh! Nasty case: the cache was re-populated while
* we waited on the semaphore. Need to revalidate.
*/
mutex_unlock(&dir->i_mutex);
if (dentry->d_op && dentry->d_op->d_revalidate) {
dentry = do_revalidate(dentry, nd);
if (!dentry)
dentry = ERR_PTR(-ENOENT);
}
if (IS_ERR(dentry))
goto fail;
goto done;
need_revalidate:
dentry = do_revalidate(dentry, nd);
if (!dentry)
goto need_lookup;
if (IS_ERR(dentry))
goto fail;
goto done;
fail:
return PTR_ERR(dentry);
}
/*
* Name resolution.
* This is the basic name resolution function, turning a pathname into
* the final dentry. We expect 'base' to be positive and a directory.
*
* Returns 0 and nd will have valid dentry and mnt on success.
* Returns error and drops reference to input namei data on failure.
*/
static int link_path_walk(const char *name, struct nameidata *nd)
{
struct path next;
struct inode *inode;
int err;
unsigned int lookup_flags = nd->flags;
while (*name=='/')
name++;
if (!*name)
goto return_reval;
inode = nd->path.dentry->d_inode;
if (nd->depth)
lookup_flags = LOOKUP_FOLLOW | (nd->flags & LOOKUP_CONTINUE);
/* At this point we know we have a real path component. */
for(;;) {
unsigned long hash;
struct qstr this;
unsigned int c;
nd->flags |= LOOKUP_CONTINUE;
err = exec_permission(inode);
if (err)
break;
this.name = name;
c = *(const unsigned char *)name;
hash = init_name_hash();
do {
name++;
hash = partial_name_hash(c, hash);
c = *(const unsigned char *)name;
} while (c && (c != '/'));
this.len = name - (const char *) this.name;
this.hash = end_name_hash(hash);
/* remove trailing slashes? */
if (!c)
goto last_component;
while (*++name == '/');
if (!*name)
goto last_with_slashes;
/*
* "." and ".." are special - ".." especially so because it has
* to be able to know about the current root directory and
* parent relationships.
*/
if (this.name[0] == '.') switch (this.len) {
default:
break;
case 2:
if (this.name[1] != '.')
break;
follow_dotdot(nd);
inode = nd->path.dentry->d_inode;
/* fallthrough */
case 1:
continue;
}
/* This does the actual lookups.. */
err = do_lookup(nd, &this, &next);
if (err)
break;
err = -ENOENT;
inode = next.dentry->d_inode;
if (!inode)
goto out_dput;
if (inode->i_op->follow_link) {
err = do_follow_link(&next, nd);
if (err)
goto return_err;
err = -ENOENT;
inode = nd->path.dentry->d_inode;
if (!inode)
break;
} else
path_to_nameidata(&next, nd);
err = -ENOTDIR;
if (!inode->i_op->lookup)
break;
continue;
/* here ends the main loop */
last_with_slashes:
lookup_flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
last_component:
/* Clear LOOKUP_CONTINUE iff it was previously unset */
nd->flags &= lookup_flags | ~LOOKUP_CONTINUE;
if (lookup_flags & LOOKUP_PARENT)
goto lookup_parent;
if (this.name[0] == '.') switch (this.len) {
default:
break;
case 2:
if (this.name[1] != '.')
break;
follow_dotdot(nd);
inode = nd->path.dentry->d_inode;
/* fallthrough */
case 1:
goto return_reval;
}
err = do_lookup(nd, &this, &next);
if (err)
break;
inode = next.dentry->d_inode;
if ((lookup_flags & LOOKUP_FOLLOW)
&& inode && inode->i_op->follow_link) {
err = do_follow_link(&next, nd);
if (err)
goto return_err;
inode = nd->path.dentry->d_inode;
} else
path_to_nameidata(&next, nd);
err = -ENOENT;
if (!inode)
break;
if (lookup_flags & LOOKUP_DIRECTORY) {
err = -ENOTDIR;
if (!inode->i_op->lookup)
break;
}
goto return_base;
lookup_parent:
nd->last = this;
nd->last_type = LAST_NORM;
if (this.name[0] != '.')
goto return_base;
if (this.len == 1)
nd->last_type = LAST_DOT;
else if (this.len == 2 && this.name[1] == '.')
nd->last_type = LAST_DOTDOT;
else
goto return_base;
return_reval:
/*
* We bypassed the ordinary revalidation routines.
* We may need to check the cached dentry for staleness.
*/
if (nd->path.dentry && nd->path.dentry->d_sb &&
(nd->path.dentry->d_sb->s_type->fs_flags & FS_REVAL_DOT)) {
err = -ESTALE;
/* Note: we do not d_invalidate() */
if (!nd->path.dentry->d_op->d_revalidate(
nd->path.dentry, nd))
break;
}
return_base:
return 0;
out_dput:
path_put_conditional(&next, nd);
break;
}
path_put(&nd->path);
return_err:
return err;
}
static int path_walk(const char *name, struct nameidata *nd)
{
struct path save = nd->path;
int result;
current->total_link_count = 0;
/* make sure the stuff we saved doesn't go away */
path_get(&save);
result = link_path_walk(name, nd);
if (result == -ESTALE) {
/* nd->path had been dropped */
current->total_link_count = 0;
nd->path = save;
path_get(&nd->path);
nd->flags |= LOOKUP_REVAL;
result = link_path_walk(name, nd);
}
path_put(&save);
return result;
}
static int path_init(int dfd, const char *name, unsigned int flags, struct nameidata *nd)
{
int retval = 0;
int fput_needed;
struct file *file;
nd->last_type = LAST_ROOT; /* if there are only slashes... */
nd->flags = flags;
nd->depth = 0;
nd->root.mnt = NULL;
if (*name=='/') {
set_root(nd);
nd->path = nd->root;
path_get(&nd->root);
} else if (dfd == AT_FDCWD) {
struct fs_struct *fs = current->fs;
read_lock(&fs->lock);
nd->path = fs->pwd;
path_get(&fs->pwd);
read_unlock(&fs->lock);
} else {
struct dentry *dentry;
file = fget_light(dfd, &fput_needed);
retval = -EBADF;
if (!file)
goto out_fail;
dentry = file->f_path.dentry;
retval = -ENOTDIR;
if (!S_ISDIR(dentry->d_inode->i_mode))
goto fput_fail;
retval = file_permission(file, MAY_EXEC);
if (retval)
goto fput_fail;
nd->path = file->f_path;
path_get(&file->f_path);
fput_light(file, fput_needed);
}
return 0;
fput_fail:
fput_light(file, fput_needed);
out_fail:
return retval;
}
/* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
static int do_path_lookup(int dfd, const char *name,
unsigned int flags, struct nameidata *nd)
{
int retval = path_init(dfd, name, flags, nd);
if (!retval)
retval = path_walk(name, nd);
if (unlikely(!retval && !audit_dummy_context() && nd->path.dentry &&
nd->path.dentry->d_inode))
audit_inode(name, nd->path.dentry);
if (nd->root.mnt) {
path_put(&nd->root);
nd->root.mnt = NULL;
}
return retval;
}
int path_lookup(const char *name, unsigned int flags,
struct nameidata *nd)
{
return do_path_lookup(AT_FDCWD, name, flags, nd);
}
int kern_path(const char *name, unsigned int flags, struct path *path)
{
struct nameidata nd;
int res = do_path_lookup(AT_FDCWD, name, flags, &nd);
if (!res)
*path = nd.path;
return res;
}
/**
* vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
* @dentry: pointer to dentry of the base directory
* @mnt: pointer to vfs mount of the base directory
* @name: pointer to file name
* @flags: lookup flags
* @nd: pointer to nameidata
*/
int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
const char *name, unsigned int flags,
struct nameidata *nd)
{
int retval;
/* same as do_path_lookup */
nd->last_type = LAST_ROOT;
nd->flags = flags;
nd->depth = 0;
nd->path.dentry = dentry;
nd->path.mnt = mnt;
path_get(&nd->path);
nd->root = nd->path;
path_get(&nd->root);
retval = path_walk(name, nd);
if (unlikely(!retval && !audit_dummy_context() && nd->path.dentry &&
nd->path.dentry->d_inode))
audit_inode(name, nd->path.dentry);
path_put(&nd->root);
nd->root.mnt = NULL;
return retval;
}
static struct dentry *__lookup_hash(struct qstr *name,
struct dentry *base, struct nameidata *nd)
{
struct dentry *dentry;
struct inode *inode;
int err;
inode = base->d_inode;
/*
* See if the low-level filesystem might want
* to use its own hash..
*/
if (base->d_op && base->d_op->d_hash) {
err = base->d_op->d_hash(base, name);
dentry = ERR_PTR(err);
if (err < 0)
goto out;
}
dentry = __d_lookup(base, name);
/* lockess __d_lookup may fail due to concurrent d_move()
* in some unrelated directory, so try with d_lookup
*/
if (!dentry)
dentry = d_lookup(base, name);
if (dentry && dentry->d_op && dentry->d_op->d_revalidate)
dentry = do_revalidate(dentry, nd);
if (!dentry) {
struct dentry *new;
/* Don't create child dentry for a dead directory. */
dentry = ERR_PTR(-ENOENT);
if (IS_DEADDIR(inode))
goto out;
new = d_alloc(base, name);
dentry = ERR_PTR(-ENOMEM);
if (!new)
goto out;
dentry = inode->i_op->lookup(inode, new, nd);
if (!dentry)
dentry = new;
else
dput(new);
}
out:
return dentry;
}
/*
* Restricted form of lookup. Doesn't follow links, single-component only,
* needs parent already locked. Doesn't follow mounts.
* SMP-safe.
*/
static struct dentry *lookup_hash(struct nameidata *nd)
{
int err;
err = exec_permission(nd->path.dentry->d_inode);
if (err)
return ERR_PTR(err);
return __lookup_hash(&nd->last, nd->path.dentry, nd);
}
static int __lookup_one_len(const char *name, struct qstr *this,
struct dentry *base, int len)
{
unsigned long hash;
unsigned int c;
this->name = name;
this->len = len;
if (!len)
return -EACCES;
hash = init_name_hash();
while (len--) {
c = *(const unsigned char *)name++;
if (c == '/' || c == '\0')
return -EACCES;
hash = partial_name_hash(c, hash);
}
this->hash = end_name_hash(hash);
return 0;
}
/**
* lookup_one_len - filesystem helper to lookup single pathname component
* @name: pathname component to lookup
* @base: base directory to lookup from
* @len: maximum length @len should be interpreted to
*
* Note that this routine is purely a helper for filesystem usage and should
* not be called by generic code. Also note that by using this function the
* nameidata argument is passed to the filesystem methods and a filesystem
* using this helper needs to be prepared for that.
*/
struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
{
int err;
struct qstr this;
WARN_ON_ONCE(!mutex_is_locked(&base->d_inode->i_mutex));
err = __lookup_one_len(name, &this, base, len);
if (err)
return ERR_PTR(err);
err = exec_permission(base->d_inode);
if (err)
return ERR_PTR(err);
return __lookup_hash(&this, base, NULL);
}
int user_path_at(int dfd, const char __user *name, unsigned flags,
struct path *path)
{
struct nameidata nd;
char *tmp = getname(name);
int err = PTR_ERR(tmp);
if (!IS_ERR(tmp)) {
BUG_ON(flags & LOOKUP_PARENT);
err = do_path_lookup(dfd, tmp, flags, &nd);
putname(tmp);
if (!err)
*path = nd.path;
}
return err;
}
static int user_path_parent(int dfd, const char __user *path,
struct nameidata *nd, char **name)
{
char *s = getname(path);
int error;
if (IS_ERR(s))
return PTR_ERR(s);
error = do_path_lookup(dfd, s, LOOKUP_PARENT, nd);
if (error)
putname(s);
else
*name = s;
return error;
}
/*
* It's inline, so penalty for filesystems that don't use sticky bit is
* minimal.
*/
static inline int check_sticky(struct inode *dir, struct inode *inode)
{
uid_t fsuid = current_fsuid();
if (!(dir->i_mode & S_ISVTX))
return 0;
if (inode->i_uid == fsuid)
return 0;
if (dir->i_uid == fsuid)
return 0;
return !capable(CAP_FOWNER);
}
/*
* Check whether we can remove a link victim from directory dir, check
* whether the type of victim is right.
* 1. We can't do it if dir is read-only (done in permission())
* 2. We should have write and exec permissions on dir
* 3. We can't remove anything from append-only dir
* 4. We can't do anything with immutable dir (done in permission())
* 5. If the sticky bit on dir is set we should either
* a. be owner of dir, or
* b. be owner of victim, or
* c. have CAP_FOWNER capability
* 6. If the victim is append-only or immutable we can't do antyhing with
* links pointing to it.
* 7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
* 8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
* 9. We can't remove a root or mountpoint.
* 10. We don't allow removal of NFS sillyrenamed files; it's handled by
* nfs_async_unlink().
*/
static int may_delete(struct inode *dir,struct dentry *victim,int isdir)
{
int error;
if (!victim->d_inode)
return -ENOENT;
BUG_ON(victim->d_parent->d_inode != dir);
audit_inode_child(victim->d_name.name, victim, dir);
error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
if (error)
return error;
if (IS_APPEND(dir))
return -EPERM;
if (check_sticky(dir, victim->d_inode)||IS_APPEND(victim->d_inode)||
IS_IMMUTABLE(victim->d_inode) || IS_SWAPFILE(victim->d_inode))
return -EPERM;
if (isdir) {
if (!S_ISDIR(victim->d_inode->i_mode))
return -ENOTDIR;
if (IS_ROOT(victim))
return -EBUSY;
} else if (S_ISDIR(victim->d_inode->i_mode))
return -EISDIR;
if (IS_DEADDIR(dir))
return -ENOENT;
if (victim->d_flags & DCACHE_NFSFS_RENAMED)
return -EBUSY;
return 0;
}
/* Check whether we can create an object with dentry child in directory
* dir.
* 1. We can't do it if child already exists (open has special treatment for
* this case, but since we are inlined it's OK)
* 2. We can't do it if dir is read-only (done in permission())
* 3. We should have write and exec permissions on dir
* 4. We can't do it if dir is immutable (done in permission())
*/
static inline int may_create(struct inode *dir, struct dentry *child)
{
if (child->d_inode)
return -EEXIST;
if (IS_DEADDIR(dir))
return -ENOENT;
return inode_permission(dir, MAY_WRITE | MAY_EXEC);
}
/*
* O_DIRECTORY translates into forcing a directory lookup.
*/
static inline int lookup_flags(unsigned int f)
{
unsigned long retval = LOOKUP_FOLLOW;
if (f & O_NOFOLLOW)
retval &= ~LOOKUP_FOLLOW;
if (f & O_DIRECTORY)
retval |= LOOKUP_DIRECTORY;
return retval;
}
/*
* p1 and p2 should be directories on the same fs.
*/
struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
{
struct dentry *p;
if (p1 == p2) {
mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
return NULL;
}
mutex_lock(&p1->d_inode->i_sb->s_vfs_rename_mutex);
p = d_ancestor(p2, p1);
if (p) {
mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT);
mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_CHILD);
return p;
}
p = d_ancestor(p1, p2);
if (p) {
mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD);
return p;
}
mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD);
return NULL;
}
void unlock_rename(struct dentry *p1, struct dentry *p2)
{
mutex_unlock(&p1->d_inode->i_mutex);
if (p1 != p2) {
mutex_unlock(&p2->d_inode->i_mutex);
mutex_unlock(&p1->d_inode->i_sb->s_vfs_rename_mutex);
}
}
int vfs_create(struct inode *dir, struct dentry *dentry, int mode,
struct nameidata *nd)
{
int error = may_create(dir, dentry);
if (error)
return error;
if (!dir->i_op->create)
return -EACCES; /* shouldn't it be ENOSYS? */
mode &= S_IALLUGO;
mode |= S_IFREG;
error = security_inode_create(dir, dentry, mode);
if (error)
return error;
vfs_dq_init(dir);
error = dir->i_op->create(dir, dentry, mode, nd);
if (!error)
fsnotify_create(dir, dentry);
return error;
}
int may_open(struct path *path, int acc_mode, int flag)
{
struct dentry *dentry = path->dentry;
struct inode *inode = dentry->d_inode;
int error;
if (!inode)
return -ENOENT;
switch (inode->i_mode & S_IFMT) {
case S_IFLNK:
return -ELOOP;
case S_IFDIR:
if (acc_mode & MAY_WRITE)
return -EISDIR;
break;
case S_IFBLK:
case S_IFCHR:
if (path->mnt->mnt_flags & MNT_NODEV)
return -EACCES;
/*FALLTHRU*/
case S_IFIFO:
case S_IFSOCK:
flag &= ~O_TRUNC;
break;
}
error = inode_permission(inode, acc_mode);
if (error)
return error;
/*
* An append-only file must be opened in append mode for writing.
*/
if (IS_APPEND(inode)) {
if ((flag & FMODE_WRITE) && !(flag & O_APPEND))
return -EPERM;
if (flag & O_TRUNC)
return -EPERM;
}
/* O_NOATIME can only be set by the owner or superuser */
if (flag & O_NOATIME && !is_owner_or_cap(inode))
return -EPERM;
/*
* Ensure there are no outstanding leases on the file.
*/
return break_lease(inode, flag);
}
static int handle_truncate(struct path *path)
{
struct inode *inode = path->dentry->d_inode;
int error = get_write_access(inode);
if (error)
return error;
/*
* Refuse to truncate files with mandatory locks held on them.
*/
error = locks_verify_locked(inode);
if (!error)
error = security_path_truncate(path, 0,
ATTR_MTIME|ATTR_CTIME|ATTR_OPEN);
if (!error) {
error = do_truncate(path->dentry, 0,
ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
NULL);
}
put_write_access(inode);
return error;
}
/*
* Be careful about ever adding any more callers of this
* function. Its flags must be in the namei format, not
* what get passed to sys_open().
*/
static int __open_namei_create(struct nameidata *nd, struct path *path,
int flag, int mode)
{
int error;
struct dentry *dir = nd->path.dentry;
if (!IS_POSIXACL(dir->d_inode))
mode &= ~current_umask();
error = security_path_mknod(&nd->path, path->dentry, mode, 0);
if (error)
goto out_unlock;
error = vfs_create(dir->d_inode, path->dentry, mode, nd);
out_unlock:
mutex_unlock(&dir->d_inode->i_mutex);
dput(nd->path.dentry);
nd->path.dentry = path->dentry;
if (error)
return error;
/* Don't check for write permission, don't truncate */
return may_open(&nd->path, 0, flag & ~O_TRUNC);
}
/*
* Note that while the flag value (low two bits) for sys_open means:
* 00 - read-only
* 01 - write-only
* 10 - read-write
* 11 - special
* it is changed into
* 00 - no permissions needed
* 01 - read-permission
* 10 - write-permission
* 11 - read-write
* for the internal routines (ie open_namei()/follow_link() etc)
* This is more logical, and also allows the 00 "no perm needed"
* to be used for symlinks (where the permissions are checked
* later).
*
*/
static inline int open_to_namei_flags(int flag)
{
if ((flag+1) & O_ACCMODE)
flag++;
return flag;
}
static int open_will_truncate(int flag, struct inode *inode)
{
/*
* We'll never write to the fs underlying
* a device file.
*/
if (special_file(inode->i_mode))
return 0;
return (flag & O_TRUNC);
}
/*
* Note that the low bits of the passed in "open_flag"
* are not the same as in the local variable "flag". See
* open_to_namei_flags() for more details.
*/
struct file *do_filp_open(int dfd, const char *pathname,
int open_flag, int mode, int acc_mode)
{
struct file *filp;
struct nameidata nd;
int error;
struct path path, save;
struct dentry *dir;
int count = 0;
int will_truncate;
int flag = open_to_namei_flags(open_flag);
/*
* O_SYNC is implemented as __O_SYNC|O_DSYNC. As many places only
* check for O_DSYNC if the need any syncing at all we enforce it's
* always set instead of having to deal with possibly weird behaviour
* for malicious applications setting only __O_SYNC.
*/
if (open_flag & __O_SYNC)
open_flag |= O_DSYNC;
if (!acc_mode)
acc_mode = MAY_OPEN | ACC_MODE(flag);
/* O_TRUNC implies we need access checks for write permissions */
if (flag & O_TRUNC)
acc_mode |= MAY_WRITE;
/* Allow the LSM permission hook to distinguish append
access from general write access. */
if (flag & O_APPEND)
acc_mode |= MAY_APPEND;
/*
* The simplest case - just a plain lookup.
*/
if (!(flag & O_CREAT)) {
filp = get_empty_filp();
if (filp == NULL)
return ERR_PTR(-ENFILE);
nd.intent.open.file = filp;
filp->f_flags = open_flag;
nd.intent.open.flags = flag;
nd.intent.open.create_mode = 0;
error = do_path_lookup(dfd, pathname,
lookup_flags(flag)|LOOKUP_OPEN, &nd);
if (IS_ERR(nd.intent.open.file)) {
if (error == 0) {
error = PTR_ERR(nd.intent.open.file);
path_put(&nd.path);
}
} else if (error)
release_open_intent(&nd);
if (error)
return ERR_PTR(error);
goto ok;
}
/*
* Create - we need to know the parent.
*/
error = path_init(dfd, pathname, LOOKUP_PARENT, &nd);
if (error)
return ERR_PTR(error);
error = path_walk(pathname, &nd);
if (error) {
if (nd.root.mnt)
path_put(&nd.root);
return ERR_PTR(error);
}
if (unlikely(!audit_dummy_context()))
audit_inode(pathname, nd.path.dentry);
/*
* We have the parent and last component. First of all, check
* that we are not asked to creat(2) an obvious directory - that
* will not do.
*/
error = -EISDIR;
if (nd.last_type != LAST_NORM || nd.last.name[nd.last.len])
goto exit_parent;
error = -ENFILE;
filp = get_empty_filp();
if (filp == NULL)
goto exit_parent;
nd.intent.open.file = filp;
filp->f_flags = open_flag;
nd.intent.open.flags = flag;
nd.intent.open.create_mode = mode;
dir = nd.path.dentry;
nd.flags &= ~LOOKUP_PARENT;
nd.flags |= LOOKUP_CREATE | LOOKUP_OPEN;
if (flag & O_EXCL)
nd.flags |= LOOKUP_EXCL;
mutex_lock(&dir->d_inode->i_mutex);
path.dentry = lookup_hash(&nd);
path.mnt = nd.path.mnt;
do_last:
error = PTR_ERR(path.dentry);
if (IS_ERR(path.dentry)) {
mutex_unlock(&dir->d_inode->i_mutex);
goto exit;
}
if (IS_ERR(nd.intent.open.file)) {
error = PTR_ERR(nd.intent.open.file);
goto exit_mutex_unlock;
}
/* Negative dentry, just create the file */
if (!path.dentry->d_inode) {
/*
* This write is needed to ensure that a
* ro->rw transition does not occur between
* the time when the file is created and when
* a permanent write count is taken through
* the 'struct file' in nameidata_to_filp().
*/
error = mnt_want_write(nd.path.mnt);
if (error)
goto exit_mutex_unlock;
error = __open_namei_create(&nd, &path, flag, mode);
if (error) {
mnt_drop_write(nd.path.mnt);
goto exit;
}
filp = nameidata_to_filp(&nd);
mnt_drop_write(nd.path.mnt);
if (nd.root.mnt)
path_put(&nd.root);
if (!IS_ERR(filp)) {
error = ima_path_check(&filp->f_path, filp->f_mode &
(MAY_READ | MAY_WRITE | MAY_EXEC));
if (error) {
fput(filp);
filp = ERR_PTR(error);
}
}
return filp;
}
/*
* It already exists.
*/
mutex_unlock(&dir->d_inode->i_mutex);
audit_inode(pathname, path.dentry);
error = -EEXIST;
if (flag & O_EXCL)
goto exit_dput;
if (__follow_mount(&path)) {
error = -ELOOP;
if (flag & O_NOFOLLOW)
goto exit_dput;
}
error = -ENOENT;
if (!path.dentry->d_inode)
goto exit_dput;
if (path.dentry->d_inode->i_op->follow_link)
goto do_link;
path_to_nameidata(&path, &nd);
error = -EISDIR;
if (S_ISDIR(path.dentry->d_inode->i_mode))
goto exit;
ok:
/*
* Consider:
* 1. may_open() truncates a file
* 2. a rw->ro mount transition occurs
* 3. nameidata_to_filp() fails due to
* the ro mount.
* That would be inconsistent, and should
* be avoided. Taking this mnt write here
* ensures that (2) can not occur.
*/
will_truncate = open_will_truncate(flag, nd.path.dentry->d_inode);
if (will_truncate) {
error = mnt_want_write(nd.path.mnt);
if (error)
goto exit;
}
error = may_open(&nd.path, acc_mode, flag);
if (error) {
if (will_truncate)
mnt_drop_write(nd.path.mnt);
goto exit;
}
filp = nameidata_to_filp(&nd);
if (!IS_ERR(filp)) {
error = ima_path_check(&filp->f_path, filp->f_mode &
(MAY_READ | MAY_WRITE | MAY_EXEC));
if (error) {
fput(filp);
filp = ERR_PTR(error);
}
}
if (!IS_ERR(filp)) {
if (acc_mode & MAY_WRITE)
vfs_dq_init(nd.path.dentry->d_inode);
if (will_truncate) {
error = handle_truncate(&nd.path);
if (error) {
fput(filp);
filp = ERR_PTR(error);
}
}
}
/*
* It is now safe to drop the mnt write
* because the filp has had a write taken
* on its behalf.
*/
if (will_truncate)
mnt_drop_write(nd.path.mnt);
if (nd.root.mnt)
path_put(&nd.root);
return filp;
exit_mutex_unlock:
mutex_unlock(&dir->d_inode->i_mutex);
exit_dput:
path_put_conditional(&path, &nd);
exit:
if (!IS_ERR(nd.intent.open.file))
release_open_intent(&nd);
exit_parent:
if (nd.root.mnt)
path_put(&nd.root);
path_put(&nd.path);
return ERR_PTR(error);
do_link:
error = -ELOOP;
if (flag & O_NOFOLLOW)
goto exit_dput;
/*
* This is subtle. Instead of calling do_follow_link() we do the
* thing by hands. The reason is that this way we have zero link_count
* and path_walk() (called from ->follow_link) honoring LOOKUP_PARENT.
* After that we have the parent and last component, i.e.
* we are in the same situation as after the first path_walk().
* Well, almost - if the last component is normal we get its copy
* stored in nd->last.name and we will have to putname() it when we
* are done. Procfs-like symlinks just set LAST_BIND.
*/
nd.flags |= LOOKUP_PARENT;
error = security_inode_follow_link(path.dentry, &nd);
if (error)
goto exit_dput;
save = nd.path;
path_get(&save);
error = __do_follow_link(&path, &nd);
if (error == -ESTALE) {
/* nd.path had been dropped */
nd.path = save;
path_get(&nd.path);
nd.flags |= LOOKUP_REVAL;
error = __do_follow_link(&path, &nd);
}
path_put(&save);
path_put(&path);
if (error) {
/* Does someone understand code flow here? Or it is only
* me so stupid? Anathema to whoever designed this non-sense
* with "intent.open".
*/
release_open_intent(&nd);
if (nd.root.mnt)
path_put(&nd.root);
return ERR_PTR(error);
}
nd.flags &= ~LOOKUP_PARENT;
if (nd.last_type == LAST_BIND)
goto ok;
error = -EISDIR;
if (nd.last_type != LAST_NORM)
goto exit;
if (nd.last.name[nd.last.len]) {
__putname(nd.last.name);
goto exit;
}
error = -ELOOP;
if (count++==32) {
__putname(nd.last.name);
goto exit;
}
dir = nd.path.dentry;
mutex_lock(&dir->d_inode->i_mutex);
path.dentry = lookup_hash(&nd);
path.mnt = nd.path.mnt;
__putname(nd.last.name);
goto do_last;
}
/**
* filp_open - open file and return file pointer
*
* @filename: path to open
* @flags: open flags as per the open(2) second argument
* @mode: mode for the new file if O_CREAT is set, else ignored
*
* This is the helper to open a file from kernelspace if you really
* have to. But in generally you should not do this, so please move
* along, nothing to see here..
*/
struct file *filp_open(const char *filename, int flags, int mode)
{
return do_filp_open(AT_FDCWD, filename, flags, mode, 0);
}
EXPORT_SYMBOL(filp_open);
/**
* lookup_create - lookup a dentry, creating it if it doesn't exist
* @nd: nameidata info
* @is_dir: directory flag
*
* Simple function to lookup and return a dentry and create it
* if it doesn't exist. Is SMP-safe.
*
* Returns with nd->path.dentry->d_inode->i_mutex locked.
*/
struct dentry *lookup_create(struct nameidata *nd, int is_dir)
{
struct dentry *dentry = ERR_PTR(-EEXIST);
mutex_lock_nested(&nd->path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
/*
* Yucky last component or no last component at all?
* (foo/., foo/.., /////)
*/
if (nd->last_type != LAST_NORM)
goto fail;
nd->flags &= ~LOOKUP_PARENT;
nd->flags |= LOOKUP_CREATE | LOOKUP_EXCL;
nd->intent.open.flags = O_EXCL;
/*
* Do the final lookup.
*/
dentry = lookup_hash(nd);
if (IS_ERR(dentry))
goto fail;
if (dentry->d_inode)
goto eexist;
/*
* Special case - lookup gave negative, but... we had foo/bar/
* From the vfs_mknod() POV we just have a negative dentry -
* all is fine. Let's be bastards - you had / on the end, you've
* been asking for (non-existent) directory. -ENOENT for you.
*/
if (unlikely(!is_dir && nd->last.name[nd->last.len])) {
dput(dentry);
dentry = ERR_PTR(-ENOENT);
}
return dentry;
eexist:
dput(dentry);
dentry = ERR_PTR(-EEXIST);
fail:
return dentry;
}
EXPORT_SYMBOL_GPL(lookup_create);
int vfs_mknod(struct inode *dir, struct dentry *dentry, int mode, dev_t dev)
{
int error = may_create(dir, dentry);
if (error)
return error;
if ((S_ISCHR(mode) || S_ISBLK(mode)) && !capable(CAP_MKNOD))
return -EPERM;
if (!dir->i_op->mknod)
return -EPERM;
error = devcgroup_inode_mknod(mode, dev);
if (error)
return error;
error = security_inode_mknod(dir, dentry, mode, dev);
if (error)
return error;
vfs_dq_init(dir);
error = dir->i_op->mknod(dir, dentry, mode, dev);
if (!error)
fsnotify_create(dir, dentry);
return error;
}
static int may_mknod(mode_t mode)
{
switch (mode & S_IFMT) {
case S_IFREG:
case S_IFCHR:
case S_IFBLK:
case S_IFIFO:
case S_IFSOCK:
case 0: /* zero mode translates to S_IFREG */
return 0;
case S_IFDIR:
return -EPERM;
default:
return -EINVAL;
}
}
SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, int, mode,
unsigned, dev)
{
int error;
char *tmp;
struct dentry *dentry;
struct nameidata nd;
if (S_ISDIR(mode))
return -EPERM;
error = user_path_parent(dfd, filename, &nd, &tmp);
if (error)
return error;
dentry = lookup_create(&nd, 0);
if (IS_ERR(dentry)) {
error = PTR_ERR(dentry);
goto out_unlock;
}
if (!IS_POSIXACL(nd.path.dentry->d_inode))
mode &= ~current_umask();
error = may_mknod(mode);
if (error)
goto out_dput;
error = mnt_want_write(nd.path.mnt);
if (error)
goto out_dput;
error = security_path_mknod(&nd.path, dentry, mode, dev);
if (error)
goto out_drop_write;
switch (mode & S_IFMT) {
case 0: case S_IFREG:
error = vfs_create(nd.path.dentry->d_inode,dentry,mode,&nd);
break;
case S_IFCHR: case S_IFBLK:
error = vfs_mknod(nd.path.dentry->d_inode,dentry,mode,
new_decode_dev(dev));
break;
case S_IFIFO: case S_IFSOCK:
error = vfs_mknod(nd.path.dentry->d_inode,dentry,mode,0);
break;
}
out_drop_write:
mnt_drop_write(nd.path.mnt);
out_dput:
dput(dentry);
out_unlock:
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
path_put(&nd.path);
putname(tmp);
return error;
}
SYSCALL_DEFINE3(mknod, const char __user *, filename, int, mode, unsigned, dev)
{
return sys_mknodat(AT_FDCWD, filename, mode, dev);
}
int vfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
{
int error = may_create(dir, dentry);
if (error)
return error;
if (!dir->i_op->mkdir)
return -EPERM;
mode &= (S_IRWXUGO|S_ISVTX);
error = security_inode_mkdir(dir, dentry, mode);
if (error)
return error;
vfs_dq_init(dir);
error = dir->i_op->mkdir(dir, dentry, mode);
if (!error)
fsnotify_mkdir(dir, dentry);
return error;
}
SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, int, mode)
{
int error = 0;
char * tmp;
struct dentry *dentry;
struct nameidata nd;
error = user_path_parent(dfd, pathname, &nd, &tmp);
if (error)
goto out_err;
dentry = lookup_create(&nd, 1);
error = PTR_ERR(dentry);
if (IS_ERR(dentry))
goto out_unlock;
if (!IS_POSIXACL(nd.path.dentry->d_inode))
mode &= ~current_umask();
error = mnt_want_write(nd.path.mnt);
if (error)
goto out_dput;
error = security_path_mkdir(&nd.path, dentry, mode);
if (error)
goto out_drop_write;
error = vfs_mkdir(nd.path.dentry->d_inode, dentry, mode);
out_drop_write:
mnt_drop_write(nd.path.mnt);
out_dput:
dput(dentry);
out_unlock:
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
path_put(&nd.path);
putname(tmp);
out_err:
return error;
}
SYSCALL_DEFINE2(mkdir, const char __user *, pathname, int, mode)
{
return sys_mkdirat(AT_FDCWD, pathname, mode);
}
/*
* We try to drop the dentry early: we should have
* a usage count of 2 if we're the only user of this
* dentry, and if that is true (possibly after pruning
* the dcache), then we drop the dentry now.
*
* A low-level filesystem can, if it choses, legally
* do a
*
* if (!d_unhashed(dentry))
* return -EBUSY;
*
* if it cannot handle the case of removing a directory
* that is still in use by something else..
*/
void dentry_unhash(struct dentry *dentry)
{
dget(dentry);
shrink_dcache_parent(dentry);
spin_lock(&dcache_lock);
spin_lock(&dentry->d_lock);
if (atomic_read(&dentry->d_count) == 2)
__d_drop(dentry);
spin_unlock(&dentry->d_lock);
spin_unlock(&dcache_lock);
}
int vfs_rmdir(struct inode *dir, struct dentry *dentry)
{
int error = may_delete(dir, dentry, 1);
if (error)
return error;
if (!dir->i_op->rmdir)
return -EPERM;
vfs_dq_init(dir);
mutex_lock(&dentry->d_inode->i_mutex);
dentry_unhash(dentry);
if (d_mountpoint(dentry))
error = -EBUSY;
else {
error = security_inode_rmdir(dir, dentry);
if (!error) {
error = dir->i_op->rmdir(dir, dentry);
if (!error)
dentry->d_inode->i_flags |= S_DEAD;
}
}
mutex_unlock(&dentry->d_inode->i_mutex);
if (!error) {
d_delete(dentry);
}
dput(dentry);
return error;
}
static long do_rmdir(int dfd, const char __user *pathname)
{
int error = 0;
char * name;
struct dentry *dentry;
struct nameidata nd;
error = user_path_parent(dfd, pathname, &nd, &name);
if (error)
return error;
switch(nd.last_type) {
case LAST_DOTDOT:
error = -ENOTEMPTY;
goto exit1;
case LAST_DOT:
error = -EINVAL;
goto exit1;
case LAST_ROOT:
error = -EBUSY;
goto exit1;
}
nd.flags &= ~LOOKUP_PARENT;
mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
dentry = lookup_hash(&nd);
error = PTR_ERR(dentry);
if (IS_ERR(dentry))
goto exit2;
error = mnt_want_write(nd.path.mnt);
if (error)
goto exit3;
error = security_path_rmdir(&nd.path, dentry);
if (error)
goto exit4;
error = vfs_rmdir(nd.path.dentry->d_inode, dentry);
exit4:
mnt_drop_write(nd.path.mnt);
exit3:
dput(dentry);
exit2:
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
exit1:
path_put(&nd.path);
putname(name);
return error;
}
SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
{
return do_rmdir(AT_FDCWD, pathname);
}
int vfs_unlink(struct inode *dir, struct dentry *dentry)
{
int error = may_delete(dir, dentry, 0);
if (error)
return error;
if (!dir->i_op->unlink)
return -EPERM;
vfs_dq_init(dir);
mutex_lock(&dentry->d_inode->i_mutex);
if (d_mountpoint(dentry))
error = -EBUSY;
else {
error = security_inode_unlink(dir, dentry);
if (!error)
error = dir->i_op->unlink(dir, dentry);
}
mutex_unlock(&dentry->d_inode->i_mutex);
/* We don't d_delete() NFS sillyrenamed files--they still exist. */
if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) {
fsnotify_link_count(dentry->d_inode);
d_delete(dentry);
}
return error;
}
/*
* Make sure that the actual truncation of the file will occur outside its
* directory's i_mutex. Truncate can take a long time if there is a lot of
* writeout happening, and we don't want to prevent access to the directory
* while waiting on the I/O.
*/
static long do_unlinkat(int dfd, const char __user *pathname)
{
int error;
char *name;
struct dentry *dentry;
struct nameidata nd;
struct inode *inode = NULL;
error = user_path_parent(dfd, pathname, &nd, &name);
if (error)
return error;
error = -EISDIR;
if (nd.last_type != LAST_NORM)
goto exit1;
nd.flags &= ~LOOKUP_PARENT;
mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
dentry = lookup_hash(&nd);
error = PTR_ERR(dentry);
if (!IS_ERR(dentry)) {
/* Why not before? Because we want correct error value */
if (nd.last.name[nd.last.len])
goto slashes;
inode = dentry->d_inode;
if (inode)
atomic_inc(&inode->i_count);
error = mnt_want_write(nd.path.mnt);
if (error)
goto exit2;
error = security_path_unlink(&nd.path, dentry);
if (error)
goto exit3;
error = vfs_unlink(nd.path.dentry->d_inode, dentry);
exit3:
mnt_drop_write(nd.path.mnt);
exit2:
dput(dentry);
}
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
if (inode)
iput(inode); /* truncate the inode here */
exit1:
path_put(&nd.path);
putname(name);
return error;
slashes:
error = !dentry->d_inode ? -ENOENT :
S_ISDIR(dentry->d_inode->i_mode) ? -EISDIR : -ENOTDIR;
goto exit2;
}
SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
{
if ((flag & ~AT_REMOVEDIR) != 0)
return -EINVAL;
if (flag & AT_REMOVEDIR)
return do_rmdir(dfd, pathname);
return do_unlinkat(dfd, pathname);
}
SYSCALL_DEFINE1(unlink, const char __user *, pathname)
{
return do_unlinkat(AT_FDCWD, pathname);
}
int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname)
{
int error = may_create(dir, dentry);
if (error)
return error;
if (!dir->i_op->symlink)
return -EPERM;
error = security_inode_symlink(dir, dentry, oldname);
if (error)
return error;
vfs_dq_init(dir);
error = dir->i_op->symlink(dir, dentry, oldname);
if (!error)
fsnotify_create(dir, dentry);
return error;
}
SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
int, newdfd, const char __user *, newname)
{
int error;
char *from;
char *to;
struct dentry *dentry;
struct nameidata nd;
from = getname(oldname);
if (IS_ERR(from))
return PTR_ERR(from);
error = user_path_parent(newdfd, newname, &nd, &to);
if (error)
goto out_putname;
dentry = lookup_create(&nd, 0);
error = PTR_ERR(dentry);
if (IS_ERR(dentry))
goto out_unlock;
error = mnt_want_write(nd.path.mnt);
if (error)
goto out_dput;
error = security_path_symlink(&nd.path, dentry, from);
if (error)
goto out_drop_write;
error = vfs_symlink(nd.path.dentry->d_inode, dentry, from);
out_drop_write:
mnt_drop_write(nd.path.mnt);
out_dput:
dput(dentry);
out_unlock:
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
path_put(&nd.path);
putname(to);
out_putname:
putname(from);
return error;
}
SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
{
return sys_symlinkat(oldname, AT_FDCWD, newname);
}
int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
{
struct inode *inode = old_dentry->d_inode;
int error;
if (!inode)
return -ENOENT;
error = may_create(dir, new_dentry);
if (error)
return error;
if (dir->i_sb != inode->i_sb)
return -EXDEV;
/*
* A link to an append-only or immutable file cannot be created.
*/
if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
return -EPERM;
if (!dir->i_op->link)
return -EPERM;
if (S_ISDIR(inode->i_mode))
return -EPERM;
error = security_inode_link(old_dentry, dir, new_dentry);
if (error)
return error;
mutex_lock(&inode->i_mutex);
vfs_dq_init(dir);
error = dir->i_op->link(old_dentry, dir, new_dentry);
mutex_unlock(&inode->i_mutex);
if (!error)
fsnotify_link(dir, inode, new_dentry);
return error;
}
/*
* Hardlinks are often used in delicate situations. We avoid
* security-related surprises by not following symlinks on the
* newname. --KAB
*
* We don't follow them on the oldname either to be compatible
* with linux 2.0, and to avoid hard-linking to directories
* and other special files. --ADM
*/
SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
int, newdfd, const char __user *, newname, int, flags)
{
struct dentry *new_dentry;
struct nameidata nd;
struct path old_path;
int error;
char *to;
if ((flags & ~AT_SYMLINK_FOLLOW) != 0)
return -EINVAL;
error = user_path_at(olddfd, oldname,
flags & AT_SYMLINK_FOLLOW ? LOOKUP_FOLLOW : 0,
&old_path);
if (error)
return error;
error = user_path_parent(newdfd, newname, &nd, &to);
if (error)
goto out;
error = -EXDEV;
if (old_path.mnt != nd.path.mnt)
goto out_release;
new_dentry = lookup_create(&nd, 0);
error = PTR_ERR(new_dentry);
if (IS_ERR(new_dentry))
goto out_unlock;
error = mnt_want_write(nd.path.mnt);
if (error)
goto out_dput;
error = security_path_link(old_path.dentry, &nd.path, new_dentry);
if (error)
goto out_drop_write;
error = vfs_link(old_path.dentry, nd.path.dentry->d_inode, new_dentry);
out_drop_write:
mnt_drop_write(nd.path.mnt);
out_dput:
dput(new_dentry);
out_unlock:
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
out_release:
path_put(&nd.path);
putname(to);
out:
path_put(&old_path);
return error;
}
SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
{
return sys_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
}
/*
* The worst of all namespace operations - renaming directory. "Perverted"
* doesn't even start to describe it. Somebody in UCB had a heck of a trip...
* Problems:
* a) we can get into loop creation. Check is done in is_subdir().
* b) race potential - two innocent renames can create a loop together.
* That's where 4.4 screws up. Current fix: serialization on
* sb->s_vfs_rename_mutex. We might be more accurate, but that's another
* story.
* c) we have to lock _three_ objects - parents and victim (if it exists).
* And that - after we got ->i_mutex on parents (until then we don't know
* whether the target exists). Solution: try to be smart with locking
* order for inodes. We rely on the fact that tree topology may change
* only under ->s_vfs_rename_mutex _and_ that parent of the object we
* move will be locked. Thus we can rank directories by the tree
* (ancestors first) and rank all non-directories after them.
* That works since everybody except rename does "lock parent, lookup,
* lock child" and rename is under ->s_vfs_rename_mutex.
* HOWEVER, it relies on the assumption that any object with ->lookup()
* has no more than 1 dentry. If "hybrid" objects will ever appear,
* we'd better make sure that there's no link(2) for them.
* d) some filesystems don't support opened-but-unlinked directories,
* either because of layout or because they are not ready to deal with
* all cases correctly. The latter will be fixed (taking this sort of
* stuff into VFS), but the former is not going away. Solution: the same
* trick as in rmdir().
* e) conversion from fhandle to dentry may come in the wrong moment - when
* we are removing the target. Solution: we will have to grab ->i_mutex
* in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
* ->i_mutex on parents, which works but leads to some truely excessive
* locking].
*/
static int vfs_rename_dir(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
int error = 0;
struct inode *target;
/*
* If we are going to change the parent - check write permissions,
* we'll need to flip '..'.
*/
if (new_dir != old_dir) {
error = inode_permission(old_dentry->d_inode, MAY_WRITE);
if (error)
return error;
}
error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry);
if (error)
return error;
target = new_dentry->d_inode;
if (target) {
mutex_lock(&target->i_mutex);
dentry_unhash(new_dentry);
}
if (d_mountpoint(old_dentry)||d_mountpoint(new_dentry))
error = -EBUSY;
else
error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry);
if (target) {
if (!error)
target->i_flags |= S_DEAD;
mutex_unlock(&target->i_mutex);
if (d_unhashed(new_dentry))
d_rehash(new_dentry);
dput(new_dentry);
}
if (!error)
if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE))
d_move(old_dentry,new_dentry);
return error;
}
static int vfs_rename_other(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
struct inode *target;
int error;
error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry);
if (error)
return error;
dget(new_dentry);
target = new_dentry->d_inode;
if (target)
mutex_lock(&target->i_mutex);
if (d_mountpoint(old_dentry)||d_mountpoint(new_dentry))
error = -EBUSY;
else
error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry);
if (!error) {
if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE))
d_move(old_dentry, new_dentry);
}
if (target)
mutex_unlock(&target->i_mutex);
dput(new_dentry);
return error;
}
int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
int error;
int is_dir = S_ISDIR(old_dentry->d_inode->i_mode);
const char *old_name;
if (old_dentry->d_inode == new_dentry->d_inode)
return 0;
error = may_delete(old_dir, old_dentry, is_dir);
if (error)
return error;
if (!new_dentry->d_inode)
error = may_create(new_dir, new_dentry);
else
error = may_delete(new_dir, new_dentry, is_dir);
if (error)
return error;
if (!old_dir->i_op->rename)
return -EPERM;
vfs_dq_init(old_dir);
vfs_dq_init(new_dir);
old_name = fsnotify_oldname_init(old_dentry->d_name.name);
if (is_dir)
error = vfs_rename_dir(old_dir,old_dentry,new_dir,new_dentry);
else
error = vfs_rename_other(old_dir,old_dentry,new_dir,new_dentry);
if (!error) {
const char *new_name = old_dentry->d_name.name;
fsnotify_move(old_dir, new_dir, old_name, new_name, is_dir,
new_dentry->d_inode, old_dentry);
}
fsnotify_oldname_free(old_name);
return error;
}
SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
int, newdfd, const char __user *, newname)
{
struct dentry *old_dir, *new_dir;
struct dentry *old_dentry, *new_dentry;
struct dentry *trap;
struct nameidata oldnd, newnd;
char *from;
char *to;
int error;
error = user_path_parent(olddfd, oldname, &oldnd, &from);
if (error)
goto exit;
error = user_path_parent(newdfd, newname, &newnd, &to);
if (error)
goto exit1;
error = -EXDEV;
if (oldnd.path.mnt != newnd.path.mnt)
goto exit2;
old_dir = oldnd.path.dentry;
error = -EBUSY;
if (oldnd.last_type != LAST_NORM)
goto exit2;
new_dir = newnd.path.dentry;
if (newnd.last_type != LAST_NORM)
goto exit2;
oldnd.flags &= ~LOOKUP_PARENT;
newnd.flags &= ~LOOKUP_PARENT;
newnd.flags |= LOOKUP_RENAME_TARGET;
trap = lock_rename(new_dir, old_dir);
old_dentry = lookup_hash(&oldnd);
error = PTR_ERR(old_dentry);
if (IS_ERR(old_dentry))
goto exit3;
/* source must exist */
error = -ENOENT;
if (!old_dentry->d_inode)
goto exit4;
/* unless the source is a directory trailing slashes give -ENOTDIR */
if (!S_ISDIR(old_dentry->d_inode->i_mode)) {
error = -ENOTDIR;
if (oldnd.last.name[oldnd.last.len])
goto exit4;
if (newnd.last.name[newnd.last.len])
goto exit4;
}
/* source should not be ancestor of target */
error = -EINVAL;
if (old_dentry == trap)
goto exit4;
new_dentry = lookup_hash(&newnd);
error = PTR_ERR(new_dentry);
if (IS_ERR(new_dentry))
goto exit4;
/* target should not be an ancestor of source */
error = -ENOTEMPTY;
if (new_dentry == trap)
goto exit5;
error = mnt_want_write(oldnd.path.mnt);
if (error)
goto exit5;
error = security_path_rename(&oldnd.path, old_dentry,
&newnd.path, new_dentry);
if (error)
goto exit6;
error = vfs_rename(old_dir->d_inode, old_dentry,
new_dir->d_inode, new_dentry);
exit6:
mnt_drop_write(oldnd.path.mnt);
exit5:
dput(new_dentry);
exit4:
dput(old_dentry);
exit3:
unlock_rename(new_dir, old_dir);
exit2:
path_put(&newnd.path);
putname(to);
exit1:
path_put(&oldnd.path);
putname(from);
exit:
return error;
}
SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
{
return sys_renameat(AT_FDCWD, oldname, AT_FDCWD, newname);
}
int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen, const char *link)
{
int len;
len = PTR_ERR(link);
if (IS_ERR(link))
goto out;
len = strlen(link);
if (len > (unsigned) buflen)
len = buflen;
if (copy_to_user(buffer, link, len))
len = -EFAULT;
out:
return len;
}
/*
* A helper for ->readlink(). This should be used *ONLY* for symlinks that
* have ->follow_link() touching nd only in nd_set_link(). Using (or not
* using) it for any given inode is up to filesystem.
*/
int generic_readlink(struct dentry *dentry, char __user *buffer, int buflen)
{
struct nameidata nd;
void *cookie;
int res;
nd.depth = 0;
cookie = dentry->d_inode->i_op->follow_link(dentry, &nd);
if (IS_ERR(cookie))
return PTR_ERR(cookie);
res = vfs_readlink(dentry, buffer, buflen, nd_get_link(&nd));
if (dentry->d_inode->i_op->put_link)
dentry->d_inode->i_op->put_link(dentry, &nd, cookie);
return res;
}
int vfs_follow_link(struct nameidata *nd, const char *link)
{
return __vfs_follow_link(nd, link);
}
/* get the link contents into pagecache */
static char *page_getlink(struct dentry * dentry, struct page **ppage)
{
char *kaddr;
struct page *page;
struct address_space *mapping = dentry->d_inode->i_mapping;
page = read_mapping_page(mapping, 0, NULL);
if (IS_ERR(page))
return (char*)page;
*ppage = page;
kaddr = kmap(page);
nd_terminate_link(kaddr, dentry->d_inode->i_size, PAGE_SIZE - 1);
return kaddr;
}
int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
{
struct page *page = NULL;
char *s = page_getlink(dentry, &page);
int res = vfs_readlink(dentry,buffer,buflen,s);
if (page) {
kunmap(page);
page_cache_release(page);
}
return res;
}
void *page_follow_link_light(struct dentry *dentry, struct nameidata *nd)
{
struct page *page = NULL;
nd_set_link(nd, page_getlink(dentry, &page));
return page;
}
void page_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie)
{
struct page *page = cookie;
if (page) {
kunmap(page);
page_cache_release(page);
}
}
/*
* The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
*/
int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
{
struct address_space *mapping = inode->i_mapping;
struct page *page;
void *fsdata;
int err;
char *kaddr;
unsigned int flags = AOP_FLAG_UNINTERRUPTIBLE;
if (nofs)
flags |= AOP_FLAG_NOFS;
retry:
err = pagecache_write_begin(NULL, mapping, 0, len-1,
flags, &page, &fsdata);
if (err)
goto fail;
kaddr = kmap_atomic(page, KM_USER0);
memcpy(kaddr, symname, len-1);
kunmap_atomic(kaddr, KM_USER0);
err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
page, fsdata);
if (err < 0)
goto fail;
if (err < len-1)
goto retry;
mark_inode_dirty(inode);
return 0;
fail:
return err;
}
int page_symlink(struct inode *inode, const char *symname, int len)
{
return __page_symlink(inode, symname, len,
!(mapping_gfp_mask(inode->i_mapping) & __GFP_FS));
}
const struct inode_operations page_symlink_inode_operations = {
.readlink = generic_readlink,
.follow_link = page_follow_link_light,
.put_link = page_put_link,
};
EXPORT_SYMBOL(user_path_at);
EXPORT_SYMBOL(follow_down);
EXPORT_SYMBOL(follow_up);
EXPORT_SYMBOL(get_write_access); /* binfmt_aout */
EXPORT_SYMBOL(getname);
EXPORT_SYMBOL(lock_rename);
EXPORT_SYMBOL(lookup_one_len);
EXPORT_SYMBOL(page_follow_link_light);
EXPORT_SYMBOL(page_put_link);
EXPORT_SYMBOL(page_readlink);
EXPORT_SYMBOL(__page_symlink);
EXPORT_SYMBOL(page_symlink);
EXPORT_SYMBOL(page_symlink_inode_operations);
EXPORT_SYMBOL(path_lookup);
EXPORT_SYMBOL(kern_path);
EXPORT_SYMBOL(vfs_path_lookup);
EXPORT_SYMBOL(inode_permission);
EXPORT_SYMBOL(file_permission);
EXPORT_SYMBOL(unlock_rename);
EXPORT_SYMBOL(vfs_create);
EXPORT_SYMBOL(vfs_follow_link);
EXPORT_SYMBOL(vfs_link);
EXPORT_SYMBOL(vfs_mkdir);
EXPORT_SYMBOL(vfs_mknod);
EXPORT_SYMBOL(generic_permission);
EXPORT_SYMBOL(vfs_readlink);
EXPORT_SYMBOL(vfs_rename);
EXPORT_SYMBOL(vfs_rmdir);
EXPORT_SYMBOL(vfs_symlink);
EXPORT_SYMBOL(vfs_unlink);
EXPORT_SYMBOL(dentry_unhash);
EXPORT_SYMBOL(generic_readlink);
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2035_0 |
crossvul-cpp_data_bad_2802_1 | /* nautilus-file-operations.c - Nautilus file operations.
*
* Copyright (C) 1999, 2000 Free Software Foundation
* Copyright (C) 2000, 2001 Eazel, Inc.
* Copyright (C) 2007 Red Hat, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, see <http://www.gnu.org/licenses/>.
*
* Authors: Alexander Larsson <alexl@redhat.com>
* Ettore Perazzoli <ettore@gnu.org>
* Pavel Cisler <pavel@eazel.com>
*/
#include <config.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <locale.h>
#include <math.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include "nautilus-file-operations.h"
#include "nautilus-file-changes-queue.h"
#include "nautilus-lib-self-check-functions.h"
#include "nautilus-progress-info.h"
#include <eel/eel-glib-extensions.h>
#include <eel/eel-gtk-extensions.h>
#include <eel/eel-stock-dialogs.h>
#include <eel/eel-vfs-extensions.h>
#include <glib/gi18n.h>
#include <glib/gstdio.h>
#include <gdk/gdk.h>
#include <gtk/gtk.h>
#include <gio/gio.h>
#include <glib.h>
#include "nautilus-operations-ui-manager.h"
#include "nautilus-file-changes-queue.h"
#include "nautilus-file-private.h"
#include "nautilus-global-preferences.h"
#include "nautilus-link.h"
#include "nautilus-trash-monitor.h"
#include "nautilus-file-utilities.h"
#include "nautilus-file-undo-operations.h"
#include "nautilus-file-undo-manager.h"
/* TODO: TESTING!!! */
typedef struct
{
GTimer *time;
GtkWindow *parent_window;
int screen_num;
guint inhibit_cookie;
NautilusProgressInfo *progress;
GCancellable *cancellable;
GHashTable *skip_files;
GHashTable *skip_readdir_error;
NautilusFileUndoInfo *undo_info;
gboolean skip_all_error;
gboolean skip_all_conflict;
gboolean merge_all;
gboolean replace_all;
gboolean delete_all;
} CommonJob;
typedef struct
{
CommonJob common;
gboolean is_move;
GList *files;
GFile *destination;
GFile *desktop_location;
GFile *fake_display_source;
GdkPoint *icon_positions;
int n_icon_positions;
GHashTable *debuting_files;
gchar *target_name;
NautilusCopyCallback done_callback;
gpointer done_callback_data;
} CopyMoveJob;
typedef struct
{
CommonJob common;
GList *files;
gboolean try_trash;
gboolean user_cancel;
NautilusDeleteCallback done_callback;
gpointer done_callback_data;
} DeleteJob;
typedef struct
{
CommonJob common;
GFile *dest_dir;
char *filename;
gboolean make_dir;
GFile *src;
char *src_data;
int length;
GdkPoint position;
gboolean has_position;
GFile *created_file;
NautilusCreateCallback done_callback;
gpointer done_callback_data;
} CreateJob;
typedef struct
{
CommonJob common;
GList *trash_dirs;
gboolean should_confirm;
NautilusOpCallback done_callback;
gpointer done_callback_data;
} EmptyTrashJob;
typedef struct
{
CommonJob common;
GFile *file;
gboolean interactive;
NautilusOpCallback done_callback;
gpointer done_callback_data;
} MarkTrustedJob;
typedef struct
{
CommonJob common;
GFile *file;
NautilusOpCallback done_callback;
gpointer done_callback_data;
guint32 file_permissions;
guint32 file_mask;
guint32 dir_permissions;
guint32 dir_mask;
} SetPermissionsJob;
typedef enum
{
OP_KIND_COPY,
OP_KIND_MOVE,
OP_KIND_DELETE,
OP_KIND_TRASH,
OP_KIND_COMPRESS
} OpKind;
typedef struct
{
int num_files;
goffset num_bytes;
int num_files_since_progress;
OpKind op;
} SourceInfo;
typedef struct
{
int num_files;
goffset num_bytes;
OpKind op;
guint64 last_report_time;
int last_reported_files_left;
} TransferInfo;
typedef struct
{
CommonJob common;
GList *source_files;
GFile *destination_directory;
GList *output_files;
gdouble base_progress;
guint64 archive_compressed_size;
guint64 total_compressed_size;
NautilusExtractCallback done_callback;
gpointer done_callback_data;
} ExtractJob;
typedef struct
{
CommonJob common;
GList *source_files;
GFile *output_file;
AutoarFormat format;
AutoarFilter filter;
guint64 total_size;
guint total_files;
gboolean success;
NautilusCreateCallback done_callback;
gpointer done_callback_data;
} CompressJob;
#define SECONDS_NEEDED_FOR_RELIABLE_TRANSFER_RATE 8
#define NSEC_PER_MICROSEC 1000
#define PROGRESS_NOTIFY_INTERVAL 100 * NSEC_PER_MICROSEC
#define MAXIMUM_DISPLAYED_FILE_NAME_LENGTH 50
#define IS_IO_ERROR(__error, KIND) (((__error)->domain == G_IO_ERROR && (__error)->code == G_IO_ERROR_ ## KIND))
#define CANCEL _("_Cancel")
#define SKIP _("_Skip")
#define SKIP_ALL _("S_kip All")
#define RETRY _("_Retry")
#define DELETE _("_Delete")
#define DELETE_ALL _("Delete _All")
#define REPLACE _("_Replace")
#define REPLACE_ALL _("Replace _All")
#define MERGE _("_Merge")
#define MERGE_ALL _("Merge _All")
#define COPY_FORCE _("Copy _Anyway")
static void
mark_desktop_file_trusted (CommonJob *common,
GCancellable *cancellable,
GFile *file,
gboolean interactive);
static gboolean
is_all_button_text (const char *button_text)
{
g_assert (button_text != NULL);
return !strcmp (button_text, SKIP_ALL) ||
!strcmp (button_text, REPLACE_ALL) ||
!strcmp (button_text, DELETE_ALL) ||
!strcmp (button_text, MERGE_ALL);
}
static void scan_sources (GList *files,
SourceInfo *source_info,
CommonJob *job,
OpKind kind);
static void empty_trash_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable);
static void empty_trash_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data);
static char *query_fs_type (GFile *file,
GCancellable *cancellable);
/* keep in time with format_time()
*
* This counts and outputs the number of “time units”
* formatted and displayed by format_time().
* For instance, if format_time outputs “3 hours, 4 minutes”
* it yields 7.
*/
static int
seconds_count_format_time_units (int seconds)
{
int minutes;
int hours;
if (seconds < 0)
{
/* Just to make sure... */
seconds = 0;
}
if (seconds < 60)
{
/* seconds */
return seconds;
}
if (seconds < 60 * 60)
{
/* minutes */
minutes = seconds / 60;
return minutes;
}
hours = seconds / (60 * 60);
if (seconds < 60 * 60 * 4)
{
/* minutes + hours */
minutes = (seconds - hours * 60 * 60) / 60;
return minutes + hours;
}
return hours;
}
static char *
format_time (int seconds)
{
int minutes;
int hours;
char *res;
if (seconds < 0)
{
/* Just to make sure... */
seconds = 0;
}
if (seconds < 60)
{
return g_strdup_printf (ngettext ("%'d second", "%'d seconds", (int) seconds), (int) seconds);
}
if (seconds < 60 * 60)
{
minutes = seconds / 60;
return g_strdup_printf (ngettext ("%'d minute", "%'d minutes", minutes), minutes);
}
hours = seconds / (60 * 60);
if (seconds < 60 * 60 * 4)
{
char *h, *m;
minutes = (seconds - hours * 60 * 60) / 60;
h = g_strdup_printf (ngettext ("%'d hour", "%'d hours", hours), hours);
m = g_strdup_printf (ngettext ("%'d minute", "%'d minutes", minutes), minutes);
res = g_strconcat (h, ", ", m, NULL);
g_free (h);
g_free (m);
return res;
}
return g_strdup_printf (ngettext ("approximately %'d hour",
"approximately %'d hours",
hours), hours);
}
static char *
shorten_utf8_string (const char *base,
int reduce_by_num_bytes)
{
int len;
char *ret;
const char *p;
len = strlen (base);
len -= reduce_by_num_bytes;
if (len <= 0)
{
return NULL;
}
ret = g_new (char, len + 1);
p = base;
while (len)
{
char *next;
next = g_utf8_next_char (p);
if (next - p > len || *next == '\0')
{
break;
}
len -= next - p;
p = next;
}
if (p - base == 0)
{
g_free (ret);
return NULL;
}
else
{
memcpy (ret, base, p - base);
ret[p - base] = '\0';
return ret;
}
}
/* Note that we have these two separate functions with separate format
* strings for ease of localization.
*/
static char *
get_link_name (const char *name,
int count,
int max_length)
{
const char *format;
char *result;
int unshortened_length;
gboolean use_count;
g_assert (name != NULL);
if (count < 0)
{
g_warning ("bad count in get_link_name");
count = 0;
}
if (count <= 2)
{
/* Handle special cases for low numbers.
* Perhaps for some locales we will need to add more.
*/
switch (count)
{
default:
{
g_assert_not_reached ();
/* fall through */
}
case 0:
{
/* duplicate original file name */
format = "%s";
}
break;
case 1:
{
/* appended to new link file */
format = _("Link to %s");
}
break;
case 2:
{
/* appended to new link file */
format = _("Another link to %s");
}
break;
}
use_count = FALSE;
}
else
{
/* Handle special cases for the first few numbers of each ten.
* For locales where getting this exactly right is difficult,
* these can just be made all the same as the general case below.
*/
switch (count % 10)
{
case 1:
{
/* Localizers: Feel free to leave out the "st" suffix
* if there's no way to do that nicely for a
* particular language.
*/
format = _("%'dst link to %s");
}
break;
case 2:
{
/* appended to new link file */
format = _("%'dnd link to %s");
}
break;
case 3:
{
/* appended to new link file */
format = _("%'drd link to %s");
}
break;
default:
{
/* appended to new link file */
format = _("%'dth link to %s");
}
break;
}
use_count = TRUE;
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
if (use_count)
{
result = g_strdup_printf (format, count, name);
}
else
{
result = g_strdup_printf (format, name);
}
if (max_length > 0 && (unshortened_length = strlen (result)) > max_length)
{
char *new_name;
new_name = shorten_utf8_string (name, unshortened_length - max_length);
if (new_name)
{
g_free (result);
if (use_count)
{
result = g_strdup_printf (format, count, new_name);
}
else
{
result = g_strdup_printf (format, new_name);
}
g_assert (strlen (result) <= max_length);
g_free (new_name);
}
}
#pragma GCC diagnostic pop
return result;
}
/* Localizers:
* Feel free to leave out the st, nd, rd and th suffix or
* make some or all of them match.
*/
/* localizers: tag used to detect the first copy of a file */
static const char untranslated_copy_duplicate_tag[] = N_(" (copy)");
/* localizers: tag used to detect the second copy of a file */
static const char untranslated_another_copy_duplicate_tag[] = N_(" (another copy)");
/* localizers: tag used to detect the x11th copy of a file */
static const char untranslated_x11th_copy_duplicate_tag[] = N_("th copy)");
/* localizers: tag used to detect the x12th copy of a file */
static const char untranslated_x12th_copy_duplicate_tag[] = N_("th copy)");
/* localizers: tag used to detect the x13th copy of a file */
static const char untranslated_x13th_copy_duplicate_tag[] = N_("th copy)");
/* localizers: tag used to detect the x1st copy of a file */
static const char untranslated_st_copy_duplicate_tag[] = N_("st copy)");
/* localizers: tag used to detect the x2nd copy of a file */
static const char untranslated_nd_copy_duplicate_tag[] = N_("nd copy)");
/* localizers: tag used to detect the x3rd copy of a file */
static const char untranslated_rd_copy_duplicate_tag[] = N_("rd copy)");
/* localizers: tag used to detect the xxth copy of a file */
static const char untranslated_th_copy_duplicate_tag[] = N_("th copy)");
#define COPY_DUPLICATE_TAG _(untranslated_copy_duplicate_tag)
#define ANOTHER_COPY_DUPLICATE_TAG _(untranslated_another_copy_duplicate_tag)
#define X11TH_COPY_DUPLICATE_TAG _(untranslated_x11th_copy_duplicate_tag)
#define X12TH_COPY_DUPLICATE_TAG _(untranslated_x12th_copy_duplicate_tag)
#define X13TH_COPY_DUPLICATE_TAG _(untranslated_x13th_copy_duplicate_tag)
#define ST_COPY_DUPLICATE_TAG _(untranslated_st_copy_duplicate_tag)
#define ND_COPY_DUPLICATE_TAG _(untranslated_nd_copy_duplicate_tag)
#define RD_COPY_DUPLICATE_TAG _(untranslated_rd_copy_duplicate_tag)
#define TH_COPY_DUPLICATE_TAG _(untranslated_th_copy_duplicate_tag)
/* localizers: appended to first file copy */
static const char untranslated_first_copy_duplicate_format[] = N_("%s (copy)%s");
/* localizers: appended to second file copy */
static const char untranslated_second_copy_duplicate_format[] = N_("%s (another copy)%s");
/* localizers: appended to x11th file copy */
static const char untranslated_x11th_copy_duplicate_format[] = N_("%s (%'dth copy)%s");
/* localizers: appended to x12th file copy */
static const char untranslated_x12th_copy_duplicate_format[] = N_("%s (%'dth copy)%s");
/* localizers: appended to x13th file copy */
static const char untranslated_x13th_copy_duplicate_format[] = N_("%s (%'dth copy)%s");
/* localizers: if in your language there's no difference between 1st, 2nd, 3rd and nth
* plurals, you can leave the st, nd, rd suffixes out and just make all the translated
* strings look like "%s (copy %'d)%s".
*/
/* localizers: appended to x1st file copy */
static const char untranslated_st_copy_duplicate_format[] = N_("%s (%'dst copy)%s");
/* localizers: appended to x2nd file copy */
static const char untranslated_nd_copy_duplicate_format[] = N_("%s (%'dnd copy)%s");
/* localizers: appended to x3rd file copy */
static const char untranslated_rd_copy_duplicate_format[] = N_("%s (%'drd copy)%s");
/* localizers: appended to xxth file copy */
static const char untranslated_th_copy_duplicate_format[] = N_("%s (%'dth copy)%s");
#define FIRST_COPY_DUPLICATE_FORMAT _(untranslated_first_copy_duplicate_format)
#define SECOND_COPY_DUPLICATE_FORMAT _(untranslated_second_copy_duplicate_format)
#define X11TH_COPY_DUPLICATE_FORMAT _(untranslated_x11th_copy_duplicate_format)
#define X12TH_COPY_DUPLICATE_FORMAT _(untranslated_x12th_copy_duplicate_format)
#define X13TH_COPY_DUPLICATE_FORMAT _(untranslated_x13th_copy_duplicate_format)
#define ST_COPY_DUPLICATE_FORMAT _(untranslated_st_copy_duplicate_format)
#define ND_COPY_DUPLICATE_FORMAT _(untranslated_nd_copy_duplicate_format)
#define RD_COPY_DUPLICATE_FORMAT _(untranslated_rd_copy_duplicate_format)
#define TH_COPY_DUPLICATE_FORMAT _(untranslated_th_copy_duplicate_format)
static char *
extract_string_until (const char *original,
const char *until_substring)
{
char *result;
g_assert ((int) strlen (original) >= until_substring - original);
g_assert (until_substring - original >= 0);
result = g_malloc (until_substring - original + 1);
strncpy (result, original, until_substring - original);
result[until_substring - original] = '\0';
return result;
}
/* Dismantle a file name, separating the base name, the file suffix and removing any
* (xxxcopy), etc. string. Figure out the count that corresponds to the given
* (xxxcopy) substring.
*/
static void
parse_previous_duplicate_name (const char *name,
char **name_base,
const char **suffix,
int *count)
{
const char *tag;
g_assert (name[0] != '\0');
*suffix = eel_filename_get_extension_offset (name);
if (*suffix == NULL || (*suffix)[1] == '\0')
{
/* no suffix */
*suffix = "";
}
tag = strstr (name, COPY_DUPLICATE_TAG);
if (tag != NULL)
{
if (tag > *suffix)
{
/* handle case "foo. (copy)" */
*suffix = "";
}
*name_base = extract_string_until (name, tag);
*count = 1;
return;
}
tag = strstr (name, ANOTHER_COPY_DUPLICATE_TAG);
if (tag != NULL)
{
if (tag > *suffix)
{
/* handle case "foo. (another copy)" */
*suffix = "";
}
*name_base = extract_string_until (name, tag);
*count = 2;
return;
}
/* Check to see if we got one of st, nd, rd, th. */
tag = strstr (name, X11TH_COPY_DUPLICATE_TAG);
if (tag == NULL)
{
tag = strstr (name, X12TH_COPY_DUPLICATE_TAG);
}
if (tag == NULL)
{
tag = strstr (name, X13TH_COPY_DUPLICATE_TAG);
}
if (tag == NULL)
{
tag = strstr (name, ST_COPY_DUPLICATE_TAG);
}
if (tag == NULL)
{
tag = strstr (name, ND_COPY_DUPLICATE_TAG);
}
if (tag == NULL)
{
tag = strstr (name, RD_COPY_DUPLICATE_TAG);
}
if (tag == NULL)
{
tag = strstr (name, TH_COPY_DUPLICATE_TAG);
}
/* If we got one of st, nd, rd, th, fish out the duplicate number. */
if (tag != NULL)
{
/* localizers: opening parentheses to match the "th copy)" string */
tag = strstr (name, _(" ("));
if (tag != NULL)
{
if (tag > *suffix)
{
/* handle case "foo. (22nd copy)" */
*suffix = "";
}
*name_base = extract_string_until (name, tag);
/* localizers: opening parentheses of the "th copy)" string */
if (sscanf (tag, _(" (%'d"), count) == 1)
{
if (*count < 1 || *count > 1000000)
{
/* keep the count within a reasonable range */
*count = 0;
}
return;
}
*count = 0;
return;
}
}
*count = 0;
if (**suffix != '\0')
{
*name_base = extract_string_until (name, *suffix);
}
else
{
*name_base = g_strdup (name);
}
}
static char *
make_next_duplicate_name (const char *base,
const char *suffix,
int count,
int max_length)
{
const char *format;
char *result;
int unshortened_length;
gboolean use_count;
if (count < 1)
{
g_warning ("bad count %d in get_duplicate_name", count);
count = 1;
}
if (count <= 2)
{
/* Handle special cases for low numbers.
* Perhaps for some locales we will need to add more.
*/
switch (count)
{
default:
{
g_assert_not_reached ();
/* fall through */
}
case 1:
{
format = FIRST_COPY_DUPLICATE_FORMAT;
}
break;
case 2:
{
format = SECOND_COPY_DUPLICATE_FORMAT;
}
break;
}
use_count = FALSE;
}
else
{
/* Handle special cases for the first few numbers of each ten.
* For locales where getting this exactly right is difficult,
* these can just be made all the same as the general case below.
*/
/* Handle special cases for x11th - x20th.
*/
switch (count % 100)
{
case 11:
{
format = X11TH_COPY_DUPLICATE_FORMAT;
}
break;
case 12:
{
format = X12TH_COPY_DUPLICATE_FORMAT;
}
break;
case 13:
{
format = X13TH_COPY_DUPLICATE_FORMAT;
}
break;
default:
{
format = NULL;
}
break;
}
if (format == NULL)
{
switch (count % 10)
{
case 1:
{
format = ST_COPY_DUPLICATE_FORMAT;
}
break;
case 2:
{
format = ND_COPY_DUPLICATE_FORMAT;
}
break;
case 3:
{
format = RD_COPY_DUPLICATE_FORMAT;
}
break;
default:
{
/* The general case. */
format = TH_COPY_DUPLICATE_FORMAT;
}
break;
}
}
use_count = TRUE;
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
if (use_count)
{
result = g_strdup_printf (format, base, count, suffix);
}
else
{
result = g_strdup_printf (format, base, suffix);
}
if (max_length > 0 && (unshortened_length = strlen (result)) > max_length)
{
char *new_base;
new_base = shorten_utf8_string (base, unshortened_length - max_length);
if (new_base)
{
g_free (result);
if (use_count)
{
result = g_strdup_printf (format, new_base, count, suffix);
}
else
{
result = g_strdup_printf (format, new_base, suffix);
}
g_assert (strlen (result) <= max_length);
g_free (new_base);
}
}
#pragma GCC diagnostic pop
return result;
}
static char *
get_duplicate_name (const char *name,
int count_increment,
int max_length)
{
char *result;
char *name_base;
const char *suffix;
int count;
parse_previous_duplicate_name (name, &name_base, &suffix, &count);
result = make_next_duplicate_name (name_base, suffix, count + count_increment, max_length);
g_free (name_base);
return result;
}
static gboolean
has_invalid_xml_char (char *str)
{
gunichar c;
while (*str != 0)
{
c = g_utf8_get_char (str);
/* characters XML permits */
if (!(c == 0x9 ||
c == 0xA ||
c == 0xD ||
(c >= 0x20 && c <= 0xD7FF) ||
(c >= 0xE000 && c <= 0xFFFD) ||
(c >= 0x10000 && c <= 0x10FFFF)))
{
return TRUE;
}
str = g_utf8_next_char (str);
}
return FALSE;
}
static char *
custom_full_name_to_string (char *format,
va_list va)
{
GFile *file;
file = va_arg (va, GFile *);
return g_file_get_parse_name (file);
}
static void
custom_full_name_skip (va_list *va)
{
(void) va_arg (*va, GFile *);
}
static char *
custom_basename_to_string (char *format,
va_list va)
{
GFile *file;
GFileInfo *info;
char *name, *basename, *tmp;
GMount *mount;
file = va_arg (va, GFile *);
if ((mount = nautilus_get_mounted_mount_for_root (file)) != NULL)
{
name = g_mount_get_name (mount);
g_object_unref (mount);
}
else
{
info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
0,
g_cancellable_get_current (),
NULL);
name = NULL;
if (info)
{
name = g_strdup (g_file_info_get_display_name (info));
g_object_unref (info);
}
}
if (name == NULL)
{
basename = g_file_get_basename (file);
if (g_utf8_validate (basename, -1, NULL))
{
name = basename;
}
else
{
name = g_uri_escape_string (basename, G_URI_RESERVED_CHARS_ALLOWED_IN_PATH, TRUE);
g_free (basename);
}
}
/* Some chars can't be put in the markup we use for the dialogs... */
if (has_invalid_xml_char (name))
{
tmp = name;
name = g_uri_escape_string (name, G_URI_RESERVED_CHARS_ALLOWED_IN_PATH, TRUE);
g_free (tmp);
}
/* Finally, if the string is too long, truncate it. */
if (name != NULL)
{
tmp = name;
name = eel_str_middle_truncate (tmp, MAXIMUM_DISPLAYED_FILE_NAME_LENGTH);
g_free (tmp);
}
return name;
}
static void
custom_basename_skip (va_list *va)
{
(void) va_arg (*va, GFile *);
}
static char *
custom_size_to_string (char *format,
va_list va)
{
goffset size;
size = va_arg (va, goffset);
return g_format_size (size);
}
static void
custom_size_skip (va_list *va)
{
(void) va_arg (*va, goffset);
}
static char *
custom_time_to_string (char *format,
va_list va)
{
int secs;
secs = va_arg (va, int);
return format_time (secs);
}
static void
custom_time_skip (va_list *va)
{
(void) va_arg (*va, int);
}
static char *
custom_mount_to_string (char *format,
va_list va)
{
GMount *mount;
mount = va_arg (va, GMount *);
return g_mount_get_name (mount);
}
static void
custom_mount_skip (va_list *va)
{
(void) va_arg (*va, GMount *);
}
static EelPrintfHandler handlers[] =
{
{ 'F', custom_full_name_to_string, custom_full_name_skip },
{ 'B', custom_basename_to_string, custom_basename_skip },
{ 'S', custom_size_to_string, custom_size_skip },
{ 'T', custom_time_to_string, custom_time_skip },
{ 'V', custom_mount_to_string, custom_mount_skip },
{ 0 }
};
static char *
f (const char *format,
...)
{
va_list va;
char *res;
va_start (va, format);
res = eel_strdup_vprintf_with_custom (handlers, format, va);
va_end (va);
return res;
}
#define op_job_new(__type, parent_window) ((__type *) (init_common (sizeof (__type), parent_window)))
static gpointer
init_common (gsize job_size,
GtkWindow *parent_window)
{
CommonJob *common;
GdkScreen *screen;
common = g_malloc0 (job_size);
if (parent_window)
{
common->parent_window = parent_window;
g_object_add_weak_pointer (G_OBJECT (common->parent_window),
(gpointer *) &common->parent_window);
}
common->progress = nautilus_progress_info_new ();
common->cancellable = nautilus_progress_info_get_cancellable (common->progress);
common->time = g_timer_new ();
common->inhibit_cookie = 0;
common->screen_num = 0;
if (parent_window)
{
screen = gtk_widget_get_screen (GTK_WIDGET (parent_window));
common->screen_num = gdk_screen_get_number (screen);
}
return common;
}
static void
finalize_common (CommonJob *common)
{
nautilus_progress_info_finish (common->progress);
if (common->inhibit_cookie != 0)
{
gtk_application_uninhibit (GTK_APPLICATION (g_application_get_default ()),
common->inhibit_cookie);
}
common->inhibit_cookie = 0;
g_timer_destroy (common->time);
if (common->parent_window)
{
g_object_remove_weak_pointer (G_OBJECT (common->parent_window),
(gpointer *) &common->parent_window);
}
if (common->skip_files)
{
g_hash_table_destroy (common->skip_files);
}
if (common->skip_readdir_error)
{
g_hash_table_destroy (common->skip_readdir_error);
}
if (common->undo_info != NULL)
{
nautilus_file_undo_manager_set_action (common->undo_info);
g_object_unref (common->undo_info);
}
g_object_unref (common->progress);
g_object_unref (common->cancellable);
g_free (common);
}
static void
skip_file (CommonJob *common,
GFile *file)
{
if (common->skip_files == NULL)
{
common->skip_files =
g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
}
g_hash_table_insert (common->skip_files, g_object_ref (file), file);
}
static void
skip_readdir_error (CommonJob *common,
GFile *dir)
{
if (common->skip_readdir_error == NULL)
{
common->skip_readdir_error =
g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
}
g_hash_table_insert (common->skip_readdir_error, g_object_ref (dir), dir);
}
static gboolean
should_skip_file (CommonJob *common,
GFile *file)
{
if (common->skip_files != NULL)
{
return g_hash_table_lookup (common->skip_files, file) != NULL;
}
return FALSE;
}
static gboolean
should_skip_readdir_error (CommonJob *common,
GFile *dir)
{
if (common->skip_readdir_error != NULL)
{
return g_hash_table_lookup (common->skip_readdir_error, dir) != NULL;
}
return FALSE;
}
static gboolean
can_delete_without_confirm (GFile *file)
{
if (g_file_has_uri_scheme (file, "burn") ||
g_file_has_uri_scheme (file, "recent") ||
g_file_has_uri_scheme (file, "x-nautilus-desktop"))
{
return TRUE;
}
return FALSE;
}
static gboolean
can_delete_files_without_confirm (GList *files)
{
g_assert (files != NULL);
while (files != NULL)
{
if (!can_delete_without_confirm (files->data))
{
return FALSE;
}
files = files->next;
}
return TRUE;
}
typedef struct
{
GtkWindow **parent_window;
gboolean ignore_close_box;
GtkMessageType message_type;
const char *primary_text;
const char *secondary_text;
const char *details_text;
const char **button_titles;
gboolean show_all;
int result;
/* Dialogs are ran from operation threads, which need to be blocked until
* the user gives a valid response
*/
gboolean completed;
GMutex mutex;
GCond cond;
} RunSimpleDialogData;
static gboolean
do_run_simple_dialog (gpointer _data)
{
RunSimpleDialogData *data = _data;
const char *button_title;
GtkWidget *dialog;
int result;
int response_id;
g_mutex_lock (&data->mutex);
/* Create the dialog. */
dialog = gtk_message_dialog_new (*data->parent_window,
0,
data->message_type,
GTK_BUTTONS_NONE,
NULL);
g_object_set (dialog,
"text", data->primary_text,
"secondary-text", data->secondary_text,
NULL);
for (response_id = 0;
data->button_titles[response_id] != NULL;
response_id++)
{
button_title = data->button_titles[response_id];
if (!data->show_all && is_all_button_text (button_title))
{
continue;
}
gtk_dialog_add_button (GTK_DIALOG (dialog), button_title, response_id);
gtk_dialog_set_default_response (GTK_DIALOG (dialog), response_id);
}
if (data->details_text)
{
eel_gtk_message_dialog_set_details_label (GTK_MESSAGE_DIALOG (dialog),
data->details_text);
}
/* Run it. */
result = gtk_dialog_run (GTK_DIALOG (dialog));
while ((result == GTK_RESPONSE_NONE || result == GTK_RESPONSE_DELETE_EVENT) && data->ignore_close_box)
{
result = gtk_dialog_run (GTK_DIALOG (dialog));
}
gtk_widget_destroy (dialog);
data->result = result;
data->completed = TRUE;
g_cond_signal (&data->cond);
g_mutex_unlock (&data->mutex);
return FALSE;
}
/* NOTE: This frees the primary / secondary strings, in order to
* avoid doing that everywhere. So, make sure they are strduped */
static int
run_simple_dialog_va (CommonJob *job,
gboolean ignore_close_box,
GtkMessageType message_type,
char *primary_text,
char *secondary_text,
const char *details_text,
gboolean show_all,
va_list varargs)
{
RunSimpleDialogData *data;
int res;
const char *button_title;
GPtrArray *ptr_array;
g_timer_stop (job->time);
data = g_new0 (RunSimpleDialogData, 1);
data->parent_window = &job->parent_window;
data->ignore_close_box = ignore_close_box;
data->message_type = message_type;
data->primary_text = primary_text;
data->secondary_text = secondary_text;
data->details_text = details_text;
data->show_all = show_all;
data->completed = FALSE;
g_mutex_init (&data->mutex);
g_cond_init (&data->cond);
ptr_array = g_ptr_array_new ();
while ((button_title = va_arg (varargs, const char *)) != NULL)
{
g_ptr_array_add (ptr_array, (char *) button_title);
}
g_ptr_array_add (ptr_array, NULL);
data->button_titles = (const char **) g_ptr_array_free (ptr_array, FALSE);
nautilus_progress_info_pause (job->progress);
g_mutex_lock (&data->mutex);
g_main_context_invoke (NULL,
do_run_simple_dialog,
data);
while (!data->completed)
{
g_cond_wait (&data->cond, &data->mutex);
}
nautilus_progress_info_resume (job->progress);
res = data->result;
g_mutex_unlock (&data->mutex);
g_mutex_clear (&data->mutex);
g_cond_clear (&data->cond);
g_free (data->button_titles);
g_free (data);
g_timer_continue (job->time);
g_free (primary_text);
g_free (secondary_text);
return res;
}
#if 0 /* Not used at the moment */
static int
run_simple_dialog (CommonJob *job,
gboolean ignore_close_box,
GtkMessageType message_type,
char *primary_text,
char *secondary_text,
const char *details_text,
...)
{
va_list varargs;
int res;
va_start (varargs, details_text);
res = run_simple_dialog_va (job,
ignore_close_box,
message_type,
primary_text,
secondary_text,
details_text,
varargs);
va_end (varargs);
return res;
}
#endif
static int
run_error (CommonJob *job,
char *primary_text,
char *secondary_text,
const char *details_text,
gboolean show_all,
...)
{
va_list varargs;
int res;
va_start (varargs, show_all);
res = run_simple_dialog_va (job,
FALSE,
GTK_MESSAGE_ERROR,
primary_text,
secondary_text,
details_text,
show_all,
varargs);
va_end (varargs);
return res;
}
static int
run_warning (CommonJob *job,
char *primary_text,
char *secondary_text,
const char *details_text,
gboolean show_all,
...)
{
va_list varargs;
int res;
va_start (varargs, show_all);
res = run_simple_dialog_va (job,
FALSE,
GTK_MESSAGE_WARNING,
primary_text,
secondary_text,
details_text,
show_all,
varargs);
va_end (varargs);
return res;
}
static int
run_question (CommonJob *job,
char *primary_text,
char *secondary_text,
const char *details_text,
gboolean show_all,
...)
{
va_list varargs;
int res;
va_start (varargs, show_all);
res = run_simple_dialog_va (job,
FALSE,
GTK_MESSAGE_QUESTION,
primary_text,
secondary_text,
details_text,
show_all,
varargs);
va_end (varargs);
return res;
}
static int
run_cancel_or_skip_warning (CommonJob *job,
char *primary_text,
char *secondary_text,
const char *details_text,
int total_operations,
int operations_remaining)
{
int response;
if (total_operations == 1)
{
response = run_warning (job,
primary_text,
secondary_text,
details_text,
FALSE,
CANCEL,
NULL);
}
else
{
response = run_warning (job,
primary_text,
secondary_text,
details_text,
operations_remaining > 1,
CANCEL, SKIP_ALL, SKIP,
NULL);
}
return response;
}
static void
inhibit_power_manager (CommonJob *job,
const char *message)
{
job->inhibit_cookie = gtk_application_inhibit (GTK_APPLICATION (g_application_get_default ()),
GTK_WINDOW (job->parent_window),
GTK_APPLICATION_INHIBIT_LOGOUT |
GTK_APPLICATION_INHIBIT_SUSPEND,
message);
}
static void
abort_job (CommonJob *job)
{
/* destroy the undo action data too */
g_clear_object (&job->undo_info);
g_cancellable_cancel (job->cancellable);
}
static gboolean
job_aborted (CommonJob *job)
{
return g_cancellable_is_cancelled (job->cancellable);
}
/* Since this happens on a thread we can't use the global prefs object */
static gboolean
should_confirm_trash (void)
{
GSettings *prefs;
gboolean confirm_trash;
prefs = g_settings_new ("org.gnome.nautilus.preferences");
confirm_trash = g_settings_get_boolean (prefs, NAUTILUS_PREFERENCES_CONFIRM_TRASH);
g_object_unref (prefs);
return confirm_trash;
}
static gboolean
confirm_delete_from_trash (CommonJob *job,
GList *files)
{
char *prompt;
int file_count;
int response;
/* Just Say Yes if the preference says not to confirm. */
if (!should_confirm_trash ())
{
return TRUE;
}
file_count = g_list_length (files);
g_assert (file_count > 0);
if (file_count == 1)
{
prompt = f (_("Are you sure you want to permanently delete “%B” "
"from the trash?"), files->data);
}
else
{
prompt = f (ngettext ("Are you sure you want to permanently delete "
"the %'d selected item from the trash?",
"Are you sure you want to permanently delete "
"the %'d selected items from the trash?",
file_count),
file_count);
}
response = run_warning (job,
prompt,
f (_("If you delete an item, it will be permanently lost.")),
NULL,
FALSE,
CANCEL, DELETE,
NULL);
return (response == 1);
}
static gboolean
confirm_empty_trash (CommonJob *job)
{
char *prompt;
int response;
/* Just Say Yes if the preference says not to confirm. */
if (!should_confirm_trash ())
{
return TRUE;
}
prompt = f (_("Empty all items from Trash?"));
response = run_warning (job,
prompt,
f (_("All items in the Trash will be permanently deleted.")),
NULL,
FALSE,
CANCEL, _("Empty _Trash"),
NULL);
return (response == 1);
}
static gboolean
confirm_delete_directly (CommonJob *job,
GList *files)
{
char *prompt;
int file_count;
int response;
/* Just Say Yes if the preference says not to confirm. */
if (!should_confirm_trash ())
{
return TRUE;
}
file_count = g_list_length (files);
g_assert (file_count > 0);
if (can_delete_files_without_confirm (files))
{
return TRUE;
}
if (file_count == 1)
{
prompt = f (_("Are you sure you want to permanently delete “%B”?"),
files->data);
}
else
{
prompt = f (ngettext ("Are you sure you want to permanently delete "
"the %'d selected item?",
"Are you sure you want to permanently delete "
"the %'d selected items?", file_count),
file_count);
}
response = run_warning (job,
prompt,
f (_("If you delete an item, it will be permanently lost.")),
NULL,
FALSE,
CANCEL, DELETE,
NULL);
return response == 1;
}
static void
report_delete_progress (CommonJob *job,
SourceInfo *source_info,
TransferInfo *transfer_info)
{
int files_left;
double elapsed, transfer_rate;
int remaining_time;
gint64 now;
char *details;
char *status;
DeleteJob *delete_job;
delete_job = (DeleteJob *) job;
now = g_get_monotonic_time ();
files_left = source_info->num_files - transfer_info->num_files;
/* Races and whatnot could cause this to be negative... */
if (files_left < 0)
{
files_left = 0;
}
/* If the number of files left is 0, we want to update the status without
* considering this time, since we want to change the status to completed
* and probably we won't get more calls to this function */
if (transfer_info->last_report_time != 0 &&
ABS ((gint64) (transfer_info->last_report_time - now)) < 100 * NSEC_PER_MICROSEC &&
files_left > 0)
{
return;
}
transfer_info->last_report_time = now;
if (source_info->num_files == 1)
{
if (files_left == 0)
{
status = _("Deleted “%B”");
}
else
{
status = _("Deleting “%B”");
}
nautilus_progress_info_take_status (job->progress,
f (status,
(GFile *) delete_job->files->data));
}
else
{
if (files_left == 0)
{
status = ngettext ("Deleted %'d file",
"Deleted %'d files",
source_info->num_files);
}
else
{
status = ngettext ("Deleting %'d file",
"Deleting %'d files",
source_info->num_files);
}
nautilus_progress_info_take_status (job->progress,
f (status,
source_info->num_files));
}
elapsed = g_timer_elapsed (job->time, NULL);
transfer_rate = 0;
remaining_time = INT_MAX;
if (elapsed > 0)
{
transfer_rate = transfer_info->num_files / elapsed;
if (transfer_rate > 0)
{
remaining_time = (source_info->num_files - transfer_info->num_files) / transfer_rate;
}
}
if (elapsed < SECONDS_NEEDED_FOR_RELIABLE_TRANSFER_RATE)
{
if (files_left > 0)
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files + 1,
source_info->num_files);
}
else
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files,
source_info->num_files);
}
}
else
{
if (files_left > 0)
{
gchar *time_left_message;
gchar *files_per_second_message;
gchar *concat_detail;
/* To translators: %T will expand to a time duration like "2 minutes".
* So the whole thing will be something like "1 / 5 -- 2 hours left (4 files/sec)"
*
* The singular/plural form will be used depending on the remaining time (i.e. the %T argument).
*/
time_left_message = ngettext ("%'d / %'d \xE2\x80\x94 %T left",
"%'d / %'d \xE2\x80\x94 %T left",
seconds_count_format_time_units (remaining_time));
transfer_rate += 0.5;
files_per_second_message = ngettext ("(%d file/sec)",
"(%d files/sec)",
(int) transfer_rate);
concat_detail = g_strconcat (time_left_message, " ", files_per_second_message, NULL);
details = f (concat_detail,
transfer_info->num_files + 1, source_info->num_files,
remaining_time,
(int) transfer_rate);
g_free (concat_detail);
}
else
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files,
source_info->num_files);
}
}
nautilus_progress_info_take_details (job->progress, details);
if (elapsed > SECONDS_NEEDED_FOR_APROXIMATE_TRANSFER_RATE)
{
nautilus_progress_info_set_remaining_time (job->progress,
remaining_time);
nautilus_progress_info_set_elapsed_time (job->progress,
elapsed);
}
if (source_info->num_files != 0)
{
nautilus_progress_info_set_progress (job->progress, transfer_info->num_files, source_info->num_files);
}
}
typedef void (*DeleteCallback) (GFile *file,
GError *error,
gpointer callback_data);
static gboolean
delete_file_recursively (GFile *file,
GCancellable *cancellable,
DeleteCallback callback,
gpointer callback_data)
{
gboolean success;
g_autoptr (GError) error = NULL;
do
{
g_autoptr (GFileEnumerator) enumerator = NULL;
success = g_file_delete (file, cancellable, &error);
if (success ||
!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_EMPTY))
{
break;
}
g_clear_error (&error);
enumerator = g_file_enumerate_children (file,
G_FILE_ATTRIBUTE_STANDARD_NAME,
G_FILE_QUERY_INFO_NONE,
cancellable, &error);
if (enumerator)
{
GFileInfo *info;
success = TRUE;
info = g_file_enumerator_next_file (enumerator,
cancellable,
&error);
while (info != NULL)
{
g_autoptr (GFile) child = NULL;
child = g_file_enumerator_get_child (enumerator, info);
success = success && delete_file_recursively (child,
cancellable,
callback,
callback_data);
g_object_unref (info);
info = g_file_enumerator_next_file (enumerator,
cancellable,
&error);
}
}
if (error != NULL)
{
success = FALSE;
}
}
while (success);
if (callback)
{
callback (file, error, callback_data);
}
return success;
}
typedef struct
{
CommonJob *job;
SourceInfo *source_info;
TransferInfo *transfer_info;
} DeleteData;
static void
file_deleted_callback (GFile *file,
GError *error,
gpointer callback_data)
{
DeleteData *data = callback_data;
CommonJob *job;
SourceInfo *source_info;
TransferInfo *transfer_info;
GFileType file_type;
char *primary;
char *secondary;
char *details = NULL;
int response;
job = data->job;
source_info = data->source_info;
transfer_info = data->transfer_info;
data->transfer_info->num_files++;
if (error == NULL)
{
nautilus_file_changes_queue_file_removed (file);
report_delete_progress (data->job, data->source_info, data->transfer_info);
return;
}
if (job_aborted (job) ||
job->skip_all_error ||
should_skip_file (job, file) ||
should_skip_readdir_error (job, file))
{
return;
}
primary = f (_("Error while deleting."));
file_type = g_file_query_file_type (file,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable);
if (file_type == G_FILE_TYPE_DIRECTORY)
{
secondary = IS_IO_ERROR (error, PERMISSION_DENIED) ?
f (_("There was an error deleting the folder “%B”."),
file) :
f (_("You do not have sufficient permissions to delete the folder “%B”."),
file);
}
else
{
secondary = IS_IO_ERROR (error, PERMISSION_DENIED) ?
f (_("There was an error deleting the file “%B”."),
file) :
f (_("You do not have sufficient permissions to delete the file “%B”."),
file);
}
details = error->message;
response = run_cancel_or_skip_warning (job,
primary,
secondary,
details,
source_info->num_files,
source_info->num_files - transfer_info->num_files);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1)
{
/* skip all */
job->skip_all_error = TRUE;
}
}
static void
delete_files (CommonJob *job,
GList *files,
int *files_skipped)
{
GList *l;
GFile *file;
SourceInfo source_info;
TransferInfo transfer_info;
DeleteData data;
if (job_aborted (job))
{
return;
}
scan_sources (files,
&source_info,
job,
OP_KIND_DELETE);
if (job_aborted (job))
{
return;
}
g_timer_start (job->time);
memset (&transfer_info, 0, sizeof (transfer_info));
report_delete_progress (job, &source_info, &transfer_info);
data.job = job;
data.source_info = &source_info;
data.transfer_info = &transfer_info;
for (l = files;
l != NULL && !job_aborted (job);
l = l->next)
{
gboolean success;
file = l->data;
if (should_skip_file (job, file))
{
(*files_skipped)++;
continue;
}
success = delete_file_recursively (file, job->cancellable,
file_deleted_callback,
&data);
if (!success)
{
(*files_skipped)++;
}
}
}
static void
report_trash_progress (CommonJob *job,
SourceInfo *source_info,
TransferInfo *transfer_info)
{
int files_left;
double elapsed, transfer_rate;
int remaining_time;
gint64 now;
char *details;
char *status;
DeleteJob *delete_job;
delete_job = (DeleteJob *) job;
now = g_get_monotonic_time ();
files_left = source_info->num_files - transfer_info->num_files;
/* Races and whatnot could cause this to be negative... */
if (files_left < 0)
{
files_left = 0;
}
/* If the number of files left is 0, we want to update the status without
* considering this time, since we want to change the status to completed
* and probably we won't get more calls to this function */
if (transfer_info->last_report_time != 0 &&
ABS ((gint64) (transfer_info->last_report_time - now)) < 100 * NSEC_PER_MICROSEC &&
files_left > 0)
{
return;
}
transfer_info->last_report_time = now;
if (source_info->num_files == 1)
{
if (files_left > 0)
{
status = _("Trashing “%B”");
}
else
{
status = _("Trashed “%B”");
}
nautilus_progress_info_take_status (job->progress,
f (status,
(GFile *) delete_job->files->data));
}
else
{
if (files_left > 0)
{
status = ngettext ("Trashing %'d file",
"Trashing %'d files",
source_info->num_files);
}
else
{
status = ngettext ("Trashed %'d file",
"Trashed %'d files",
source_info->num_files);
}
nautilus_progress_info_take_status (job->progress,
f (status,
source_info->num_files));
}
elapsed = g_timer_elapsed (job->time, NULL);
transfer_rate = 0;
remaining_time = INT_MAX;
if (elapsed > 0)
{
transfer_rate = transfer_info->num_files / elapsed;
if (transfer_rate > 0)
{
remaining_time = (source_info->num_files - transfer_info->num_files) / transfer_rate;
}
}
if (elapsed < SECONDS_NEEDED_FOR_RELIABLE_TRANSFER_RATE)
{
if (files_left > 0)
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files + 1,
source_info->num_files);
}
else
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files,
source_info->num_files);
}
}
else
{
if (files_left > 0)
{
gchar *time_left_message;
gchar *files_per_second_message;
gchar *concat_detail;
/* To translators: %T will expand to a time duration like "2 minutes".
* So the whole thing will be something like "1 / 5 -- 2 hours left (4 files/sec)"
*
* The singular/plural form will be used depending on the remaining time (i.e. the %T argument).
*/
time_left_message = ngettext ("%'d / %'d \xE2\x80\x94 %T left",
"%'d / %'d \xE2\x80\x94 %T left",
seconds_count_format_time_units (remaining_time));
files_per_second_message = ngettext ("(%d file/sec)",
"(%d files/sec)",
(int) (transfer_rate + 0.5));
concat_detail = g_strconcat (time_left_message, " ", files_per_second_message, NULL);
details = f (concat_detail,
transfer_info->num_files + 1, source_info->num_files,
remaining_time,
(int) transfer_rate + 0.5);
g_free (concat_detail);
}
else
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files,
source_info->num_files);
}
}
nautilus_progress_info_set_details (job->progress, details);
if (elapsed > SECONDS_NEEDED_FOR_APROXIMATE_TRANSFER_RATE)
{
nautilus_progress_info_set_remaining_time (job->progress,
remaining_time);
nautilus_progress_info_set_elapsed_time (job->progress,
elapsed);
}
if (source_info->num_files != 0)
{
nautilus_progress_info_set_progress (job->progress, transfer_info->num_files, source_info->num_files);
}
}
static void
trash_file (CommonJob *job,
GFile *file,
gboolean *skipped_file,
SourceInfo *source_info,
TransferInfo *transfer_info,
gboolean toplevel,
GList **to_delete)
{
GError *error;
char *primary, *secondary, *details;
int response;
if (should_skip_file (job, file))
{
*skipped_file = TRUE;
return;
}
error = NULL;
if (g_file_trash (file, job->cancellable, &error))
{
transfer_info->num_files++;
nautilus_file_changes_queue_file_removed (file);
if (job->undo_info != NULL)
{
nautilus_file_undo_info_trash_add_file (NAUTILUS_FILE_UNDO_INFO_TRASH (job->undo_info), file);
}
report_trash_progress (job, source_info, transfer_info);
return;
}
if (job->skip_all_error)
{
*skipped_file = TRUE;
goto skip;
}
if (job->delete_all)
{
*to_delete = g_list_prepend (*to_delete, file);
goto skip;
}
/* Translators: %B is a file name */
primary = f (_("“%B” can’t be put in the trash. Do you want to delete it immediately?"), file);
details = NULL;
secondary = NULL;
if (!IS_IO_ERROR (error, NOT_SUPPORTED))
{
details = error->message;
}
else if (!g_file_is_native (file))
{
secondary = f (_("This remote location does not support sending items to the trash."));
}
response = run_question (job,
primary,
secondary,
details,
(source_info->num_files - transfer_info->num_files) > 1,
CANCEL, SKIP_ALL, SKIP, DELETE_ALL, DELETE,
NULL);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
((DeleteJob *) job)->user_cancel = TRUE;
abort_job (job);
}
else if (response == 1) /* skip all */
{
*skipped_file = TRUE;
job->skip_all_error = TRUE;
}
else if (response == 2) /* skip */
{
*skipped_file = TRUE;
job->skip_all_error = TRUE;
}
else if (response == 3) /* delete all */
{
*to_delete = g_list_prepend (*to_delete, file);
job->delete_all = TRUE;
}
else if (response == 4) /* delete */
{
*to_delete = g_list_prepend (*to_delete, file);
}
skip:
g_error_free (error);
}
static void
transfer_add_file_to_count (GFile *file,
CommonJob *job,
TransferInfo *transfer_info)
{
g_autoptr (GFileInfo) file_info = NULL;
if (g_cancellable_is_cancelled (job->cancellable))
{
return;
}
file_info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_SIZE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable,
NULL);
transfer_info->num_files++;
if (file_info != NULL)
{
transfer_info->num_bytes += g_file_info_get_size (file_info);
}
}
static void
trash_files (CommonJob *job,
GList *files,
int *files_skipped)
{
GList *l;
GFile *file;
GList *to_delete;
SourceInfo source_info;
TransferInfo transfer_info;
gboolean skipped_file;
if (job_aborted (job))
{
return;
}
scan_sources (files,
&source_info,
job,
OP_KIND_TRASH);
if (job_aborted (job))
{
return;
}
g_timer_start (job->time);
memset (&transfer_info, 0, sizeof (transfer_info));
report_trash_progress (job, &source_info, &transfer_info);
to_delete = NULL;
for (l = files;
l != NULL && !job_aborted (job);
l = l->next)
{
file = l->data;
skipped_file = FALSE;
trash_file (job, file,
&skipped_file,
&source_info, &transfer_info,
TRUE, &to_delete);
if (skipped_file)
{
(*files_skipped)++;
transfer_add_file_to_count (file, job, &transfer_info);
report_trash_progress (job, &source_info, &transfer_info);
}
}
if (to_delete)
{
to_delete = g_list_reverse (to_delete);
delete_files (job, to_delete, files_skipped);
g_list_free (to_delete);
}
}
static void
delete_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
DeleteJob *job;
GHashTable *debuting_uris;
job = user_data;
g_list_free_full (job->files, g_object_unref);
if (job->done_callback)
{
debuting_uris = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
job->done_callback (debuting_uris, job->user_cancel, job->done_callback_data);
g_hash_table_unref (debuting_uris);
}
finalize_common ((CommonJob *) job);
nautilus_file_changes_consume_changes (TRUE);
}
static void
delete_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
DeleteJob *job = task_data;
GList *to_trash_files;
GList *to_delete_files;
GList *l;
GFile *file;
gboolean confirmed;
CommonJob *common;
gboolean must_confirm_delete_in_trash;
gboolean must_confirm_delete;
int files_skipped;
common = (CommonJob *) job;
nautilus_progress_info_start (job->common.progress);
to_trash_files = NULL;
to_delete_files = NULL;
must_confirm_delete_in_trash = FALSE;
must_confirm_delete = FALSE;
files_skipped = 0;
for (l = job->files; l != NULL; l = l->next)
{
file = l->data;
if (job->try_trash &&
g_file_has_uri_scheme (file, "trash"))
{
must_confirm_delete_in_trash = TRUE;
to_delete_files = g_list_prepend (to_delete_files, file);
}
else if (can_delete_without_confirm (file))
{
to_delete_files = g_list_prepend (to_delete_files, file);
}
else
{
if (job->try_trash)
{
to_trash_files = g_list_prepend (to_trash_files, file);
}
else
{
must_confirm_delete = TRUE;
to_delete_files = g_list_prepend (to_delete_files, file);
}
}
}
if (to_delete_files != NULL)
{
to_delete_files = g_list_reverse (to_delete_files);
confirmed = TRUE;
if (must_confirm_delete_in_trash)
{
confirmed = confirm_delete_from_trash (common, to_delete_files);
}
else if (must_confirm_delete)
{
confirmed = confirm_delete_directly (common, to_delete_files);
}
if (confirmed)
{
delete_files (common, to_delete_files, &files_skipped);
}
else
{
job->user_cancel = TRUE;
}
}
if (to_trash_files != NULL)
{
to_trash_files = g_list_reverse (to_trash_files);
trash_files (common, to_trash_files, &files_skipped);
}
g_list_free (to_trash_files);
g_list_free (to_delete_files);
if (files_skipped == g_list_length (job->files))
{
/* User has skipped all files, report user cancel */
job->user_cancel = TRUE;
}
}
static void
trash_or_delete_internal (GList *files,
GtkWindow *parent_window,
gboolean try_trash,
NautilusDeleteCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
DeleteJob *job;
/* TODO: special case desktop icon link files ... */
job = op_job_new (DeleteJob, parent_window);
job->files = g_list_copy_deep (files, (GCopyFunc) g_object_ref, NULL);
job->try_trash = try_trash;
job->user_cancel = FALSE;
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
if (try_trash)
{
inhibit_power_manager ((CommonJob *) job, _("Trashing Files"));
}
else
{
inhibit_power_manager ((CommonJob *) job, _("Deleting Files"));
}
if (!nautilus_file_undo_manager_is_operating () && try_trash)
{
job->common.undo_info = nautilus_file_undo_info_trash_new (g_list_length (files));
}
task = g_task_new (NULL, NULL, delete_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, delete_task_thread_func);
g_object_unref (task);
}
void
nautilus_file_operations_trash_or_delete (GList *files,
GtkWindow *parent_window,
NautilusDeleteCallback done_callback,
gpointer done_callback_data)
{
trash_or_delete_internal (files, parent_window,
TRUE,
done_callback, done_callback_data);
}
void
nautilus_file_operations_delete (GList *files,
GtkWindow *parent_window,
NautilusDeleteCallback done_callback,
gpointer done_callback_data)
{
trash_or_delete_internal (files, parent_window,
FALSE,
done_callback, done_callback_data);
}
typedef struct
{
gboolean eject;
GMount *mount;
GMountOperation *mount_operation;
GtkWindow *parent_window;
NautilusUnmountCallback callback;
gpointer callback_data;
} UnmountData;
static void
unmount_data_free (UnmountData *data)
{
if (data->parent_window)
{
g_object_remove_weak_pointer (G_OBJECT (data->parent_window),
(gpointer *) &data->parent_window);
}
g_clear_object (&data->mount_operation);
g_object_unref (data->mount);
g_free (data);
}
static void
unmount_mount_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
UnmountData *data = user_data;
GError *error;
char *primary;
gboolean unmounted;
error = NULL;
if (data->eject)
{
unmounted = g_mount_eject_with_operation_finish (G_MOUNT (source_object),
res, &error);
}
else
{
unmounted = g_mount_unmount_with_operation_finish (G_MOUNT (source_object),
res, &error);
}
if (!unmounted)
{
if (error->code != G_IO_ERROR_FAILED_HANDLED)
{
if (data->eject)
{
primary = f (_("Unable to eject %V"), source_object);
}
else
{
primary = f (_("Unable to unmount %V"), source_object);
}
eel_show_error_dialog (primary,
error->message,
data->parent_window);
g_free (primary);
}
}
if (data->callback)
{
data->callback (data->callback_data);
}
if (error != NULL)
{
g_error_free (error);
}
unmount_data_free (data);
}
static void
do_unmount (UnmountData *data)
{
GMountOperation *mount_op;
if (data->mount_operation)
{
mount_op = g_object_ref (data->mount_operation);
}
else
{
mount_op = gtk_mount_operation_new (data->parent_window);
}
if (data->eject)
{
g_mount_eject_with_operation (data->mount,
0,
mount_op,
NULL,
unmount_mount_callback,
data);
}
else
{
g_mount_unmount_with_operation (data->mount,
0,
mount_op,
NULL,
unmount_mount_callback,
data);
}
g_object_unref (mount_op);
}
static gboolean
dir_has_files (GFile *dir)
{
GFileEnumerator *enumerator;
gboolean res;
GFileInfo *file_info;
res = FALSE;
enumerator = g_file_enumerate_children (dir,
G_FILE_ATTRIBUTE_STANDARD_NAME,
0,
NULL, NULL);
if (enumerator)
{
file_info = g_file_enumerator_next_file (enumerator, NULL, NULL);
if (file_info != NULL)
{
res = TRUE;
g_object_unref (file_info);
}
g_file_enumerator_close (enumerator, NULL, NULL);
g_object_unref (enumerator);
}
return res;
}
static GList *
get_trash_dirs_for_mount (GMount *mount)
{
GFile *root;
GFile *trash;
char *relpath;
GList *list;
root = g_mount_get_root (mount);
if (root == NULL)
{
return NULL;
}
list = NULL;
if (g_file_is_native (root))
{
relpath = g_strdup_printf (".Trash/%d", getuid ());
trash = g_file_resolve_relative_path (root, relpath);
g_free (relpath);
list = g_list_prepend (list, g_file_get_child (trash, "files"));
list = g_list_prepend (list, g_file_get_child (trash, "info"));
g_object_unref (trash);
relpath = g_strdup_printf (".Trash-%d", getuid ());
trash = g_file_get_child (root, relpath);
g_free (relpath);
list = g_list_prepend (list, g_file_get_child (trash, "files"));
list = g_list_prepend (list, g_file_get_child (trash, "info"));
g_object_unref (trash);
}
g_object_unref (root);
return list;
}
static gboolean
has_trash_files (GMount *mount)
{
GList *dirs, *l;
GFile *dir;
gboolean res;
dirs = get_trash_dirs_for_mount (mount);
res = FALSE;
for (l = dirs; l != NULL; l = l->next)
{
dir = l->data;
if (dir_has_files (dir))
{
res = TRUE;
break;
}
}
g_list_free_full (dirs, g_object_unref);
return res;
}
static gint
prompt_empty_trash (GtkWindow *parent_window)
{
gint result;
GtkWidget *dialog;
GdkScreen *screen;
screen = NULL;
if (parent_window != NULL)
{
screen = gtk_widget_get_screen (GTK_WIDGET (parent_window));
}
/* Do we need to be modal ? */
dialog = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL,
GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE,
_("Do you want to empty the trash before you unmount?"));
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
_("In order to regain the "
"free space on this volume "
"the trash must be emptied. "
"All trashed items on the volume "
"will be permanently lost."));
gtk_dialog_add_buttons (GTK_DIALOG (dialog),
_("Do _not Empty Trash"), GTK_RESPONSE_REJECT,
CANCEL, GTK_RESPONSE_CANCEL,
_("Empty _Trash"), GTK_RESPONSE_ACCEPT, NULL);
gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_ACCEPT);
gtk_window_set_title (GTK_WINDOW (dialog), ""); /* as per HIG */
gtk_window_set_skip_taskbar_hint (GTK_WINDOW (dialog), TRUE);
if (screen)
{
gtk_window_set_screen (GTK_WINDOW (dialog), screen);
}
atk_object_set_role (gtk_widget_get_accessible (dialog), ATK_ROLE_ALERT);
gtk_window_set_wmclass (GTK_WINDOW (dialog), "empty_trash",
"Nautilus");
/* Make transient for the window group */
gtk_widget_realize (dialog);
if (screen != NULL)
{
gdk_window_set_transient_for (gtk_widget_get_window (GTK_WIDGET (dialog)),
gdk_screen_get_root_window (screen));
}
result = gtk_dialog_run (GTK_DIALOG (dialog));
gtk_widget_destroy (dialog);
return result;
}
static void
empty_trash_for_unmount_done (gboolean success,
gpointer user_data)
{
UnmountData *data = user_data;
do_unmount (data);
}
void
nautilus_file_operations_unmount_mount_full (GtkWindow *parent_window,
GMount *mount,
GMountOperation *mount_operation,
gboolean eject,
gboolean check_trash,
NautilusUnmountCallback callback,
gpointer callback_data)
{
UnmountData *data;
int response;
data = g_new0 (UnmountData, 1);
data->callback = callback;
data->callback_data = callback_data;
if (parent_window)
{
data->parent_window = parent_window;
g_object_add_weak_pointer (G_OBJECT (data->parent_window),
(gpointer *) &data->parent_window);
}
if (mount_operation)
{
data->mount_operation = g_object_ref (mount_operation);
}
data->eject = eject;
data->mount = g_object_ref (mount);
if (check_trash && has_trash_files (mount))
{
response = prompt_empty_trash (parent_window);
if (response == GTK_RESPONSE_ACCEPT)
{
GTask *task;
EmptyTrashJob *job;
job = op_job_new (EmptyTrashJob, parent_window);
job->should_confirm = FALSE;
job->trash_dirs = get_trash_dirs_for_mount (mount);
job->done_callback = empty_trash_for_unmount_done;
job->done_callback_data = data;
task = g_task_new (NULL, NULL, empty_trash_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, empty_trash_thread_func);
g_object_unref (task);
return;
}
else if (response == GTK_RESPONSE_CANCEL)
{
if (callback)
{
callback (callback_data);
}
unmount_data_free (data);
return;
}
}
do_unmount (data);
}
void
nautilus_file_operations_unmount_mount (GtkWindow *parent_window,
GMount *mount,
gboolean eject,
gboolean check_trash)
{
nautilus_file_operations_unmount_mount_full (parent_window, mount, NULL, eject,
check_trash, NULL, NULL);
}
static void
mount_callback_data_notify (gpointer data,
GObject *object)
{
GMountOperation *mount_op;
mount_op = G_MOUNT_OPERATION (data);
g_object_set_data (G_OBJECT (mount_op), "mount-callback", NULL);
g_object_set_data (G_OBJECT (mount_op), "mount-callback-data", NULL);
}
static void
volume_mount_cb (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
NautilusMountCallback mount_callback;
GObject *mount_callback_data_object;
GMountOperation *mount_op = user_data;
GError *error;
char *primary;
char *name;
gboolean success;
success = TRUE;
error = NULL;
if (!g_volume_mount_finish (G_VOLUME (source_object), res, &error))
{
if (error->code != G_IO_ERROR_FAILED_HANDLED &&
error->code != G_IO_ERROR_ALREADY_MOUNTED)
{
GtkWindow *parent;
parent = gtk_mount_operation_get_parent (GTK_MOUNT_OPERATION (mount_op));
name = g_volume_get_name (G_VOLUME (source_object));
primary = g_strdup_printf (_("Unable to access “%s”"), name);
g_free (name);
success = FALSE;
eel_show_error_dialog (primary,
error->message,
parent);
g_free (primary);
}
g_error_free (error);
}
mount_callback = (NautilusMountCallback)
g_object_get_data (G_OBJECT (mount_op), "mount-callback");
mount_callback_data_object =
g_object_get_data (G_OBJECT (mount_op), "mount-callback-data");
if (mount_callback != NULL)
{
(*mount_callback)(G_VOLUME (source_object),
success,
mount_callback_data_object);
if (mount_callback_data_object != NULL)
{
g_object_weak_unref (mount_callback_data_object,
mount_callback_data_notify,
mount_op);
}
}
g_object_unref (mount_op);
}
void
nautilus_file_operations_mount_volume (GtkWindow *parent_window,
GVolume *volume)
{
nautilus_file_operations_mount_volume_full (parent_window, volume,
NULL, NULL);
}
void
nautilus_file_operations_mount_volume_full (GtkWindow *parent_window,
GVolume *volume,
NautilusMountCallback mount_callback,
GObject *mount_callback_data_object)
{
GMountOperation *mount_op;
mount_op = gtk_mount_operation_new (parent_window);
g_mount_operation_set_password_save (mount_op, G_PASSWORD_SAVE_FOR_SESSION);
g_object_set_data (G_OBJECT (mount_op),
"mount-callback",
mount_callback);
if (mount_callback != NULL &&
mount_callback_data_object != NULL)
{
g_object_weak_ref (mount_callback_data_object,
mount_callback_data_notify,
mount_op);
}
g_object_set_data (G_OBJECT (mount_op),
"mount-callback-data",
mount_callback_data_object);
g_volume_mount (volume, 0, mount_op, NULL, volume_mount_cb, mount_op);
}
static void
report_preparing_count_progress (CommonJob *job,
SourceInfo *source_info)
{
char *s;
switch (source_info->op)
{
default:
case OP_KIND_COPY:
{
s = f (ngettext ("Preparing to copy %'d file (%S)",
"Preparing to copy %'d files (%S)",
source_info->num_files),
source_info->num_files, source_info->num_bytes);
}
break;
case OP_KIND_MOVE:
{
s = f (ngettext ("Preparing to move %'d file (%S)",
"Preparing to move %'d files (%S)",
source_info->num_files),
source_info->num_files, source_info->num_bytes);
}
break;
case OP_KIND_DELETE:
{
s = f (ngettext ("Preparing to delete %'d file (%S)",
"Preparing to delete %'d files (%S)",
source_info->num_files),
source_info->num_files, source_info->num_bytes);
}
break;
case OP_KIND_TRASH:
{
s = f (ngettext ("Preparing to trash %'d file",
"Preparing to trash %'d files",
source_info->num_files),
source_info->num_files);
}
break;
case OP_KIND_COMPRESS:
s = f (ngettext ("Preparing to compress %'d file",
"Preparing to compress %'d files",
source_info->num_files),
source_info->num_files);
}
nautilus_progress_info_take_details (job->progress, s);
nautilus_progress_info_pulse_progress (job->progress);
}
static void
count_file (GFileInfo *info,
CommonJob *job,
SourceInfo *source_info)
{
source_info->num_files += 1;
source_info->num_bytes += g_file_info_get_size (info);
if (source_info->num_files_since_progress++ > 100)
{
report_preparing_count_progress (job, source_info);
source_info->num_files_since_progress = 0;
}
}
static char *
get_scan_primary (OpKind kind)
{
switch (kind)
{
default:
case OP_KIND_COPY:
{
return f (_("Error while copying."));
}
case OP_KIND_MOVE:
{
return f (_("Error while moving."));
}
case OP_KIND_DELETE:
{
return f (_("Error while deleting."));
}
case OP_KIND_TRASH:
{
return f (_("Error while moving files to trash."));
}
case OP_KIND_COMPRESS:
return f (_("Error while compressing files."));
}
}
static void
scan_dir (GFile *dir,
SourceInfo *source_info,
CommonJob *job,
GQueue *dirs,
GHashTable *scanned)
{
GFileInfo *info;
GError *error;
GFile *subdir;
GFileEnumerator *enumerator;
char *primary, *secondary, *details;
int response;
SourceInfo saved_info;
saved_info = *source_info;
retry:
error = NULL;
enumerator = g_file_enumerate_children (dir,
G_FILE_ATTRIBUTE_STANDARD_NAME ","
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_STANDARD_SIZE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable,
&error);
if (enumerator)
{
error = NULL;
while ((info = g_file_enumerator_next_file (enumerator, job->cancellable, &error)) != NULL)
{
g_autoptr (GFile) file = NULL;
g_autofree char *file_uri = NULL;
file = g_file_enumerator_get_child (enumerator, info);
file_uri = g_file_get_uri (file);
if (!g_hash_table_contains (scanned, file_uri))
{
g_hash_table_add (scanned, g_strdup (file_uri));
count_file (info, job, source_info);
if (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
{
subdir = g_file_get_child (dir,
g_file_info_get_name (info));
/* Push to head, since we want depth-first */
g_queue_push_head (dirs, subdir);
}
}
g_object_unref (info);
}
g_file_enumerator_close (enumerator, job->cancellable, NULL);
g_object_unref (enumerator);
if (error && IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
else if (error)
{
primary = get_scan_primary (source_info->op);
details = NULL;
if (IS_IO_ERROR (error, PERMISSION_DENIED))
{
secondary = f (_("Files in the folder “%B” cannot be handled because you do "
"not have permissions to see them."), dir);
}
else
{
secondary = f (_("There was an error getting information about the files in the folder “%B”."), dir);
details = error->message;
}
response = run_warning (job,
primary,
secondary,
details,
FALSE,
CANCEL, RETRY, SKIP,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1)
{
*source_info = saved_info;
goto retry;
}
else if (response == 2)
{
skip_readdir_error (job, dir);
}
else
{
g_assert_not_reached ();
}
}
}
else if (job->skip_all_error)
{
g_error_free (error);
skip_file (job, dir);
}
else if (IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
else
{
primary = get_scan_primary (source_info->op);
details = NULL;
if (IS_IO_ERROR (error, PERMISSION_DENIED))
{
secondary = f (_("The folder “%B” cannot be handled because you do not have "
"permissions to read it."), dir);
}
else
{
secondary = f (_("There was an error reading the folder “%B”."), dir);
details = error->message;
}
/* set show_all to TRUE here, as we don't know how many
* files we'll end up processing yet.
*/
response = run_warning (job,
primary,
secondary,
details,
TRUE,
CANCEL, SKIP_ALL, SKIP, RETRY,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1 || response == 2)
{
if (response == 1)
{
job->skip_all_error = TRUE;
}
skip_file (job, dir);
}
else if (response == 3)
{
goto retry;
}
else
{
g_assert_not_reached ();
}
}
}
static void
scan_file (GFile *file,
SourceInfo *source_info,
CommonJob *job,
GHashTable *scanned)
{
GFileInfo *info;
GError *error;
GQueue *dirs;
GFile *dir;
char *primary;
char *secondary;
char *details;
int response;
dirs = g_queue_new ();
retry:
error = NULL;
info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_STANDARD_SIZE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable,
&error);
if (info)
{
g_autofree char *file_uri = NULL;
file_uri = g_file_get_uri (file);
if (!g_hash_table_contains (scanned, file_uri))
{
g_hash_table_add (scanned, g_strdup (file_uri));
count_file (info, job, source_info);
/* trashing operation doesn't recurse */
if (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY &&
source_info->op != OP_KIND_TRASH)
{
g_queue_push_head (dirs, g_object_ref (file));
}
}
g_object_unref (info);
}
else if (job->skip_all_error)
{
g_error_free (error);
skip_file (job, file);
}
else if (IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
else
{
primary = get_scan_primary (source_info->op);
details = NULL;
if (IS_IO_ERROR (error, PERMISSION_DENIED))
{
secondary = f (_("The file “%B” cannot be handled because you do not have "
"permissions to read it."), file);
}
else
{
secondary = f (_("There was an error getting information about “%B”."), file);
details = error->message;
}
/* set show_all to TRUE here, as we don't know how many
* files we'll end up processing yet.
*/
response = run_warning (job,
primary,
secondary,
details,
TRUE,
CANCEL, SKIP_ALL, SKIP, RETRY,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1 || response == 2)
{
if (response == 1)
{
job->skip_all_error = TRUE;
}
skip_file (job, file);
}
else if (response == 3)
{
goto retry;
}
else
{
g_assert_not_reached ();
}
}
while (!job_aborted (job) &&
(dir = g_queue_pop_head (dirs)) != NULL)
{
scan_dir (dir, source_info, job, dirs, scanned);
g_object_unref (dir);
}
/* Free all from queue if we exited early */
g_queue_foreach (dirs, (GFunc) g_object_unref, NULL);
g_queue_free (dirs);
}
static void
scan_sources (GList *files,
SourceInfo *source_info,
CommonJob *job,
OpKind kind)
{
GList *l;
GFile *file;
g_autoptr (GHashTable) scanned = NULL;
memset (source_info, 0, sizeof (SourceInfo));
source_info->op = kind;
scanned = g_hash_table_new_full (g_str_hash,
g_str_equal,
(GDestroyNotify) g_free,
NULL);
report_preparing_count_progress (job, source_info);
for (l = files; l != NULL && !job_aborted (job); l = l->next)
{
file = l->data;
scan_file (file,
source_info,
job,
scanned);
}
/* Make sure we report the final count */
report_preparing_count_progress (job, source_info);
}
static void
verify_destination (CommonJob *job,
GFile *dest,
char **dest_fs_id,
goffset required_size)
{
GFileInfo *info, *fsinfo;
GError *error;
guint64 free_size;
guint64 size_difference;
char *primary, *secondary, *details;
int response;
GFileType file_type;
gboolean dest_is_symlink = FALSE;
if (dest_fs_id)
{
*dest_fs_id = NULL;
}
retry:
error = NULL;
info = g_file_query_info (dest,
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_ID_FILESYSTEM,
dest_is_symlink ? G_FILE_QUERY_INFO_NONE : G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable,
&error);
if (info == NULL)
{
if (IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
return;
}
primary = f (_("Error while copying to “%B”."), dest);
details = NULL;
if (IS_IO_ERROR (error, PERMISSION_DENIED))
{
secondary = f (_("You do not have permissions to access the destination folder."));
}
else
{
secondary = f (_("There was an error getting information about the destination."));
details = error->message;
}
response = run_error (job,
primary,
secondary,
details,
FALSE,
CANCEL, RETRY,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1)
{
goto retry;
}
else
{
g_assert_not_reached ();
}
return;
}
file_type = g_file_info_get_file_type (info);
if (!dest_is_symlink && file_type == G_FILE_TYPE_SYMBOLIC_LINK)
{
/* Record that destination is a symlink and do real stat() once again */
dest_is_symlink = TRUE;
g_object_unref (info);
goto retry;
}
if (dest_fs_id)
{
*dest_fs_id =
g_strdup (g_file_info_get_attribute_string (info,
G_FILE_ATTRIBUTE_ID_FILESYSTEM));
}
g_object_unref (info);
if (file_type != G_FILE_TYPE_DIRECTORY)
{
primary = f (_("Error while copying to “%B”."), dest);
secondary = f (_("The destination is not a folder."));
run_error (job,
primary,
secondary,
NULL,
FALSE,
CANCEL,
NULL);
abort_job (job);
return;
}
if (dest_is_symlink)
{
/* We can't reliably statfs() destination if it's a symlink, thus not doing any further checks. */
return;
}
fsinfo = g_file_query_filesystem_info (dest,
G_FILE_ATTRIBUTE_FILESYSTEM_FREE ","
G_FILE_ATTRIBUTE_FILESYSTEM_READONLY,
job->cancellable,
NULL);
if (fsinfo == NULL)
{
/* All sorts of things can go wrong getting the fs info (like not supported)
* only check these things if the fs returns them
*/
return;
}
if (required_size > 0 &&
g_file_info_has_attribute (fsinfo, G_FILE_ATTRIBUTE_FILESYSTEM_FREE))
{
free_size = g_file_info_get_attribute_uint64 (fsinfo,
G_FILE_ATTRIBUTE_FILESYSTEM_FREE);
if (free_size < required_size)
{
size_difference = required_size - free_size;
primary = f (_("Error while copying to “%B”."), dest);
secondary = f (_("There is not enough space on the destination. Try to remove files to make space."));
details = f (_("%S more space is required to copy to the destination."), size_difference);
response = run_warning (job,
primary,
secondary,
details,
FALSE,
CANCEL,
COPY_FORCE,
RETRY,
NULL);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 2)
{
goto retry;
}
else if (response == 1)
{
/* We are forced to copy - just fall through ... */
}
else
{
g_assert_not_reached ();
}
}
}
if (!job_aborted (job) &&
g_file_info_get_attribute_boolean (fsinfo,
G_FILE_ATTRIBUTE_FILESYSTEM_READONLY))
{
primary = f (_("Error while copying to “%B”."), dest);
secondary = f (_("The destination is read-only."));
run_error (job,
primary,
secondary,
NULL,
FALSE,
CANCEL,
NULL);
g_error_free (error);
abort_job (job);
}
g_object_unref (fsinfo);
}
static void
report_copy_progress (CopyMoveJob *copy_job,
SourceInfo *source_info,
TransferInfo *transfer_info)
{
int files_left;
goffset total_size;
double elapsed, transfer_rate;
int remaining_time;
guint64 now;
CommonJob *job;
gboolean is_move;
gchar *status;
char *details;
job = (CommonJob *) copy_job;
is_move = copy_job->is_move;
now = g_get_monotonic_time ();
files_left = source_info->num_files - transfer_info->num_files;
/* Races and whatnot could cause this to be negative... */
if (files_left < 0)
{
files_left = 0;
}
/* If the number of files left is 0, we want to update the status without
* considering this time, since we want to change the status to completed
* and probably we won't get more calls to this function */
if (transfer_info->last_report_time != 0 &&
ABS ((gint64) (transfer_info->last_report_time - now)) < 100 * NSEC_PER_MICROSEC &&
files_left > 0)
{
return;
}
transfer_info->last_report_time = now;
if (files_left != transfer_info->last_reported_files_left ||
transfer_info->last_reported_files_left == 0)
{
/* Avoid changing this unless files_left changed since last time */
transfer_info->last_reported_files_left = files_left;
if (source_info->num_files == 1)
{
if (copy_job->destination != NULL)
{
if (is_move)
{
if (files_left > 0)
{
status = _("Moving “%B” to “%B”");
}
else
{
status = _("Moved “%B” to “%B”");
}
}
else
{
if (files_left > 0)
{
status = _("Copying “%B” to “%B”");
}
else
{
status = _("Copied “%B” to “%B”");
}
}
nautilus_progress_info_take_status (job->progress,
f (status,
copy_job->fake_display_source != NULL ?
copy_job->fake_display_source :
(GFile *) copy_job->files->data,
copy_job->destination));
}
else
{
if (files_left > 0)
{
status = _("Duplicating “%B”");
}
else
{
status = _("Duplicated “%B”");
}
nautilus_progress_info_take_status (job->progress,
f (status,
(GFile *) copy_job->files->data));
}
}
else if (copy_job->files != NULL)
{
if (copy_job->destination != NULL)
{
if (files_left > 0)
{
if (is_move)
{
status = ngettext ("Moving %'d file to “%B”",
"Moving %'d files to “%B”",
source_info->num_files);
}
else
{
status = ngettext ("Copying %'d file to “%B”",
"Copying %'d files to “%B”",
source_info->num_files);
}
nautilus_progress_info_take_status (job->progress,
f (status,
source_info->num_files,
(GFile *) copy_job->destination));
}
else
{
if (is_move)
{
status = ngettext ("Moved %'d file to “%B”",
"Moved %'d files to “%B”",
source_info->num_files);
}
else
{
status = ngettext ("Copied %'d file to “%B”",
"Copied %'d files to “%B”",
source_info->num_files);
}
nautilus_progress_info_take_status (job->progress,
f (status,
source_info->num_files,
(GFile *) copy_job->destination));
}
}
else
{
GFile *parent;
parent = g_file_get_parent (copy_job->files->data);
if (files_left > 0)
{
status = ngettext ("Duplicating %'d file in “%B”",
"Duplicating %'d files in “%B”",
source_info->num_files);
nautilus_progress_info_take_status (job->progress,
f (status,
source_info->num_files,
parent));
}
else
{
status = ngettext ("Duplicated %'d file in “%B”",
"Duplicated %'d files in “%B”",
source_info->num_files);
nautilus_progress_info_take_status (job->progress,
f (status,
source_info->num_files,
parent));
}
g_object_unref (parent);
}
}
}
total_size = MAX (source_info->num_bytes, transfer_info->num_bytes);
elapsed = g_timer_elapsed (job->time, NULL);
transfer_rate = 0;
remaining_time = INT_MAX;
if (elapsed > 0)
{
transfer_rate = transfer_info->num_bytes / elapsed;
if (transfer_rate > 0)
{
remaining_time = (total_size - transfer_info->num_bytes) / transfer_rate;
}
}
if (elapsed < SECONDS_NEEDED_FOR_RELIABLE_TRANSFER_RATE &&
transfer_rate > 0)
{
if (source_info->num_files == 1)
{
/* To translators: %S will expand to a size like "2 bytes" or "3 MB", so something like "4 kb / 4 MB" */
details = f (_("%S / %S"), transfer_info->num_bytes, total_size);
}
else
{
if (files_left > 0)
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files + 1,
source_info->num_files);
}
else
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files,
source_info->num_files);
}
}
}
else
{
if (source_info->num_files == 1)
{
if (files_left > 0)
{
/* To translators: %S will expand to a size like "2 bytes" or "3 MB", %T to a time duration like
* "2 minutes". So the whole thing will be something like "2 kb / 4 MB -- 2 hours left (4kb/sec)"
*
* The singular/plural form will be used depending on the remaining time (i.e. the %T argument).
*/
details = f (ngettext ("%S / %S \xE2\x80\x94 %T left (%S/sec)",
"%S / %S \xE2\x80\x94 %T left (%S/sec)",
seconds_count_format_time_units (remaining_time)),
transfer_info->num_bytes, total_size,
remaining_time,
(goffset) transfer_rate);
}
else
{
/* To translators: %S will expand to a size like "2 bytes" or "3 MB". */
details = f (_("%S / %S"),
transfer_info->num_bytes,
total_size);
}
}
else
{
if (files_left > 0)
{
/* To translators: %T will expand to a time duration like "2 minutes".
* So the whole thing will be something like "1 / 5 -- 2 hours left (4kb/sec)"
*
* The singular/plural form will be used depending on the remaining time (i.e. the %T argument).
*/
details = f (ngettext ("%'d / %'d \xE2\x80\x94 %T left (%S/sec)",
"%'d / %'d \xE2\x80\x94 %T left (%S/sec)",
seconds_count_format_time_units (remaining_time)),
transfer_info->num_files + 1, source_info->num_files,
remaining_time,
(goffset) transfer_rate);
}
else
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files,
source_info->num_files);
}
}
}
nautilus_progress_info_take_details (job->progress, details);
if (elapsed > SECONDS_NEEDED_FOR_APROXIMATE_TRANSFER_RATE)
{
nautilus_progress_info_set_remaining_time (job->progress,
remaining_time);
nautilus_progress_info_set_elapsed_time (job->progress,
elapsed);
}
nautilus_progress_info_set_progress (job->progress, transfer_info->num_bytes, total_size);
}
static int
get_max_name_length (GFile *file_dir)
{
int max_length;
char *dir;
long max_path;
long max_name;
max_length = -1;
if (!g_file_has_uri_scheme (file_dir, "file"))
{
return max_length;
}
dir = g_file_get_path (file_dir);
if (!dir)
{
return max_length;
}
max_path = pathconf (dir, _PC_PATH_MAX);
max_name = pathconf (dir, _PC_NAME_MAX);
if (max_name == -1 && max_path == -1)
{
max_length = -1;
}
else if (max_name == -1 && max_path != -1)
{
max_length = max_path - (strlen (dir) + 1);
}
else if (max_name != -1 && max_path == -1)
{
max_length = max_name;
}
else
{
int leftover;
leftover = max_path - (strlen (dir) + 1);
max_length = MIN (leftover, max_name);
}
g_free (dir);
return max_length;
}
#define FAT_FORBIDDEN_CHARACTERS "/:;*?\"<>"
static gboolean
fat_str_replace (char *str,
char replacement)
{
gboolean success;
int i;
success = FALSE;
for (i = 0; str[i] != '\0'; i++)
{
if (strchr (FAT_FORBIDDEN_CHARACTERS, str[i]) ||
str[i] < 32)
{
success = TRUE;
str[i] = replacement;
}
}
return success;
}
static gboolean
make_file_name_valid_for_dest_fs (char *filename,
const char *dest_fs_type)
{
if (dest_fs_type != NULL && filename != NULL)
{
if (!strcmp (dest_fs_type, "fat") ||
!strcmp (dest_fs_type, "vfat") ||
!strcmp (dest_fs_type, "msdos") ||
!strcmp (dest_fs_type, "msdosfs"))
{
gboolean ret;
int i, old_len;
ret = fat_str_replace (filename, '_');
old_len = strlen (filename);
for (i = 0; i < old_len; i++)
{
if (filename[i] != ' ')
{
g_strchomp (filename);
ret |= (old_len != strlen (filename));
break;
}
}
return ret;
}
}
return FALSE;
}
static GFile *
get_unique_target_file (GFile *src,
GFile *dest_dir,
gboolean same_fs,
const char *dest_fs_type,
int count)
{
const char *editname, *end;
char *basename, *new_name;
GFileInfo *info;
GFile *dest;
int max_length;
max_length = get_max_name_length (dest_dir);
dest = NULL;
info = g_file_query_info (src,
G_FILE_ATTRIBUTE_STANDARD_EDIT_NAME,
0, NULL, NULL);
if (info != NULL)
{
editname = g_file_info_get_attribute_string (info, G_FILE_ATTRIBUTE_STANDARD_EDIT_NAME);
if (editname != NULL)
{
new_name = get_duplicate_name (editname, count, max_length);
make_file_name_valid_for_dest_fs (new_name, dest_fs_type);
dest = g_file_get_child_for_display_name (dest_dir, new_name, NULL);
g_free (new_name);
}
g_object_unref (info);
}
if (dest == NULL)
{
basename = g_file_get_basename (src);
if (g_utf8_validate (basename, -1, NULL))
{
new_name = get_duplicate_name (basename, count, max_length);
make_file_name_valid_for_dest_fs (new_name, dest_fs_type);
dest = g_file_get_child_for_display_name (dest_dir, new_name, NULL);
g_free (new_name);
}
if (dest == NULL)
{
end = strrchr (basename, '.');
if (end != NULL)
{
count += atoi (end + 1);
}
new_name = g_strdup_printf ("%s.%d", basename, count);
make_file_name_valid_for_dest_fs (new_name, dest_fs_type);
dest = g_file_get_child (dest_dir, new_name);
g_free (new_name);
}
g_free (basename);
}
return dest;
}
static GFile *
get_target_file_for_link (GFile *src,
GFile *dest_dir,
const char *dest_fs_type,
int count)
{
const char *editname;
char *basename, *new_name;
GFileInfo *info;
GFile *dest;
int max_length;
max_length = get_max_name_length (dest_dir);
dest = NULL;
info = g_file_query_info (src,
G_FILE_ATTRIBUTE_STANDARD_EDIT_NAME,
0, NULL, NULL);
if (info != NULL)
{
editname = g_file_info_get_attribute_string (info, G_FILE_ATTRIBUTE_STANDARD_EDIT_NAME);
if (editname != NULL)
{
new_name = get_link_name (editname, count, max_length);
make_file_name_valid_for_dest_fs (new_name, dest_fs_type);
dest = g_file_get_child_for_display_name (dest_dir, new_name, NULL);
g_free (new_name);
}
g_object_unref (info);
}
if (dest == NULL)
{
basename = g_file_get_basename (src);
make_file_name_valid_for_dest_fs (basename, dest_fs_type);
if (g_utf8_validate (basename, -1, NULL))
{
new_name = get_link_name (basename, count, max_length);
make_file_name_valid_for_dest_fs (new_name, dest_fs_type);
dest = g_file_get_child_for_display_name (dest_dir, new_name, NULL);
g_free (new_name);
}
if (dest == NULL)
{
if (count == 1)
{
new_name = g_strdup_printf ("%s.lnk", basename);
}
else
{
new_name = g_strdup_printf ("%s.lnk%d", basename, count);
}
make_file_name_valid_for_dest_fs (new_name, dest_fs_type);
dest = g_file_get_child (dest_dir, new_name);
g_free (new_name);
}
g_free (basename);
}
return dest;
}
static GFile *
get_target_file_with_custom_name (GFile *src,
GFile *dest_dir,
const char *dest_fs_type,
gboolean same_fs,
const gchar *custom_name)
{
char *basename;
GFile *dest;
GFileInfo *info;
char *copyname;
dest = NULL;
if (custom_name != NULL)
{
copyname = g_strdup (custom_name);
make_file_name_valid_for_dest_fs (copyname, dest_fs_type);
dest = g_file_get_child_for_display_name (dest_dir, copyname, NULL);
g_free (copyname);
}
if (dest == NULL && !same_fs)
{
info = g_file_query_info (src,
G_FILE_ATTRIBUTE_STANDARD_COPY_NAME ","
G_FILE_ATTRIBUTE_TRASH_ORIG_PATH,
0, NULL, NULL);
if (info)
{
copyname = NULL;
/* if file is being restored from trash make sure it uses its original name */
if (g_file_has_uri_scheme (src, "trash"))
{
copyname = g_path_get_basename (g_file_info_get_attribute_byte_string (info, G_FILE_ATTRIBUTE_TRASH_ORIG_PATH));
}
if (copyname == NULL)
{
copyname = g_strdup (g_file_info_get_attribute_string (info, G_FILE_ATTRIBUTE_STANDARD_COPY_NAME));
}
if (copyname)
{
make_file_name_valid_for_dest_fs (copyname, dest_fs_type);
dest = g_file_get_child_for_display_name (dest_dir, copyname, NULL);
g_free (copyname);
}
g_object_unref (info);
}
}
if (dest == NULL)
{
basename = g_file_get_basename (src);
make_file_name_valid_for_dest_fs (basename, dest_fs_type);
dest = g_file_get_child (dest_dir, basename);
g_free (basename);
}
return dest;
}
static GFile *
get_target_file (GFile *src,
GFile *dest_dir,
const char *dest_fs_type,
gboolean same_fs)
{
return get_target_file_with_custom_name (src, dest_dir, dest_fs_type, same_fs, NULL);
}
static gboolean
has_fs_id (GFile *file,
const char *fs_id)
{
const char *id;
GFileInfo *info;
gboolean res;
res = FALSE;
info = g_file_query_info (file,
G_FILE_ATTRIBUTE_ID_FILESYSTEM,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
NULL, NULL);
if (info)
{
id = g_file_info_get_attribute_string (info, G_FILE_ATTRIBUTE_ID_FILESYSTEM);
if (id && strcmp (id, fs_id) == 0)
{
res = TRUE;
}
g_object_unref (info);
}
return res;
}
static gboolean
is_dir (GFile *file)
{
GFileInfo *info;
gboolean res;
res = FALSE;
info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_TYPE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
NULL, NULL);
if (info)
{
res = g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY;
g_object_unref (info);
}
return res;
}
static GFile *
map_possibly_volatile_file_to_real (GFile *volatile_file,
GCancellable *cancellable,
GError **error)
{
GFile *real_file = NULL;
GFileInfo *info = NULL;
info = g_file_query_info (volatile_file,
G_FILE_ATTRIBUTE_STANDARD_IS_SYMLINK ","
G_FILE_ATTRIBUTE_STANDARD_IS_VOLATILE ","
G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
cancellable,
error);
if (info == NULL)
{
return NULL;
}
else
{
gboolean is_volatile;
is_volatile = g_file_info_get_attribute_boolean (info,
G_FILE_ATTRIBUTE_STANDARD_IS_VOLATILE);
if (is_volatile)
{
const gchar *target;
target = g_file_info_get_symlink_target (info);
real_file = g_file_resolve_relative_path (volatile_file, target);
}
}
g_object_unref (info);
if (real_file == NULL)
{
real_file = g_object_ref (volatile_file);
}
return real_file;
}
static GFile *
map_possibly_volatile_file_to_real_on_write (GFile *volatile_file,
GFileOutputStream *stream,
GCancellable *cancellable,
GError **error)
{
GFile *real_file = NULL;
GFileInfo *info = NULL;
info = g_file_output_stream_query_info (stream,
G_FILE_ATTRIBUTE_STANDARD_IS_SYMLINK ","
G_FILE_ATTRIBUTE_STANDARD_IS_VOLATILE ","
G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
cancellable,
error);
if (info == NULL)
{
return NULL;
}
else
{
gboolean is_volatile;
is_volatile = g_file_info_get_attribute_boolean (info,
G_FILE_ATTRIBUTE_STANDARD_IS_VOLATILE);
if (is_volatile)
{
const gchar *target;
target = g_file_info_get_symlink_target (info);
real_file = g_file_resolve_relative_path (volatile_file, target);
}
}
g_object_unref (info);
if (real_file == NULL)
{
real_file = g_object_ref (volatile_file);
}
return real_file;
}
static void copy_move_file (CopyMoveJob *job,
GFile *src,
GFile *dest_dir,
gboolean same_fs,
gboolean unique_names,
char **dest_fs_type,
SourceInfo *source_info,
TransferInfo *transfer_info,
GHashTable *debuting_files,
GdkPoint *point,
gboolean overwrite,
gboolean *skipped_file,
gboolean readonly_source_fs);
typedef enum
{
CREATE_DEST_DIR_RETRY,
CREATE_DEST_DIR_FAILED,
CREATE_DEST_DIR_SUCCESS
} CreateDestDirResult;
static CreateDestDirResult
create_dest_dir (CommonJob *job,
GFile *src,
GFile **dest,
gboolean same_fs,
char **dest_fs_type)
{
GError *error;
GFile *new_dest, *dest_dir;
char *primary, *secondary, *details;
int response;
gboolean handled_invalid_filename;
gboolean res;
handled_invalid_filename = *dest_fs_type != NULL;
retry:
/* First create the directory, then copy stuff to it before
* copying the attributes, because we need to be sure we can write to it */
error = NULL;
res = g_file_make_directory (*dest, job->cancellable, &error);
if (res)
{
GFile *real;
real = map_possibly_volatile_file_to_real (*dest, job->cancellable, &error);
if (real == NULL)
{
res = FALSE;
}
else
{
g_object_unref (*dest);
*dest = real;
}
}
if (!res)
{
if (IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
return CREATE_DEST_DIR_FAILED;
}
else if (IS_IO_ERROR (error, INVALID_FILENAME) &&
!handled_invalid_filename)
{
handled_invalid_filename = TRUE;
g_assert (*dest_fs_type == NULL);
dest_dir = g_file_get_parent (*dest);
if (dest_dir != NULL)
{
*dest_fs_type = query_fs_type (dest_dir, job->cancellable);
new_dest = get_target_file (src, dest_dir, *dest_fs_type, same_fs);
g_object_unref (dest_dir);
if (!g_file_equal (*dest, new_dest))
{
g_object_unref (*dest);
*dest = new_dest;
g_error_free (error);
return CREATE_DEST_DIR_RETRY;
}
else
{
g_object_unref (new_dest);
}
}
}
primary = f (_("Error while copying."));
details = NULL;
if (IS_IO_ERROR (error, PERMISSION_DENIED))
{
secondary = f (_("The folder “%B” cannot be copied because you do not have "
"permissions to create it in the destination."), src);
}
else
{
secondary = f (_("There was an error creating the folder “%B”."), src);
details = error->message;
}
response = run_warning (job,
primary,
secondary,
details,
FALSE,
CANCEL, SKIP, RETRY,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1)
{
/* Skip: Do Nothing */
}
else if (response == 2)
{
goto retry;
}
else
{
g_assert_not_reached ();
}
return CREATE_DEST_DIR_FAILED;
}
nautilus_file_changes_queue_file_added (*dest);
if (job->undo_info != NULL)
{
nautilus_file_undo_info_ext_add_origin_target_pair (NAUTILUS_FILE_UNDO_INFO_EXT (job->undo_info),
src, *dest);
}
return CREATE_DEST_DIR_SUCCESS;
}
/* a return value of FALSE means retry, i.e.
* the destination has changed and the source
* is expected to re-try the preceding
* g_file_move() or g_file_copy() call with
* the new destination.
*/
static gboolean
copy_move_directory (CopyMoveJob *copy_job,
GFile *src,
GFile **dest,
gboolean same_fs,
gboolean create_dest,
char **parent_dest_fs_type,
SourceInfo *source_info,
TransferInfo *transfer_info,
GHashTable *debuting_files,
gboolean *skipped_file,
gboolean readonly_source_fs)
{
GFileInfo *info;
GError *error;
GFile *src_file;
GFileEnumerator *enumerator;
char *primary, *secondary, *details;
char *dest_fs_type;
int response;
gboolean skip_error;
gboolean local_skipped_file;
CommonJob *job;
GFileCopyFlags flags;
job = (CommonJob *) copy_job;
if (create_dest)
{
switch (create_dest_dir (job, src, dest, same_fs, parent_dest_fs_type))
{
case CREATE_DEST_DIR_RETRY:
{
/* next time copy_move_directory() is called,
* create_dest will be FALSE if a directory already
* exists under the new name (i.e. WOULD_RECURSE)
*/
return FALSE;
}
case CREATE_DEST_DIR_FAILED:
{
*skipped_file = TRUE;
return TRUE;
}
case CREATE_DEST_DIR_SUCCESS:
default:
{
}
break;
}
if (debuting_files)
{
g_hash_table_replace (debuting_files, g_object_ref (*dest), GINT_TO_POINTER (TRUE));
}
}
local_skipped_file = FALSE;
dest_fs_type = NULL;
skip_error = should_skip_readdir_error (job, src);
retry:
error = NULL;
enumerator = g_file_enumerate_children (src,
G_FILE_ATTRIBUTE_STANDARD_NAME,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable,
&error);
if (enumerator)
{
error = NULL;
while (!job_aborted (job) &&
(info = g_file_enumerator_next_file (enumerator, job->cancellable, skip_error ? NULL : &error)) != NULL)
{
src_file = g_file_get_child (src,
g_file_info_get_name (info));
copy_move_file (copy_job, src_file, *dest, same_fs, FALSE, &dest_fs_type,
source_info, transfer_info, NULL, NULL, FALSE, &local_skipped_file,
readonly_source_fs);
if (local_skipped_file)
{
transfer_add_file_to_count (src_file, job, transfer_info);
report_copy_progress (copy_job, source_info, transfer_info);
}
g_object_unref (src_file);
g_object_unref (info);
}
g_file_enumerator_close (enumerator, job->cancellable, NULL);
g_object_unref (enumerator);
if (error && IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
else if (error)
{
if (copy_job->is_move)
{
primary = f (_("Error while moving."));
}
else
{
primary = f (_("Error while copying."));
}
details = NULL;
if (IS_IO_ERROR (error, PERMISSION_DENIED))
{
secondary = f (_("Files in the folder “%B” cannot be copied because you do "
"not have permissions to see them."), src);
}
else
{
secondary = f (_("There was an error getting information about the files in the folder “%B”."), src);
details = error->message;
}
response = run_warning (job,
primary,
secondary,
details,
FALSE,
CANCEL, _("_Skip files"),
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1)
{
/* Skip: Do Nothing */
local_skipped_file = TRUE;
}
else
{
g_assert_not_reached ();
}
}
/* Count the copied directory as a file */
transfer_info->num_files++;
report_copy_progress (copy_job, source_info, transfer_info);
if (debuting_files)
{
g_hash_table_replace (debuting_files, g_object_ref (*dest), GINT_TO_POINTER (create_dest));
}
}
else if (IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
else
{
if (copy_job->is_move)
{
primary = f (_("Error while moving."));
}
else
{
primary = f (_("Error while copying."));
}
details = NULL;
if (IS_IO_ERROR (error, PERMISSION_DENIED))
{
secondary = f (_("The folder “%B” cannot be copied because you do not have "
"permissions to read it."), src);
}
else
{
secondary = f (_("There was an error reading the folder “%B”."), src);
details = error->message;
}
response = run_warning (job,
primary,
secondary,
details,
FALSE,
CANCEL, SKIP, RETRY,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1)
{
/* Skip: Do Nothing */
local_skipped_file = TRUE;
}
else if (response == 2)
{
goto retry;
}
else
{
g_assert_not_reached ();
}
}
if (create_dest)
{
flags = (readonly_source_fs) ? G_FILE_COPY_NOFOLLOW_SYMLINKS | G_FILE_COPY_TARGET_DEFAULT_PERMS
: G_FILE_COPY_NOFOLLOW_SYMLINKS;
/* Ignore errors here. Failure to copy metadata is not a hard error */
g_file_copy_attributes (src, *dest,
flags,
job->cancellable, NULL);
}
if (!job_aborted (job) && copy_job->is_move &&
/* Don't delete source if there was a skipped file */
!local_skipped_file)
{
if (!g_file_delete (src, job->cancellable, &error))
{
if (job->skip_all_error)
{
goto skip;
}
primary = f (_("Error while moving “%B”."), src);
secondary = f (_("Could not remove the source folder."));
details = error->message;
response = run_cancel_or_skip_warning (job,
primary,
secondary,
details,
source_info->num_files,
source_info->num_files - transfer_info->num_files);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1) /* skip all */
{
job->skip_all_error = TRUE;
local_skipped_file = TRUE;
}
else if (response == 2) /* skip */
{
local_skipped_file = TRUE;
}
else
{
g_assert_not_reached ();
}
skip:
g_error_free (error);
}
}
if (local_skipped_file)
{
*skipped_file = TRUE;
}
g_free (dest_fs_type);
return TRUE;
}
typedef struct
{
CommonJob *job;
GFile *source;
} DeleteExistingFileData;
static void
existing_file_removed_callback (GFile *file,
GError *error,
gpointer callback_data)
{
DeleteExistingFileData *data = callback_data;
CommonJob *job;
GFile *source;
GFileType file_type;
char *primary;
char *secondary;
char *details = NULL;
int response;
job = data->job;
source = data->source;
if (error == NULL)
{
nautilus_file_changes_queue_file_removed (file);
return;
}
if (job_aborted (job) || job->skip_all_error)
{
return;
}
primary = f (_("Error while copying “%B”."), source);
file_type = g_file_query_file_type (file,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable);
if (file_type == G_FILE_TYPE_DIRECTORY)
{
secondary = f (_("Could not remove the already existing folder %F."),
file);
}
else
{
secondary = f (_("Could not remove the already existing file %F."),
file);
}
details = error->message;
/* set show_all to TRUE here, as we don't know how many
* files we'll end up processing yet.
*/
response = run_warning (job,
primary,
secondary,
details,
TRUE,
CANCEL, SKIP_ALL, SKIP,
NULL);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1)
{
/* skip all */
job->skip_all_error = TRUE;
}
}
typedef struct
{
CopyMoveJob *job;
goffset last_size;
SourceInfo *source_info;
TransferInfo *transfer_info;
} ProgressData;
static void
copy_file_progress_callback (goffset current_num_bytes,
goffset total_num_bytes,
gpointer user_data)
{
ProgressData *pdata;
goffset new_size;
pdata = user_data;
new_size = current_num_bytes - pdata->last_size;
if (new_size > 0)
{
pdata->transfer_info->num_bytes += new_size;
pdata->last_size = current_num_bytes;
report_copy_progress (pdata->job,
pdata->source_info,
pdata->transfer_info);
}
}
static gboolean
test_dir_is_parent (GFile *child,
GFile *root)
{
GFile *f, *tmp;
f = g_file_dup (child);
while (f)
{
if (g_file_equal (f, root))
{
g_object_unref (f);
return TRUE;
}
tmp = f;
f = g_file_get_parent (f);
g_object_unref (tmp);
}
if (f)
{
g_object_unref (f);
}
return FALSE;
}
static char *
query_fs_type (GFile *file,
GCancellable *cancellable)
{
GFileInfo *fsinfo;
char *ret;
ret = NULL;
fsinfo = g_file_query_filesystem_info (file,
G_FILE_ATTRIBUTE_FILESYSTEM_TYPE,
cancellable,
NULL);
if (fsinfo != NULL)
{
ret = g_strdup (g_file_info_get_attribute_string (fsinfo, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE));
g_object_unref (fsinfo);
}
if (ret == NULL)
{
/* ensure that we don't attempt to query
* the FS type for each file in a given
* directory, if it can't be queried. */
ret = g_strdup ("");
}
return ret;
}
static gboolean
is_trusted_desktop_file (GFile *file,
GCancellable *cancellable)
{
char *basename;
gboolean res;
GFileInfo *info;
/* Don't trust non-local files */
if (!g_file_is_native (file))
{
return FALSE;
}
basename = g_file_get_basename (file);
if (!g_str_has_suffix (basename, ".desktop"))
{
g_free (basename);
return FALSE;
}
g_free (basename);
info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
cancellable,
NULL);
if (info == NULL)
{
return FALSE;
}
res = FALSE;
/* Weird file => not trusted,
* Already executable => no need to mark trusted */
if (g_file_info_get_file_type (info) == G_FILE_TYPE_REGULAR &&
!g_file_info_get_attribute_boolean (info,
G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE) &&
nautilus_is_in_system_dir (file))
{
res = TRUE;
}
g_object_unref (info);
return res;
}
static FileConflictResponse *
handle_copy_move_conflict (CommonJob *job,
GFile *src,
GFile *dest,
GFile *dest_dir)
{
FileConflictResponse *response;
g_timer_stop (job->time);
nautilus_progress_info_pause (job->progress);
response = copy_move_conflict_ask_user_action (job->parent_window,
src,
dest,
dest_dir);
nautilus_progress_info_resume (job->progress);
g_timer_continue (job->time);
return response;
}
static GFile *
get_target_file_for_display_name (GFile *dir,
const gchar *name)
{
GFile *dest;
dest = NULL;
dest = g_file_get_child_for_display_name (dir, name, NULL);
if (dest == NULL)
{
dest = g_file_get_child (dir, name);
}
return dest;
}
/* Debuting files is non-NULL only for toplevel items */
static void
copy_move_file (CopyMoveJob *copy_job,
GFile *src,
GFile *dest_dir,
gboolean same_fs,
gboolean unique_names,
char **dest_fs_type,
SourceInfo *source_info,
TransferInfo *transfer_info,
GHashTable *debuting_files,
GdkPoint *position,
gboolean overwrite,
gboolean *skipped_file,
gboolean readonly_source_fs)
{
GFile *dest, *new_dest;
g_autofree gchar *dest_uri = NULL;
GError *error;
GFileCopyFlags flags;
char *primary, *secondary, *details;
int response;
ProgressData pdata;
gboolean would_recurse, is_merge;
CommonJob *job;
gboolean res;
int unique_name_nr;
gboolean handled_invalid_filename;
job = (CommonJob *) copy_job;
if (should_skip_file (job, src))
{
*skipped_file = TRUE;
return;
}
unique_name_nr = 1;
/* another file in the same directory might have handled the invalid
* filename condition for us
*/
handled_invalid_filename = *dest_fs_type != NULL;
if (unique_names)
{
dest = get_unique_target_file (src, dest_dir, same_fs, *dest_fs_type, unique_name_nr++);
}
else if (copy_job->target_name != NULL)
{
dest = get_target_file_with_custom_name (src, dest_dir, *dest_fs_type, same_fs,
copy_job->target_name);
}
else
{
dest = get_target_file (src, dest_dir, *dest_fs_type, same_fs);
}
/* Don't allow recursive move/copy into itself.
* (We would get a file system error if we proceeded but it is nicer to
* detect and report it at this level) */
if (test_dir_is_parent (dest_dir, src))
{
if (job->skip_all_error)
{
goto out;
}
/* the run_warning() frees all strings passed in automatically */
primary = copy_job->is_move ? g_strdup (_("You cannot move a folder into itself."))
: g_strdup (_("You cannot copy a folder into itself."));
secondary = g_strdup (_("The destination folder is inside the source folder."));
response = run_cancel_or_skip_warning (job,
primary,
secondary,
NULL,
source_info->num_files,
source_info->num_files - transfer_info->num_files);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1) /* skip all */
{
job->skip_all_error = TRUE;
}
else if (response == 2) /* skip */
{ /* do nothing */
}
else
{
g_assert_not_reached ();
}
goto out;
}
/* Don't allow copying over the source or one of the parents of the source.
*/
if (test_dir_is_parent (src, dest))
{
if (job->skip_all_error)
{
goto out;
}
/* the run_warning() frees all strings passed in automatically */
primary = copy_job->is_move ? g_strdup (_("You cannot move a file over itself."))
: g_strdup (_("You cannot copy a file over itself."));
secondary = g_strdup (_("The source file would be overwritten by the destination."));
response = run_cancel_or_skip_warning (job,
primary,
secondary,
NULL,
source_info->num_files,
source_info->num_files - transfer_info->num_files);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1) /* skip all */
{
job->skip_all_error = TRUE;
}
else if (response == 2) /* skip */
{ /* do nothing */
}
else
{
g_assert_not_reached ();
}
goto out;
}
retry:
error = NULL;
flags = G_FILE_COPY_NOFOLLOW_SYMLINKS;
if (overwrite)
{
flags |= G_FILE_COPY_OVERWRITE;
}
if (readonly_source_fs)
{
flags |= G_FILE_COPY_TARGET_DEFAULT_PERMS;
}
pdata.job = copy_job;
pdata.last_size = 0;
pdata.source_info = source_info;
pdata.transfer_info = transfer_info;
if (copy_job->is_move)
{
res = g_file_move (src, dest,
flags,
job->cancellable,
copy_file_progress_callback,
&pdata,
&error);
}
else
{
res = g_file_copy (src, dest,
flags,
job->cancellable,
copy_file_progress_callback,
&pdata,
&error);
}
if (res)
{
GFile *real;
real = map_possibly_volatile_file_to_real (dest, job->cancellable, &error);
if (real == NULL)
{
res = FALSE;
}
else
{
g_object_unref (dest);
dest = real;
}
}
if (res)
{
transfer_info->num_files++;
report_copy_progress (copy_job, source_info, transfer_info);
if (debuting_files)
{
dest_uri = g_file_get_uri (dest);
if (position)
{
nautilus_file_changes_queue_schedule_position_set (dest, *position, job->screen_num);
}
else if (eel_uri_is_desktop (dest_uri))
{
nautilus_file_changes_queue_schedule_position_remove (dest);
}
g_hash_table_replace (debuting_files, g_object_ref (dest), GINT_TO_POINTER (TRUE));
}
if (copy_job->is_move)
{
nautilus_file_changes_queue_file_moved (src, dest);
}
else
{
nautilus_file_changes_queue_file_added (dest);
}
/* If copying a trusted desktop file to the desktop,
* mark it as trusted. */
if (copy_job->desktop_location != NULL &&
g_file_equal (copy_job->desktop_location, dest_dir) &&
is_trusted_desktop_file (src, job->cancellable))
{
mark_desktop_file_trusted (job,
job->cancellable,
dest,
FALSE);
}
if (job->undo_info != NULL)
{
nautilus_file_undo_info_ext_add_origin_target_pair (NAUTILUS_FILE_UNDO_INFO_EXT (job->undo_info),
src, dest);
}
g_object_unref (dest);
return;
}
if (!handled_invalid_filename &&
IS_IO_ERROR (error, INVALID_FILENAME))
{
handled_invalid_filename = TRUE;
g_assert (*dest_fs_type == NULL);
*dest_fs_type = query_fs_type (dest_dir, job->cancellable);
if (unique_names)
{
new_dest = get_unique_target_file (src, dest_dir, same_fs, *dest_fs_type, unique_name_nr);
}
else
{
new_dest = get_target_file (src, dest_dir, *dest_fs_type, same_fs);
}
if (!g_file_equal (dest, new_dest))
{
g_object_unref (dest);
dest = new_dest;
g_error_free (error);
goto retry;
}
else
{
g_object_unref (new_dest);
}
}
/* Conflict */
if (!overwrite &&
IS_IO_ERROR (error, EXISTS))
{
gboolean is_merge;
FileConflictResponse *response;
g_error_free (error);
if (unique_names)
{
g_object_unref (dest);
dest = get_unique_target_file (src, dest_dir, same_fs, *dest_fs_type, unique_name_nr++);
goto retry;
}
is_merge = FALSE;
if (is_dir (dest) && is_dir (src))
{
is_merge = TRUE;
}
if ((is_merge && job->merge_all) ||
(!is_merge && job->replace_all))
{
overwrite = TRUE;
goto retry;
}
if (job->skip_all_conflict)
{
goto out;
}
response = handle_copy_move_conflict (job, src, dest, dest_dir);
if (response->id == GTK_RESPONSE_CANCEL ||
response->id == GTK_RESPONSE_DELETE_EVENT)
{
file_conflict_response_free (response);
abort_job (job);
}
else if (response->id == CONFLICT_RESPONSE_SKIP)
{
if (response->apply_to_all)
{
job->skip_all_conflict = TRUE;
}
file_conflict_response_free (response);
}
else if (response->id == CONFLICT_RESPONSE_REPLACE) /* merge/replace */
{
if (response->apply_to_all)
{
if (is_merge)
{
job->merge_all = TRUE;
}
else
{
job->replace_all = TRUE;
}
}
overwrite = TRUE;
file_conflict_response_free (response);
goto retry;
}
else if (response->id == CONFLICT_RESPONSE_RENAME)
{
g_object_unref (dest);
dest = get_target_file_for_display_name (dest_dir,
response->new_name);
file_conflict_response_free (response);
goto retry;
}
else
{
g_assert_not_reached ();
}
}
else if (overwrite &&
IS_IO_ERROR (error, IS_DIRECTORY))
{
gboolean existing_file_deleted;
DeleteExistingFileData data;
g_error_free (error);
data.job = job;
data.source = src;
existing_file_deleted =
delete_file_recursively (dest,
job->cancellable,
existing_file_removed_callback,
&data);
if (existing_file_deleted)
{
goto retry;
}
}
/* Needs to recurse */
else if (IS_IO_ERROR (error, WOULD_RECURSE) ||
IS_IO_ERROR (error, WOULD_MERGE))
{
is_merge = error->code == G_IO_ERROR_WOULD_MERGE;
would_recurse = error->code == G_IO_ERROR_WOULD_RECURSE;
g_error_free (error);
if (overwrite && would_recurse)
{
error = NULL;
/* Copying a dir onto file, first remove the file */
if (!g_file_delete (dest, job->cancellable, &error) &&
!IS_IO_ERROR (error, NOT_FOUND))
{
if (job->skip_all_error)
{
g_error_free (error);
goto out;
}
if (copy_job->is_move)
{
primary = f (_("Error while moving “%B”."), src);
}
else
{
primary = f (_("Error while copying “%B”."), src);
}
secondary = f (_("Could not remove the already existing file with the same name in %F."), dest_dir);
details = error->message;
/* setting TRUE on show_all here, as we could have
* another error on the same file later.
*/
response = run_warning (job,
primary,
secondary,
details,
TRUE,
CANCEL, SKIP_ALL, SKIP,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1) /* skip all */
{
job->skip_all_error = TRUE;
}
else if (response == 2) /* skip */
{ /* do nothing */
}
else
{
g_assert_not_reached ();
}
goto out;
}
if (error)
{
g_error_free (error);
error = NULL;
}
nautilus_file_changes_queue_file_removed (dest);
}
if (is_merge)
{
/* On merge we now write in the target directory, which may not
* be in the same directory as the source, even if the parent is
* (if the merged directory is a mountpoint). This could cause
* problems as we then don't transcode filenames.
* We just set same_fs to FALSE which is safe but a bit slower. */
same_fs = FALSE;
}
if (!copy_move_directory (copy_job, src, &dest, same_fs,
would_recurse, dest_fs_type,
source_info, transfer_info,
debuting_files, skipped_file,
readonly_source_fs))
{
/* destination changed, since it was an invalid file name */
g_assert (*dest_fs_type != NULL);
handled_invalid_filename = TRUE;
goto retry;
}
g_object_unref (dest);
return;
}
else if (IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
/* Other error */
else
{
if (job->skip_all_error)
{
g_error_free (error);
goto out;
}
primary = f (_("Error while copying “%B”."), src);
secondary = f (_("There was an error copying the file into %F."), dest_dir);
details = error->message;
response = run_cancel_or_skip_warning (job,
primary,
secondary,
details,
source_info->num_files,
source_info->num_files - transfer_info->num_files);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1) /* skip all */
{
job->skip_all_error = TRUE;
}
else if (response == 2) /* skip */
{ /* do nothing */
}
else
{
g_assert_not_reached ();
}
}
out:
*skipped_file = TRUE; /* Or aborted, but same-same */
g_object_unref (dest);
}
static void
copy_files (CopyMoveJob *job,
const char *dest_fs_id,
SourceInfo *source_info,
TransferInfo *transfer_info)
{
CommonJob *common;
GList *l;
GFile *src;
gboolean same_fs;
int i;
GdkPoint *point;
gboolean skipped_file;
gboolean unique_names;
GFile *dest;
GFile *source_dir;
char *dest_fs_type;
GFileInfo *inf;
gboolean readonly_source_fs;
dest_fs_type = NULL;
readonly_source_fs = FALSE;
common = &job->common;
report_copy_progress (job, source_info, transfer_info);
/* Query the source dir, not the file because if it's a symlink we'll follow it */
source_dir = g_file_get_parent ((GFile *) job->files->data);
if (source_dir)
{
inf = g_file_query_filesystem_info (source_dir, "filesystem::readonly", NULL, NULL);
if (inf != NULL)
{
readonly_source_fs = g_file_info_get_attribute_boolean (inf, "filesystem::readonly");
g_object_unref (inf);
}
g_object_unref (source_dir);
}
unique_names = (job->destination == NULL);
i = 0;
for (l = job->files;
l != NULL && !job_aborted (common);
l = l->next)
{
src = l->data;
if (i < job->n_icon_positions)
{
point = &job->icon_positions[i];
}
else
{
point = NULL;
}
same_fs = FALSE;
if (dest_fs_id)
{
same_fs = has_fs_id (src, dest_fs_id);
}
if (job->destination)
{
dest = g_object_ref (job->destination);
}
else
{
dest = g_file_get_parent (src);
}
if (dest)
{
skipped_file = FALSE;
copy_move_file (job, src, dest,
same_fs, unique_names,
&dest_fs_type,
source_info, transfer_info,
job->debuting_files,
point, FALSE, &skipped_file,
readonly_source_fs);
g_object_unref (dest);
if (skipped_file)
{
transfer_add_file_to_count (src, common, transfer_info);
report_copy_progress (job, source_info, transfer_info);
}
}
i++;
}
g_free (dest_fs_type);
}
static void
copy_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
CopyMoveJob *job;
job = user_data;
if (job->done_callback)
{
job->done_callback (job->debuting_files,
!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
g_list_free_full (job->files, g_object_unref);
if (job->destination)
{
g_object_unref (job->destination);
}
if (job->desktop_location)
{
g_object_unref (job->desktop_location);
}
g_hash_table_unref (job->debuting_files);
g_free (job->icon_positions);
g_free (job->target_name);
g_clear_object (&job->fake_display_source);
finalize_common ((CommonJob *) job);
nautilus_file_changes_consume_changes (TRUE);
}
static void
copy_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
CopyMoveJob *job;
CommonJob *common;
SourceInfo source_info;
TransferInfo transfer_info;
char *dest_fs_id;
GFile *dest;
job = task_data;
common = &job->common;
dest_fs_id = NULL;
nautilus_progress_info_start (job->common.progress);
scan_sources (job->files,
&source_info,
common,
OP_KIND_COPY);
if (job_aborted (common))
{
goto aborted;
}
if (job->destination)
{
dest = g_object_ref (job->destination);
}
else
{
/* Duplication, no dest,
* use source for free size, etc
*/
dest = g_file_get_parent (job->files->data);
}
verify_destination (&job->common,
dest,
&dest_fs_id,
source_info.num_bytes);
g_object_unref (dest);
if (job_aborted (common))
{
goto aborted;
}
g_timer_start (job->common.time);
memset (&transfer_info, 0, sizeof (transfer_info));
copy_files (job,
dest_fs_id,
&source_info, &transfer_info);
aborted:
g_free (dest_fs_id);
}
void
nautilus_file_operations_copy_file (GFile *source_file,
GFile *target_dir,
const gchar *source_display_name,
const gchar *new_name,
GtkWindow *parent_window,
NautilusCopyCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
CopyMoveJob *job;
job = op_job_new (CopyMoveJob, parent_window);
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
job->files = g_list_append (NULL, g_object_ref (source_file));
job->destination = g_object_ref (target_dir);
/* Need to indicate the destination for the operation notification open
* button. */
nautilus_progress_info_set_destination (((CommonJob *) job)->progress, target_dir);
job->target_name = g_strdup (new_name);
job->debuting_files = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
if (source_display_name != NULL)
{
gchar *path;
path = g_build_filename ("/", source_display_name, NULL);
job->fake_display_source = g_file_new_for_path (path);
g_free (path);
}
inhibit_power_manager ((CommonJob *) job, _("Copying Files"));
task = g_task_new (NULL, job->common.cancellable, copy_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, copy_task_thread_func);
g_object_unref (task);
}
void
nautilus_file_operations_copy (GList *files,
GArray *relative_item_points,
GFile *target_dir,
GtkWindow *parent_window,
NautilusCopyCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
CopyMoveJob *job;
job = op_job_new (CopyMoveJob, parent_window);
job->desktop_location = nautilus_get_desktop_location ();
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
job->files = g_list_copy_deep (files, (GCopyFunc) g_object_ref, NULL);
job->destination = g_object_ref (target_dir);
/* Need to indicate the destination for the operation notification open
* button. */
nautilus_progress_info_set_destination (((CommonJob *) job)->progress, target_dir);
if (relative_item_points != NULL &&
relative_item_points->len > 0)
{
job->icon_positions =
g_memdup (relative_item_points->data,
sizeof (GdkPoint) * relative_item_points->len);
job->n_icon_positions = relative_item_points->len;
}
job->debuting_files = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
inhibit_power_manager ((CommonJob *) job, _("Copying Files"));
if (!nautilus_file_undo_manager_is_operating ())
{
GFile *src_dir;
src_dir = g_file_get_parent (files->data);
job->common.undo_info = nautilus_file_undo_info_ext_new (NAUTILUS_FILE_UNDO_OP_COPY,
g_list_length (files),
src_dir, target_dir);
g_object_unref (src_dir);
}
task = g_task_new (NULL, job->common.cancellable, copy_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, copy_task_thread_func);
g_object_unref (task);
}
static void
report_preparing_move_progress (CopyMoveJob *move_job,
int total,
int left)
{
CommonJob *job;
job = (CommonJob *) move_job;
nautilus_progress_info_take_status (job->progress,
f (_("Preparing to move to “%B”"),
move_job->destination));
nautilus_progress_info_take_details (job->progress,
f (ngettext ("Preparing to move %'d file",
"Preparing to move %'d files",
left), left));
nautilus_progress_info_pulse_progress (job->progress);
}
typedef struct
{
GFile *file;
gboolean overwrite;
gboolean has_position;
GdkPoint position;
} MoveFileCopyFallback;
static MoveFileCopyFallback *
move_copy_file_callback_new (GFile *file,
gboolean overwrite,
GdkPoint *position)
{
MoveFileCopyFallback *fallback;
fallback = g_new (MoveFileCopyFallback, 1);
fallback->file = file;
fallback->overwrite = overwrite;
if (position)
{
fallback->has_position = TRUE;
fallback->position = *position;
}
else
{
fallback->has_position = FALSE;
}
return fallback;
}
static GList *
get_files_from_fallbacks (GList *fallbacks)
{
MoveFileCopyFallback *fallback;
GList *res, *l;
res = NULL;
for (l = fallbacks; l != NULL; l = l->next)
{
fallback = l->data;
res = g_list_prepend (res, fallback->file);
}
return g_list_reverse (res);
}
static void
move_file_prepare (CopyMoveJob *move_job,
GFile *src,
GFile *dest_dir,
gboolean same_fs,
char **dest_fs_type,
GHashTable *debuting_files,
GdkPoint *position,
GList **fallback_files,
int files_left)
{
GFile *dest, *new_dest;
g_autofree gchar *dest_uri = NULL;
GError *error;
CommonJob *job;
gboolean overwrite;
char *primary, *secondary, *details;
int response;
GFileCopyFlags flags;
MoveFileCopyFallback *fallback;
gboolean handled_invalid_filename;
overwrite = FALSE;
handled_invalid_filename = *dest_fs_type != NULL;
job = (CommonJob *) move_job;
dest = get_target_file (src, dest_dir, *dest_fs_type, same_fs);
/* Don't allow recursive move/copy into itself.
* (We would get a file system error if we proceeded but it is nicer to
* detect and report it at this level) */
if (test_dir_is_parent (dest_dir, src))
{
if (job->skip_all_error)
{
goto out;
}
/* the run_warning() frees all strings passed in automatically */
primary = move_job->is_move ? g_strdup (_("You cannot move a folder into itself."))
: g_strdup (_("You cannot copy a folder into itself."));
secondary = g_strdup (_("The destination folder is inside the source folder."));
response = run_warning (job,
primary,
secondary,
NULL,
files_left > 1,
CANCEL, SKIP_ALL, SKIP,
NULL);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1) /* skip all */
{
job->skip_all_error = TRUE;
}
else if (response == 2) /* skip */
{ /* do nothing */
}
else
{
g_assert_not_reached ();
}
goto out;
}
retry:
flags = G_FILE_COPY_NOFOLLOW_SYMLINKS | G_FILE_COPY_NO_FALLBACK_FOR_MOVE;
if (overwrite)
{
flags |= G_FILE_COPY_OVERWRITE;
}
error = NULL;
if (g_file_move (src, dest,
flags,
job->cancellable,
NULL,
NULL,
&error))
{
if (debuting_files)
{
g_hash_table_replace (debuting_files, g_object_ref (dest), GINT_TO_POINTER (TRUE));
}
nautilus_file_changes_queue_file_moved (src, dest);
dest_uri = g_file_get_uri (dest);
if (position)
{
nautilus_file_changes_queue_schedule_position_set (dest, *position, job->screen_num);
}
else if (eel_uri_is_desktop (dest_uri))
{
nautilus_file_changes_queue_schedule_position_remove (dest);
}
if (job->undo_info != NULL)
{
nautilus_file_undo_info_ext_add_origin_target_pair (NAUTILUS_FILE_UNDO_INFO_EXT (job->undo_info),
src, dest);
}
return;
}
if (IS_IO_ERROR (error, INVALID_FILENAME) &&
!handled_invalid_filename)
{
g_error_free (error);
handled_invalid_filename = TRUE;
g_assert (*dest_fs_type == NULL);
*dest_fs_type = query_fs_type (dest_dir, job->cancellable);
new_dest = get_target_file (src, dest_dir, *dest_fs_type, same_fs);
if (!g_file_equal (dest, new_dest))
{
g_object_unref (dest);
dest = new_dest;
goto retry;
}
else
{
g_object_unref (new_dest);
}
}
/* Conflict */
else if (!overwrite &&
IS_IO_ERROR (error, EXISTS))
{
gboolean is_merge;
FileConflictResponse *response;
g_error_free (error);
is_merge = FALSE;
if (is_dir (dest) && is_dir (src))
{
is_merge = TRUE;
}
if ((is_merge && job->merge_all) ||
(!is_merge && job->replace_all))
{
overwrite = TRUE;
goto retry;
}
if (job->skip_all_conflict)
{
goto out;
}
response = handle_copy_move_conflict (job, src, dest, dest_dir);
if (response->id == GTK_RESPONSE_CANCEL ||
response->id == GTK_RESPONSE_DELETE_EVENT)
{
file_conflict_response_free (response);
abort_job (job);
}
else if (response->id == CONFLICT_RESPONSE_SKIP)
{
if (response->apply_to_all)
{
job->skip_all_conflict = TRUE;
}
file_conflict_response_free (response);
}
else if (response->id == CONFLICT_RESPONSE_REPLACE) /* merge/replace */
{
if (response->apply_to_all)
{
if (is_merge)
{
job->merge_all = TRUE;
}
else
{
job->replace_all = TRUE;
}
}
overwrite = TRUE;
file_conflict_response_free (response);
goto retry;
}
else if (response->id == CONFLICT_RESPONSE_RENAME)
{
g_object_unref (dest);
dest = get_target_file_for_display_name (dest_dir,
response->new_name);
file_conflict_response_free (response);
goto retry;
}
else
{
g_assert_not_reached ();
}
}
else if (IS_IO_ERROR (error, WOULD_RECURSE) ||
IS_IO_ERROR (error, WOULD_MERGE) ||
IS_IO_ERROR (error, NOT_SUPPORTED) ||
(overwrite && IS_IO_ERROR (error, IS_DIRECTORY)))
{
g_error_free (error);
fallback = move_copy_file_callback_new (src,
overwrite,
position);
*fallback_files = g_list_prepend (*fallback_files, fallback);
}
else if (IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
/* Other error */
else
{
if (job->skip_all_error)
{
g_error_free (error);
goto out;
}
primary = f (_("Error while moving “%B”."), src);
secondary = f (_("There was an error moving the file into %F."), dest_dir);
details = error->message;
response = run_warning (job,
primary,
secondary,
details,
files_left > 1,
CANCEL, SKIP_ALL, SKIP,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1) /* skip all */
{
job->skip_all_error = TRUE;
}
else if (response == 2) /* skip */
{ /* do nothing */
}
else
{
g_assert_not_reached ();
}
}
out:
g_object_unref (dest);
}
static void
move_files_prepare (CopyMoveJob *job,
const char *dest_fs_id,
char **dest_fs_type,
GList **fallbacks)
{
CommonJob *common;
GList *l;
GFile *src;
gboolean same_fs;
int i;
GdkPoint *point;
int total, left;
common = &job->common;
total = left = g_list_length (job->files);
report_preparing_move_progress (job, total, left);
i = 0;
for (l = job->files;
l != NULL && !job_aborted (common);
l = l->next)
{
src = l->data;
if (i < job->n_icon_positions)
{
point = &job->icon_positions[i];
}
else
{
point = NULL;
}
same_fs = FALSE;
if (dest_fs_id)
{
same_fs = has_fs_id (src, dest_fs_id);
}
move_file_prepare (job, src, job->destination,
same_fs, dest_fs_type,
job->debuting_files,
point,
fallbacks,
left);
report_preparing_move_progress (job, total, --left);
i++;
}
*fallbacks = g_list_reverse (*fallbacks);
}
static void
move_files (CopyMoveJob *job,
GList *fallbacks,
const char *dest_fs_id,
char **dest_fs_type,
SourceInfo *source_info,
TransferInfo *transfer_info)
{
CommonJob *common;
GList *l;
GFile *src;
gboolean same_fs;
int i;
GdkPoint *point;
gboolean skipped_file;
MoveFileCopyFallback *fallback;
common = &job->common;
report_copy_progress (job, source_info, transfer_info);
i = 0;
for (l = fallbacks;
l != NULL && !job_aborted (common);
l = l->next)
{
fallback = l->data;
src = fallback->file;
if (fallback->has_position)
{
point = &fallback->position;
}
else
{
point = NULL;
}
same_fs = FALSE;
if (dest_fs_id)
{
same_fs = has_fs_id (src, dest_fs_id);
}
/* Set overwrite to true, as the user has
* selected overwrite on all toplevel items */
skipped_file = FALSE;
copy_move_file (job, src, job->destination,
same_fs, FALSE, dest_fs_type,
source_info, transfer_info,
job->debuting_files,
point, fallback->overwrite, &skipped_file, FALSE);
i++;
if (skipped_file)
{
transfer_add_file_to_count (src, common, transfer_info);
report_copy_progress (job, source_info, transfer_info);
}
}
}
static void
move_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
CopyMoveJob *job;
job = user_data;
if (job->done_callback)
{
job->done_callback (job->debuting_files,
!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
g_list_free_full (job->files, g_object_unref);
g_object_unref (job->destination);
g_hash_table_unref (job->debuting_files);
g_free (job->icon_positions);
finalize_common ((CommonJob *) job);
nautilus_file_changes_consume_changes (TRUE);
}
static void
move_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
CopyMoveJob *job;
CommonJob *common;
GList *fallbacks;
SourceInfo source_info;
TransferInfo transfer_info;
char *dest_fs_id;
char *dest_fs_type;
GList *fallback_files;
job = task_data;
common = &job->common;
dest_fs_id = NULL;
dest_fs_type = NULL;
fallbacks = NULL;
nautilus_progress_info_start (job->common.progress);
verify_destination (&job->common,
job->destination,
&dest_fs_id,
-1);
if (job_aborted (common))
{
goto aborted;
}
/* This moves all files that we can do without copy + delete */
move_files_prepare (job, dest_fs_id, &dest_fs_type, &fallbacks);
if (job_aborted (common))
{
goto aborted;
}
/* The rest we need to do deep copy + delete behind on,
* so scan for size */
fallback_files = get_files_from_fallbacks (fallbacks);
scan_sources (fallback_files,
&source_info,
common,
OP_KIND_MOVE);
g_list_free (fallback_files);
if (job_aborted (common))
{
goto aborted;
}
verify_destination (&job->common,
job->destination,
NULL,
source_info.num_bytes);
if (job_aborted (common))
{
goto aborted;
}
memset (&transfer_info, 0, sizeof (transfer_info));
move_files (job,
fallbacks,
dest_fs_id, &dest_fs_type,
&source_info, &transfer_info);
aborted:
g_list_free_full (fallbacks, g_free);
g_free (dest_fs_id);
g_free (dest_fs_type);
}
void
nautilus_file_operations_move (GList *files,
GArray *relative_item_points,
GFile *target_dir,
GtkWindow *parent_window,
NautilusCopyCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
CopyMoveJob *job;
job = op_job_new (CopyMoveJob, parent_window);
job->is_move = TRUE;
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
job->files = g_list_copy_deep (files, (GCopyFunc) g_object_ref, NULL);
job->destination = g_object_ref (target_dir);
/* Need to indicate the destination for the operation notification open
* button. */
nautilus_progress_info_set_destination (((CommonJob *) job)->progress, target_dir);
if (relative_item_points != NULL &&
relative_item_points->len > 0)
{
job->icon_positions =
g_memdup (relative_item_points->data,
sizeof (GdkPoint) * relative_item_points->len);
job->n_icon_positions = relative_item_points->len;
}
job->debuting_files = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
inhibit_power_manager ((CommonJob *) job, _("Moving Files"));
if (!nautilus_file_undo_manager_is_operating ())
{
GFile *src_dir;
src_dir = g_file_get_parent (files->data);
if (g_file_has_uri_scheme (g_list_first (files)->data, "trash"))
{
job->common.undo_info = nautilus_file_undo_info_ext_new (NAUTILUS_FILE_UNDO_OP_RESTORE_FROM_TRASH,
g_list_length (files),
src_dir, target_dir);
}
else
{
job->common.undo_info = nautilus_file_undo_info_ext_new (NAUTILUS_FILE_UNDO_OP_MOVE,
g_list_length (files),
src_dir, target_dir);
}
g_object_unref (src_dir);
}
task = g_task_new (NULL, job->common.cancellable, move_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, move_task_thread_func);
g_object_unref (task);
}
static void
report_preparing_link_progress (CopyMoveJob *link_job,
int total,
int left)
{
CommonJob *job;
job = (CommonJob *) link_job;
nautilus_progress_info_take_status (job->progress,
f (_("Creating links in “%B”"),
link_job->destination));
nautilus_progress_info_take_details (job->progress,
f (ngettext ("Making link to %'d file",
"Making links to %'d files",
left), left));
nautilus_progress_info_set_progress (job->progress, left, total);
}
static char *
get_abs_path_for_symlink (GFile *file,
GFile *destination)
{
GFile *root, *parent;
char *relative, *abs;
if (g_file_is_native (file) || g_file_is_native (destination))
{
return g_file_get_path (file);
}
root = g_object_ref (file);
while ((parent = g_file_get_parent (root)) != NULL)
{
g_object_unref (root);
root = parent;
}
relative = g_file_get_relative_path (root, file);
g_object_unref (root);
abs = g_strconcat ("/", relative, NULL);
g_free (relative);
return abs;
}
static void
link_file (CopyMoveJob *job,
GFile *src,
GFile *dest_dir,
char **dest_fs_type,
GHashTable *debuting_files,
GdkPoint *position,
int files_left)
{
GFile *src_dir, *dest, *new_dest;
g_autofree gchar *dest_uri = NULL;
int count;
char *path;
gboolean not_local;
GError *error;
CommonJob *common;
char *primary, *secondary, *details;
int response;
gboolean handled_invalid_filename;
common = (CommonJob *) job;
count = 0;
src_dir = g_file_get_parent (src);
if (g_file_equal (src_dir, dest_dir))
{
count = 1;
}
g_object_unref (src_dir);
handled_invalid_filename = *dest_fs_type != NULL;
dest = get_target_file_for_link (src, dest_dir, *dest_fs_type, count);
retry:
error = NULL;
not_local = FALSE;
path = get_abs_path_for_symlink (src, dest);
if (path == NULL)
{
not_local = TRUE;
}
else if (g_file_make_symbolic_link (dest,
path,
common->cancellable,
&error))
{
if (common->undo_info != NULL)
{
nautilus_file_undo_info_ext_add_origin_target_pair (NAUTILUS_FILE_UNDO_INFO_EXT (common->undo_info),
src, dest);
}
g_free (path);
if (debuting_files)
{
g_hash_table_replace (debuting_files, g_object_ref (dest), GINT_TO_POINTER (TRUE));
}
nautilus_file_changes_queue_file_added (dest);
dest_uri = g_file_get_uri (dest);
if (position)
{
nautilus_file_changes_queue_schedule_position_set (dest, *position, common->screen_num);
}
else if (eel_uri_is_desktop (dest_uri))
{
nautilus_file_changes_queue_schedule_position_remove (dest);
}
g_object_unref (dest);
return;
}
g_free (path);
if (error != NULL &&
IS_IO_ERROR (error, INVALID_FILENAME) &&
!handled_invalid_filename)
{
handled_invalid_filename = TRUE;
g_assert (*dest_fs_type == NULL);
*dest_fs_type = query_fs_type (dest_dir, common->cancellable);
new_dest = get_target_file_for_link (src, dest_dir, *dest_fs_type, count);
if (!g_file_equal (dest, new_dest))
{
g_object_unref (dest);
dest = new_dest;
g_error_free (error);
goto retry;
}
else
{
g_object_unref (new_dest);
}
}
/* Conflict */
if (error != NULL && IS_IO_ERROR (error, EXISTS))
{
g_object_unref (dest);
dest = get_target_file_for_link (src, dest_dir, *dest_fs_type, count++);
g_error_free (error);
goto retry;
}
else if (error != NULL && IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
/* Other error */
else if (error != NULL)
{
if (common->skip_all_error)
{
goto out;
}
primary = f (_("Error while creating link to %B."), src);
if (not_local)
{
secondary = f (_("Symbolic links only supported for local files"));
details = NULL;
}
else if (IS_IO_ERROR (error, NOT_SUPPORTED))
{
secondary = f (_("The target doesn’t support symbolic links."));
details = NULL;
}
else
{
secondary = f (_("There was an error creating the symlink in %F."), dest_dir);
details = error->message;
}
response = run_warning (common,
primary,
secondary,
details,
files_left > 1,
CANCEL, SKIP_ALL, SKIP,
NULL);
if (error)
{
g_error_free (error);
}
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (common);
}
else if (response == 1) /* skip all */
{
common->skip_all_error = TRUE;
}
else if (response == 2) /* skip */
{ /* do nothing */
}
else
{
g_assert_not_reached ();
}
}
out:
g_object_unref (dest);
}
static void
link_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
CopyMoveJob *job;
job = user_data;
if (job->done_callback)
{
job->done_callback (job->debuting_files,
!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
g_list_free_full (job->files, g_object_unref);
g_object_unref (job->destination);
g_hash_table_unref (job->debuting_files);
g_free (job->icon_positions);
finalize_common ((CommonJob *) job);
nautilus_file_changes_consume_changes (TRUE);
}
static void
link_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
CopyMoveJob *job;
CommonJob *common;
GFile *src;
GdkPoint *point;
char *dest_fs_type;
int total, left;
int i;
GList *l;
job = task_data;
common = &job->common;
dest_fs_type = NULL;
nautilus_progress_info_start (job->common.progress);
verify_destination (&job->common,
job->destination,
NULL,
-1);
if (job_aborted (common))
{
goto aborted;
}
total = left = g_list_length (job->files);
report_preparing_link_progress (job, total, left);
i = 0;
for (l = job->files;
l != NULL && !job_aborted (common);
l = l->next)
{
src = l->data;
if (i < job->n_icon_positions)
{
point = &job->icon_positions[i];
}
else
{
point = NULL;
}
link_file (job, src, job->destination,
&dest_fs_type, job->debuting_files,
point, left);
report_preparing_link_progress (job, total, --left);
i++;
}
aborted:
g_free (dest_fs_type);
}
void
nautilus_file_operations_link (GList *files,
GArray *relative_item_points,
GFile *target_dir,
GtkWindow *parent_window,
NautilusCopyCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
CopyMoveJob *job;
job = op_job_new (CopyMoveJob, parent_window);
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
job->files = g_list_copy_deep (files, (GCopyFunc) g_object_ref, NULL);
job->destination = g_object_ref (target_dir);
/* Need to indicate the destination for the operation notification open
* button. */
nautilus_progress_info_set_destination (((CommonJob *) job)->progress, target_dir);
if (relative_item_points != NULL &&
relative_item_points->len > 0)
{
job->icon_positions =
g_memdup (relative_item_points->data,
sizeof (GdkPoint) * relative_item_points->len);
job->n_icon_positions = relative_item_points->len;
}
job->debuting_files = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
if (!nautilus_file_undo_manager_is_operating ())
{
GFile *src_dir;
src_dir = g_file_get_parent (files->data);
job->common.undo_info = nautilus_file_undo_info_ext_new (NAUTILUS_FILE_UNDO_OP_CREATE_LINK,
g_list_length (files),
src_dir, target_dir);
g_object_unref (src_dir);
}
task = g_task_new (NULL, job->common.cancellable, link_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, link_task_thread_func);
g_object_unref (task);
}
void
nautilus_file_operations_duplicate (GList *files,
GArray *relative_item_points,
GtkWindow *parent_window,
NautilusCopyCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
CopyMoveJob *job;
GFile *parent;
job = op_job_new (CopyMoveJob, parent_window);
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
job->files = g_list_copy_deep (files, (GCopyFunc) g_object_ref, NULL);
job->destination = NULL;
/* Duplicate files doesn't have a destination, since is the same as source.
* For that set as destination the source parent folder */
parent = g_file_get_parent (files->data);
/* Need to indicate the destination for the operation notification open
* button. */
nautilus_progress_info_set_destination (((CommonJob *) job)->progress, parent);
if (relative_item_points != NULL &&
relative_item_points->len > 0)
{
job->icon_positions =
g_memdup (relative_item_points->data,
sizeof (GdkPoint) * relative_item_points->len);
job->n_icon_positions = relative_item_points->len;
}
job->debuting_files = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
if (!nautilus_file_undo_manager_is_operating ())
{
GFile *src_dir;
src_dir = g_file_get_parent (files->data);
job->common.undo_info =
nautilus_file_undo_info_ext_new (NAUTILUS_FILE_UNDO_OP_DUPLICATE,
g_list_length (files),
src_dir, src_dir);
g_object_unref (src_dir);
}
task = g_task_new (NULL, job->common.cancellable, copy_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, copy_task_thread_func);
g_object_unref (task);
g_object_unref (parent);
}
static void
set_permissions_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
SetPermissionsJob *job;
job = user_data;
g_object_unref (job->file);
if (job->done_callback)
{
job->done_callback (!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
finalize_common ((CommonJob *) job);
}
static void
set_permissions_file (SetPermissionsJob *job,
GFile *file,
GFileInfo *info)
{
CommonJob *common;
GFileInfo *child_info;
gboolean free_info;
guint32 current;
guint32 value;
guint32 mask;
GFileEnumerator *enumerator;
GFile *child;
common = (CommonJob *) job;
nautilus_progress_info_pulse_progress (common->progress);
free_info = FALSE;
if (info == NULL)
{
free_info = TRUE;
info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_UNIX_MODE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
common->cancellable,
NULL);
/* Ignore errors */
if (info == NULL)
{
return;
}
}
if (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
{
value = job->dir_permissions;
mask = job->dir_mask;
}
else
{
value = job->file_permissions;
mask = job->file_mask;
}
if (!job_aborted (common) &&
g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_UNIX_MODE))
{
current = g_file_info_get_attribute_uint32 (info, G_FILE_ATTRIBUTE_UNIX_MODE);
if (common->undo_info != NULL)
{
nautilus_file_undo_info_rec_permissions_add_file (NAUTILUS_FILE_UNDO_INFO_REC_PERMISSIONS (common->undo_info),
file, current);
}
current = (current & ~mask) | value;
g_file_set_attribute_uint32 (file, G_FILE_ATTRIBUTE_UNIX_MODE,
current, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
common->cancellable, NULL);
}
if (!job_aborted (common) &&
g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
{
enumerator = g_file_enumerate_children (file,
G_FILE_ATTRIBUTE_STANDARD_NAME ","
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_UNIX_MODE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
common->cancellable,
NULL);
if (enumerator)
{
while (!job_aborted (common) &&
(child_info = g_file_enumerator_next_file (enumerator, common->cancellable, NULL)) != NULL)
{
child = g_file_get_child (file,
g_file_info_get_name (child_info));
set_permissions_file (job, child, child_info);
g_object_unref (child);
g_object_unref (child_info);
}
g_file_enumerator_close (enumerator, common->cancellable, NULL);
g_object_unref (enumerator);
}
}
if (free_info)
{
g_object_unref (info);
}
}
static void
set_permissions_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
SetPermissionsJob *job = task_data;
CommonJob *common;
common = (CommonJob *) job;
nautilus_progress_info_set_status (common->progress,
_("Setting permissions"));
nautilus_progress_info_start (job->common.progress);
set_permissions_file (job, job->file, NULL);
}
void
nautilus_file_set_permissions_recursive (const char *directory,
guint32 file_permissions,
guint32 file_mask,
guint32 dir_permissions,
guint32 dir_mask,
NautilusOpCallback callback,
gpointer callback_data)
{
GTask *task;
SetPermissionsJob *job;
job = op_job_new (SetPermissionsJob, NULL);
job->file = g_file_new_for_uri (directory);
job->file_permissions = file_permissions;
job->file_mask = file_mask;
job->dir_permissions = dir_permissions;
job->dir_mask = dir_mask;
job->done_callback = callback;
job->done_callback_data = callback_data;
if (!nautilus_file_undo_manager_is_operating ())
{
job->common.undo_info =
nautilus_file_undo_info_rec_permissions_new (job->file,
file_permissions, file_mask,
dir_permissions, dir_mask);
}
task = g_task_new (NULL, NULL, set_permissions_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, set_permissions_thread_func);
g_object_unref (task);
}
static GList *
location_list_from_uri_list (const GList *uris)
{
const GList *l;
GList *files;
GFile *f;
files = NULL;
for (l = uris; l != NULL; l = l->next)
{
f = g_file_new_for_uri (l->data);
files = g_list_prepend (files, f);
}
return g_list_reverse (files);
}
typedef struct
{
NautilusCopyCallback real_callback;
gpointer real_data;
} MoveTrashCBData;
static void
callback_for_move_to_trash (GHashTable *debuting_uris,
gboolean user_cancelled,
MoveTrashCBData *data)
{
if (data->real_callback)
{
data->real_callback (debuting_uris, !user_cancelled, data->real_data);
}
g_slice_free (MoveTrashCBData, data);
}
void
nautilus_file_operations_copy_move (const GList *item_uris,
GArray *relative_item_points,
const char *target_dir,
GdkDragAction copy_action,
GtkWidget *parent_view,
NautilusCopyCallback done_callback,
gpointer done_callback_data)
{
GList *locations;
GList *p;
GFile *dest, *src_dir;
GtkWindow *parent_window;
gboolean target_is_mapping;
gboolean have_nonmapping_source;
dest = NULL;
target_is_mapping = FALSE;
have_nonmapping_source = FALSE;
if (target_dir)
{
dest = g_file_new_for_uri (target_dir);
if (g_file_has_uri_scheme (dest, "burn"))
{
target_is_mapping = TRUE;
}
}
locations = location_list_from_uri_list (item_uris);
for (p = locations; p != NULL; p = p->next)
{
if (!g_file_has_uri_scheme ((GFile * ) p->data, "burn"))
{
have_nonmapping_source = TRUE;
}
}
if (target_is_mapping && have_nonmapping_source && copy_action == GDK_ACTION_MOVE)
{
/* never move to "burn:///", but fall back to copy.
* This is a workaround, because otherwise the source files would be removed.
*/
copy_action = GDK_ACTION_COPY;
}
parent_window = NULL;
if (parent_view)
{
parent_window = (GtkWindow *) gtk_widget_get_ancestor (parent_view, GTK_TYPE_WINDOW);
}
if (copy_action == GDK_ACTION_COPY)
{
src_dir = g_file_get_parent (locations->data);
if (target_dir == NULL ||
(src_dir != NULL &&
g_file_equal (src_dir, dest)))
{
nautilus_file_operations_duplicate (locations,
relative_item_points,
parent_window,
done_callback, done_callback_data);
}
else
{
nautilus_file_operations_copy (locations,
relative_item_points,
dest,
parent_window,
done_callback, done_callback_data);
}
if (src_dir)
{
g_object_unref (src_dir);
}
}
else if (copy_action == GDK_ACTION_MOVE)
{
if (g_file_has_uri_scheme (dest, "trash"))
{
MoveTrashCBData *cb_data;
cb_data = g_slice_new0 (MoveTrashCBData);
cb_data->real_callback = done_callback;
cb_data->real_data = done_callback_data;
nautilus_file_operations_trash_or_delete (locations,
parent_window,
(NautilusDeleteCallback) callback_for_move_to_trash,
cb_data);
}
else
{
nautilus_file_operations_move (locations,
relative_item_points,
dest,
parent_window,
done_callback, done_callback_data);
}
}
else
{
nautilus_file_operations_link (locations,
relative_item_points,
dest,
parent_window,
done_callback, done_callback_data);
}
g_list_free_full (locations, g_object_unref);
if (dest)
{
g_object_unref (dest);
}
}
static void
create_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
CreateJob *job;
job = user_data;
if (job->done_callback)
{
job->done_callback (job->created_file,
!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
g_object_unref (job->dest_dir);
if (job->src)
{
g_object_unref (job->src);
}
g_free (job->src_data);
g_free (job->filename);
if (job->created_file)
{
g_object_unref (job->created_file);
}
finalize_common ((CommonJob *) job);
nautilus_file_changes_consume_changes (TRUE);
}
static void
create_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
CreateJob *job;
CommonJob *common;
int count;
GFile *dest;
g_autofree gchar *dest_uri = NULL;
char *basename;
char *filename, *filename2, *new_filename;
char *filename_base, *suffix;
char *dest_fs_type;
GError *error;
gboolean res;
gboolean filename_is_utf8;
char *primary, *secondary, *details;
int response;
char *data;
int length;
GFileOutputStream *out;
gboolean handled_invalid_filename;
int max_length, offset;
job = task_data;
common = &job->common;
nautilus_progress_info_start (job->common.progress);
handled_invalid_filename = FALSE;
dest_fs_type = NULL;
filename = NULL;
dest = NULL;
max_length = get_max_name_length (job->dest_dir);
verify_destination (common,
job->dest_dir,
NULL, -1);
if (job_aborted (common))
{
goto aborted;
}
filename = g_strdup (job->filename);
filename_is_utf8 = FALSE;
if (filename)
{
filename_is_utf8 = g_utf8_validate (filename, -1, NULL);
}
if (filename == NULL)
{
if (job->make_dir)
{
/* localizers: the initial name of a new folder */
filename = g_strdup (_("Untitled Folder"));
filename_is_utf8 = TRUE; /* Pass in utf8 */
}
else
{
if (job->src != NULL)
{
basename = g_file_get_basename (job->src);
/* localizers: the initial name of a new template document */
filename = g_strdup_printf ("%s", basename);
g_free (basename);
}
if (filename == NULL)
{
/* localizers: the initial name of a new empty document */
filename = g_strdup (_("Untitled Document"));
filename_is_utf8 = TRUE; /* Pass in utf8 */
}
}
}
make_file_name_valid_for_dest_fs (filename, dest_fs_type);
if (filename_is_utf8)
{
dest = g_file_get_child_for_display_name (job->dest_dir, filename, NULL);
}
if (dest == NULL)
{
dest = g_file_get_child (job->dest_dir, filename);
}
count = 1;
retry:
error = NULL;
if (job->make_dir)
{
res = g_file_make_directory (dest,
common->cancellable,
&error);
if (res)
{
GFile *real;
real = map_possibly_volatile_file_to_real (dest, common->cancellable, &error);
if (real == NULL)
{
res = FALSE;
}
else
{
g_object_unref (dest);
dest = real;
}
}
if (res && common->undo_info != NULL)
{
nautilus_file_undo_info_create_set_data (NAUTILUS_FILE_UNDO_INFO_CREATE (common->undo_info),
dest, NULL, 0);
}
}
else
{
if (job->src)
{
res = g_file_copy (job->src,
dest,
G_FILE_COPY_NONE,
common->cancellable,
NULL, NULL,
&error);
if (res)
{
GFile *real;
real = map_possibly_volatile_file_to_real (dest, common->cancellable, &error);
if (real == NULL)
{
res = FALSE;
}
else
{
g_object_unref (dest);
dest = real;
}
}
if (res && common->undo_info != NULL)
{
gchar *uri;
uri = g_file_get_uri (job->src);
nautilus_file_undo_info_create_set_data (NAUTILUS_FILE_UNDO_INFO_CREATE (common->undo_info),
dest, uri, 0);
g_free (uri);
}
}
else
{
data = "";
length = 0;
if (job->src_data)
{
data = job->src_data;
length = job->length;
}
out = g_file_create (dest,
G_FILE_CREATE_NONE,
common->cancellable,
&error);
if (out)
{
GFile *real;
real = map_possibly_volatile_file_to_real_on_write (dest,
out,
common->cancellable,
&error);
if (real == NULL)
{
res = FALSE;
g_object_unref (out);
}
else
{
g_object_unref (dest);
dest = real;
res = g_output_stream_write_all (G_OUTPUT_STREAM (out),
data, length,
NULL,
common->cancellable,
&error);
if (res)
{
res = g_output_stream_close (G_OUTPUT_STREAM (out),
common->cancellable,
&error);
if (res && common->undo_info != NULL)
{
nautilus_file_undo_info_create_set_data (NAUTILUS_FILE_UNDO_INFO_CREATE (common->undo_info),
dest, data, length);
}
}
/* This will close if the write failed and we didn't close */
g_object_unref (out);
}
}
else
{
res = FALSE;
}
}
}
if (res)
{
job->created_file = g_object_ref (dest);
nautilus_file_changes_queue_file_added (dest);
dest_uri = g_file_get_uri (dest);
if (job->has_position)
{
nautilus_file_changes_queue_schedule_position_set (dest, job->position, common->screen_num);
}
else if (eel_uri_is_desktop (dest_uri))
{
nautilus_file_changes_queue_schedule_position_remove (dest);
}
}
else
{
g_assert (error != NULL);
if (IS_IO_ERROR (error, INVALID_FILENAME) &&
!handled_invalid_filename)
{
handled_invalid_filename = TRUE;
g_assert (dest_fs_type == NULL);
dest_fs_type = query_fs_type (job->dest_dir, common->cancellable);
if (count == 1)
{
new_filename = g_strdup (filename);
}
else
{
filename_base = eel_filename_strip_extension (filename);
offset = strlen (filename_base);
suffix = g_strdup (filename + offset);
filename2 = g_strdup_printf ("%s %d%s", filename_base, count, suffix);
new_filename = NULL;
if (max_length > 0 && strlen (filename2) > max_length)
{
new_filename = shorten_utf8_string (filename2, strlen (filename2) - max_length);
}
if (new_filename == NULL)
{
new_filename = g_strdup (filename2);
}
g_free (filename2);
g_free (suffix);
}
if (make_file_name_valid_for_dest_fs (new_filename, dest_fs_type))
{
g_object_unref (dest);
if (filename_is_utf8)
{
dest = g_file_get_child_for_display_name (job->dest_dir, new_filename, NULL);
}
if (dest == NULL)
{
dest = g_file_get_child (job->dest_dir, new_filename);
}
g_free (new_filename);
g_error_free (error);
goto retry;
}
g_free (new_filename);
}
if (IS_IO_ERROR (error, EXISTS))
{
g_object_unref (dest);
dest = NULL;
filename_base = eel_filename_strip_extension (filename);
offset = strlen (filename_base);
suffix = g_strdup (filename + offset);
filename2 = g_strdup_printf ("%s %d%s", filename_base, ++count, suffix);
if (max_length > 0 && strlen (filename2) > max_length)
{
new_filename = shorten_utf8_string (filename2, strlen (filename2) - max_length);
if (new_filename != NULL)
{
g_free (filename2);
filename2 = new_filename;
}
}
make_file_name_valid_for_dest_fs (filename2, dest_fs_type);
if (filename_is_utf8)
{
dest = g_file_get_child_for_display_name (job->dest_dir, filename2, NULL);
}
if (dest == NULL)
{
dest = g_file_get_child (job->dest_dir, filename2);
}
g_free (filename2);
g_free (suffix);
g_error_free (error);
goto retry;
}
else if (IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
/* Other error */
else
{
if (job->make_dir)
{
primary = f (_("Error while creating directory %B."), dest);
}
else
{
primary = f (_("Error while creating file %B."), dest);
}
secondary = f (_("There was an error creating the directory in %F."), job->dest_dir);
details = error->message;
response = run_warning (common,
primary,
secondary,
details,
FALSE,
CANCEL, SKIP,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (common);
}
else if (response == 1) /* skip */
{ /* do nothing */
}
else
{
g_assert_not_reached ();
}
}
}
aborted:
if (dest)
{
g_object_unref (dest);
}
g_free (filename);
g_free (dest_fs_type);
}
void
nautilus_file_operations_new_folder (GtkWidget *parent_view,
GdkPoint *target_point,
const char *parent_dir,
const char *folder_name,
NautilusCreateCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
CreateJob *job;
GtkWindow *parent_window;
parent_window = NULL;
if (parent_view)
{
parent_window = (GtkWindow *) gtk_widget_get_ancestor (parent_view, GTK_TYPE_WINDOW);
}
job = op_job_new (CreateJob, parent_window);
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
job->dest_dir = g_file_new_for_uri (parent_dir);
job->filename = g_strdup (folder_name);
job->make_dir = TRUE;
if (target_point != NULL)
{
job->position = *target_point;
job->has_position = TRUE;
}
if (!nautilus_file_undo_manager_is_operating ())
{
job->common.undo_info = nautilus_file_undo_info_create_new (NAUTILUS_FILE_UNDO_OP_CREATE_FOLDER);
}
task = g_task_new (NULL, job->common.cancellable, create_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, create_task_thread_func);
g_object_unref (task);
}
void
nautilus_file_operations_new_file_from_template (GtkWidget *parent_view,
GdkPoint *target_point,
const char *parent_dir,
const char *target_filename,
const char *template_uri,
NautilusCreateCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
CreateJob *job;
GtkWindow *parent_window;
parent_window = NULL;
if (parent_view)
{
parent_window = (GtkWindow *) gtk_widget_get_ancestor (parent_view, GTK_TYPE_WINDOW);
}
job = op_job_new (CreateJob, parent_window);
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
job->dest_dir = g_file_new_for_uri (parent_dir);
if (target_point != NULL)
{
job->position = *target_point;
job->has_position = TRUE;
}
job->filename = g_strdup (target_filename);
if (template_uri)
{
job->src = g_file_new_for_uri (template_uri);
}
if (!nautilus_file_undo_manager_is_operating ())
{
job->common.undo_info = nautilus_file_undo_info_create_new (NAUTILUS_FILE_UNDO_OP_CREATE_FILE_FROM_TEMPLATE);
}
task = g_task_new (NULL, job->common.cancellable, create_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, create_task_thread_func);
g_object_unref (task);
}
void
nautilus_file_operations_new_file (GtkWidget *parent_view,
GdkPoint *target_point,
const char *parent_dir,
const char *target_filename,
const char *initial_contents,
int length,
NautilusCreateCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
CreateJob *job;
GtkWindow *parent_window;
parent_window = NULL;
if (parent_view)
{
parent_window = (GtkWindow *) gtk_widget_get_ancestor (parent_view, GTK_TYPE_WINDOW);
}
job = op_job_new (CreateJob, parent_window);
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
job->dest_dir = g_file_new_for_uri (parent_dir);
if (target_point != NULL)
{
job->position = *target_point;
job->has_position = TRUE;
}
job->src_data = g_memdup (initial_contents, length);
job->length = length;
job->filename = g_strdup (target_filename);
if (!nautilus_file_undo_manager_is_operating ())
{
job->common.undo_info = nautilus_file_undo_info_create_new (NAUTILUS_FILE_UNDO_OP_CREATE_EMPTY_FILE);
}
task = g_task_new (NULL, job->common.cancellable, create_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, create_task_thread_func);
g_object_unref (task);
}
static void
delete_trash_file (CommonJob *job,
GFile *file,
gboolean del_file,
gboolean del_children)
{
GFileInfo *info;
GFile *child;
GFileEnumerator *enumerator;
if (job_aborted (job))
{
return;
}
if (del_children)
{
enumerator = g_file_enumerate_children (file,
G_FILE_ATTRIBUTE_STANDARD_NAME ","
G_FILE_ATTRIBUTE_STANDARD_TYPE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable,
NULL);
if (enumerator)
{
while (!job_aborted (job) &&
(info = g_file_enumerator_next_file (enumerator, job->cancellable, NULL)) != NULL)
{
child = g_file_get_child (file,
g_file_info_get_name (info));
delete_trash_file (job, child, TRUE,
g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY);
g_object_unref (child);
g_object_unref (info);
}
g_file_enumerator_close (enumerator, job->cancellable, NULL);
g_object_unref (enumerator);
}
}
if (!job_aborted (job) && del_file)
{
g_file_delete (file, job->cancellable, NULL);
}
}
static void
empty_trash_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
EmptyTrashJob *job;
job = user_data;
g_list_free_full (job->trash_dirs, g_object_unref);
if (job->done_callback)
{
job->done_callback (!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
finalize_common ((CommonJob *) job);
}
static void
empty_trash_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
EmptyTrashJob *job = task_data;
CommonJob *common;
GList *l;
gboolean confirmed;
common = (CommonJob *) job;
nautilus_progress_info_start (job->common.progress);
if (job->should_confirm)
{
confirmed = confirm_empty_trash (common);
}
else
{
confirmed = TRUE;
}
if (confirmed)
{
for (l = job->trash_dirs;
l != NULL && !job_aborted (common);
l = l->next)
{
delete_trash_file (common, l->data, FALSE, TRUE);
}
}
}
void
nautilus_file_operations_empty_trash (GtkWidget *parent_view)
{
GTask *task;
EmptyTrashJob *job;
GtkWindow *parent_window;
parent_window = NULL;
if (parent_view)
{
parent_window = (GtkWindow *) gtk_widget_get_ancestor (parent_view, GTK_TYPE_WINDOW);
}
job = op_job_new (EmptyTrashJob, parent_window);
job->trash_dirs = g_list_prepend (job->trash_dirs,
g_file_new_for_uri ("trash:"));
job->should_confirm = TRUE;
inhibit_power_manager ((CommonJob *) job, _("Emptying Trash"));
task = g_task_new (NULL, NULL, empty_trash_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, empty_trash_thread_func);
g_object_unref (task);
}
static void
mark_trusted_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
MarkTrustedJob *job = user_data;
g_object_unref (job->file);
if (job->done_callback)
{
job->done_callback (!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
finalize_common ((CommonJob *) job);
}
#define TRUSTED_SHEBANG "#!/usr/bin/env xdg-open\n"
static void
mark_desktop_file_trusted (CommonJob *common,
GCancellable *cancellable,
GFile *file,
gboolean interactive)
{
char *contents, *new_contents;
gsize length, new_length;
GError *error;
guint32 current_perms, new_perms;
int response;
GFileInfo *info;
retry:
error = NULL;
if (!g_file_load_contents (file,
cancellable,
&contents, &length,
NULL, &error))
{
if (interactive)
{
response = run_error (common,
g_strdup (_("Unable to mark launcher trusted (executable)")),
error->message,
NULL,
FALSE,
CANCEL, RETRY,
NULL);
}
else
{
response = 0;
}
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (common);
}
else if (response == 1)
{
goto retry;
}
else
{
g_assert_not_reached ();
}
goto out;
}
if (!g_str_has_prefix (contents, "#!"))
{
new_length = length + strlen (TRUSTED_SHEBANG);
new_contents = g_malloc (new_length);
strcpy (new_contents, TRUSTED_SHEBANG);
memcpy (new_contents + strlen (TRUSTED_SHEBANG),
contents, length);
if (!g_file_replace_contents (file,
new_contents,
new_length,
NULL,
FALSE, 0,
NULL, cancellable, &error))
{
g_free (contents);
g_free (new_contents);
if (interactive)
{
response = run_error (common,
g_strdup (_("Unable to mark launcher trusted (executable)")),
error->message,
NULL,
FALSE,
CANCEL, RETRY,
NULL);
}
else
{
response = 0;
}
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (common);
}
else if (response == 1)
{
goto retry;
}
else
{
g_assert_not_reached ();
}
goto out;
}
g_free (new_contents);
}
g_free (contents);
info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_UNIX_MODE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
common->cancellable,
&error);
if (info == NULL)
{
if (interactive)
{
response = run_error (common,
g_strdup (_("Unable to mark launcher trusted (executable)")),
error->message,
NULL,
FALSE,
CANCEL, RETRY,
NULL);
}
else
{
response = 0;
}
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (common);
}
else if (response == 1)
{
goto retry;
}
else
{
g_assert_not_reached ();
}
goto out;
}
if (g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_UNIX_MODE))
{
current_perms = g_file_info_get_attribute_uint32 (info, G_FILE_ATTRIBUTE_UNIX_MODE);
new_perms = current_perms | S_IXGRP | S_IXUSR | S_IXOTH;
if ((current_perms != new_perms) &&
!g_file_set_attribute_uint32 (file, G_FILE_ATTRIBUTE_UNIX_MODE,
new_perms, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
common->cancellable, &error))
{
g_object_unref (info);
if (interactive)
{
response = run_error (common,
g_strdup (_("Unable to mark launcher trusted (executable)")),
error->message,
NULL,
FALSE,
CANCEL, RETRY,
NULL);
}
else
{
response = 0;
}
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (common);
}
else if (response == 1)
{
goto retry;
}
else
{
g_assert_not_reached ();
}
goto out;
}
}
g_object_unref (info);
out:
;
}
static void
mark_trusted_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
MarkTrustedJob *job = task_data;
CommonJob *common;
common = (CommonJob *) job;
nautilus_progress_info_start (job->common.progress);
mark_desktop_file_trusted (common,
cancellable,
job->file,
job->interactive);
}
void
nautilus_file_mark_desktop_file_trusted (GFile *file,
GtkWindow *parent_window,
gboolean interactive,
NautilusOpCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
MarkTrustedJob *job;
job = op_job_new (MarkTrustedJob, parent_window);
job->file = g_object_ref (file);
job->interactive = interactive;
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
task = g_task_new (NULL, NULL, mark_trusted_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, mark_trusted_task_thread_func);
g_object_unref (task);
}
static void
extract_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
ExtractJob *extract_job;
extract_job = user_data;
if (extract_job->done_callback)
{
extract_job->done_callback (extract_job->output_files,
extract_job->done_callback_data);
}
g_list_free_full (extract_job->source_files, g_object_unref);
g_list_free_full (extract_job->output_files, g_object_unref);
g_object_unref (extract_job->destination_directory);
finalize_common ((CommonJob *) extract_job);
nautilus_file_changes_consume_changes (TRUE);
}
static GFile *
extract_job_on_decide_destination (AutoarExtractor *extractor,
GFile *destination,
GList *files,
gpointer user_data)
{
ExtractJob *extract_job = user_data;
GFile *decided_destination;
g_autofree char *basename = NULL;
nautilus_progress_info_set_details (extract_job->common.progress,
_("Verifying destination"));
basename = g_file_get_basename (destination);
decided_destination = nautilus_generate_unique_file_in_directory (extract_job->destination_directory,
basename);
if (job_aborted ((CommonJob *) extract_job))
{
g_object_unref (decided_destination);
return NULL;
}
extract_job->output_files = g_list_prepend (extract_job->output_files,
decided_destination);
return g_object_ref (decided_destination);
}
static void
extract_job_on_progress (AutoarExtractor *extractor,
guint64 archive_current_decompressed_size,
guint archive_current_decompressed_files,
gpointer user_data)
{
ExtractJob *extract_job = user_data;
CommonJob *common = user_data;
GFile *source_file;
char *details;
double elapsed;
double transfer_rate;
int remaining_time;
guint64 archive_total_decompressed_size;
gdouble archive_weight;
gdouble archive_decompress_progress;
guint64 job_completed_size;
gdouble job_progress;
source_file = autoar_extractor_get_source_file (extractor);
nautilus_progress_info_take_status (common->progress,
f (_("Extracting “%B”"), source_file));
archive_total_decompressed_size = autoar_extractor_get_total_size (extractor);
archive_decompress_progress = (gdouble) archive_current_decompressed_size /
(gdouble) archive_total_decompressed_size;
archive_weight = 0;
if (extract_job->total_compressed_size)
{
archive_weight = (gdouble) extract_job->archive_compressed_size /
(gdouble) extract_job->total_compressed_size;
}
job_progress = archive_decompress_progress * archive_weight + extract_job->base_progress;
elapsed = g_timer_elapsed (common->time, NULL);
transfer_rate = 0;
remaining_time = -1;
job_completed_size = job_progress * extract_job->total_compressed_size;
if (elapsed > 0)
{
transfer_rate = job_completed_size / elapsed;
}
if (transfer_rate > 0)
{
remaining_time = (extract_job->total_compressed_size - job_completed_size) /
transfer_rate;
}
if (elapsed < SECONDS_NEEDED_FOR_RELIABLE_TRANSFER_RATE ||
transfer_rate == 0)
{
/* To translators: %S will expand to a size like "2 bytes" or
* "3 MB", so something like "4 kb / 4 MB"
*/
details = f (_("%S / %S"), job_completed_size, extract_job->total_compressed_size);
}
else
{
/* To translators: %S will expand to a size like "2 bytes" or
* "3 MB", %T to a time duration like "2 minutes". So the whole
* thing will be something like
* "2 kb / 4 MB -- 2 hours left (4kb/sec)"
*
* The singular/plural form will be used depending on the
* remaining time (i.e. the %T argument).
*/
details = f (ngettext ("%S / %S \xE2\x80\x94 %T left (%S/sec)",
"%S / %S \xE2\x80\x94 %T left (%S/sec)",
seconds_count_format_time_units (remaining_time)),
job_completed_size, extract_job->total_compressed_size,
remaining_time,
(goffset) transfer_rate);
}
nautilus_progress_info_take_details (common->progress, details);
if (elapsed > SECONDS_NEEDED_FOR_APROXIMATE_TRANSFER_RATE)
{
nautilus_progress_info_set_remaining_time (common->progress,
remaining_time);
nautilus_progress_info_set_elapsed_time (common->progress,
elapsed);
}
nautilus_progress_info_set_progress (common->progress, job_progress, 1);
}
static void
extract_job_on_error (AutoarExtractor *extractor,
GError *error,
gpointer user_data)
{
ExtractJob *extract_job = user_data;
GFile *source_file;
gint response_id;
source_file = autoar_extractor_get_source_file (extractor);
if (IS_IO_ERROR (error, NOT_SUPPORTED))
{
handle_unsupported_compressed_file (extract_job->common.parent_window,
source_file);
return;
}
nautilus_progress_info_take_status (extract_job->common.progress,
f (_("Error extracting “%B”"),
source_file));
response_id = run_warning ((CommonJob *) extract_job,
f (_("There was an error while extracting “%B”."),
source_file),
g_strdup (error->message),
NULL,
FALSE,
CANCEL,
SKIP,
NULL);
if (response_id == 0 || response_id == GTK_RESPONSE_DELETE_EVENT)
{
abort_job ((CommonJob *) extract_job);
}
}
static void
extract_job_on_completed (AutoarExtractor *extractor,
gpointer user_data)
{
ExtractJob *extract_job = user_data;
GFile *output_file;
output_file = G_FILE (extract_job->output_files->data);
nautilus_file_changes_queue_file_added (output_file);
}
static void
report_extract_final_progress (ExtractJob *extract_job,
gint total_files)
{
char *status;
nautilus_progress_info_set_destination (extract_job->common.progress,
extract_job->destination_directory);
if (total_files == 1)
{
GFile *source_file;
source_file = G_FILE (extract_job->source_files->data);
status = f (_("Extracted “%B” to “%B”"),
source_file,
extract_job->destination_directory);
}
else
{
status = f (ngettext ("Extracted %'d file to “%B”",
"Extracted %'d files to “%B”",
total_files),
total_files,
extract_job->destination_directory);
}
nautilus_progress_info_take_status (extract_job->common.progress,
status);
nautilus_progress_info_take_details (extract_job->common.progress,
f (_("%S / %S"),
extract_job->total_compressed_size,
extract_job->total_compressed_size));
}
static void
extract_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
ExtractJob *extract_job = task_data;
GList *l;
GList *existing_output_files = NULL;
gint total_files;
g_autofree guint64 *archive_compressed_sizes = NULL;
gint i;
g_timer_start (extract_job->common.time);
nautilus_progress_info_start (extract_job->common.progress);
nautilus_progress_info_set_details (extract_job->common.progress,
_("Preparing to extract"));
total_files = g_list_length (extract_job->source_files);
archive_compressed_sizes = g_malloc0_n (total_files, sizeof (guint64));
extract_job->total_compressed_size = 0;
for (l = extract_job->source_files, i = 0;
l != NULL && !job_aborted ((CommonJob *) extract_job);
l = l->next, i++)
{
GFile *source_file;
g_autoptr (GFileInfo) info = NULL;
source_file = G_FILE (l->data);
info = g_file_query_info (source_file,
G_FILE_ATTRIBUTE_STANDARD_SIZE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
extract_job->common.cancellable,
NULL);
if (info)
{
archive_compressed_sizes[i] = g_file_info_get_size (info);
extract_job->total_compressed_size += archive_compressed_sizes[i];
}
}
extract_job->base_progress = 0;
for (l = extract_job->source_files, i = 0;
l != NULL && !job_aborted ((CommonJob *) extract_job);
l = l->next, i++)
{
g_autoptr (AutoarExtractor) extractor = NULL;
extractor = autoar_extractor_new (G_FILE (l->data),
extract_job->destination_directory);
autoar_extractor_set_notify_interval (extractor,
PROGRESS_NOTIFY_INTERVAL);
g_signal_connect (extractor, "error",
G_CALLBACK (extract_job_on_error),
extract_job);
g_signal_connect (extractor, "decide-destination",
G_CALLBACK (extract_job_on_decide_destination),
extract_job);
g_signal_connect (extractor, "progress",
G_CALLBACK (extract_job_on_progress),
extract_job);
g_signal_connect (extractor, "completed",
G_CALLBACK (extract_job_on_completed),
extract_job);
extract_job->archive_compressed_size = archive_compressed_sizes[i];
autoar_extractor_start (extractor,
extract_job->common.cancellable);
g_signal_handlers_disconnect_by_data (extractor,
extract_job);
extract_job->base_progress += (gdouble) extract_job->archive_compressed_size /
(gdouble) extract_job->total_compressed_size;
}
if (!job_aborted ((CommonJob *) extract_job))
{
report_extract_final_progress (extract_job, total_files);
}
for (l = extract_job->output_files; l != NULL; l = l->next)
{
GFile *output_file;
output_file = G_FILE (l->data);
if (g_file_query_exists (output_file, NULL))
{
existing_output_files = g_list_prepend (existing_output_files,
g_object_ref (output_file));
}
}
g_list_free_full (extract_job->output_files, g_object_unref);
extract_job->output_files = existing_output_files;
if (extract_job->common.undo_info)
{
if (extract_job->output_files)
{
NautilusFileUndoInfoExtract *undo_info;
undo_info = NAUTILUS_FILE_UNDO_INFO_EXTRACT (extract_job->common.undo_info);
nautilus_file_undo_info_extract_set_outputs (undo_info,
extract_job->output_files);
}
else
{
/* There is nothing to undo if there is no output */
g_clear_object (&extract_job->common.undo_info);
}
}
}
void
nautilus_file_operations_extract_files (GList *files,
GFile *destination_directory,
GtkWindow *parent_window,
NautilusExtractCallback done_callback,
gpointer done_callback_data)
{
ExtractJob *extract_job;
g_autoptr (GTask) task = NULL;
extract_job = op_job_new (ExtractJob, parent_window);
extract_job->source_files = g_list_copy_deep (files,
(GCopyFunc) g_object_ref,
NULL);
extract_job->destination_directory = g_object_ref (destination_directory);
extract_job->done_callback = done_callback;
extract_job->done_callback_data = done_callback_data;
inhibit_power_manager ((CommonJob *) extract_job, _("Extracting Files"));
if (!nautilus_file_undo_manager_is_operating ())
{
extract_job->common.undo_info = nautilus_file_undo_info_extract_new (files,
destination_directory);
}
task = g_task_new (NULL, extract_job->common.cancellable,
extract_task_done, extract_job);
g_task_set_task_data (task, extract_job, NULL);
g_task_run_in_thread (task, extract_task_thread_func);
}
static void
compress_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
CompressJob *compress_job = user_data;
if (compress_job->done_callback)
{
compress_job->done_callback (compress_job->output_file,
compress_job->success,
compress_job->done_callback_data);
}
g_object_unref (compress_job->output_file);
g_list_free_full (compress_job->source_files, g_object_unref);
finalize_common ((CommonJob *) compress_job);
nautilus_file_changes_consume_changes (TRUE);
}
static void
compress_job_on_progress (AutoarCompressor *compressor,
guint64 completed_size,
guint completed_files,
gpointer user_data)
{
CompressJob *compress_job = user_data;
CommonJob *common = user_data;
char *status;
char *details;
int files_left;
double elapsed;
double transfer_rate;
int remaining_time;
files_left = compress_job->total_files - completed_files;
if (compress_job->total_files == 1)
{
status = f (_("Compressing “%B” into “%B”"),
G_FILE (compress_job->source_files->data),
compress_job->output_file);
}
else
{
status = f (ngettext ("Compressing %'d file into “%B”",
"Compressing %'d files into “%B”",
compress_job->total_files),
compress_job->total_files,
compress_job->output_file);
}
nautilus_progress_info_take_status (common->progress, status);
elapsed = g_timer_elapsed (common->time, NULL);
transfer_rate = 0;
remaining_time = -1;
if (elapsed > 0)
{
if (completed_size > 0)
{
transfer_rate = completed_size / elapsed;
remaining_time = (compress_job->total_size - completed_size) / transfer_rate;
}
else if (completed_files > 0)
{
transfer_rate = completed_files / elapsed;
remaining_time = (compress_job->total_files - completed_files) / transfer_rate;
}
}
if (elapsed < SECONDS_NEEDED_FOR_RELIABLE_TRANSFER_RATE ||
transfer_rate == 0)
{
if (compress_job->total_files == 1)
{
/* To translators: %S will expand to a size like "2 bytes" or "3 MB", so something like "4 kb / 4 MB" */
details = f (_("%S / %S"), completed_size, compress_job->total_size);
}
else
{
details = f (_("%'d / %'d"),
files_left > 0 ? completed_files + 1 : completed_files,
compress_job->total_files);
}
}
else
{
if (compress_job->total_files == 1)
{
if (files_left > 0)
{
/* To translators: %S will expand to a size like "2 bytes" or "3 MB", %T to a time duration like
* "2 minutes". So the whole thing will be something like "2 kb / 4 MB -- 2 hours left (4kb/sec)"
*
* The singular/plural form will be used depending on the remaining time (i.e. the %T argument).
*/
details = f (ngettext ("%S / %S \xE2\x80\x94 %T left (%S/sec)",
"%S / %S \xE2\x80\x94 %T left (%S/sec)",
seconds_count_format_time_units (remaining_time)),
completed_size, compress_job->total_size,
remaining_time,
(goffset) transfer_rate);
}
else
{
/* To translators: %S will expand to a size like "2 bytes" or "3 MB". */
details = f (_("%S / %S"),
completed_size,
compress_job->total_size);
}
}
else
{
if (files_left > 0)
{
/* To translators: %T will expand to a time duration like "2 minutes".
* So the whole thing will be something like "1 / 5 -- 2 hours left (4kb/sec)"
*
* The singular/plural form will be used depending on the remaining time (i.e. the %T argument).
*/
details = f (ngettext ("%'d / %'d \xE2\x80\x94 %T left (%S/sec)",
"%'d / %'d \xE2\x80\x94 %T left (%S/sec)",
seconds_count_format_time_units (remaining_time)),
completed_files + 1, compress_job->total_files,
remaining_time,
(goffset) transfer_rate);
}
else
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
completed_files,
compress_job->total_files);
}
}
}
nautilus_progress_info_take_details (common->progress, details);
if (elapsed > SECONDS_NEEDED_FOR_APROXIMATE_TRANSFER_RATE)
{
nautilus_progress_info_set_remaining_time (common->progress,
remaining_time);
nautilus_progress_info_set_elapsed_time (common->progress,
elapsed);
}
nautilus_progress_info_set_progress (common->progress,
completed_size,
compress_job->total_size);
}
static void
compress_job_on_error (AutoarCompressor *compressor,
GError *error,
gpointer user_data)
{
CompressJob *compress_job = user_data;
char *status;
if (compress_job->total_files == 1)
{
status = f (_("Error compressing “%B” into “%B”"),
G_FILE (compress_job->source_files->data),
compress_job->output_file);
}
else
{
status = f (ngettext ("Error compressing %'d file into “%B”",
"Error compressing %'d files into “%B”",
compress_job->total_files),
compress_job->total_files,
compress_job->output_file);
}
nautilus_progress_info_take_status (compress_job->common.progress,
status);
run_error ((CommonJob *) compress_job,
g_strdup (_("There was an error while compressing files.")),
g_strdup (error->message),
NULL,
FALSE,
CANCEL,
NULL);
abort_job ((CommonJob *) compress_job);
}
static void
compress_job_on_completed (AutoarCompressor *compressor,
gpointer user_data)
{
CompressJob *compress_job = user_data;
g_autoptr (GFile) destination_directory = NULL;
char *status;
if (compress_job->total_files == 1)
{
status = f (_("Compressed “%B” into “%B”"),
G_FILE (compress_job->source_files->data),
compress_job->output_file);
}
else
{
status = f (ngettext ("Compressed %'d file into “%B”",
"Compressed %'d files into “%B”",
compress_job->total_files),
compress_job->total_files,
compress_job->output_file);
}
nautilus_progress_info_take_status (compress_job->common.progress,
status);
nautilus_file_changes_queue_file_added (compress_job->output_file);
destination_directory = g_file_get_parent (compress_job->output_file);
nautilus_progress_info_set_destination (compress_job->common.progress,
destination_directory);
}
static void
compress_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
CompressJob *compress_job = task_data;
SourceInfo source_info;
g_autoptr (AutoarCompressor) compressor = NULL;
g_timer_start (compress_job->common.time);
nautilus_progress_info_start (compress_job->common.progress);
scan_sources (compress_job->source_files,
&source_info,
(CommonJob *) compress_job,
OP_KIND_COMPRESS);
compress_job->total_files = source_info.num_files;
compress_job->total_size = source_info.num_bytes;
compressor = autoar_compressor_new (compress_job->source_files,
compress_job->output_file,
compress_job->format,
compress_job->filter,
FALSE);
autoar_compressor_set_output_is_dest (compressor, TRUE);
autoar_compressor_set_notify_interval (compressor,
PROGRESS_NOTIFY_INTERVAL);
g_signal_connect (compressor, "progress",
G_CALLBACK (compress_job_on_progress), compress_job);
g_signal_connect (compressor, "error",
G_CALLBACK (compress_job_on_error), compress_job);
g_signal_connect (compressor, "completed",
G_CALLBACK (compress_job_on_completed), compress_job);
autoar_compressor_start (compressor,
compress_job->common.cancellable);
compress_job->success = g_file_query_exists (compress_job->output_file,
NULL);
/* There is nothing to undo if the output was not created */
if (compress_job->common.undo_info != NULL && !compress_job->success)
{
g_clear_object (&compress_job->common.undo_info);
}
}
void
nautilus_file_operations_compress (GList *files,
GFile *output,
AutoarFormat format,
AutoarFilter filter,
GtkWindow *parent_window,
NautilusCreateCallback done_callback,
gpointer done_callback_data)
{
g_autoptr (GTask) task = NULL;
CompressJob *compress_job;
compress_job = op_job_new (CompressJob, parent_window);
compress_job->source_files = g_list_copy_deep (files,
(GCopyFunc) g_object_ref,
NULL);
compress_job->output_file = g_object_ref (output);
compress_job->format = format;
compress_job->filter = filter;
compress_job->done_callback = done_callback;
compress_job->done_callback_data = done_callback_data;
inhibit_power_manager ((CommonJob *) compress_job, _("Compressing Files"));
if (!nautilus_file_undo_manager_is_operating ())
{
compress_job->common.undo_info = nautilus_file_undo_info_compress_new (files,
output,
format,
filter);
}
task = g_task_new (NULL, compress_job->common.cancellable,
compress_task_done, compress_job);
g_task_set_task_data (task, compress_job, NULL);
g_task_run_in_thread (task, compress_task_thread_func);
}
#if !defined (NAUTILUS_OMIT_SELF_CHECK)
void
nautilus_self_check_file_operations (void)
{
setlocale (LC_MESSAGES, "C");
/* test the next duplicate name generator */
EEL_CHECK_STRING_RESULT (get_duplicate_name (" (copy)", 1, -1), " (another copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo", 1, -1), "foo (copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name (".bashrc", 1, -1), ".bashrc (copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name (".foo.txt", 1, -1), ".foo (copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo foo", 1, -1), "foo foo (copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo.txt", 1, -1), "foo (copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo foo.txt", 1, -1), "foo foo (copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo foo.txt txt", 1, -1), "foo foo (copy).txt txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo...txt", 1, -1), "foo.. (copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo...", 1, -1), "foo... (copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo. (copy)", 1, -1), "foo. (another copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (copy)", 1, -1), "foo (another copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (copy).txt", 1, -1), "foo (another copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (another copy)", 1, -1), "foo (3rd copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (another copy).txt", 1, -1), "foo (3rd copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo foo (another copy).txt", 1, -1), "foo foo (3rd copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (13th copy)", 1, -1), "foo (14th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (13th copy).txt", 1, -1), "foo (14th copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (21st copy)", 1, -1), "foo (22nd copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (21st copy).txt", 1, -1), "foo (22nd copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (22nd copy)", 1, -1), "foo (23rd copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (22nd copy).txt", 1, -1), "foo (23rd copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (23rd copy)", 1, -1), "foo (24th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (23rd copy).txt", 1, -1), "foo (24th copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (24th copy)", 1, -1), "foo (25th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (24th copy).txt", 1, -1), "foo (25th copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo foo (24th copy)", 1, -1), "foo foo (25th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo foo (24th copy).txt", 1, -1), "foo foo (25th copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo foo (100000000000000th copy).txt", 1, -1), "foo foo (copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (10th copy)", 1, -1), "foo (11th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (10th copy).txt", 1, -1), "foo (11th copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (11th copy)", 1, -1), "foo (12th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (11th copy).txt", 1, -1), "foo (12th copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (12th copy)", 1, -1), "foo (13th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (12th copy).txt", 1, -1), "foo (13th copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (110th copy)", 1, -1), "foo (111th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (110th copy).txt", 1, -1), "foo (111th copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (122nd copy)", 1, -1), "foo (123rd copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (122nd copy).txt", 1, -1), "foo (123rd copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (123rd copy)", 1, -1), "foo (124th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (123rd copy).txt", 1, -1), "foo (124th copy).txt");
setlocale (LC_MESSAGES, "");
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2802_1 |
crossvul-cpp_data_good_2089_0 | /*
* linux/fs/nfs/write.c
*
* Write file data over NFS.
*
* Copyright (C) 1996, 1997, Olaf Kirch <okir@monad.swb.de>
*/
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/pagemap.h>
#include <linux/file.h>
#include <linux/writeback.h>
#include <linux/swap.h>
#include <linux/migrate.h>
#include <linux/sunrpc/clnt.h>
#include <linux/nfs_fs.h>
#include <linux/nfs_mount.h>
#include <linux/nfs_page.h>
#include <linux/backing-dev.h>
#include <linux/export.h>
#include <asm/uaccess.h>
#include "delegation.h"
#include "internal.h"
#include "iostat.h"
#include "nfs4_fs.h"
#include "fscache.h"
#include "pnfs.h"
#include "nfstrace.h"
#define NFSDBG_FACILITY NFSDBG_PAGECACHE
#define MIN_POOL_WRITE (32)
#define MIN_POOL_COMMIT (4)
/*
* Local function declarations
*/
static void nfs_redirty_request(struct nfs_page *req);
static const struct rpc_call_ops nfs_write_common_ops;
static const struct rpc_call_ops nfs_commit_ops;
static const struct nfs_pgio_completion_ops nfs_async_write_completion_ops;
static const struct nfs_commit_completion_ops nfs_commit_completion_ops;
static struct kmem_cache *nfs_wdata_cachep;
static mempool_t *nfs_wdata_mempool;
static struct kmem_cache *nfs_cdata_cachep;
static mempool_t *nfs_commit_mempool;
struct nfs_commit_data *nfs_commitdata_alloc(void)
{
struct nfs_commit_data *p = mempool_alloc(nfs_commit_mempool, GFP_NOIO);
if (p) {
memset(p, 0, sizeof(*p));
INIT_LIST_HEAD(&p->pages);
}
return p;
}
EXPORT_SYMBOL_GPL(nfs_commitdata_alloc);
void nfs_commit_free(struct nfs_commit_data *p)
{
mempool_free(p, nfs_commit_mempool);
}
EXPORT_SYMBOL_GPL(nfs_commit_free);
struct nfs_write_header *nfs_writehdr_alloc(void)
{
struct nfs_write_header *p = mempool_alloc(nfs_wdata_mempool, GFP_NOIO);
if (p) {
struct nfs_pgio_header *hdr = &p->header;
memset(p, 0, sizeof(*p));
INIT_LIST_HEAD(&hdr->pages);
INIT_LIST_HEAD(&hdr->rpc_list);
spin_lock_init(&hdr->lock);
atomic_set(&hdr->refcnt, 0);
hdr->verf = &p->verf;
}
return p;
}
EXPORT_SYMBOL_GPL(nfs_writehdr_alloc);
static struct nfs_write_data *nfs_writedata_alloc(struct nfs_pgio_header *hdr,
unsigned int pagecount)
{
struct nfs_write_data *data, *prealloc;
prealloc = &container_of(hdr, struct nfs_write_header, header)->rpc_data;
if (prealloc->header == NULL)
data = prealloc;
else
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (!data)
goto out;
if (nfs_pgarray_set(&data->pages, pagecount)) {
data->header = hdr;
atomic_inc(&hdr->refcnt);
} else {
if (data != prealloc)
kfree(data);
data = NULL;
}
out:
return data;
}
void nfs_writehdr_free(struct nfs_pgio_header *hdr)
{
struct nfs_write_header *whdr = container_of(hdr, struct nfs_write_header, header);
mempool_free(whdr, nfs_wdata_mempool);
}
EXPORT_SYMBOL_GPL(nfs_writehdr_free);
void nfs_writedata_release(struct nfs_write_data *wdata)
{
struct nfs_pgio_header *hdr = wdata->header;
struct nfs_write_header *write_header = container_of(hdr, struct nfs_write_header, header);
put_nfs_open_context(wdata->args.context);
if (wdata->pages.pagevec != wdata->pages.page_array)
kfree(wdata->pages.pagevec);
if (wdata == &write_header->rpc_data) {
wdata->header = NULL;
wdata = NULL;
}
if (atomic_dec_and_test(&hdr->refcnt))
hdr->completion_ops->completion(hdr);
/* Note: we only free the rpc_task after callbacks are done.
* See the comment in rpc_free_task() for why
*/
kfree(wdata);
}
EXPORT_SYMBOL_GPL(nfs_writedata_release);
static void nfs_context_set_write_error(struct nfs_open_context *ctx, int error)
{
ctx->error = error;
smp_wmb();
set_bit(NFS_CONTEXT_ERROR_WRITE, &ctx->flags);
}
static struct nfs_page *
nfs_page_find_request_locked(struct nfs_inode *nfsi, struct page *page)
{
struct nfs_page *req = NULL;
if (PagePrivate(page))
req = (struct nfs_page *)page_private(page);
else if (unlikely(PageSwapCache(page))) {
struct nfs_page *freq, *t;
/* Linearly search the commit list for the correct req */
list_for_each_entry_safe(freq, t, &nfsi->commit_info.list, wb_list) {
if (freq->wb_page == page) {
req = freq;
break;
}
}
}
if (req)
kref_get(&req->wb_kref);
return req;
}
static struct nfs_page *nfs_page_find_request(struct page *page)
{
struct inode *inode = page_file_mapping(page)->host;
struct nfs_page *req = NULL;
spin_lock(&inode->i_lock);
req = nfs_page_find_request_locked(NFS_I(inode), page);
spin_unlock(&inode->i_lock);
return req;
}
/* Adjust the file length if we're writing beyond the end */
static void nfs_grow_file(struct page *page, unsigned int offset, unsigned int count)
{
struct inode *inode = page_file_mapping(page)->host;
loff_t end, i_size;
pgoff_t end_index;
spin_lock(&inode->i_lock);
i_size = i_size_read(inode);
end_index = (i_size - 1) >> PAGE_CACHE_SHIFT;
if (i_size > 0 && page_file_index(page) < end_index)
goto out;
end = page_file_offset(page) + ((loff_t)offset+count);
if (i_size >= end)
goto out;
i_size_write(inode, end);
nfs_inc_stats(inode, NFSIOS_EXTENDWRITE);
out:
spin_unlock(&inode->i_lock);
}
/* A writeback failed: mark the page as bad, and invalidate the page cache */
static void nfs_set_pageerror(struct page *page)
{
nfs_zap_mapping(page_file_mapping(page)->host, page_file_mapping(page));
}
/* We can set the PG_uptodate flag if we see that a write request
* covers the full page.
*/
static void nfs_mark_uptodate(struct page *page, unsigned int base, unsigned int count)
{
if (PageUptodate(page))
return;
if (base != 0)
return;
if (count != nfs_page_length(page))
return;
SetPageUptodate(page);
}
static int wb_priority(struct writeback_control *wbc)
{
if (wbc->for_reclaim)
return FLUSH_HIGHPRI | FLUSH_STABLE;
if (wbc->for_kupdate || wbc->for_background)
return FLUSH_LOWPRI | FLUSH_COND_STABLE;
return FLUSH_COND_STABLE;
}
/*
* NFS congestion control
*/
int nfs_congestion_kb;
#define NFS_CONGESTION_ON_THRESH (nfs_congestion_kb >> (PAGE_SHIFT-10))
#define NFS_CONGESTION_OFF_THRESH \
(NFS_CONGESTION_ON_THRESH - (NFS_CONGESTION_ON_THRESH >> 2))
static void nfs_set_page_writeback(struct page *page)
{
struct nfs_server *nfss = NFS_SERVER(page_file_mapping(page)->host);
int ret = test_set_page_writeback(page);
WARN_ON_ONCE(ret != 0);
if (atomic_long_inc_return(&nfss->writeback) >
NFS_CONGESTION_ON_THRESH) {
set_bdi_congested(&nfss->backing_dev_info,
BLK_RW_ASYNC);
}
}
static void nfs_end_page_writeback(struct page *page)
{
struct inode *inode = page_file_mapping(page)->host;
struct nfs_server *nfss = NFS_SERVER(inode);
end_page_writeback(page);
if (atomic_long_dec_return(&nfss->writeback) < NFS_CONGESTION_OFF_THRESH)
clear_bdi_congested(&nfss->backing_dev_info, BLK_RW_ASYNC);
}
static struct nfs_page *nfs_find_and_lock_request(struct page *page, bool nonblock)
{
struct inode *inode = page_file_mapping(page)->host;
struct nfs_page *req;
int ret;
spin_lock(&inode->i_lock);
for (;;) {
req = nfs_page_find_request_locked(NFS_I(inode), page);
if (req == NULL)
break;
if (nfs_lock_request(req))
break;
/* Note: If we hold the page lock, as is the case in nfs_writepage,
* then the call to nfs_lock_request() will always
* succeed provided that someone hasn't already marked the
* request as dirty (in which case we don't care).
*/
spin_unlock(&inode->i_lock);
if (!nonblock)
ret = nfs_wait_on_request(req);
else
ret = -EAGAIN;
nfs_release_request(req);
if (ret != 0)
return ERR_PTR(ret);
spin_lock(&inode->i_lock);
}
spin_unlock(&inode->i_lock);
return req;
}
/*
* Find an associated nfs write request, and prepare to flush it out
* May return an error if the user signalled nfs_wait_on_request().
*/
static int nfs_page_async_flush(struct nfs_pageio_descriptor *pgio,
struct page *page, bool nonblock)
{
struct nfs_page *req;
int ret = 0;
req = nfs_find_and_lock_request(page, nonblock);
if (!req)
goto out;
ret = PTR_ERR(req);
if (IS_ERR(req))
goto out;
nfs_set_page_writeback(page);
WARN_ON_ONCE(test_bit(PG_CLEAN, &req->wb_flags));
ret = 0;
if (!nfs_pageio_add_request(pgio, req)) {
nfs_redirty_request(req);
ret = pgio->pg_error;
}
out:
return ret;
}
static int nfs_do_writepage(struct page *page, struct writeback_control *wbc, struct nfs_pageio_descriptor *pgio)
{
struct inode *inode = page_file_mapping(page)->host;
int ret;
nfs_inc_stats(inode, NFSIOS_VFSWRITEPAGE);
nfs_add_stats(inode, NFSIOS_WRITEPAGES, 1);
nfs_pageio_cond_complete(pgio, page_file_index(page));
ret = nfs_page_async_flush(pgio, page, wbc->sync_mode == WB_SYNC_NONE);
if (ret == -EAGAIN) {
redirty_page_for_writepage(wbc, page);
ret = 0;
}
return ret;
}
/*
* Write an mmapped page to the server.
*/
static int nfs_writepage_locked(struct page *page, struct writeback_control *wbc)
{
struct nfs_pageio_descriptor pgio;
int err;
NFS_PROTO(page_file_mapping(page)->host)->write_pageio_init(&pgio,
page->mapping->host,
wb_priority(wbc),
&nfs_async_write_completion_ops);
err = nfs_do_writepage(page, wbc, &pgio);
nfs_pageio_complete(&pgio);
if (err < 0)
return err;
if (pgio.pg_error < 0)
return pgio.pg_error;
return 0;
}
int nfs_writepage(struct page *page, struct writeback_control *wbc)
{
int ret;
ret = nfs_writepage_locked(page, wbc);
unlock_page(page);
return ret;
}
static int nfs_writepages_callback(struct page *page, struct writeback_control *wbc, void *data)
{
int ret;
ret = nfs_do_writepage(page, wbc, data);
unlock_page(page);
return ret;
}
int nfs_writepages(struct address_space *mapping, struct writeback_control *wbc)
{
struct inode *inode = mapping->host;
unsigned long *bitlock = &NFS_I(inode)->flags;
struct nfs_pageio_descriptor pgio;
int err;
/* Stop dirtying of new pages while we sync */
err = wait_on_bit_lock(bitlock, NFS_INO_FLUSHING,
nfs_wait_bit_killable, TASK_KILLABLE);
if (err)
goto out_err;
nfs_inc_stats(inode, NFSIOS_VFSWRITEPAGES);
NFS_PROTO(inode)->write_pageio_init(&pgio, inode, wb_priority(wbc), &nfs_async_write_completion_ops);
err = write_cache_pages(mapping, wbc, nfs_writepages_callback, &pgio);
nfs_pageio_complete(&pgio);
clear_bit_unlock(NFS_INO_FLUSHING, bitlock);
smp_mb__after_clear_bit();
wake_up_bit(bitlock, NFS_INO_FLUSHING);
if (err < 0)
goto out_err;
err = pgio.pg_error;
if (err < 0)
goto out_err;
return 0;
out_err:
return err;
}
/*
* Insert a write request into an inode
*/
static void nfs_inode_add_request(struct inode *inode, struct nfs_page *req)
{
struct nfs_inode *nfsi = NFS_I(inode);
/* Lock the request! */
nfs_lock_request(req);
spin_lock(&inode->i_lock);
if (!nfsi->npages && NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))
inode->i_version++;
/*
* Swap-space should not get truncated. Hence no need to plug the race
* with invalidate/truncate.
*/
if (likely(!PageSwapCache(req->wb_page))) {
set_bit(PG_MAPPED, &req->wb_flags);
SetPagePrivate(req->wb_page);
set_page_private(req->wb_page, (unsigned long)req);
}
nfsi->npages++;
kref_get(&req->wb_kref);
spin_unlock(&inode->i_lock);
}
/*
* Remove a write request from an inode
*/
static void nfs_inode_remove_request(struct nfs_page *req)
{
struct inode *inode = req->wb_context->dentry->d_inode;
struct nfs_inode *nfsi = NFS_I(inode);
spin_lock(&inode->i_lock);
if (likely(!PageSwapCache(req->wb_page))) {
set_page_private(req->wb_page, 0);
ClearPagePrivate(req->wb_page);
clear_bit(PG_MAPPED, &req->wb_flags);
}
nfsi->npages--;
spin_unlock(&inode->i_lock);
nfs_release_request(req);
}
static void
nfs_mark_request_dirty(struct nfs_page *req)
{
__set_page_dirty_nobuffers(req->wb_page);
}
#if IS_ENABLED(CONFIG_NFS_V3) || IS_ENABLED(CONFIG_NFS_V4)
/**
* nfs_request_add_commit_list - add request to a commit list
* @req: pointer to a struct nfs_page
* @dst: commit list head
* @cinfo: holds list lock and accounting info
*
* This sets the PG_CLEAN bit, updates the cinfo count of
* number of outstanding requests requiring a commit as well as
* the MM page stats.
*
* The caller must _not_ hold the cinfo->lock, but must be
* holding the nfs_page lock.
*/
void
nfs_request_add_commit_list(struct nfs_page *req, struct list_head *dst,
struct nfs_commit_info *cinfo)
{
set_bit(PG_CLEAN, &(req)->wb_flags);
spin_lock(cinfo->lock);
nfs_list_add_request(req, dst);
cinfo->mds->ncommit++;
spin_unlock(cinfo->lock);
if (!cinfo->dreq) {
inc_zone_page_state(req->wb_page, NR_UNSTABLE_NFS);
inc_bdi_stat(page_file_mapping(req->wb_page)->backing_dev_info,
BDI_RECLAIMABLE);
__mark_inode_dirty(req->wb_context->dentry->d_inode,
I_DIRTY_DATASYNC);
}
}
EXPORT_SYMBOL_GPL(nfs_request_add_commit_list);
/**
* nfs_request_remove_commit_list - Remove request from a commit list
* @req: pointer to a nfs_page
* @cinfo: holds list lock and accounting info
*
* This clears the PG_CLEAN bit, and updates the cinfo's count of
* number of outstanding requests requiring a commit
* It does not update the MM page stats.
*
* The caller _must_ hold the cinfo->lock and the nfs_page lock.
*/
void
nfs_request_remove_commit_list(struct nfs_page *req,
struct nfs_commit_info *cinfo)
{
if (!test_and_clear_bit(PG_CLEAN, &(req)->wb_flags))
return;
nfs_list_remove_request(req);
cinfo->mds->ncommit--;
}
EXPORT_SYMBOL_GPL(nfs_request_remove_commit_list);
static void nfs_init_cinfo_from_inode(struct nfs_commit_info *cinfo,
struct inode *inode)
{
cinfo->lock = &inode->i_lock;
cinfo->mds = &NFS_I(inode)->commit_info;
cinfo->ds = pnfs_get_ds_info(inode);
cinfo->dreq = NULL;
cinfo->completion_ops = &nfs_commit_completion_ops;
}
void nfs_init_cinfo(struct nfs_commit_info *cinfo,
struct inode *inode,
struct nfs_direct_req *dreq)
{
if (dreq)
nfs_init_cinfo_from_dreq(cinfo, dreq);
else
nfs_init_cinfo_from_inode(cinfo, inode);
}
EXPORT_SYMBOL_GPL(nfs_init_cinfo);
/*
* Add a request to the inode's commit list.
*/
void
nfs_mark_request_commit(struct nfs_page *req, struct pnfs_layout_segment *lseg,
struct nfs_commit_info *cinfo)
{
if (pnfs_mark_request_commit(req, lseg, cinfo))
return;
nfs_request_add_commit_list(req, &cinfo->mds->list, cinfo);
}
static void
nfs_clear_page_commit(struct page *page)
{
dec_zone_page_state(page, NR_UNSTABLE_NFS);
dec_bdi_stat(page_file_mapping(page)->backing_dev_info, BDI_RECLAIMABLE);
}
static void
nfs_clear_request_commit(struct nfs_page *req)
{
if (test_bit(PG_CLEAN, &req->wb_flags)) {
struct inode *inode = req->wb_context->dentry->d_inode;
struct nfs_commit_info cinfo;
nfs_init_cinfo_from_inode(&cinfo, inode);
if (!pnfs_clear_request_commit(req, &cinfo)) {
spin_lock(cinfo.lock);
nfs_request_remove_commit_list(req, &cinfo);
spin_unlock(cinfo.lock);
}
nfs_clear_page_commit(req->wb_page);
}
}
static inline
int nfs_write_need_commit(struct nfs_write_data *data)
{
if (data->verf.committed == NFS_DATA_SYNC)
return data->header->lseg == NULL;
return data->verf.committed != NFS_FILE_SYNC;
}
#else
static void nfs_init_cinfo_from_inode(struct nfs_commit_info *cinfo,
struct inode *inode)
{
}
void nfs_init_cinfo(struct nfs_commit_info *cinfo,
struct inode *inode,
struct nfs_direct_req *dreq)
{
}
void
nfs_mark_request_commit(struct nfs_page *req, struct pnfs_layout_segment *lseg,
struct nfs_commit_info *cinfo)
{
}
static void
nfs_clear_request_commit(struct nfs_page *req)
{
}
static inline
int nfs_write_need_commit(struct nfs_write_data *data)
{
return 0;
}
#endif
static void nfs_write_completion(struct nfs_pgio_header *hdr)
{
struct nfs_commit_info cinfo;
unsigned long bytes = 0;
if (test_bit(NFS_IOHDR_REDO, &hdr->flags))
goto out;
nfs_init_cinfo_from_inode(&cinfo, hdr->inode);
while (!list_empty(&hdr->pages)) {
struct nfs_page *req = nfs_list_entry(hdr->pages.next);
bytes += req->wb_bytes;
nfs_list_remove_request(req);
if (test_bit(NFS_IOHDR_ERROR, &hdr->flags) &&
(hdr->good_bytes < bytes)) {
nfs_set_pageerror(req->wb_page);
nfs_context_set_write_error(req->wb_context, hdr->error);
goto remove_req;
}
if (test_bit(NFS_IOHDR_NEED_RESCHED, &hdr->flags)) {
nfs_mark_request_dirty(req);
goto next;
}
if (test_bit(NFS_IOHDR_NEED_COMMIT, &hdr->flags)) {
memcpy(&req->wb_verf, &hdr->verf->verifier, sizeof(req->wb_verf));
nfs_mark_request_commit(req, hdr->lseg, &cinfo);
goto next;
}
remove_req:
nfs_inode_remove_request(req);
next:
nfs_unlock_request(req);
nfs_end_page_writeback(req->wb_page);
nfs_release_request(req);
}
out:
hdr->release(hdr);
}
#if IS_ENABLED(CONFIG_NFS_V3) || IS_ENABLED(CONFIG_NFS_V4)
static unsigned long
nfs_reqs_to_commit(struct nfs_commit_info *cinfo)
{
return cinfo->mds->ncommit;
}
/* cinfo->lock held by caller */
int
nfs_scan_commit_list(struct list_head *src, struct list_head *dst,
struct nfs_commit_info *cinfo, int max)
{
struct nfs_page *req, *tmp;
int ret = 0;
list_for_each_entry_safe(req, tmp, src, wb_list) {
if (!nfs_lock_request(req))
continue;
kref_get(&req->wb_kref);
if (cond_resched_lock(cinfo->lock))
list_safe_reset_next(req, tmp, wb_list);
nfs_request_remove_commit_list(req, cinfo);
nfs_list_add_request(req, dst);
ret++;
if ((ret == max) && !cinfo->dreq)
break;
}
return ret;
}
/*
* nfs_scan_commit - Scan an inode for commit requests
* @inode: NFS inode to scan
* @dst: mds destination list
* @cinfo: mds and ds lists of reqs ready to commit
*
* Moves requests from the inode's 'commit' request list.
* The requests are *not* checked to ensure that they form a contiguous set.
*/
int
nfs_scan_commit(struct inode *inode, struct list_head *dst,
struct nfs_commit_info *cinfo)
{
int ret = 0;
spin_lock(cinfo->lock);
if (cinfo->mds->ncommit > 0) {
const int max = INT_MAX;
ret = nfs_scan_commit_list(&cinfo->mds->list, dst,
cinfo, max);
ret += pnfs_scan_commit_lists(inode, cinfo, max - ret);
}
spin_unlock(cinfo->lock);
return ret;
}
#else
static unsigned long nfs_reqs_to_commit(struct nfs_commit_info *cinfo)
{
return 0;
}
int nfs_scan_commit(struct inode *inode, struct list_head *dst,
struct nfs_commit_info *cinfo)
{
return 0;
}
#endif
/*
* Search for an existing write request, and attempt to update
* it to reflect a new dirty region on a given page.
*
* If the attempt fails, then the existing request is flushed out
* to disk.
*/
static struct nfs_page *nfs_try_to_update_request(struct inode *inode,
struct page *page,
unsigned int offset,
unsigned int bytes)
{
struct nfs_page *req;
unsigned int rqend;
unsigned int end;
int error;
if (!PagePrivate(page))
return NULL;
end = offset + bytes;
spin_lock(&inode->i_lock);
for (;;) {
req = nfs_page_find_request_locked(NFS_I(inode), page);
if (req == NULL)
goto out_unlock;
rqend = req->wb_offset + req->wb_bytes;
/*
* Tell the caller to flush out the request if
* the offsets are non-contiguous.
* Note: nfs_flush_incompatible() will already
* have flushed out requests having wrong owners.
*/
if (offset > rqend
|| end < req->wb_offset)
goto out_flushme;
if (nfs_lock_request(req))
break;
/* The request is locked, so wait and then retry */
spin_unlock(&inode->i_lock);
error = nfs_wait_on_request(req);
nfs_release_request(req);
if (error != 0)
goto out_err;
spin_lock(&inode->i_lock);
}
/* Okay, the request matches. Update the region */
if (offset < req->wb_offset) {
req->wb_offset = offset;
req->wb_pgbase = offset;
}
if (end > rqend)
req->wb_bytes = end - req->wb_offset;
else
req->wb_bytes = rqend - req->wb_offset;
out_unlock:
spin_unlock(&inode->i_lock);
if (req)
nfs_clear_request_commit(req);
return req;
out_flushme:
spin_unlock(&inode->i_lock);
nfs_release_request(req);
error = nfs_wb_page(inode, page);
out_err:
return ERR_PTR(error);
}
/*
* Try to update an existing write request, or create one if there is none.
*
* Note: Should always be called with the Page Lock held to prevent races
* if we have to add a new request. Also assumes that the caller has
* already called nfs_flush_incompatible() if necessary.
*/
static struct nfs_page * nfs_setup_write_request(struct nfs_open_context* ctx,
struct page *page, unsigned int offset, unsigned int bytes)
{
struct inode *inode = page_file_mapping(page)->host;
struct nfs_page *req;
req = nfs_try_to_update_request(inode, page, offset, bytes);
if (req != NULL)
goto out;
req = nfs_create_request(ctx, inode, page, offset, bytes);
if (IS_ERR(req))
goto out;
nfs_inode_add_request(inode, req);
out:
return req;
}
static int nfs_writepage_setup(struct nfs_open_context *ctx, struct page *page,
unsigned int offset, unsigned int count)
{
struct nfs_page *req;
req = nfs_setup_write_request(ctx, page, offset, count);
if (IS_ERR(req))
return PTR_ERR(req);
/* Update file length */
nfs_grow_file(page, offset, count);
nfs_mark_uptodate(page, req->wb_pgbase, req->wb_bytes);
nfs_mark_request_dirty(req);
nfs_unlock_and_release_request(req);
return 0;
}
int nfs_flush_incompatible(struct file *file, struct page *page)
{
struct nfs_open_context *ctx = nfs_file_open_context(file);
struct nfs_lock_context *l_ctx;
struct nfs_page *req;
int do_flush, status;
/*
* Look for a request corresponding to this page. If there
* is one, and it belongs to another file, we flush it out
* before we try to copy anything into the page. Do this
* due to the lack of an ACCESS-type call in NFSv2.
* Also do the same if we find a request from an existing
* dropped page.
*/
do {
req = nfs_page_find_request(page);
if (req == NULL)
return 0;
l_ctx = req->wb_lock_context;
do_flush = req->wb_page != page || req->wb_context != ctx;
if (l_ctx && ctx->dentry->d_inode->i_flock != NULL) {
do_flush |= l_ctx->lockowner.l_owner != current->files
|| l_ctx->lockowner.l_pid != current->tgid;
}
nfs_release_request(req);
if (!do_flush)
return 0;
status = nfs_wb_page(page_file_mapping(page)->host, page);
} while (status == 0);
return status;
}
/*
* Avoid buffered writes when a open context credential's key would
* expire soon.
*
* Returns -EACCES if the key will expire within RPC_KEY_EXPIRE_FAIL.
*
* Return 0 and set a credential flag which triggers the inode to flush
* and performs NFS_FILE_SYNC writes if the key will expired within
* RPC_KEY_EXPIRE_TIMEO.
*/
int
nfs_key_timeout_notify(struct file *filp, struct inode *inode)
{
struct nfs_open_context *ctx = nfs_file_open_context(filp);
struct rpc_auth *auth = NFS_SERVER(inode)->client->cl_auth;
return rpcauth_key_timeout_notify(auth, ctx->cred);
}
/*
* Test if the open context credential key is marked to expire soon.
*/
bool nfs_ctx_key_to_expire(struct nfs_open_context *ctx)
{
return rpcauth_cred_key_to_expire(ctx->cred);
}
/*
* If the page cache is marked as unsafe or invalid, then we can't rely on
* the PageUptodate() flag. In this case, we will need to turn off
* write optimisations that depend on the page contents being correct.
*/
static bool nfs_write_pageuptodate(struct page *page, struct inode *inode)
{
if (nfs_have_delegated_attributes(inode))
goto out;
if (NFS_I(inode)->cache_validity & (NFS_INO_INVALID_DATA|NFS_INO_REVAL_PAGECACHE))
return false;
out:
return PageUptodate(page) != 0;
}
/* If we know the page is up to date, and we're not using byte range locks (or
* if we have the whole file locked for writing), it may be more efficient to
* extend the write to cover the entire page in order to avoid fragmentation
* inefficiencies.
*
* If the file is opened for synchronous writes then we can just skip the rest
* of the checks.
*/
static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode)
{
if (file->f_flags & O_DSYNC)
return 0;
if (!nfs_write_pageuptodate(page, inode))
return 0;
if (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))
return 1;
if (inode->i_flock == NULL || (inode->i_flock->fl_start == 0 &&
inode->i_flock->fl_end == OFFSET_MAX &&
inode->i_flock->fl_type != F_RDLCK))
return 1;
return 0;
}
/*
* Update and possibly write a cached page of an NFS file.
*
* XXX: Keep an eye on generic_file_read to make sure it doesn't do bad
* things with a page scheduled for an RPC call (e.g. invalidate it).
*/
int nfs_updatepage(struct file *file, struct page *page,
unsigned int offset, unsigned int count)
{
struct nfs_open_context *ctx = nfs_file_open_context(file);
struct inode *inode = page_file_mapping(page)->host;
int status = 0;
nfs_inc_stats(inode, NFSIOS_VFSUPDATEPAGE);
dprintk("NFS: nfs_updatepage(%pD2 %d@%lld)\n",
file, count, (long long)(page_file_offset(page) + offset));
if (nfs_can_extend_write(file, page, inode)) {
count = max(count + offset, nfs_page_length(page));
offset = 0;
}
status = nfs_writepage_setup(ctx, page, offset, count);
if (status < 0)
nfs_set_pageerror(page);
else
__set_page_dirty_nobuffers(page);
dprintk("NFS: nfs_updatepage returns %d (isize %lld)\n",
status, (long long)i_size_read(inode));
return status;
}
static int flush_task_priority(int how)
{
switch (how & (FLUSH_HIGHPRI|FLUSH_LOWPRI)) {
case FLUSH_HIGHPRI:
return RPC_PRIORITY_HIGH;
case FLUSH_LOWPRI:
return RPC_PRIORITY_LOW;
}
return RPC_PRIORITY_NORMAL;
}
int nfs_initiate_write(struct rpc_clnt *clnt,
struct nfs_write_data *data,
const struct rpc_call_ops *call_ops,
int how, int flags)
{
struct inode *inode = data->header->inode;
int priority = flush_task_priority(how);
struct rpc_task *task;
struct rpc_message msg = {
.rpc_argp = &data->args,
.rpc_resp = &data->res,
.rpc_cred = data->header->cred,
};
struct rpc_task_setup task_setup_data = {
.rpc_client = clnt,
.task = &data->task,
.rpc_message = &msg,
.callback_ops = call_ops,
.callback_data = data,
.workqueue = nfsiod_workqueue,
.flags = RPC_TASK_ASYNC | flags,
.priority = priority,
};
int ret = 0;
/* Set up the initial task struct. */
NFS_PROTO(inode)->write_setup(data, &msg);
dprintk("NFS: %5u initiated write call "
"(req %s/%llu, %u bytes @ offset %llu)\n",
data->task.tk_pid,
inode->i_sb->s_id,
(unsigned long long)NFS_FILEID(inode),
data->args.count,
(unsigned long long)data->args.offset);
nfs4_state_protect_write(NFS_SERVER(inode)->nfs_client,
&task_setup_data.rpc_client, &msg, data);
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task)) {
ret = PTR_ERR(task);
goto out;
}
if (how & FLUSH_SYNC) {
ret = rpc_wait_for_completion_task(task);
if (ret == 0)
ret = task->tk_status;
}
rpc_put_task(task);
out:
return ret;
}
EXPORT_SYMBOL_GPL(nfs_initiate_write);
/*
* Set up the argument/result storage required for the RPC call.
*/
static void nfs_write_rpcsetup(struct nfs_write_data *data,
unsigned int count, unsigned int offset,
int how, struct nfs_commit_info *cinfo)
{
struct nfs_page *req = data->header->req;
/* Set up the RPC argument and reply structs
* NB: take care not to mess about with data->commit et al. */
data->args.fh = NFS_FH(data->header->inode);
data->args.offset = req_offset(req) + offset;
/* pnfs_set_layoutcommit needs this */
data->mds_offset = data->args.offset;
data->args.pgbase = req->wb_pgbase + offset;
data->args.pages = data->pages.pagevec;
data->args.count = count;
data->args.context = get_nfs_open_context(req->wb_context);
data->args.lock_context = req->wb_lock_context;
data->args.stable = NFS_UNSTABLE;
switch (how & (FLUSH_STABLE | FLUSH_COND_STABLE)) {
case 0:
break;
case FLUSH_COND_STABLE:
if (nfs_reqs_to_commit(cinfo))
break;
default:
data->args.stable = NFS_FILE_SYNC;
}
data->res.fattr = &data->fattr;
data->res.count = count;
data->res.verf = &data->verf;
nfs_fattr_init(&data->fattr);
}
static int nfs_do_write(struct nfs_write_data *data,
const struct rpc_call_ops *call_ops,
int how)
{
struct inode *inode = data->header->inode;
return nfs_initiate_write(NFS_CLIENT(inode), data, call_ops, how, 0);
}
static int nfs_do_multiple_writes(struct list_head *head,
const struct rpc_call_ops *call_ops,
int how)
{
struct nfs_write_data *data;
int ret = 0;
while (!list_empty(head)) {
int ret2;
data = list_first_entry(head, struct nfs_write_data, list);
list_del_init(&data->list);
ret2 = nfs_do_write(data, call_ops, how);
if (ret == 0)
ret = ret2;
}
return ret;
}
/* If a nfs_flush_* function fails, it should remove reqs from @head and
* call this on each, which will prepare them to be retried on next
* writeback using standard nfs.
*/
static void nfs_redirty_request(struct nfs_page *req)
{
nfs_mark_request_dirty(req);
nfs_unlock_request(req);
nfs_end_page_writeback(req->wb_page);
nfs_release_request(req);
}
static void nfs_async_write_error(struct list_head *head)
{
struct nfs_page *req;
while (!list_empty(head)) {
req = nfs_list_entry(head->next);
nfs_list_remove_request(req);
nfs_redirty_request(req);
}
}
static const struct nfs_pgio_completion_ops nfs_async_write_completion_ops = {
.error_cleanup = nfs_async_write_error,
.completion = nfs_write_completion,
};
static void nfs_flush_error(struct nfs_pageio_descriptor *desc,
struct nfs_pgio_header *hdr)
{
set_bit(NFS_IOHDR_REDO, &hdr->flags);
while (!list_empty(&hdr->rpc_list)) {
struct nfs_write_data *data = list_first_entry(&hdr->rpc_list,
struct nfs_write_data, list);
list_del(&data->list);
nfs_writedata_release(data);
}
desc->pg_completion_ops->error_cleanup(&desc->pg_list);
}
/*
* Generate multiple small requests to write out a single
* contiguous dirty area on one page.
*/
static int nfs_flush_multi(struct nfs_pageio_descriptor *desc,
struct nfs_pgio_header *hdr)
{
struct nfs_page *req = hdr->req;
struct page *page = req->wb_page;
struct nfs_write_data *data;
size_t wsize = desc->pg_bsize, nbytes;
unsigned int offset;
int requests = 0;
struct nfs_commit_info cinfo;
nfs_init_cinfo(&cinfo, desc->pg_inode, desc->pg_dreq);
if ((desc->pg_ioflags & FLUSH_COND_STABLE) &&
(desc->pg_moreio || nfs_reqs_to_commit(&cinfo) ||
desc->pg_count > wsize))
desc->pg_ioflags &= ~FLUSH_COND_STABLE;
offset = 0;
nbytes = desc->pg_count;
do {
size_t len = min(nbytes, wsize);
data = nfs_writedata_alloc(hdr, 1);
if (!data) {
nfs_flush_error(desc, hdr);
return -ENOMEM;
}
data->pages.pagevec[0] = page;
nfs_write_rpcsetup(data, len, offset, desc->pg_ioflags, &cinfo);
list_add(&data->list, &hdr->rpc_list);
requests++;
nbytes -= len;
offset += len;
} while (nbytes != 0);
nfs_list_remove_request(req);
nfs_list_add_request(req, &hdr->pages);
desc->pg_rpc_callops = &nfs_write_common_ops;
return 0;
}
/*
* Create an RPC task for the given write request and kick it.
* The page must have been locked by the caller.
*
* It may happen that the page we're passed is not marked dirty.
* This is the case if nfs_updatepage detects a conflicting request
* that has been written but not committed.
*/
static int nfs_flush_one(struct nfs_pageio_descriptor *desc,
struct nfs_pgio_header *hdr)
{
struct nfs_page *req;
struct page **pages;
struct nfs_write_data *data;
struct list_head *head = &desc->pg_list;
struct nfs_commit_info cinfo;
data = nfs_writedata_alloc(hdr, nfs_page_array_len(desc->pg_base,
desc->pg_count));
if (!data) {
nfs_flush_error(desc, hdr);
return -ENOMEM;
}
nfs_init_cinfo(&cinfo, desc->pg_inode, desc->pg_dreq);
pages = data->pages.pagevec;
while (!list_empty(head)) {
req = nfs_list_entry(head->next);
nfs_list_remove_request(req);
nfs_list_add_request(req, &hdr->pages);
*pages++ = req->wb_page;
}
if ((desc->pg_ioflags & FLUSH_COND_STABLE) &&
(desc->pg_moreio || nfs_reqs_to_commit(&cinfo)))
desc->pg_ioflags &= ~FLUSH_COND_STABLE;
/* Set up the argument struct */
nfs_write_rpcsetup(data, desc->pg_count, 0, desc->pg_ioflags, &cinfo);
list_add(&data->list, &hdr->rpc_list);
desc->pg_rpc_callops = &nfs_write_common_ops;
return 0;
}
int nfs_generic_flush(struct nfs_pageio_descriptor *desc,
struct nfs_pgio_header *hdr)
{
if (desc->pg_bsize < PAGE_CACHE_SIZE)
return nfs_flush_multi(desc, hdr);
return nfs_flush_one(desc, hdr);
}
EXPORT_SYMBOL_GPL(nfs_generic_flush);
static int nfs_generic_pg_writepages(struct nfs_pageio_descriptor *desc)
{
struct nfs_write_header *whdr;
struct nfs_pgio_header *hdr;
int ret;
whdr = nfs_writehdr_alloc();
if (!whdr) {
desc->pg_completion_ops->error_cleanup(&desc->pg_list);
return -ENOMEM;
}
hdr = &whdr->header;
nfs_pgheader_init(desc, hdr, nfs_writehdr_free);
atomic_inc(&hdr->refcnt);
ret = nfs_generic_flush(desc, hdr);
if (ret == 0)
ret = nfs_do_multiple_writes(&hdr->rpc_list,
desc->pg_rpc_callops,
desc->pg_ioflags);
if (atomic_dec_and_test(&hdr->refcnt))
hdr->completion_ops->completion(hdr);
return ret;
}
static const struct nfs_pageio_ops nfs_pageio_write_ops = {
.pg_test = nfs_generic_pg_test,
.pg_doio = nfs_generic_pg_writepages,
};
void nfs_pageio_init_write(struct nfs_pageio_descriptor *pgio,
struct inode *inode, int ioflags,
const struct nfs_pgio_completion_ops *compl_ops)
{
nfs_pageio_init(pgio, inode, &nfs_pageio_write_ops, compl_ops,
NFS_SERVER(inode)->wsize, ioflags);
}
EXPORT_SYMBOL_GPL(nfs_pageio_init_write);
void nfs_pageio_reset_write_mds(struct nfs_pageio_descriptor *pgio)
{
pgio->pg_ops = &nfs_pageio_write_ops;
pgio->pg_bsize = NFS_SERVER(pgio->pg_inode)->wsize;
}
EXPORT_SYMBOL_GPL(nfs_pageio_reset_write_mds);
void nfs_write_prepare(struct rpc_task *task, void *calldata)
{
struct nfs_write_data *data = calldata;
int err;
err = NFS_PROTO(data->header->inode)->write_rpc_prepare(task, data);
if (err)
rpc_exit(task, err);
}
void nfs_commit_prepare(struct rpc_task *task, void *calldata)
{
struct nfs_commit_data *data = calldata;
NFS_PROTO(data->inode)->commit_rpc_prepare(task, data);
}
/*
* Handle a write reply that flushes a whole page.
*
* FIXME: There is an inherent race with invalidate_inode_pages and
* writebacks since the page->count is kept > 1 for as long
* as the page has a write request pending.
*/
static void nfs_writeback_done_common(struct rpc_task *task, void *calldata)
{
struct nfs_write_data *data = calldata;
nfs_writeback_done(task, data);
}
static void nfs_writeback_release_common(void *calldata)
{
struct nfs_write_data *data = calldata;
struct nfs_pgio_header *hdr = data->header;
int status = data->task.tk_status;
if ((status >= 0) && nfs_write_need_commit(data)) {
spin_lock(&hdr->lock);
if (test_bit(NFS_IOHDR_NEED_RESCHED, &hdr->flags))
; /* Do nothing */
else if (!test_and_set_bit(NFS_IOHDR_NEED_COMMIT, &hdr->flags))
memcpy(hdr->verf, &data->verf, sizeof(*hdr->verf));
else if (memcmp(hdr->verf, &data->verf, sizeof(*hdr->verf)))
set_bit(NFS_IOHDR_NEED_RESCHED, &hdr->flags);
spin_unlock(&hdr->lock);
}
nfs_writedata_release(data);
}
static const struct rpc_call_ops nfs_write_common_ops = {
.rpc_call_prepare = nfs_write_prepare,
.rpc_call_done = nfs_writeback_done_common,
.rpc_release = nfs_writeback_release_common,
};
/*
* This function is called when the WRITE call is complete.
*/
void nfs_writeback_done(struct rpc_task *task, struct nfs_write_data *data)
{
struct nfs_writeargs *argp = &data->args;
struct nfs_writeres *resp = &data->res;
struct inode *inode = data->header->inode;
int status;
dprintk("NFS: %5u nfs_writeback_done (status %d)\n",
task->tk_pid, task->tk_status);
/*
* ->write_done will attempt to use post-op attributes to detect
* conflicting writes by other clients. A strict interpretation
* of close-to-open would allow us to continue caching even if
* another writer had changed the file, but some applications
* depend on tighter cache coherency when writing.
*/
status = NFS_PROTO(inode)->write_done(task, data);
if (status != 0)
return;
nfs_add_stats(inode, NFSIOS_SERVERWRITTENBYTES, resp->count);
#if IS_ENABLED(CONFIG_NFS_V3) || IS_ENABLED(CONFIG_NFS_V4)
if (resp->verf->committed < argp->stable && task->tk_status >= 0) {
/* We tried a write call, but the server did not
* commit data to stable storage even though we
* requested it.
* Note: There is a known bug in Tru64 < 5.0 in which
* the server reports NFS_DATA_SYNC, but performs
* NFS_FILE_SYNC. We therefore implement this checking
* as a dprintk() in order to avoid filling syslog.
*/
static unsigned long complain;
/* Note this will print the MDS for a DS write */
if (time_before(complain, jiffies)) {
dprintk("NFS: faulty NFS server %s:"
" (committed = %d) != (stable = %d)\n",
NFS_SERVER(inode)->nfs_client->cl_hostname,
resp->verf->committed, argp->stable);
complain = jiffies + 300 * HZ;
}
}
#endif
if (task->tk_status < 0)
nfs_set_pgio_error(data->header, task->tk_status, argp->offset);
else if (resp->count < argp->count) {
static unsigned long complain;
/* This a short write! */
nfs_inc_stats(inode, NFSIOS_SHORTWRITE);
/* Has the server at least made some progress? */
if (resp->count == 0) {
if (time_before(complain, jiffies)) {
printk(KERN_WARNING
"NFS: Server wrote zero bytes, expected %u.\n",
argp->count);
complain = jiffies + 300 * HZ;
}
nfs_set_pgio_error(data->header, -EIO, argp->offset);
task->tk_status = -EIO;
return;
}
/* Was this an NFSv2 write or an NFSv3 stable write? */
if (resp->verf->committed != NFS_UNSTABLE) {
/* Resend from where the server left off */
data->mds_offset += resp->count;
argp->offset += resp->count;
argp->pgbase += resp->count;
argp->count -= resp->count;
} else {
/* Resend as a stable write in order to avoid
* headaches in the case of a server crash.
*/
argp->stable = NFS_FILE_SYNC;
}
rpc_restart_call_prepare(task);
}
}
#if IS_ENABLED(CONFIG_NFS_V3) || IS_ENABLED(CONFIG_NFS_V4)
static int nfs_commit_set_lock(struct nfs_inode *nfsi, int may_wait)
{
int ret;
if (!test_and_set_bit(NFS_INO_COMMIT, &nfsi->flags))
return 1;
if (!may_wait)
return 0;
ret = out_of_line_wait_on_bit_lock(&nfsi->flags,
NFS_INO_COMMIT,
nfs_wait_bit_killable,
TASK_KILLABLE);
return (ret < 0) ? ret : 1;
}
static void nfs_commit_clear_lock(struct nfs_inode *nfsi)
{
clear_bit(NFS_INO_COMMIT, &nfsi->flags);
smp_mb__after_clear_bit();
wake_up_bit(&nfsi->flags, NFS_INO_COMMIT);
}
void nfs_commitdata_release(struct nfs_commit_data *data)
{
put_nfs_open_context(data->context);
nfs_commit_free(data);
}
EXPORT_SYMBOL_GPL(nfs_commitdata_release);
int nfs_initiate_commit(struct rpc_clnt *clnt, struct nfs_commit_data *data,
const struct rpc_call_ops *call_ops,
int how, int flags)
{
struct rpc_task *task;
int priority = flush_task_priority(how);
struct rpc_message msg = {
.rpc_argp = &data->args,
.rpc_resp = &data->res,
.rpc_cred = data->cred,
};
struct rpc_task_setup task_setup_data = {
.task = &data->task,
.rpc_client = clnt,
.rpc_message = &msg,
.callback_ops = call_ops,
.callback_data = data,
.workqueue = nfsiod_workqueue,
.flags = RPC_TASK_ASYNC | flags,
.priority = priority,
};
/* Set up the initial task struct. */
NFS_PROTO(data->inode)->commit_setup(data, &msg);
dprintk("NFS: %5u initiated commit call\n", data->task.tk_pid);
nfs4_state_protect(NFS_SERVER(data->inode)->nfs_client,
NFS_SP4_MACH_CRED_COMMIT, &task_setup_data.rpc_client, &msg);
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task))
return PTR_ERR(task);
if (how & FLUSH_SYNC)
rpc_wait_for_completion_task(task);
rpc_put_task(task);
return 0;
}
EXPORT_SYMBOL_GPL(nfs_initiate_commit);
/*
* Set up the argument/result storage required for the RPC call.
*/
void nfs_init_commit(struct nfs_commit_data *data,
struct list_head *head,
struct pnfs_layout_segment *lseg,
struct nfs_commit_info *cinfo)
{
struct nfs_page *first = nfs_list_entry(head->next);
struct inode *inode = first->wb_context->dentry->d_inode;
/* Set up the RPC argument and reply structs
* NB: take care not to mess about with data->commit et al. */
list_splice_init(head, &data->pages);
data->inode = inode;
data->cred = first->wb_context->cred;
data->lseg = lseg; /* reference transferred */
data->mds_ops = &nfs_commit_ops;
data->completion_ops = cinfo->completion_ops;
data->dreq = cinfo->dreq;
data->args.fh = NFS_FH(data->inode);
/* Note: we always request a commit of the entire inode */
data->args.offset = 0;
data->args.count = 0;
data->context = get_nfs_open_context(first->wb_context);
data->res.fattr = &data->fattr;
data->res.verf = &data->verf;
nfs_fattr_init(&data->fattr);
}
EXPORT_SYMBOL_GPL(nfs_init_commit);
void nfs_retry_commit(struct list_head *page_list,
struct pnfs_layout_segment *lseg,
struct nfs_commit_info *cinfo)
{
struct nfs_page *req;
while (!list_empty(page_list)) {
req = nfs_list_entry(page_list->next);
nfs_list_remove_request(req);
nfs_mark_request_commit(req, lseg, cinfo);
if (!cinfo->dreq) {
dec_zone_page_state(req->wb_page, NR_UNSTABLE_NFS);
dec_bdi_stat(page_file_mapping(req->wb_page)->backing_dev_info,
BDI_RECLAIMABLE);
}
nfs_unlock_and_release_request(req);
}
}
EXPORT_SYMBOL_GPL(nfs_retry_commit);
/*
* Commit dirty pages
*/
static int
nfs_commit_list(struct inode *inode, struct list_head *head, int how,
struct nfs_commit_info *cinfo)
{
struct nfs_commit_data *data;
data = nfs_commitdata_alloc();
if (!data)
goto out_bad;
/* Set up the argument struct */
nfs_init_commit(data, head, NULL, cinfo);
atomic_inc(&cinfo->mds->rpcs_out);
return nfs_initiate_commit(NFS_CLIENT(inode), data, data->mds_ops,
how, 0);
out_bad:
nfs_retry_commit(head, NULL, cinfo);
cinfo->completion_ops->error_cleanup(NFS_I(inode));
return -ENOMEM;
}
/*
* COMMIT call returned
*/
static void nfs_commit_done(struct rpc_task *task, void *calldata)
{
struct nfs_commit_data *data = calldata;
dprintk("NFS: %5u nfs_commit_done (status %d)\n",
task->tk_pid, task->tk_status);
/* Call the NFS version-specific code */
NFS_PROTO(data->inode)->commit_done(task, data);
}
static void nfs_commit_release_pages(struct nfs_commit_data *data)
{
struct nfs_page *req;
int status = data->task.tk_status;
struct nfs_commit_info cinfo;
while (!list_empty(&data->pages)) {
req = nfs_list_entry(data->pages.next);
nfs_list_remove_request(req);
nfs_clear_page_commit(req->wb_page);
dprintk("NFS: commit (%s/%llu %d@%lld)",
req->wb_context->dentry->d_sb->s_id,
(unsigned long long)NFS_FILEID(req->wb_context->dentry->d_inode),
req->wb_bytes,
(long long)req_offset(req));
if (status < 0) {
nfs_context_set_write_error(req->wb_context, status);
nfs_inode_remove_request(req);
dprintk(", error = %d\n", status);
goto next;
}
/* Okay, COMMIT succeeded, apparently. Check the verifier
* returned by the server against all stored verfs. */
if (!memcmp(&req->wb_verf, &data->verf.verifier, sizeof(req->wb_verf))) {
/* We have a match */
nfs_inode_remove_request(req);
dprintk(" OK\n");
goto next;
}
/* We have a mismatch. Write the page again */
dprintk(" mismatch\n");
nfs_mark_request_dirty(req);
set_bit(NFS_CONTEXT_RESEND_WRITES, &req->wb_context->flags);
next:
nfs_unlock_and_release_request(req);
}
nfs_init_cinfo(&cinfo, data->inode, data->dreq);
if (atomic_dec_and_test(&cinfo.mds->rpcs_out))
nfs_commit_clear_lock(NFS_I(data->inode));
}
static void nfs_commit_release(void *calldata)
{
struct nfs_commit_data *data = calldata;
data->completion_ops->completion(data);
nfs_commitdata_release(calldata);
}
static const struct rpc_call_ops nfs_commit_ops = {
.rpc_call_prepare = nfs_commit_prepare,
.rpc_call_done = nfs_commit_done,
.rpc_release = nfs_commit_release,
};
static const struct nfs_commit_completion_ops nfs_commit_completion_ops = {
.completion = nfs_commit_release_pages,
.error_cleanup = nfs_commit_clear_lock,
};
int nfs_generic_commit_list(struct inode *inode, struct list_head *head,
int how, struct nfs_commit_info *cinfo)
{
int status;
status = pnfs_commit_list(inode, head, how, cinfo);
if (status == PNFS_NOT_ATTEMPTED)
status = nfs_commit_list(inode, head, how, cinfo);
return status;
}
int nfs_commit_inode(struct inode *inode, int how)
{
LIST_HEAD(head);
struct nfs_commit_info cinfo;
int may_wait = how & FLUSH_SYNC;
int res;
res = nfs_commit_set_lock(NFS_I(inode), may_wait);
if (res <= 0)
goto out_mark_dirty;
nfs_init_cinfo_from_inode(&cinfo, inode);
res = nfs_scan_commit(inode, &head, &cinfo);
if (res) {
int error;
error = nfs_generic_commit_list(inode, &head, how, &cinfo);
if (error < 0)
return error;
if (!may_wait)
goto out_mark_dirty;
error = wait_on_bit(&NFS_I(inode)->flags,
NFS_INO_COMMIT,
nfs_wait_bit_killable,
TASK_KILLABLE);
if (error < 0)
return error;
} else
nfs_commit_clear_lock(NFS_I(inode));
return res;
/* Note: If we exit without ensuring that the commit is complete,
* we must mark the inode as dirty. Otherwise, future calls to
* sync_inode() with the WB_SYNC_ALL flag set will fail to ensure
* that the data is on the disk.
*/
out_mark_dirty:
__mark_inode_dirty(inode, I_DIRTY_DATASYNC);
return res;
}
static int nfs_commit_unstable_pages(struct inode *inode, struct writeback_control *wbc)
{
struct nfs_inode *nfsi = NFS_I(inode);
int flags = FLUSH_SYNC;
int ret = 0;
/* no commits means nothing needs to be done */
if (!nfsi->commit_info.ncommit)
return ret;
if (wbc->sync_mode == WB_SYNC_NONE) {
/* Don't commit yet if this is a non-blocking flush and there
* are a lot of outstanding writes for this mapping.
*/
if (nfsi->commit_info.ncommit <= (nfsi->npages >> 1))
goto out_mark_dirty;
/* don't wait for the COMMIT response */
flags = 0;
}
ret = nfs_commit_inode(inode, flags);
if (ret >= 0) {
if (wbc->sync_mode == WB_SYNC_NONE) {
if (ret < wbc->nr_to_write)
wbc->nr_to_write -= ret;
else
wbc->nr_to_write = 0;
}
return 0;
}
out_mark_dirty:
__mark_inode_dirty(inode, I_DIRTY_DATASYNC);
return ret;
}
#else
static int nfs_commit_unstable_pages(struct inode *inode, struct writeback_control *wbc)
{
return 0;
}
#endif
int nfs_write_inode(struct inode *inode, struct writeback_control *wbc)
{
return nfs_commit_unstable_pages(inode, wbc);
}
EXPORT_SYMBOL_GPL(nfs_write_inode);
/*
* flush the inode to disk.
*/
int nfs_wb_all(struct inode *inode)
{
struct writeback_control wbc = {
.sync_mode = WB_SYNC_ALL,
.nr_to_write = LONG_MAX,
.range_start = 0,
.range_end = LLONG_MAX,
};
int ret;
trace_nfs_writeback_inode_enter(inode);
ret = sync_inode(inode, &wbc);
trace_nfs_writeback_inode_exit(inode, ret);
return ret;
}
EXPORT_SYMBOL_GPL(nfs_wb_all);
int nfs_wb_page_cancel(struct inode *inode, struct page *page)
{
struct nfs_page *req;
int ret = 0;
for (;;) {
wait_on_page_writeback(page);
req = nfs_page_find_request(page);
if (req == NULL)
break;
if (nfs_lock_request(req)) {
nfs_clear_request_commit(req);
nfs_inode_remove_request(req);
/*
* In case nfs_inode_remove_request has marked the
* page as being dirty
*/
cancel_dirty_page(page, PAGE_CACHE_SIZE);
nfs_unlock_and_release_request(req);
break;
}
ret = nfs_wait_on_request(req);
nfs_release_request(req);
if (ret < 0)
break;
}
return ret;
}
/*
* Write back all requests on one page - we do this before reading it.
*/
int nfs_wb_page(struct inode *inode, struct page *page)
{
loff_t range_start = page_file_offset(page);
loff_t range_end = range_start + (loff_t)(PAGE_CACHE_SIZE - 1);
struct writeback_control wbc = {
.sync_mode = WB_SYNC_ALL,
.nr_to_write = 0,
.range_start = range_start,
.range_end = range_end,
};
int ret;
trace_nfs_writeback_page_enter(inode);
for (;;) {
wait_on_page_writeback(page);
if (clear_page_dirty_for_io(page)) {
ret = nfs_writepage_locked(page, &wbc);
if (ret < 0)
goto out_error;
continue;
}
ret = 0;
if (!PagePrivate(page))
break;
ret = nfs_commit_inode(inode, FLUSH_SYNC);
if (ret < 0)
goto out_error;
}
out_error:
trace_nfs_writeback_page_exit(inode, ret);
return ret;
}
#ifdef CONFIG_MIGRATION
int nfs_migrate_page(struct address_space *mapping, struct page *newpage,
struct page *page, enum migrate_mode mode)
{
/*
* If PagePrivate is set, then the page is currently associated with
* an in-progress read or write request. Don't try to migrate it.
*
* FIXME: we could do this in principle, but we'll need a way to ensure
* that we can safely release the inode reference while holding
* the page lock.
*/
if (PagePrivate(page))
return -EBUSY;
if (!nfs_fscache_release_page(page, GFP_KERNEL))
return -EBUSY;
return migrate_page(mapping, newpage, page, mode);
}
#endif
int __init nfs_init_writepagecache(void)
{
nfs_wdata_cachep = kmem_cache_create("nfs_write_data",
sizeof(struct nfs_write_header),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (nfs_wdata_cachep == NULL)
return -ENOMEM;
nfs_wdata_mempool = mempool_create_slab_pool(MIN_POOL_WRITE,
nfs_wdata_cachep);
if (nfs_wdata_mempool == NULL)
goto out_destroy_write_cache;
nfs_cdata_cachep = kmem_cache_create("nfs_commit_data",
sizeof(struct nfs_commit_data),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (nfs_cdata_cachep == NULL)
goto out_destroy_write_mempool;
nfs_commit_mempool = mempool_create_slab_pool(MIN_POOL_COMMIT,
nfs_cdata_cachep);
if (nfs_commit_mempool == NULL)
goto out_destroy_commit_cache;
/*
* NFS congestion size, scale with available memory.
*
* 64MB: 8192k
* 128MB: 11585k
* 256MB: 16384k
* 512MB: 23170k
* 1GB: 32768k
* 2GB: 46340k
* 4GB: 65536k
* 8GB: 92681k
* 16GB: 131072k
*
* This allows larger machines to have larger/more transfers.
* Limit the default to 256M
*/
nfs_congestion_kb = (16*int_sqrt(totalram_pages)) << (PAGE_SHIFT-10);
if (nfs_congestion_kb > 256*1024)
nfs_congestion_kb = 256*1024;
return 0;
out_destroy_commit_cache:
kmem_cache_destroy(nfs_cdata_cachep);
out_destroy_write_mempool:
mempool_destroy(nfs_wdata_mempool);
out_destroy_write_cache:
kmem_cache_destroy(nfs_wdata_cachep);
return -ENOMEM;
}
void nfs_destroy_writepagecache(void)
{
mempool_destroy(nfs_commit_mempool);
kmem_cache_destroy(nfs_cdata_cachep);
mempool_destroy(nfs_wdata_mempool);
kmem_cache_destroy(nfs_wdata_cachep);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2089_0 |
crossvul-cpp_data_bad_406_0 | /*
* Copyright (C) 2012,2013 - ARM Ltd
* Author: Marc Zyngier <marc.zyngier@arm.com>
*
* Derived from arch/arm/kvm/guest.c:
* Copyright (C) 2012 - Virtual Open Systems and Columbia University
* Author: Christoffer Dall <c.dall@virtualopensystems.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/kvm_host.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/fs.h>
#include <kvm/arm_psci.h>
#include <asm/cputype.h>
#include <linux/uaccess.h>
#include <asm/kvm.h>
#include <asm/kvm_emulate.h>
#include <asm/kvm_coproc.h>
#include "trace.h"
#define VM_STAT(x) { #x, offsetof(struct kvm, stat.x), KVM_STAT_VM }
#define VCPU_STAT(x) { #x, offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU }
struct kvm_stats_debugfs_item debugfs_entries[] = {
VCPU_STAT(hvc_exit_stat),
VCPU_STAT(wfe_exit_stat),
VCPU_STAT(wfi_exit_stat),
VCPU_STAT(mmio_exit_user),
VCPU_STAT(mmio_exit_kernel),
VCPU_STAT(exits),
{ NULL }
};
int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
{
return 0;
}
static u64 core_reg_offset_from_id(u64 id)
{
return id & ~(KVM_REG_ARCH_MASK | KVM_REG_SIZE_MASK | KVM_REG_ARM_CORE);
}
static int get_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
/*
* Because the kvm_regs structure is a mix of 32, 64 and
* 128bit fields, we index it as if it was a 32bit
* array. Hence below, nr_regs is the number of entries, and
* off the index in the "array".
*/
__u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr;
struct kvm_regs *regs = vcpu_gp_regs(vcpu);
int nr_regs = sizeof(*regs) / sizeof(__u32);
u32 off;
/* Our ID is an index into the kvm_regs struct. */
off = core_reg_offset_from_id(reg->id);
if (off >= nr_regs ||
(off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs)
return -ENOENT;
if (copy_to_user(uaddr, ((u32 *)regs) + off, KVM_REG_SIZE(reg->id)))
return -EFAULT;
return 0;
}
static int set_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
__u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr;
struct kvm_regs *regs = vcpu_gp_regs(vcpu);
int nr_regs = sizeof(*regs) / sizeof(__u32);
__uint128_t tmp;
void *valp = &tmp;
u64 off;
int err = 0;
/* Our ID is an index into the kvm_regs struct. */
off = core_reg_offset_from_id(reg->id);
if (off >= nr_regs ||
(off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs)
return -ENOENT;
if (KVM_REG_SIZE(reg->id) > sizeof(tmp))
return -EINVAL;
if (copy_from_user(valp, uaddr, KVM_REG_SIZE(reg->id))) {
err = -EFAULT;
goto out;
}
if (off == KVM_REG_ARM_CORE_REG(regs.pstate)) {
u32 mode = (*(u32 *)valp) & PSR_AA32_MODE_MASK;
switch (mode) {
case PSR_AA32_MODE_USR:
case PSR_AA32_MODE_FIQ:
case PSR_AA32_MODE_IRQ:
case PSR_AA32_MODE_SVC:
case PSR_AA32_MODE_ABT:
case PSR_AA32_MODE_UND:
case PSR_MODE_EL0t:
case PSR_MODE_EL1t:
case PSR_MODE_EL1h:
break;
default:
err = -EINVAL;
goto out;
}
}
memcpy((u32 *)regs + off, valp, KVM_REG_SIZE(reg->id));
out:
return err;
}
int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
{
return -EINVAL;
}
int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
{
return -EINVAL;
}
static unsigned long num_core_regs(void)
{
return sizeof(struct kvm_regs) / sizeof(__u32);
}
/**
* ARM64 versions of the TIMER registers, always available on arm64
*/
#define NUM_TIMER_REGS 3
static bool is_timer_reg(u64 index)
{
switch (index) {
case KVM_REG_ARM_TIMER_CTL:
case KVM_REG_ARM_TIMER_CNT:
case KVM_REG_ARM_TIMER_CVAL:
return true;
}
return false;
}
static int copy_timer_indices(struct kvm_vcpu *vcpu, u64 __user *uindices)
{
if (put_user(KVM_REG_ARM_TIMER_CTL, uindices))
return -EFAULT;
uindices++;
if (put_user(KVM_REG_ARM_TIMER_CNT, uindices))
return -EFAULT;
uindices++;
if (put_user(KVM_REG_ARM_TIMER_CVAL, uindices))
return -EFAULT;
return 0;
}
static int set_timer_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
void __user *uaddr = (void __user *)(long)reg->addr;
u64 val;
int ret;
ret = copy_from_user(&val, uaddr, KVM_REG_SIZE(reg->id));
if (ret != 0)
return -EFAULT;
return kvm_arm_timer_set_reg(vcpu, reg->id, val);
}
static int get_timer_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
void __user *uaddr = (void __user *)(long)reg->addr;
u64 val;
val = kvm_arm_timer_get_reg(vcpu, reg->id);
return copy_to_user(uaddr, &val, KVM_REG_SIZE(reg->id)) ? -EFAULT : 0;
}
/**
* kvm_arm_num_regs - how many registers do we present via KVM_GET_ONE_REG
*
* This is for all registers.
*/
unsigned long kvm_arm_num_regs(struct kvm_vcpu *vcpu)
{
return num_core_regs() + kvm_arm_num_sys_reg_descs(vcpu)
+ kvm_arm_get_fw_num_regs(vcpu) + NUM_TIMER_REGS;
}
/**
* kvm_arm_copy_reg_indices - get indices of all registers.
*
* We do core registers right here, then we append system regs.
*/
int kvm_arm_copy_reg_indices(struct kvm_vcpu *vcpu, u64 __user *uindices)
{
unsigned int i;
const u64 core_reg = KVM_REG_ARM64 | KVM_REG_SIZE_U64 | KVM_REG_ARM_CORE;
int ret;
for (i = 0; i < sizeof(struct kvm_regs) / sizeof(__u32); i++) {
if (put_user(core_reg | i, uindices))
return -EFAULT;
uindices++;
}
ret = kvm_arm_copy_fw_reg_indices(vcpu, uindices);
if (ret)
return ret;
uindices += kvm_arm_get_fw_num_regs(vcpu);
ret = copy_timer_indices(vcpu, uindices);
if (ret)
return ret;
uindices += NUM_TIMER_REGS;
return kvm_arm_copy_sys_reg_indices(vcpu, uindices);
}
int kvm_arm_get_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
/* We currently use nothing arch-specific in upper 32 bits */
if ((reg->id & ~KVM_REG_SIZE_MASK) >> 32 != KVM_REG_ARM64 >> 32)
return -EINVAL;
/* Register group 16 means we want a core register. */
if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_CORE)
return get_core_reg(vcpu, reg);
if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_FW)
return kvm_arm_get_fw_reg(vcpu, reg);
if (is_timer_reg(reg->id))
return get_timer_reg(vcpu, reg);
return kvm_arm_sys_reg_get_reg(vcpu, reg);
}
int kvm_arm_set_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
/* We currently use nothing arch-specific in upper 32 bits */
if ((reg->id & ~KVM_REG_SIZE_MASK) >> 32 != KVM_REG_ARM64 >> 32)
return -EINVAL;
/* Register group 16 means we set a core register. */
if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_CORE)
return set_core_reg(vcpu, reg);
if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_FW)
return kvm_arm_set_fw_reg(vcpu, reg);
if (is_timer_reg(reg->id))
return set_timer_reg(vcpu, reg);
return kvm_arm_sys_reg_set_reg(vcpu, reg);
}
int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
struct kvm_sregs *sregs)
{
return -EINVAL;
}
int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
struct kvm_sregs *sregs)
{
return -EINVAL;
}
int __kvm_arm_vcpu_get_events(struct kvm_vcpu *vcpu,
struct kvm_vcpu_events *events)
{
events->exception.serror_pending = !!(vcpu->arch.hcr_el2 & HCR_VSE);
events->exception.serror_has_esr = cpus_have_const_cap(ARM64_HAS_RAS_EXTN);
if (events->exception.serror_pending && events->exception.serror_has_esr)
events->exception.serror_esr = vcpu_get_vsesr(vcpu);
return 0;
}
int __kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu,
struct kvm_vcpu_events *events)
{
bool serror_pending = events->exception.serror_pending;
bool has_esr = events->exception.serror_has_esr;
if (serror_pending && has_esr) {
if (!cpus_have_const_cap(ARM64_HAS_RAS_EXTN))
return -EINVAL;
if (!((events->exception.serror_esr) & ~ESR_ELx_ISS_MASK))
kvm_set_sei_esr(vcpu, events->exception.serror_esr);
else
return -EINVAL;
} else if (serror_pending) {
kvm_inject_vabt(vcpu);
}
return 0;
}
int __attribute_const__ kvm_target_cpu(void)
{
unsigned long implementor = read_cpuid_implementor();
unsigned long part_number = read_cpuid_part_number();
switch (implementor) {
case ARM_CPU_IMP_ARM:
switch (part_number) {
case ARM_CPU_PART_AEM_V8:
return KVM_ARM_TARGET_AEM_V8;
case ARM_CPU_PART_FOUNDATION:
return KVM_ARM_TARGET_FOUNDATION_V8;
case ARM_CPU_PART_CORTEX_A53:
return KVM_ARM_TARGET_CORTEX_A53;
case ARM_CPU_PART_CORTEX_A57:
return KVM_ARM_TARGET_CORTEX_A57;
};
break;
case ARM_CPU_IMP_APM:
switch (part_number) {
case APM_CPU_PART_POTENZA:
return KVM_ARM_TARGET_XGENE_POTENZA;
};
break;
};
/* Return a default generic target */
return KVM_ARM_TARGET_GENERIC_V8;
}
int kvm_vcpu_preferred_target(struct kvm_vcpu_init *init)
{
int target = kvm_target_cpu();
if (target < 0)
return -ENODEV;
memset(init, 0, sizeof(*init));
/*
* For now, we don't return any features.
* In future, we might use features to return target
* specific features available for the preferred
* target type.
*/
init->target = (__u32)target;
return 0;
}
int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
{
return -EINVAL;
}
int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
{
return -EINVAL;
}
int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
struct kvm_translation *tr)
{
return -EINVAL;
}
#define KVM_GUESTDBG_VALID_MASK (KVM_GUESTDBG_ENABLE | \
KVM_GUESTDBG_USE_SW_BP | \
KVM_GUESTDBG_USE_HW | \
KVM_GUESTDBG_SINGLESTEP)
/**
* kvm_arch_vcpu_ioctl_set_guest_debug - set up guest debugging
* @kvm: pointer to the KVM struct
* @kvm_guest_debug: the ioctl data buffer
*
* This sets up and enables the VM for guest debugging. Userspace
* passes in a control flag to enable different debug types and
* potentially other architecture specific information in the rest of
* the structure.
*/
int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
struct kvm_guest_debug *dbg)
{
int ret = 0;
trace_kvm_set_guest_debug(vcpu, dbg->control);
if (dbg->control & ~KVM_GUESTDBG_VALID_MASK) {
ret = -EINVAL;
goto out;
}
if (dbg->control & KVM_GUESTDBG_ENABLE) {
vcpu->guest_debug = dbg->control;
/* Hardware assisted Break and Watch points */
if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW) {
vcpu->arch.external_debug_state = dbg->arch;
}
} else {
/* If not enabled clear all flags */
vcpu->guest_debug = 0;
}
out:
return ret;
}
int kvm_arm_vcpu_arch_set_attr(struct kvm_vcpu *vcpu,
struct kvm_device_attr *attr)
{
int ret;
switch (attr->group) {
case KVM_ARM_VCPU_PMU_V3_CTRL:
ret = kvm_arm_pmu_v3_set_attr(vcpu, attr);
break;
case KVM_ARM_VCPU_TIMER_CTRL:
ret = kvm_arm_timer_set_attr(vcpu, attr);
break;
default:
ret = -ENXIO;
break;
}
return ret;
}
int kvm_arm_vcpu_arch_get_attr(struct kvm_vcpu *vcpu,
struct kvm_device_attr *attr)
{
int ret;
switch (attr->group) {
case KVM_ARM_VCPU_PMU_V3_CTRL:
ret = kvm_arm_pmu_v3_get_attr(vcpu, attr);
break;
case KVM_ARM_VCPU_TIMER_CTRL:
ret = kvm_arm_timer_get_attr(vcpu, attr);
break;
default:
ret = -ENXIO;
break;
}
return ret;
}
int kvm_arm_vcpu_arch_has_attr(struct kvm_vcpu *vcpu,
struct kvm_device_attr *attr)
{
int ret;
switch (attr->group) {
case KVM_ARM_VCPU_PMU_V3_CTRL:
ret = kvm_arm_pmu_v3_has_attr(vcpu, attr);
break;
case KVM_ARM_VCPU_TIMER_CTRL:
ret = kvm_arm_timer_has_attr(vcpu, attr);
break;
default:
ret = -ENXIO;
break;
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_406_0 |
crossvul-cpp_data_good_5845_12 | /*
* Copyright (C) ST-Ericsson AB 2010
* Author: Sjur Brendeland
* License terms: GNU General Public License (GPL) version 2
*/
#define pr_fmt(fmt) KBUILD_MODNAME ":%s(): " fmt, __func__
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <linux/list.h>
#include <linux/wait.h>
#include <linux/poll.h>
#include <linux/tcp.h>
#include <linux/uaccess.h>
#include <linux/debugfs.h>
#include <linux/caif/caif_socket.h>
#include <linux/pkt_sched.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <net/caif/caif_layer.h>
#include <net/caif/caif_dev.h>
#include <net/caif/cfpkt.h>
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(AF_CAIF);
/*
* CAIF state is re-using the TCP socket states.
* caif_states stored in sk_state reflect the state as reported by
* the CAIF stack, while sk_socket->state is the state of the socket.
*/
enum caif_states {
CAIF_CONNECTED = TCP_ESTABLISHED,
CAIF_CONNECTING = TCP_SYN_SENT,
CAIF_DISCONNECTED = TCP_CLOSE
};
#define TX_FLOW_ON_BIT 1
#define RX_FLOW_ON_BIT 2
struct caifsock {
struct sock sk; /* must be first member */
struct cflayer layer;
u32 flow_state;
struct caif_connect_request conn_req;
struct mutex readlock;
struct dentry *debugfs_socket_dir;
int headroom, tailroom, maxframe;
};
static int rx_flow_is_on(struct caifsock *cf_sk)
{
return test_bit(RX_FLOW_ON_BIT,
(void *) &cf_sk->flow_state);
}
static int tx_flow_is_on(struct caifsock *cf_sk)
{
return test_bit(TX_FLOW_ON_BIT,
(void *) &cf_sk->flow_state);
}
static void set_rx_flow_off(struct caifsock *cf_sk)
{
clear_bit(RX_FLOW_ON_BIT,
(void *) &cf_sk->flow_state);
}
static void set_rx_flow_on(struct caifsock *cf_sk)
{
set_bit(RX_FLOW_ON_BIT,
(void *) &cf_sk->flow_state);
}
static void set_tx_flow_off(struct caifsock *cf_sk)
{
clear_bit(TX_FLOW_ON_BIT,
(void *) &cf_sk->flow_state);
}
static void set_tx_flow_on(struct caifsock *cf_sk)
{
set_bit(TX_FLOW_ON_BIT,
(void *) &cf_sk->flow_state);
}
static void caif_read_lock(struct sock *sk)
{
struct caifsock *cf_sk;
cf_sk = container_of(sk, struct caifsock, sk);
mutex_lock(&cf_sk->readlock);
}
static void caif_read_unlock(struct sock *sk)
{
struct caifsock *cf_sk;
cf_sk = container_of(sk, struct caifsock, sk);
mutex_unlock(&cf_sk->readlock);
}
static int sk_rcvbuf_lowwater(struct caifsock *cf_sk)
{
/* A quarter of full buffer is used a low water mark */
return cf_sk->sk.sk_rcvbuf / 4;
}
static void caif_flow_ctrl(struct sock *sk, int mode)
{
struct caifsock *cf_sk;
cf_sk = container_of(sk, struct caifsock, sk);
if (cf_sk->layer.dn && cf_sk->layer.dn->modemcmd)
cf_sk->layer.dn->modemcmd(cf_sk->layer.dn, mode);
}
/*
* Copied from sock.c:sock_queue_rcv_skb(), but changed so packets are
* not dropped, but CAIF is sending flow off instead.
*/
static int caif_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
int err;
int skb_len;
unsigned long flags;
struct sk_buff_head *list = &sk->sk_receive_queue;
struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
(unsigned int)sk->sk_rcvbuf && rx_flow_is_on(cf_sk)) {
net_dbg_ratelimited("sending flow OFF (queue len = %d %d)\n",
atomic_read(&cf_sk->sk.sk_rmem_alloc),
sk_rcvbuf_lowwater(cf_sk));
set_rx_flow_off(cf_sk);
caif_flow_ctrl(sk, CAIF_MODEMCMD_FLOW_OFF_REQ);
}
err = sk_filter(sk, skb);
if (err)
return err;
if (!sk_rmem_schedule(sk, skb, skb->truesize) && rx_flow_is_on(cf_sk)) {
set_rx_flow_off(cf_sk);
net_dbg_ratelimited("sending flow OFF due to rmem_schedule\n");
caif_flow_ctrl(sk, CAIF_MODEMCMD_FLOW_OFF_REQ);
}
skb->dev = NULL;
skb_set_owner_r(skb, sk);
/* Cache the SKB length before we tack it onto the receive
* queue. Once it is added it no longer belongs to us and
* may be freed by other threads of control pulling packets
* from the queue.
*/
skb_len = skb->len;
spin_lock_irqsave(&list->lock, flags);
if (!sock_flag(sk, SOCK_DEAD))
__skb_queue_tail(list, skb);
spin_unlock_irqrestore(&list->lock, flags);
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_data_ready(sk, skb_len);
else
kfree_skb(skb);
return 0;
}
/* Packet Receive Callback function called from CAIF Stack */
static int caif_sktrecv_cb(struct cflayer *layr, struct cfpkt *pkt)
{
struct caifsock *cf_sk;
struct sk_buff *skb;
cf_sk = container_of(layr, struct caifsock, layer);
skb = cfpkt_tonative(pkt);
if (unlikely(cf_sk->sk.sk_state != CAIF_CONNECTED)) {
kfree_skb(skb);
return 0;
}
caif_queue_rcv_skb(&cf_sk->sk, skb);
return 0;
}
static void cfsk_hold(struct cflayer *layr)
{
struct caifsock *cf_sk = container_of(layr, struct caifsock, layer);
sock_hold(&cf_sk->sk);
}
static void cfsk_put(struct cflayer *layr)
{
struct caifsock *cf_sk = container_of(layr, struct caifsock, layer);
sock_put(&cf_sk->sk);
}
/* Packet Control Callback function called from CAIF */
static void caif_ctrl_cb(struct cflayer *layr,
enum caif_ctrlcmd flow,
int phyid)
{
struct caifsock *cf_sk = container_of(layr, struct caifsock, layer);
switch (flow) {
case CAIF_CTRLCMD_FLOW_ON_IND:
/* OK from modem to start sending again */
set_tx_flow_on(cf_sk);
cf_sk->sk.sk_state_change(&cf_sk->sk);
break;
case CAIF_CTRLCMD_FLOW_OFF_IND:
/* Modem asks us to shut up */
set_tx_flow_off(cf_sk);
cf_sk->sk.sk_state_change(&cf_sk->sk);
break;
case CAIF_CTRLCMD_INIT_RSP:
/* We're now connected */
caif_client_register_refcnt(&cf_sk->layer,
cfsk_hold, cfsk_put);
cf_sk->sk.sk_state = CAIF_CONNECTED;
set_tx_flow_on(cf_sk);
cf_sk->sk.sk_shutdown = 0;
cf_sk->sk.sk_state_change(&cf_sk->sk);
break;
case CAIF_CTRLCMD_DEINIT_RSP:
/* We're now disconnected */
cf_sk->sk.sk_state = CAIF_DISCONNECTED;
cf_sk->sk.sk_state_change(&cf_sk->sk);
break;
case CAIF_CTRLCMD_INIT_FAIL_RSP:
/* Connect request failed */
cf_sk->sk.sk_err = ECONNREFUSED;
cf_sk->sk.sk_state = CAIF_DISCONNECTED;
cf_sk->sk.sk_shutdown = SHUTDOWN_MASK;
/*
* Socket "standards" seems to require POLLOUT to
* be set at connect failure.
*/
set_tx_flow_on(cf_sk);
cf_sk->sk.sk_state_change(&cf_sk->sk);
break;
case CAIF_CTRLCMD_REMOTE_SHUTDOWN_IND:
/* Modem has closed this connection, or device is down. */
cf_sk->sk.sk_shutdown = SHUTDOWN_MASK;
cf_sk->sk.sk_err = ECONNRESET;
set_rx_flow_on(cf_sk);
cf_sk->sk.sk_error_report(&cf_sk->sk);
break;
default:
pr_debug("Unexpected flow command %d\n", flow);
}
}
static void caif_check_flow_release(struct sock *sk)
{
struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
if (rx_flow_is_on(cf_sk))
return;
if (atomic_read(&sk->sk_rmem_alloc) <= sk_rcvbuf_lowwater(cf_sk)) {
set_rx_flow_on(cf_sk);
caif_flow_ctrl(sk, CAIF_MODEMCMD_FLOW_ON_REQ);
}
}
/*
* Copied from unix_dgram_recvmsg, but removed credit checks,
* changed locking, address handling and added MSG_TRUNC.
*/
static int caif_seqpkt_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t len, int flags)
{
struct sock *sk = sock->sk;
struct sk_buff *skb;
int ret;
int copylen;
ret = -EOPNOTSUPP;
if (m->msg_flags&MSG_OOB)
goto read_error;
skb = skb_recv_datagram(sk, flags, 0 , &ret);
if (!skb)
goto read_error;
copylen = skb->len;
if (len < copylen) {
m->msg_flags |= MSG_TRUNC;
copylen = len;
}
ret = skb_copy_datagram_iovec(skb, 0, m->msg_iov, copylen);
if (ret)
goto out_free;
ret = (flags & MSG_TRUNC) ? skb->len : copylen;
out_free:
skb_free_datagram(sk, skb);
caif_check_flow_release(sk);
return ret;
read_error:
return ret;
}
/* Copied from unix_stream_wait_data, identical except for lock call. */
static long caif_stream_data_wait(struct sock *sk, long timeo)
{
DEFINE_WAIT(wait);
lock_sock(sk);
for (;;) {
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
if (!skb_queue_empty(&sk->sk_receive_queue) ||
sk->sk_err ||
sk->sk_state != CAIF_CONNECTED ||
sock_flag(sk, SOCK_DEAD) ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
signal_pending(current) ||
!timeo)
break;
set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
release_sock(sk);
timeo = schedule_timeout(timeo);
lock_sock(sk);
clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
}
finish_wait(sk_sleep(sk), &wait);
release_sock(sk);
return timeo;
}
/*
* Copied from unix_stream_recvmsg, but removed credit checks,
* changed locking calls, changed address handling.
*/
static int caif_stream_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size,
int flags)
{
struct sock *sk = sock->sk;
int copied = 0;
int target;
int err = 0;
long timeo;
err = -EOPNOTSUPP;
if (flags&MSG_OOB)
goto out;
/*
* Lock the socket to prevent queue disordering
* while sleeps in memcpy_tomsg
*/
err = -EAGAIN;
if (sk->sk_state == CAIF_CONNECTING)
goto out;
caif_read_lock(sk);
target = sock_rcvlowat(sk, flags&MSG_WAITALL, size);
timeo = sock_rcvtimeo(sk, flags&MSG_DONTWAIT);
do {
int chunk;
struct sk_buff *skb;
lock_sock(sk);
skb = skb_dequeue(&sk->sk_receive_queue);
caif_check_flow_release(sk);
if (skb == NULL) {
if (copied >= target)
goto unlock;
/*
* POSIX 1003.1g mandates this order.
*/
err = sock_error(sk);
if (err)
goto unlock;
err = -ECONNRESET;
if (sk->sk_shutdown & RCV_SHUTDOWN)
goto unlock;
err = -EPIPE;
if (sk->sk_state != CAIF_CONNECTED)
goto unlock;
if (sock_flag(sk, SOCK_DEAD))
goto unlock;
release_sock(sk);
err = -EAGAIN;
if (!timeo)
break;
caif_read_unlock(sk);
timeo = caif_stream_data_wait(sk, timeo);
if (signal_pending(current)) {
err = sock_intr_errno(timeo);
goto out;
}
caif_read_lock(sk);
continue;
unlock:
release_sock(sk);
break;
}
release_sock(sk);
chunk = min_t(unsigned int, skb->len, size);
if (memcpy_toiovec(msg->msg_iov, skb->data, chunk)) {
skb_queue_head(&sk->sk_receive_queue, skb);
if (copied == 0)
copied = -EFAULT;
break;
}
copied += chunk;
size -= chunk;
/* Mark read part of skb as used */
if (!(flags & MSG_PEEK)) {
skb_pull(skb, chunk);
/* put the skb back if we didn't use it up. */
if (skb->len) {
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
kfree_skb(skb);
} else {
/*
* It is questionable, see note in unix_dgram_recvmsg.
*/
/* put message back and return */
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
} while (size);
caif_read_unlock(sk);
out:
return copied ? : err;
}
/*
* Copied from sock.c:sock_wait_for_wmem, but change to wait for
* CAIF flow-on and sock_writable.
*/
static long caif_wait_for_flow_on(struct caifsock *cf_sk,
int wait_writeable, long timeo, int *err)
{
struct sock *sk = &cf_sk->sk;
DEFINE_WAIT(wait);
for (;;) {
*err = 0;
if (tx_flow_is_on(cf_sk) &&
(!wait_writeable || sock_writeable(&cf_sk->sk)))
break;
*err = -ETIMEDOUT;
if (!timeo)
break;
*err = -ERESTARTSYS;
if (signal_pending(current))
break;
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
*err = -ECONNRESET;
if (sk->sk_shutdown & SHUTDOWN_MASK)
break;
*err = -sk->sk_err;
if (sk->sk_err)
break;
*err = -EPIPE;
if (cf_sk->sk.sk_state != CAIF_CONNECTED)
break;
timeo = schedule_timeout(timeo);
}
finish_wait(sk_sleep(sk), &wait);
return timeo;
}
/*
* Transmit a SKB. The device may temporarily request re-transmission
* by returning EAGAIN.
*/
static int transmit_skb(struct sk_buff *skb, struct caifsock *cf_sk,
int noblock, long timeo)
{
struct cfpkt *pkt;
pkt = cfpkt_fromnative(CAIF_DIR_OUT, skb);
memset(skb->cb, 0, sizeof(struct caif_payload_info));
cfpkt_set_prio(pkt, cf_sk->sk.sk_priority);
if (cf_sk->layer.dn == NULL) {
kfree_skb(skb);
return -EINVAL;
}
return cf_sk->layer.dn->transmit(cf_sk->layer.dn, pkt);
}
/* Copied from af_unix:unix_dgram_sendmsg, and adapted to CAIF */
static int caif_seqpkt_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
int buffer_size;
int ret = 0;
struct sk_buff *skb = NULL;
int noblock;
long timeo;
caif_assert(cf_sk);
ret = sock_error(sk);
if (ret)
goto err;
ret = -EOPNOTSUPP;
if (msg->msg_flags&MSG_OOB)
goto err;
ret = -EOPNOTSUPP;
if (msg->msg_namelen)
goto err;
ret = -EINVAL;
if (unlikely(msg->msg_iov->iov_base == NULL))
goto err;
noblock = msg->msg_flags & MSG_DONTWAIT;
timeo = sock_sndtimeo(sk, noblock);
timeo = caif_wait_for_flow_on(container_of(sk, struct caifsock, sk),
1, timeo, &ret);
if (ret)
goto err;
ret = -EPIPE;
if (cf_sk->sk.sk_state != CAIF_CONNECTED ||
sock_flag(sk, SOCK_DEAD) ||
(sk->sk_shutdown & RCV_SHUTDOWN))
goto err;
/* Error if trying to write more than maximum frame size. */
ret = -EMSGSIZE;
if (len > cf_sk->maxframe && cf_sk->sk.sk_protocol != CAIFPROTO_RFM)
goto err;
buffer_size = len + cf_sk->headroom + cf_sk->tailroom;
ret = -ENOMEM;
skb = sock_alloc_send_skb(sk, buffer_size, noblock, &ret);
if (!skb || skb_tailroom(skb) < buffer_size)
goto err;
skb_reserve(skb, cf_sk->headroom);
ret = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len);
if (ret)
goto err;
ret = transmit_skb(skb, cf_sk, noblock, timeo);
if (ret < 0)
/* skb is already freed */
return ret;
return len;
err:
kfree_skb(skb);
return ret;
}
/*
* Copied from unix_stream_sendmsg and adapted to CAIF:
* Changed removed permission handling and added waiting for flow on
* and other minor adaptations.
*/
static int caif_stream_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
int err, size;
struct sk_buff *skb;
int sent = 0;
long timeo;
err = -EOPNOTSUPP;
if (unlikely(msg->msg_flags&MSG_OOB))
goto out_err;
if (unlikely(msg->msg_namelen))
goto out_err;
timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
timeo = caif_wait_for_flow_on(cf_sk, 1, timeo, &err);
if (unlikely(sk->sk_shutdown & SEND_SHUTDOWN))
goto pipe_err;
while (sent < len) {
size = len-sent;
if (size > cf_sk->maxframe)
size = cf_sk->maxframe;
/* If size is more than half of sndbuf, chop up message */
if (size > ((sk->sk_sndbuf >> 1) - 64))
size = (sk->sk_sndbuf >> 1) - 64;
if (size > SKB_MAX_ALLOC)
size = SKB_MAX_ALLOC;
skb = sock_alloc_send_skb(sk,
size + cf_sk->headroom +
cf_sk->tailroom,
msg->msg_flags&MSG_DONTWAIT,
&err);
if (skb == NULL)
goto out_err;
skb_reserve(skb, cf_sk->headroom);
/*
* If you pass two values to the sock_alloc_send_skb
* it tries to grab the large buffer with GFP_NOFS
* (which can fail easily), and if it fails grab the
* fallback size buffer which is under a page and will
* succeed. [Alan]
*/
size = min_t(int, size, skb_tailroom(skb));
err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size);
if (err) {
kfree_skb(skb);
goto out_err;
}
err = transmit_skb(skb, cf_sk,
msg->msg_flags&MSG_DONTWAIT, timeo);
if (err < 0)
/* skb is already freed */
goto pipe_err;
sent += size;
}
return sent;
pipe_err:
if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL))
send_sig(SIGPIPE, current, 0);
err = -EPIPE;
out_err:
return sent ? : err;
}
static int setsockopt(struct socket *sock,
int lvl, int opt, char __user *ov, unsigned int ol)
{
struct sock *sk = sock->sk;
struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
int linksel;
if (cf_sk->sk.sk_socket->state != SS_UNCONNECTED)
return -ENOPROTOOPT;
switch (opt) {
case CAIFSO_LINK_SELECT:
if (ol < sizeof(int))
return -EINVAL;
if (lvl != SOL_CAIF)
goto bad_sol;
if (copy_from_user(&linksel, ov, sizeof(int)))
return -EINVAL;
lock_sock(&(cf_sk->sk));
cf_sk->conn_req.link_selector = linksel;
release_sock(&cf_sk->sk);
return 0;
case CAIFSO_REQ_PARAM:
if (lvl != SOL_CAIF)
goto bad_sol;
if (cf_sk->sk.sk_protocol != CAIFPROTO_UTIL)
return -ENOPROTOOPT;
lock_sock(&(cf_sk->sk));
if (ol > sizeof(cf_sk->conn_req.param.data) ||
copy_from_user(&cf_sk->conn_req.param.data, ov, ol)) {
release_sock(&cf_sk->sk);
return -EINVAL;
}
cf_sk->conn_req.param.size = ol;
release_sock(&cf_sk->sk);
return 0;
default:
return -ENOPROTOOPT;
}
return 0;
bad_sol:
return -ENOPROTOOPT;
}
/*
* caif_connect() - Connect a CAIF Socket
* Copied and modified af_irda.c:irda_connect().
*
* Note : by consulting "errno", the user space caller may learn the cause
* of the failure. Most of them are visible in the function, others may come
* from subroutines called and are listed here :
* o -EAFNOSUPPORT: bad socket family or type.
* o -ESOCKTNOSUPPORT: bad socket type or protocol
* o -EINVAL: bad socket address, or CAIF link type
* o -ECONNREFUSED: remote end refused the connection.
* o -EINPROGRESS: connect request sent but timed out (or non-blocking)
* o -EISCONN: already connected.
* o -ETIMEDOUT: Connection timed out (send timeout)
* o -ENODEV: No link layer to send request
* o -ECONNRESET: Received Shutdown indication or lost link layer
* o -ENOMEM: Out of memory
*
* State Strategy:
* o sk_state: holds the CAIF_* protocol state, it's updated by
* caif_ctrl_cb.
* o sock->state: holds the SS_* socket state and is updated by connect and
* disconnect.
*/
static int caif_connect(struct socket *sock, struct sockaddr *uaddr,
int addr_len, int flags)
{
struct sock *sk = sock->sk;
struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
long timeo;
int err;
int ifindex, headroom, tailroom;
unsigned int mtu;
struct net_device *dev;
lock_sock(sk);
err = -EAFNOSUPPORT;
if (uaddr->sa_family != AF_CAIF)
goto out;
switch (sock->state) {
case SS_UNCONNECTED:
/* Normal case, a fresh connect */
caif_assert(sk->sk_state == CAIF_DISCONNECTED);
break;
case SS_CONNECTING:
switch (sk->sk_state) {
case CAIF_CONNECTED:
sock->state = SS_CONNECTED;
err = -EISCONN;
goto out;
case CAIF_DISCONNECTED:
/* Reconnect allowed */
break;
case CAIF_CONNECTING:
err = -EALREADY;
if (flags & O_NONBLOCK)
goto out;
goto wait_connect;
}
break;
case SS_CONNECTED:
caif_assert(sk->sk_state == CAIF_CONNECTED ||
sk->sk_state == CAIF_DISCONNECTED);
if (sk->sk_shutdown & SHUTDOWN_MASK) {
/* Allow re-connect after SHUTDOWN_IND */
caif_disconnect_client(sock_net(sk), &cf_sk->layer);
caif_free_client(&cf_sk->layer);
break;
}
/* No reconnect on a seqpacket socket */
err = -EISCONN;
goto out;
case SS_DISCONNECTING:
case SS_FREE:
caif_assert(1); /*Should never happen */
break;
}
sk->sk_state = CAIF_DISCONNECTED;
sock->state = SS_UNCONNECTED;
sk_stream_kill_queues(&cf_sk->sk);
err = -EINVAL;
if (addr_len != sizeof(struct sockaddr_caif))
goto out;
memcpy(&cf_sk->conn_req.sockaddr, uaddr,
sizeof(struct sockaddr_caif));
/* Move to connecting socket, start sending Connect Requests */
sock->state = SS_CONNECTING;
sk->sk_state = CAIF_CONNECTING;
/* Check priority value comming from socket */
/* if priority value is out of range it will be ajusted */
if (cf_sk->sk.sk_priority > CAIF_PRIO_MAX)
cf_sk->conn_req.priority = CAIF_PRIO_MAX;
else if (cf_sk->sk.sk_priority < CAIF_PRIO_MIN)
cf_sk->conn_req.priority = CAIF_PRIO_MIN;
else
cf_sk->conn_req.priority = cf_sk->sk.sk_priority;
/*ifindex = id of the interface.*/
cf_sk->conn_req.ifindex = cf_sk->sk.sk_bound_dev_if;
cf_sk->layer.receive = caif_sktrecv_cb;
err = caif_connect_client(sock_net(sk), &cf_sk->conn_req,
&cf_sk->layer, &ifindex, &headroom, &tailroom);
if (err < 0) {
cf_sk->sk.sk_socket->state = SS_UNCONNECTED;
cf_sk->sk.sk_state = CAIF_DISCONNECTED;
goto out;
}
err = -ENODEV;
rcu_read_lock();
dev = dev_get_by_index_rcu(sock_net(sk), ifindex);
if (!dev) {
rcu_read_unlock();
goto out;
}
cf_sk->headroom = LL_RESERVED_SPACE_EXTRA(dev, headroom);
mtu = dev->mtu;
rcu_read_unlock();
cf_sk->tailroom = tailroom;
cf_sk->maxframe = mtu - (headroom + tailroom);
if (cf_sk->maxframe < 1) {
pr_warn("CAIF Interface MTU too small (%d)\n", dev->mtu);
err = -ENODEV;
goto out;
}
err = -EINPROGRESS;
wait_connect:
if (sk->sk_state != CAIF_CONNECTED && (flags & O_NONBLOCK))
goto out;
timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
release_sock(sk);
err = -ERESTARTSYS;
timeo = wait_event_interruptible_timeout(*sk_sleep(sk),
sk->sk_state != CAIF_CONNECTING,
timeo);
lock_sock(sk);
if (timeo < 0)
goto out; /* -ERESTARTSYS */
err = -ETIMEDOUT;
if (timeo == 0 && sk->sk_state != CAIF_CONNECTED)
goto out;
if (sk->sk_state != CAIF_CONNECTED) {
sock->state = SS_UNCONNECTED;
err = sock_error(sk);
if (!err)
err = -ECONNREFUSED;
goto out;
}
sock->state = SS_CONNECTED;
err = 0;
out:
release_sock(sk);
return err;
}
/*
* caif_release() - Disconnect a CAIF Socket
* Copied and modified af_irda.c:irda_release().
*/
static int caif_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
if (!sk)
return 0;
set_tx_flow_off(cf_sk);
/*
* Ensure that packets are not queued after this point in time.
* caif_queue_rcv_skb checks SOCK_DEAD holding the queue lock,
* this ensures no packets when sock is dead.
*/
spin_lock_bh(&sk->sk_receive_queue.lock);
sock_set_flag(sk, SOCK_DEAD);
spin_unlock_bh(&sk->sk_receive_queue.lock);
sock->sk = NULL;
WARN_ON(IS_ERR(cf_sk->debugfs_socket_dir));
if (cf_sk->debugfs_socket_dir != NULL)
debugfs_remove_recursive(cf_sk->debugfs_socket_dir);
lock_sock(&(cf_sk->sk));
sk->sk_state = CAIF_DISCONNECTED;
sk->sk_shutdown = SHUTDOWN_MASK;
caif_disconnect_client(sock_net(sk), &cf_sk->layer);
cf_sk->sk.sk_socket->state = SS_DISCONNECTING;
wake_up_interruptible_poll(sk_sleep(sk), POLLERR|POLLHUP);
sock_orphan(sk);
sk_stream_kill_queues(&cf_sk->sk);
release_sock(sk);
sock_put(sk);
return 0;
}
/* Copied from af_unix.c:unix_poll(), added CAIF tx_flow handling */
static unsigned int caif_poll(struct file *file,
struct socket *sock, poll_table *wait)
{
struct sock *sk = sock->sk;
unsigned int mask;
struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
/* exceptional events? */
if (sk->sk_err)
mask |= POLLERR;
if (sk->sk_shutdown == SHUTDOWN_MASK)
mask |= POLLHUP;
if (sk->sk_shutdown & RCV_SHUTDOWN)
mask |= POLLRDHUP;
/* readable? */
if (!skb_queue_empty(&sk->sk_receive_queue) ||
(sk->sk_shutdown & RCV_SHUTDOWN))
mask |= POLLIN | POLLRDNORM;
/*
* we set writable also when the other side has shut down the
* connection. This prevents stuck sockets.
*/
if (sock_writeable(sk) && tx_flow_is_on(cf_sk))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
return mask;
}
static const struct proto_ops caif_seqpacket_ops = {
.family = PF_CAIF,
.owner = THIS_MODULE,
.release = caif_release,
.bind = sock_no_bind,
.connect = caif_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = sock_no_getname,
.poll = caif_poll,
.ioctl = sock_no_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = caif_seqpkt_sendmsg,
.recvmsg = caif_seqpkt_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static const struct proto_ops caif_stream_ops = {
.family = PF_CAIF,
.owner = THIS_MODULE,
.release = caif_release,
.bind = sock_no_bind,
.connect = caif_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = sock_no_getname,
.poll = caif_poll,
.ioctl = sock_no_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = caif_stream_sendmsg,
.recvmsg = caif_stream_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
/* This function is called when a socket is finally destroyed. */
static void caif_sock_destructor(struct sock *sk)
{
struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
caif_assert(!atomic_read(&sk->sk_wmem_alloc));
caif_assert(sk_unhashed(sk));
caif_assert(!sk->sk_socket);
if (!sock_flag(sk, SOCK_DEAD)) {
pr_debug("Attempt to release alive CAIF socket: %p\n", sk);
return;
}
sk_stream_kill_queues(&cf_sk->sk);
caif_free_client(&cf_sk->layer);
}
static int caif_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk = NULL;
struct caifsock *cf_sk = NULL;
static struct proto prot = {.name = "PF_CAIF",
.owner = THIS_MODULE,
.obj_size = sizeof(struct caifsock),
};
if (!capable(CAP_SYS_ADMIN) && !capable(CAP_NET_ADMIN))
return -EPERM;
/*
* The sock->type specifies the socket type to use.
* The CAIF socket is a packet stream in the sense
* that it is packet based. CAIF trusts the reliability
* of the link, no resending is implemented.
*/
if (sock->type == SOCK_SEQPACKET)
sock->ops = &caif_seqpacket_ops;
else if (sock->type == SOCK_STREAM)
sock->ops = &caif_stream_ops;
else
return -ESOCKTNOSUPPORT;
if (protocol < 0 || protocol >= CAIFPROTO_MAX)
return -EPROTONOSUPPORT;
/*
* Set the socket state to unconnected. The socket state
* is really not used at all in the net/core or socket.c but the
* initialization makes sure that sock->state is not uninitialized.
*/
sk = sk_alloc(net, PF_CAIF, GFP_KERNEL, &prot);
if (!sk)
return -ENOMEM;
cf_sk = container_of(sk, struct caifsock, sk);
/* Store the protocol */
sk->sk_protocol = (unsigned char) protocol;
/* Initialize default priority for well-known cases */
switch (protocol) {
case CAIFPROTO_AT:
sk->sk_priority = TC_PRIO_CONTROL;
break;
case CAIFPROTO_RFM:
sk->sk_priority = TC_PRIO_INTERACTIVE_BULK;
break;
default:
sk->sk_priority = TC_PRIO_BESTEFFORT;
}
/*
* Lock in order to try to stop someone from opening the socket
* too early.
*/
lock_sock(&(cf_sk->sk));
/* Initialize the nozero default sock structure data. */
sock_init_data(sock, sk);
sk->sk_destruct = caif_sock_destructor;
mutex_init(&cf_sk->readlock); /* single task reading lock */
cf_sk->layer.ctrlcmd = caif_ctrl_cb;
cf_sk->sk.sk_socket->state = SS_UNCONNECTED;
cf_sk->sk.sk_state = CAIF_DISCONNECTED;
set_tx_flow_off(cf_sk);
set_rx_flow_on(cf_sk);
/* Set default options on configuration */
cf_sk->conn_req.link_selector = CAIF_LINK_LOW_LATENCY;
cf_sk->conn_req.protocol = protocol;
release_sock(&cf_sk->sk);
return 0;
}
static struct net_proto_family caif_family_ops = {
.family = PF_CAIF,
.create = caif_create,
.owner = THIS_MODULE,
};
static int __init caif_sktinit_module(void)
{
int err = sock_register(&caif_family_ops);
if (!err)
return err;
return 0;
}
static void __exit caif_sktexit_module(void)
{
sock_unregister(PF_CAIF);
}
module_init(caif_sktinit_module);
module_exit(caif_sktexit_module);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_12 |
crossvul-cpp_data_bad_190_0 | /*
* MPEG-4 encoder
* Copyright (c) 2000,2001 Fabrice Bellard
* Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/attributes.h"
#include "libavutil/log.h"
#include "libavutil/opt.h"
#include "mpegutils.h"
#include "mpegvideo.h"
#include "h263.h"
#include "mpeg4video.h"
/* The uni_DCtab_* tables below contain unified bits+length tables to encode DC
* differences in MPEG-4. Unified in the sense that the specification specifies
* this encoding in several steps. */
static uint8_t uni_DCtab_lum_len[512];
static uint8_t uni_DCtab_chrom_len[512];
static uint16_t uni_DCtab_lum_bits[512];
static uint16_t uni_DCtab_chrom_bits[512];
/* Unified encoding tables for run length encoding of coefficients.
* Unified in the sense that the specification specifies the encoding in several steps. */
static uint32_t uni_mpeg4_intra_rl_bits[64 * 64 * 2 * 2];
static uint8_t uni_mpeg4_intra_rl_len[64 * 64 * 2 * 2];
static uint32_t uni_mpeg4_inter_rl_bits[64 * 64 * 2 * 2];
static uint8_t uni_mpeg4_inter_rl_len[64 * 64 * 2 * 2];
//#define UNI_MPEG4_ENC_INDEX(last, run, level) ((last) * 128 + (run) * 256 + (level))
//#define UNI_MPEG4_ENC_INDEX(last, run, level) ((last) * 128 * 64 + (run) + (level) * 64)
#define UNI_MPEG4_ENC_INDEX(last, run, level) ((last) * 128 * 64 + (run) * 128 + (level))
/* MPEG-4
* inter
* max level: 24/6
* max run: 53/63
*
* intra
* max level: 53/16
* max run: 29/41
*/
/**
* Return the number of bits that encoding the 8x8 block in block would need.
* @param[in] block_last_index last index in scantable order that refers to a non zero element in block.
*/
static inline int get_block_rate(MpegEncContext *s, int16_t block[64],
int block_last_index, uint8_t scantable[64])
{
int last = 0;
int j;
int rate = 0;
for (j = 1; j <= block_last_index; j++) {
const int index = scantable[j];
int level = block[index];
if (level) {
level += 64;
if ((level & (~127)) == 0) {
if (j < block_last_index)
rate += s->intra_ac_vlc_length[UNI_AC_ENC_INDEX(j - last - 1, level)];
else
rate += s->intra_ac_vlc_last_length[UNI_AC_ENC_INDEX(j - last - 1, level)];
} else
rate += s->ac_esc_length;
last = j;
}
}
return rate;
}
/**
* Restore the ac coefficients in block that have been changed by decide_ac_pred().
* This function also restores s->block_last_index.
* @param[in,out] block MB coefficients, these will be restored
* @param[in] dir ac prediction direction for each 8x8 block
* @param[out] st scantable for each 8x8 block
* @param[in] zigzag_last_index index referring to the last non zero coefficient in zigzag order
*/
static inline void restore_ac_coeffs(MpegEncContext *s, int16_t block[6][64],
const int dir[6], uint8_t *st[6],
const int zigzag_last_index[6])
{
int i, n;
memcpy(s->block_last_index, zigzag_last_index, sizeof(int) * 6);
for (n = 0; n < 6; n++) {
int16_t *ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
st[n] = s->intra_scantable.permutated;
if (dir[n]) {
/* top prediction */
for (i = 1; i < 8; i++)
block[n][s->idsp.idct_permutation[i]] = ac_val[i + 8];
} else {
/* left prediction */
for (i = 1; i < 8; i++)
block[n][s->idsp.idct_permutation[i << 3]] = ac_val[i];
}
}
}
/**
* Return the optimal value (0 or 1) for the ac_pred element for the given MB in MPEG-4.
* This function will also update s->block_last_index and s->ac_val.
* @param[in,out] block MB coefficients, these will be updated if 1 is returned
* @param[in] dir ac prediction direction for each 8x8 block
* @param[out] st scantable for each 8x8 block
* @param[out] zigzag_last_index index referring to the last non zero coefficient in zigzag order
*/
static inline int decide_ac_pred(MpegEncContext *s, int16_t block[6][64],
const int dir[6], uint8_t *st[6],
int zigzag_last_index[6])
{
int score = 0;
int i, n;
int8_t *const qscale_table = s->current_picture.qscale_table;
memcpy(zigzag_last_index, s->block_last_index, sizeof(int) * 6);
for (n = 0; n < 6; n++) {
int16_t *ac_val, *ac_val1;
score -= get_block_rate(s, block[n], s->block_last_index[n],
s->intra_scantable.permutated);
ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
ac_val1 = ac_val;
if (dir[n]) {
const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride;
/* top prediction */
ac_val -= s->block_wrap[n] * 16;
if (s->mb_y == 0 || s->qscale == qscale_table[xy] || n == 2 || n == 3) {
/* same qscale */
for (i = 1; i < 8; i++) {
const int level = block[n][s->idsp.idct_permutation[i]];
block[n][s->idsp.idct_permutation[i]] = level - ac_val[i + 8];
ac_val1[i] = block[n][s->idsp.idct_permutation[i << 3]];
ac_val1[i + 8] = level;
}
} else {
/* different qscale, we must rescale */
for (i = 1; i < 8; i++) {
const int level = block[n][s->idsp.idct_permutation[i]];
block[n][s->idsp.idct_permutation[i]] = level - ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale);
ac_val1[i] = block[n][s->idsp.idct_permutation[i << 3]];
ac_val1[i + 8] = level;
}
}
st[n] = s->intra_h_scantable.permutated;
} else {
const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride;
/* left prediction */
ac_val -= 16;
if (s->mb_x == 0 || s->qscale == qscale_table[xy] || n == 1 || n == 3) {
/* same qscale */
for (i = 1; i < 8; i++) {
const int level = block[n][s->idsp.idct_permutation[i << 3]];
block[n][s->idsp.idct_permutation[i << 3]] = level - ac_val[i];
ac_val1[i] = level;
ac_val1[i + 8] = block[n][s->idsp.idct_permutation[i]];
}
} else {
/* different qscale, we must rescale */
for (i = 1; i < 8; i++) {
const int level = block[n][s->idsp.idct_permutation[i << 3]];
block[n][s->idsp.idct_permutation[i << 3]] = level - ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale);
ac_val1[i] = level;
ac_val1[i + 8] = block[n][s->idsp.idct_permutation[i]];
}
}
st[n] = s->intra_v_scantable.permutated;
}
for (i = 63; i > 0; i--) // FIXME optimize
if (block[n][st[n][i]])
break;
s->block_last_index[n] = i;
score += get_block_rate(s, block[n], s->block_last_index[n], st[n]);
}
if (score < 0) {
return 1;
} else {
restore_ac_coeffs(s, block, dir, st, zigzag_last_index);
return 0;
}
}
/**
* modify mb_type & qscale so that encoding is actually possible in MPEG-4
*/
void ff_clean_mpeg4_qscales(MpegEncContext *s)
{
int i;
int8_t *const qscale_table = s->current_picture.qscale_table;
ff_clean_h263_qscales(s);
if (s->pict_type == AV_PICTURE_TYPE_B) {
int odd = 0;
/* ok, come on, this isn't funny anymore, there's more code for
* handling this MPEG-4 mess than for the actual adaptive quantization */
for (i = 0; i < s->mb_num; i++) {
int mb_xy = s->mb_index2xy[i];
odd += qscale_table[mb_xy] & 1;
}
if (2 * odd > s->mb_num)
odd = 1;
else
odd = 0;
for (i = 0; i < s->mb_num; i++) {
int mb_xy = s->mb_index2xy[i];
if ((qscale_table[mb_xy] & 1) != odd)
qscale_table[mb_xy]++;
if (qscale_table[mb_xy] > 31)
qscale_table[mb_xy] = 31;
}
for (i = 1; i < s->mb_num; i++) {
int mb_xy = s->mb_index2xy[i];
if (qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i - 1]] &&
(s->mb_type[mb_xy] & CANDIDATE_MB_TYPE_DIRECT)) {
s->mb_type[mb_xy] |= CANDIDATE_MB_TYPE_BIDIR;
}
}
}
}
/**
* Encode the dc value.
* @param n block index (0-3 are luma, 4-5 are chroma)
*/
static inline void mpeg4_encode_dc(PutBitContext *s, int level, int n)
{
/* DC will overflow if level is outside the [-255,255] range. */
level += 256;
if (n < 4) {
/* luminance */
put_bits(s, uni_DCtab_lum_len[level], uni_DCtab_lum_bits[level]);
} else {
/* chrominance */
put_bits(s, uni_DCtab_chrom_len[level], uni_DCtab_chrom_bits[level]);
}
}
static inline int mpeg4_get_dc_length(int level, int n)
{
if (n < 4)
return uni_DCtab_lum_len[level + 256];
else
return uni_DCtab_chrom_len[level + 256];
}
/**
* Encode an 8x8 block.
* @param n block index (0-3 are luma, 4-5 are chroma)
*/
static inline void mpeg4_encode_block(MpegEncContext *s,
int16_t *block, int n, int intra_dc,
uint8_t *scan_table, PutBitContext *dc_pb,
PutBitContext *ac_pb)
{
int i, last_non_zero;
uint32_t *bits_tab;
uint8_t *len_tab;
const int last_index = s->block_last_index[n];
if (s->mb_intra) { // Note gcc (3.2.1 at least) will optimize this away
/* MPEG-4 based DC predictor */
mpeg4_encode_dc(dc_pb, intra_dc, n);
if (last_index < 1)
return;
i = 1;
bits_tab = uni_mpeg4_intra_rl_bits;
len_tab = uni_mpeg4_intra_rl_len;
} else {
if (last_index < 0)
return;
i = 0;
bits_tab = uni_mpeg4_inter_rl_bits;
len_tab = uni_mpeg4_inter_rl_len;
}
/* AC coefs */
last_non_zero = i - 1;
for (; i < last_index; i++) {
int level = block[scan_table[i]];
if (level) {
int run = i - last_non_zero - 1;
level += 64;
if ((level & (~127)) == 0) {
const int index = UNI_MPEG4_ENC_INDEX(0, run, level);
put_bits(ac_pb, len_tab[index], bits_tab[index]);
} else { // ESC3
put_bits(ac_pb,
7 + 2 + 1 + 6 + 1 + 12 + 1,
(3 << 23) + (3 << 21) + (0 << 20) + (run << 14) +
(1 << 13) + (((level - 64) & 0xfff) << 1) + 1);
}
last_non_zero = i;
}
}
/* if (i <= last_index) */ {
int level = block[scan_table[i]];
int run = i - last_non_zero - 1;
level += 64;
if ((level & (~127)) == 0) {
const int index = UNI_MPEG4_ENC_INDEX(1, run, level);
put_bits(ac_pb, len_tab[index], bits_tab[index]);
} else { // ESC3
put_bits(ac_pb,
7 + 2 + 1 + 6 + 1 + 12 + 1,
(3 << 23) + (3 << 21) + (1 << 20) + (run << 14) +
(1 << 13) + (((level - 64) & 0xfff) << 1) + 1);
}
}
}
static int mpeg4_get_block_length(MpegEncContext *s,
int16_t *block, int n,
int intra_dc, uint8_t *scan_table)
{
int i, last_non_zero;
uint8_t *len_tab;
const int last_index = s->block_last_index[n];
int len = 0;
if (s->mb_intra) { // Note gcc (3.2.1 at least) will optimize this away
/* MPEG-4 based DC predictor */
len += mpeg4_get_dc_length(intra_dc, n);
if (last_index < 1)
return len;
i = 1;
len_tab = uni_mpeg4_intra_rl_len;
} else {
if (last_index < 0)
return 0;
i = 0;
len_tab = uni_mpeg4_inter_rl_len;
}
/* AC coefs */
last_non_zero = i - 1;
for (; i < last_index; i++) {
int level = block[scan_table[i]];
if (level) {
int run = i - last_non_zero - 1;
level += 64;
if ((level & (~127)) == 0) {
const int index = UNI_MPEG4_ENC_INDEX(0, run, level);
len += len_tab[index];
} else { // ESC3
len += 7 + 2 + 1 + 6 + 1 + 12 + 1;
}
last_non_zero = i;
}
}
/* if (i <= last_index) */ {
int level = block[scan_table[i]];
int run = i - last_non_zero - 1;
level += 64;
if ((level & (~127)) == 0) {
const int index = UNI_MPEG4_ENC_INDEX(1, run, level);
len += len_tab[index];
} else { // ESC3
len += 7 + 2 + 1 + 6 + 1 + 12 + 1;
}
}
return len;
}
static inline void mpeg4_encode_blocks(MpegEncContext *s, int16_t block[6][64],
int intra_dc[6], uint8_t **scan_table,
PutBitContext *dc_pb,
PutBitContext *ac_pb)
{
int i;
if (scan_table) {
if (s->avctx->flags2 & AV_CODEC_FLAG2_NO_OUTPUT) {
for (i = 0; i < 6; i++)
skip_put_bits(&s->pb,
mpeg4_get_block_length(s, block[i], i,
intra_dc[i], scan_table[i]));
} else {
/* encode each block */
for (i = 0; i < 6; i++)
mpeg4_encode_block(s, block[i], i,
intra_dc[i], scan_table[i], dc_pb, ac_pb);
}
} else {
if (s->avctx->flags2 & AV_CODEC_FLAG2_NO_OUTPUT) {
for (i = 0; i < 6; i++)
skip_put_bits(&s->pb,
mpeg4_get_block_length(s, block[i], i, 0,
s->intra_scantable.permutated));
} else {
/* encode each block */
for (i = 0; i < 6; i++)
mpeg4_encode_block(s, block[i], i, 0,
s->intra_scantable.permutated, dc_pb, ac_pb);
}
}
}
static inline int get_b_cbp(MpegEncContext *s, int16_t block[6][64],
int motion_x, int motion_y, int mb_type)
{
int cbp = 0, i;
if (s->mpv_flags & FF_MPV_FLAG_CBP_RD) {
int score = 0;
const int lambda = s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
for (i = 0; i < 6; i++) {
if (s->coded_score[i] < 0) {
score += s->coded_score[i];
cbp |= 1 << (5 - i);
}
}
if (cbp) {
int zero_score = -6;
if ((motion_x | motion_y | s->dquant | mb_type) == 0)
zero_score -= 4; // 2 * MV + mb_type + cbp bit
zero_score *= lambda;
if (zero_score <= score)
cbp = 0;
}
for (i = 0; i < 6; i++) {
if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i)) & 1) == 0) {
s->block_last_index[i] = -1;
s->bdsp.clear_block(s->block[i]);
}
}
} else {
for (i = 0; i < 6; i++) {
if (s->block_last_index[i] >= 0)
cbp |= 1 << (5 - i);
}
}
return cbp;
}
// FIXME this is duplicated to h263.c
static const int dquant_code[5] = { 1, 0, 9, 2, 3 };
void ff_mpeg4_encode_mb(MpegEncContext *s, int16_t block[6][64],
int motion_x, int motion_y)
{
int cbpc, cbpy, pred_x, pred_y;
PutBitContext *const pb2 = s->data_partitioning ? &s->pb2 : &s->pb;
PutBitContext *const tex_pb = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B ? &s->tex_pb : &s->pb;
PutBitContext *const dc_pb = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_I ? &s->pb2 : &s->pb;
const int interleaved_stats = (s->avctx->flags & AV_CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
if (!s->mb_intra) {
int i, cbp;
if (s->pict_type == AV_PICTURE_TYPE_B) {
/* convert from mv_dir to type */
static const int mb_type_table[8] = { -1, 3, 2, 1, -1, -1, -1, 0 };
int mb_type = mb_type_table[s->mv_dir];
if (s->mb_x == 0) {
for (i = 0; i < 2; i++)
s->last_mv[i][0][0] =
s->last_mv[i][0][1] =
s->last_mv[i][1][0] =
s->last_mv[i][1][1] = 0;
}
av_assert2(s->dquant >= -2 && s->dquant <= 2);
av_assert2((s->dquant & 1) == 0);
av_assert2(mb_type >= 0);
/* nothing to do if this MB was skipped in the next P-frame */
if (s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]) { // FIXME avoid DCT & ...
s->skip_count++;
s->mv[0][0][0] =
s->mv[0][0][1] =
s->mv[1][0][0] =
s->mv[1][0][1] = 0;
s->mv_dir = MV_DIR_FORWARD; // doesn't matter
s->qscale -= s->dquant;
// s->mb_skipped = 1;
return;
}
cbp = get_b_cbp(s, block, motion_x, motion_y, mb_type);
if ((cbp | motion_x | motion_y | mb_type) == 0) {
/* direct MB with MV={0,0} */
av_assert2(s->dquant == 0);
put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
if (interleaved_stats) {
s->misc_bits++;
s->last_bits++;
}
s->skip_count++;
return;
}
put_bits(&s->pb, 1, 0); /* mb coded modb1=0 */
put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ // FIXME merge
put_bits(&s->pb, mb_type + 1, 1); // this table is so simple that we don't need it :)
if (cbp)
put_bits(&s->pb, 6, cbp);
if (cbp && mb_type) {
if (s->dquant)
put_bits(&s->pb, 2, (s->dquant >> 2) + 3);
else
put_bits(&s->pb, 1, 0);
} else
s->qscale -= s->dquant;
if (!s->progressive_sequence) {
if (cbp)
put_bits(&s->pb, 1, s->interlaced_dct);
if (mb_type) // not direct mode
put_bits(&s->pb, 1, s->mv_type == MV_TYPE_FIELD);
}
if (interleaved_stats)
s->misc_bits += get_bits_diff(s);
if (!mb_type) {
av_assert2(s->mv_dir & MV_DIRECT);
ff_h263_encode_motion_vector(s, motion_x, motion_y, 1);
s->b_count++;
s->f_count++;
} else {
av_assert2(mb_type > 0 && mb_type < 4);
if (s->mv_type != MV_TYPE_FIELD) {
if (s->mv_dir & MV_DIR_FORWARD) {
ff_h263_encode_motion_vector(s,
s->mv[0][0][0] - s->last_mv[0][0][0],
s->mv[0][0][1] - s->last_mv[0][0][1],
s->f_code);
s->last_mv[0][0][0] =
s->last_mv[0][1][0] = s->mv[0][0][0];
s->last_mv[0][0][1] =
s->last_mv[0][1][1] = s->mv[0][0][1];
s->f_count++;
}
if (s->mv_dir & MV_DIR_BACKWARD) {
ff_h263_encode_motion_vector(s,
s->mv[1][0][0] - s->last_mv[1][0][0],
s->mv[1][0][1] - s->last_mv[1][0][1],
s->b_code);
s->last_mv[1][0][0] =
s->last_mv[1][1][0] = s->mv[1][0][0];
s->last_mv[1][0][1] =
s->last_mv[1][1][1] = s->mv[1][0][1];
s->b_count++;
}
} else {
if (s->mv_dir & MV_DIR_FORWARD) {
put_bits(&s->pb, 1, s->field_select[0][0]);
put_bits(&s->pb, 1, s->field_select[0][1]);
}
if (s->mv_dir & MV_DIR_BACKWARD) {
put_bits(&s->pb, 1, s->field_select[1][0]);
put_bits(&s->pb, 1, s->field_select[1][1]);
}
if (s->mv_dir & MV_DIR_FORWARD) {
for (i = 0; i < 2; i++) {
ff_h263_encode_motion_vector(s,
s->mv[0][i][0] - s->last_mv[0][i][0],
s->mv[0][i][1] - s->last_mv[0][i][1] / 2,
s->f_code);
s->last_mv[0][i][0] = s->mv[0][i][0];
s->last_mv[0][i][1] = s->mv[0][i][1] * 2;
}
s->f_count++;
}
if (s->mv_dir & MV_DIR_BACKWARD) {
for (i = 0; i < 2; i++) {
ff_h263_encode_motion_vector(s,
s->mv[1][i][0] - s->last_mv[1][i][0],
s->mv[1][i][1] - s->last_mv[1][i][1] / 2,
s->b_code);
s->last_mv[1][i][0] = s->mv[1][i][0];
s->last_mv[1][i][1] = s->mv[1][i][1] * 2;
}
s->b_count++;
}
}
}
if (interleaved_stats)
s->mv_bits += get_bits_diff(s);
mpeg4_encode_blocks(s, block, NULL, NULL, NULL, &s->pb);
if (interleaved_stats)
s->p_tex_bits += get_bits_diff(s);
} else { /* s->pict_type==AV_PICTURE_TYPE_B */
cbp = get_p_cbp(s, block, motion_x, motion_y);
if ((cbp | motion_x | motion_y | s->dquant) == 0 &&
s->mv_type == MV_TYPE_16X16) {
/* Check if the B-frames can skip it too, as we must skip it
* if we skip here why didn't they just compress
* the skip-mb bits instead of reusing them ?! */
if (s->max_b_frames > 0) {
int i;
int x, y, offset;
uint8_t *p_pic;
x = s->mb_x * 16;
y = s->mb_y * 16;
offset = x + y * s->linesize;
p_pic = s->new_picture.f->data[0] + offset;
s->mb_skipped = 1;
for (i = 0; i < s->max_b_frames; i++) {
uint8_t *b_pic;
int diff;
Picture *pic = s->reordered_input_picture[i + 1];
if (!pic || pic->f->pict_type != AV_PICTURE_TYPE_B)
break;
b_pic = pic->f->data[0] + offset;
if (!pic->shared)
b_pic += INPLACE_OFFSET;
if (x + 16 > s->width || y + 16 > s->height) {
int x1, y1;
int xe = FFMIN(16, s->width - x);
int ye = FFMIN(16, s->height - y);
diff = 0;
for (y1 = 0; y1 < ye; y1++) {
for (x1 = 0; x1 < xe; x1++) {
diff += FFABS(p_pic[x1 + y1 * s->linesize] - b_pic[x1 + y1 * s->linesize]);
}
}
diff = diff * 256 / (xe * ye);
} else {
diff = s->mecc.sad[0](NULL, p_pic, b_pic, s->linesize, 16);
}
if (diff > s->qscale * 70) { // FIXME check that 70 is optimal
s->mb_skipped = 0;
break;
}
}
} else
s->mb_skipped = 1;
if (s->mb_skipped == 1) {
/* skip macroblock */
put_bits(&s->pb, 1, 1);
if (interleaved_stats) {
s->misc_bits++;
s->last_bits++;
}
s->skip_count++;
return;
}
}
put_bits(&s->pb, 1, 0); /* mb coded */
cbpc = cbp & 3;
cbpy = cbp >> 2;
cbpy ^= 0xf;
if (s->mv_type == MV_TYPE_16X16) {
if (s->dquant)
cbpc += 8;
put_bits(&s->pb,
ff_h263_inter_MCBPC_bits[cbpc],
ff_h263_inter_MCBPC_code[cbpc]);
put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
if (s->dquant)
put_bits(pb2, 2, dquant_code[s->dquant + 2]);
if (!s->progressive_sequence) {
if (cbp)
put_bits(pb2, 1, s->interlaced_dct);
put_bits(pb2, 1, 0);
}
if (interleaved_stats)
s->misc_bits += get_bits_diff(s);
/* motion vectors: 16x16 mode */
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
ff_h263_encode_motion_vector(s,
motion_x - pred_x,
motion_y - pred_y,
s->f_code);
} else if (s->mv_type == MV_TYPE_FIELD) {
if (s->dquant)
cbpc += 8;
put_bits(&s->pb,
ff_h263_inter_MCBPC_bits[cbpc],
ff_h263_inter_MCBPC_code[cbpc]);
put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
if (s->dquant)
put_bits(pb2, 2, dquant_code[s->dquant + 2]);
av_assert2(!s->progressive_sequence);
if (cbp)
put_bits(pb2, 1, s->interlaced_dct);
put_bits(pb2, 1, 1);
if (interleaved_stats)
s->misc_bits += get_bits_diff(s);
/* motion vectors: 16x8 interlaced mode */
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
pred_y /= 2;
put_bits(&s->pb, 1, s->field_select[0][0]);
put_bits(&s->pb, 1, s->field_select[0][1]);
ff_h263_encode_motion_vector(s,
s->mv[0][0][0] - pred_x,
s->mv[0][0][1] - pred_y,
s->f_code);
ff_h263_encode_motion_vector(s,
s->mv[0][1][0] - pred_x,
s->mv[0][1][1] - pred_y,
s->f_code);
} else {
av_assert2(s->mv_type == MV_TYPE_8X8);
put_bits(&s->pb,
ff_h263_inter_MCBPC_bits[cbpc + 16],
ff_h263_inter_MCBPC_code[cbpc + 16]);
put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
if (!s->progressive_sequence && cbp)
put_bits(pb2, 1, s->interlaced_dct);
if (interleaved_stats)
s->misc_bits += get_bits_diff(s);
for (i = 0; i < 4; i++) {
/* motion vectors: 8x8 mode*/
ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
ff_h263_encode_motion_vector(s,
s->current_picture.motion_val[0][s->block_index[i]][0] - pred_x,
s->current_picture.motion_val[0][s->block_index[i]][1] - pred_y,
s->f_code);
}
}
if (interleaved_stats)
s->mv_bits += get_bits_diff(s);
mpeg4_encode_blocks(s, block, NULL, NULL, NULL, tex_pb);
if (interleaved_stats)
s->p_tex_bits += get_bits_diff(s);
s->f_count++;
}
} else {
int cbp;
int dc_diff[6]; // dc values with the dc prediction subtracted
int dir[6]; // prediction direction
int zigzag_last_index[6];
uint8_t *scan_table[6];
int i;
for (i = 0; i < 6; i++)
dc_diff[i] = ff_mpeg4_pred_dc(s, i, block[i][0], &dir[i], 1);
if (s->avctx->flags & AV_CODEC_FLAG_AC_PRED) {
s->ac_pred = decide_ac_pred(s, block, dir, scan_table, zigzag_last_index);
} else {
for (i = 0; i < 6; i++)
scan_table[i] = s->intra_scantable.permutated;
}
/* compute cbp */
cbp = 0;
for (i = 0; i < 6; i++)
if (s->block_last_index[i] >= 1)
cbp |= 1 << (5 - i);
cbpc = cbp & 3;
if (s->pict_type == AV_PICTURE_TYPE_I) {
if (s->dquant)
cbpc += 4;
put_bits(&s->pb,
ff_h263_intra_MCBPC_bits[cbpc],
ff_h263_intra_MCBPC_code[cbpc]);
} else {
if (s->dquant)
cbpc += 8;
put_bits(&s->pb, 1, 0); /* mb coded */
put_bits(&s->pb,
ff_h263_inter_MCBPC_bits[cbpc + 4],
ff_h263_inter_MCBPC_code[cbpc + 4]);
}
put_bits(pb2, 1, s->ac_pred);
cbpy = cbp >> 2;
put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
if (s->dquant)
put_bits(dc_pb, 2, dquant_code[s->dquant + 2]);
if (!s->progressive_sequence)
put_bits(dc_pb, 1, s->interlaced_dct);
if (interleaved_stats)
s->misc_bits += get_bits_diff(s);
mpeg4_encode_blocks(s, block, dc_diff, scan_table, dc_pb, tex_pb);
if (interleaved_stats)
s->i_tex_bits += get_bits_diff(s);
s->i_count++;
/* restore ac coeffs & last_index stuff
* if we messed them up with the prediction */
if (s->ac_pred)
restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
}
}
/**
* add MPEG-4 stuffing bits (01...1)
*/
void ff_mpeg4_stuffing(PutBitContext *pbc)
{
int length;
put_bits(pbc, 1, 0);
length = (-put_bits_count(pbc)) & 7;
if (length)
put_bits(pbc, length, (1 << length) - 1);
}
/* must be called before writing the header */
void ff_set_mpeg4_time(MpegEncContext *s)
{
if (s->pict_type == AV_PICTURE_TYPE_B) {
ff_mpeg4_init_direct_mv(s);
} else {
s->last_time_base = s->time_base;
s->time_base = FFUDIV(s->time, s->avctx->time_base.den);
}
}
static void mpeg4_encode_gop_header(MpegEncContext *s)
{
int hours, minutes, seconds;
int64_t time;
put_bits(&s->pb, 16, 0);
put_bits(&s->pb, 16, GOP_STARTCODE);
time = s->current_picture_ptr->f->pts;
if (s->reordered_input_picture[1])
time = FFMIN(time, s->reordered_input_picture[1]->f->pts);
time = time * s->avctx->time_base.num;
s->last_time_base = FFUDIV(time, s->avctx->time_base.den);
seconds = FFUDIV(time, s->avctx->time_base.den);
minutes = FFUDIV(seconds, 60); seconds = FFUMOD(seconds, 60);
hours = FFUDIV(minutes, 60); minutes = FFUMOD(minutes, 60);
hours = FFUMOD(hours , 24);
put_bits(&s->pb, 5, hours);
put_bits(&s->pb, 6, minutes);
put_bits(&s->pb, 1, 1);
put_bits(&s->pb, 6, seconds);
put_bits(&s->pb, 1, !!(s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP));
put_bits(&s->pb, 1, 0); // broken link == NO
ff_mpeg4_stuffing(&s->pb);
}
static void mpeg4_encode_visual_object_header(MpegEncContext *s)
{
int profile_and_level_indication;
int vo_ver_id;
if (s->avctx->profile != FF_PROFILE_UNKNOWN) {
profile_and_level_indication = s->avctx->profile << 4;
} else if (s->max_b_frames || s->quarter_sample) {
profile_and_level_indication = 0xF0; // adv simple
} else {
profile_and_level_indication = 0x00; // simple
}
if (s->avctx->level != FF_LEVEL_UNKNOWN)
profile_and_level_indication |= s->avctx->level;
else
profile_and_level_indication |= 1; // level 1
if (profile_and_level_indication >> 4 == 0xF)
vo_ver_id = 5;
else
vo_ver_id = 1;
// FIXME levels
put_bits(&s->pb, 16, 0);
put_bits(&s->pb, 16, VOS_STARTCODE);
put_bits(&s->pb, 8, profile_and_level_indication);
put_bits(&s->pb, 16, 0);
put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
put_bits(&s->pb, 1, 1);
put_bits(&s->pb, 4, vo_ver_id);
put_bits(&s->pb, 3, 1); // priority
put_bits(&s->pb, 4, 1); // visual obj type== video obj
put_bits(&s->pb, 1, 0); // video signal type == no clue // FIXME
ff_mpeg4_stuffing(&s->pb);
}
static void mpeg4_encode_vol_header(MpegEncContext *s,
int vo_number,
int vol_number)
{
int vo_ver_id;
if (!CONFIG_MPEG4_ENCODER)
return;
if (s->max_b_frames || s->quarter_sample) {
vo_ver_id = 5;
s->vo_type = ADV_SIMPLE_VO_TYPE;
} else {
vo_ver_id = 1;
s->vo_type = SIMPLE_VO_TYPE;
}
put_bits(&s->pb, 16, 0);
put_bits(&s->pb, 16, 0x100 + vo_number); /* video obj */
put_bits(&s->pb, 16, 0);
put_bits(&s->pb, 16, 0x120 + vol_number); /* video obj layer */
put_bits(&s->pb, 1, 0); /* random access vol */
put_bits(&s->pb, 8, s->vo_type); /* video obj type indication */
if (s->workaround_bugs & FF_BUG_MS) {
put_bits(&s->pb, 1, 0); /* is obj layer id= no */
} else {
put_bits(&s->pb, 1, 1); /* is obj layer id= yes */
put_bits(&s->pb, 4, vo_ver_id); /* is obj layer ver id */
put_bits(&s->pb, 3, 1); /* is obj layer priority */
}
s->aspect_ratio_info = ff_h263_aspect_to_info(s->avctx->sample_aspect_ratio);
put_bits(&s->pb, 4, s->aspect_ratio_info); /* aspect ratio info */
if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
av_reduce(&s->avctx->sample_aspect_ratio.num, &s->avctx->sample_aspect_ratio.den,
s->avctx->sample_aspect_ratio.num, s->avctx->sample_aspect_ratio.den, 255);
put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
}
if (s->workaround_bugs & FF_BUG_MS) {
put_bits(&s->pb, 1, 0); /* vol control parameters= no @@@ */
} else {
put_bits(&s->pb, 1, 1); /* vol control parameters= yes */
put_bits(&s->pb, 2, 1); /* chroma format YUV 420/YV12 */
put_bits(&s->pb, 1, s->low_delay);
put_bits(&s->pb, 1, 0); /* vbv parameters= no */
}
put_bits(&s->pb, 2, RECT_SHAPE); /* vol shape= rectangle */
put_bits(&s->pb, 1, 1); /* marker bit */
put_bits(&s->pb, 16, s->avctx->time_base.den);
if (s->time_increment_bits < 1)
s->time_increment_bits = 1;
put_bits(&s->pb, 1, 1); /* marker bit */
put_bits(&s->pb, 1, 0); /* fixed vop rate=no */
put_bits(&s->pb, 1, 1); /* marker bit */
put_bits(&s->pb, 13, s->width); /* vol width */
put_bits(&s->pb, 1, 1); /* marker bit */
put_bits(&s->pb, 13, s->height); /* vol height */
put_bits(&s->pb, 1, 1); /* marker bit */
put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
put_bits(&s->pb, 1, 1); /* obmc disable */
if (vo_ver_id == 1)
put_bits(&s->pb, 1, 0); /* sprite enable */
else
put_bits(&s->pb, 2, 0); /* sprite enable */
put_bits(&s->pb, 1, 0); /* not 8 bit == false */
put_bits(&s->pb, 1, s->mpeg_quant); /* quant type = (0 = H.263 style) */
if (s->mpeg_quant) {
ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
}
if (vo_ver_id != 1)
put_bits(&s->pb, 1, s->quarter_sample);
put_bits(&s->pb, 1, 1); /* complexity estimation disable */
put_bits(&s->pb, 1, s->rtp_mode ? 0 : 1); /* resync marker disable */
put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
if (s->data_partitioning)
put_bits(&s->pb, 1, 0); /* no rvlc */
if (vo_ver_id != 1) {
put_bits(&s->pb, 1, 0); /* newpred */
put_bits(&s->pb, 1, 0); /* reduced res vop */
}
put_bits(&s->pb, 1, 0); /* scalability */
ff_mpeg4_stuffing(&s->pb);
/* user data */
if (!(s->avctx->flags & AV_CODEC_FLAG_BITEXACT)) {
put_bits(&s->pb, 16, 0);
put_bits(&s->pb, 16, 0x1B2); /* user_data */
avpriv_put_string(&s->pb, LIBAVCODEC_IDENT, 0);
}
}
/* write MPEG-4 VOP header */
int ff_mpeg4_encode_picture_header(MpegEncContext *s, int picture_number)
{
uint64_t time_incr;
int64_t time_div, time_mod;
if (s->pict_type == AV_PICTURE_TYPE_I) {
if (!(s->avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
if (s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT) // HACK, the reference sw is buggy
mpeg4_encode_visual_object_header(s);
if (s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT || picture_number == 0) // HACK, the reference sw is buggy
mpeg4_encode_vol_header(s, 0, 0);
}
if (!(s->workaround_bugs & FF_BUG_MS))
mpeg4_encode_gop_header(s);
}
s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;
put_bits(&s->pb, 16, 0); /* vop header */
put_bits(&s->pb, 16, VOP_STARTCODE); /* vop header */
put_bits(&s->pb, 2, s->pict_type - 1); /* pict type: I = 0 , P = 1 */
time_div = FFUDIV(s->time, s->avctx->time_base.den);
time_mod = FFUMOD(s->time, s->avctx->time_base.den);
time_incr = time_div - s->last_time_base;
// This limits the frame duration to max 1 hour
if (time_incr > 3600) {
av_log(s->avctx, AV_LOG_ERROR, "time_incr %"PRIu64" too large\n", time_incr);
return AVERROR(EINVAL);
}
while (time_incr--)
put_bits(&s->pb, 1, 1);
put_bits(&s->pb, 1, 0);
put_bits(&s->pb, 1, 1); /* marker */
put_bits(&s->pb, s->time_increment_bits, time_mod); /* time increment */
put_bits(&s->pb, 1, 1); /* marker */
put_bits(&s->pb, 1, 1); /* vop coded */
if (s->pict_type == AV_PICTURE_TYPE_P) {
put_bits(&s->pb, 1, s->no_rounding); /* rounding type */
}
put_bits(&s->pb, 3, 0); /* intra dc VLC threshold */
if (!s->progressive_sequence) {
put_bits(&s->pb, 1, s->current_picture_ptr->f->top_field_first);
put_bits(&s->pb, 1, s->alternate_scan);
}
// FIXME sprite stuff
put_bits(&s->pb, 5, s->qscale);
if (s->pict_type != AV_PICTURE_TYPE_I)
put_bits(&s->pb, 3, s->f_code); /* fcode_for */
if (s->pict_type == AV_PICTURE_TYPE_B)
put_bits(&s->pb, 3, s->b_code); /* fcode_back */
return 0;
}
static av_cold void init_uni_dc_tab(void)
{
int level, uni_code, uni_len;
for (level = -256; level < 256; level++) {
int size, v, l;
/* find number of bits */
size = 0;
v = abs(level);
while (v) {
v >>= 1;
size++;
}
if (level < 0)
l = (-level) ^ ((1 << size) - 1);
else
l = level;
/* luminance */
uni_code = ff_mpeg4_DCtab_lum[size][0];
uni_len = ff_mpeg4_DCtab_lum[size][1];
if (size > 0) {
uni_code <<= size;
uni_code |= l;
uni_len += size;
if (size > 8) {
uni_code <<= 1;
uni_code |= 1;
uni_len++;
}
}
uni_DCtab_lum_bits[level + 256] = uni_code;
uni_DCtab_lum_len[level + 256] = uni_len;
/* chrominance */
uni_code = ff_mpeg4_DCtab_chrom[size][0];
uni_len = ff_mpeg4_DCtab_chrom[size][1];
if (size > 0) {
uni_code <<= size;
uni_code |= l;
uni_len += size;
if (size > 8) {
uni_code <<= 1;
uni_code |= 1;
uni_len++;
}
}
uni_DCtab_chrom_bits[level + 256] = uni_code;
uni_DCtab_chrom_len[level + 256] = uni_len;
}
}
static av_cold void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab,
uint8_t *len_tab)
{
int slevel, run, last;
av_assert0(MAX_LEVEL >= 64);
av_assert0(MAX_RUN >= 63);
for (slevel = -64; slevel < 64; slevel++) {
if (slevel == 0)
continue;
for (run = 0; run < 64; run++) {
for (last = 0; last <= 1; last++) {
const int index = UNI_MPEG4_ENC_INDEX(last, run, slevel + 64);
int level = slevel < 0 ? -slevel : slevel;
int sign = slevel < 0 ? 1 : 0;
int bits, len, code;
int level1, run1;
len_tab[index] = 100;
/* ESC0 */
code = get_rl_index(rl, last, run, level);
bits = rl->table_vlc[code][0];
len = rl->table_vlc[code][1];
bits = bits * 2 + sign;
len++;
if (code != rl->n && len < len_tab[index]) {
bits_tab[index] = bits;
len_tab[index] = len;
}
/* ESC1 */
bits = rl->table_vlc[rl->n][0];
len = rl->table_vlc[rl->n][1];
bits = bits * 2;
len++; // esc1
level1 = level - rl->max_level[last][run];
if (level1 > 0) {
code = get_rl_index(rl, last, run, level1);
bits <<= rl->table_vlc[code][1];
len += rl->table_vlc[code][1];
bits += rl->table_vlc[code][0];
bits = bits * 2 + sign;
len++;
if (code != rl->n && len < len_tab[index]) {
bits_tab[index] = bits;
len_tab[index] = len;
}
}
/* ESC2 */
bits = rl->table_vlc[rl->n][0];
len = rl->table_vlc[rl->n][1];
bits = bits * 4 + 2;
len += 2; // esc2
run1 = run - rl->max_run[last][level] - 1;
if (run1 >= 0) {
code = get_rl_index(rl, last, run1, level);
bits <<= rl->table_vlc[code][1];
len += rl->table_vlc[code][1];
bits += rl->table_vlc[code][0];
bits = bits * 2 + sign;
len++;
if (code != rl->n && len < len_tab[index]) {
bits_tab[index] = bits;
len_tab[index] = len;
}
}
/* ESC3 */
bits = rl->table_vlc[rl->n][0];
len = rl->table_vlc[rl->n][1];
bits = bits * 4 + 3;
len += 2; // esc3
bits = bits * 2 + last;
len++;
bits = bits * 64 + run;
len += 6;
bits = bits * 2 + 1;
len++; // marker
bits = bits * 4096 + (slevel & 0xfff);
len += 12;
bits = bits * 2 + 1;
len++; // marker
if (len < len_tab[index]) {
bits_tab[index] = bits;
len_tab[index] = len;
}
}
}
}
}
static av_cold int encode_init(AVCodecContext *avctx)
{
MpegEncContext *s = avctx->priv_data;
int ret;
static int done = 0;
if (avctx->width >= (1<<13) || avctx->height >= (1<<13)) {
av_log(avctx, AV_LOG_ERROR, "dimensions too large for MPEG-4\n");
return AVERROR(EINVAL);
}
if ((ret = ff_mpv_encode_init(avctx)) < 0)
return ret;
if (!done) {
done = 1;
init_uni_dc_tab();
ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
init_uni_mpeg4_rl_tab(&ff_mpeg4_rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
init_uni_mpeg4_rl_tab(&ff_h263_rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
}
s->min_qcoeff = -2048;
s->max_qcoeff = 2047;
s->intra_ac_vlc_length = uni_mpeg4_intra_rl_len;
s->intra_ac_vlc_last_length = uni_mpeg4_intra_rl_len + 128 * 64;
s->inter_ac_vlc_length = uni_mpeg4_inter_rl_len;
s->inter_ac_vlc_last_length = uni_mpeg4_inter_rl_len + 128 * 64;
s->luma_dc_vlc_length = uni_DCtab_lum_len;
s->ac_esc_length = 7 + 2 + 1 + 6 + 1 + 12 + 1;
s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table;
s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table;
if (s->avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
s->avctx->extradata = av_malloc(1024);
init_put_bits(&s->pb, s->avctx->extradata, 1024);
if (!(s->workaround_bugs & FF_BUG_MS))
mpeg4_encode_visual_object_header(s);
mpeg4_encode_vol_header(s, 0, 0);
// ff_mpeg4_stuffing(&s->pb); ?
flush_put_bits(&s->pb);
s->avctx->extradata_size = (put_bits_count(&s->pb) + 7) >> 3;
}
return 0;
}
void ff_mpeg4_init_partitions(MpegEncContext *s)
{
uint8_t *start = put_bits_ptr(&s->pb);
uint8_t *end = s->pb.buf_end;
int size = end - start;
int pb_size = (((intptr_t)start + size / 3) & (~3)) - (intptr_t)start;
int tex_size = (size - 2 * pb_size) & (~3);
set_put_bits_buffer_size(&s->pb, pb_size);
init_put_bits(&s->tex_pb, start + pb_size, tex_size);
init_put_bits(&s->pb2, start + pb_size + tex_size, pb_size);
}
void ff_mpeg4_merge_partitions(MpegEncContext *s)
{
const int pb2_len = put_bits_count(&s->pb2);
const int tex_pb_len = put_bits_count(&s->tex_pb);
const int bits = put_bits_count(&s->pb);
if (s->pict_type == AV_PICTURE_TYPE_I) {
put_bits(&s->pb, 19, DC_MARKER);
s->misc_bits += 19 + pb2_len + bits - s->last_bits;
s->i_tex_bits += tex_pb_len;
} else {
put_bits(&s->pb, 17, MOTION_MARKER);
s->misc_bits += 17 + pb2_len;
s->mv_bits += bits - s->last_bits;
s->p_tex_bits += tex_pb_len;
}
flush_put_bits(&s->pb2);
flush_put_bits(&s->tex_pb);
set_put_bits_buffer_size(&s->pb, s->pb2.buf_end - s->pb.buf);
avpriv_copy_bits(&s->pb, s->pb2.buf, pb2_len);
avpriv_copy_bits(&s->pb, s->tex_pb.buf, tex_pb_len);
s->last_bits = put_bits_count(&s->pb);
}
void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
{
int mb_num_bits = av_log2(s->mb_num - 1) + 1;
put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
put_bits(&s->pb, 1, 1);
put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y * s->mb_width);
put_bits(&s->pb, s->quant_precision, s->qscale);
put_bits(&s->pb, 1, 0); /* no HEC */
}
#define OFFSET(x) offsetof(MpegEncContext, x)
#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
static const AVOption options[] = {
{ "data_partitioning", "Use data partitioning.", OFFSET(data_partitioning), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
{ "alternate_scan", "Enable alternate scantable.", OFFSET(alternate_scan), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
FF_MPV_COMMON_OPTS
{ NULL },
};
static const AVClass mpeg4enc_class = {
.class_name = "MPEG4 encoder",
.item_name = av_default_item_name,
.option = options,
.version = LIBAVUTIL_VERSION_INT,
};
AVCodec ff_mpeg4_encoder = {
.name = "mpeg4",
.long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_MPEG4,
.priv_data_size = sizeof(MpegEncContext),
.init = encode_init,
.encode2 = ff_mpv_encode_picture,
.close = ff_mpv_encode_end,
.pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
.capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS,
.priv_class = &mpeg4enc_class,
};
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_190_0 |
crossvul-cpp_data_bad_2891_7 | /* Keyring handling
*
* Copyright (C) 2004-2005, 2008, 2013 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/security.h>
#include <linux/seq_file.h>
#include <linux/err.h>
#include <keys/keyring-type.h>
#include <keys/user-type.h>
#include <linux/assoc_array_priv.h>
#include <linux/uaccess.h>
#include "internal.h"
/*
* When plumbing the depths of the key tree, this sets a hard limit
* set on how deep we're willing to go.
*/
#define KEYRING_SEARCH_MAX_DEPTH 6
/*
* We keep all named keyrings in a hash to speed looking them up.
*/
#define KEYRING_NAME_HASH_SIZE (1 << 5)
/*
* We mark pointers we pass to the associative array with bit 1 set if
* they're keyrings and clear otherwise.
*/
#define KEYRING_PTR_SUBTYPE 0x2UL
static inline bool keyring_ptr_is_keyring(const struct assoc_array_ptr *x)
{
return (unsigned long)x & KEYRING_PTR_SUBTYPE;
}
static inline struct key *keyring_ptr_to_key(const struct assoc_array_ptr *x)
{
void *object = assoc_array_ptr_to_leaf(x);
return (struct key *)((unsigned long)object & ~KEYRING_PTR_SUBTYPE);
}
static inline void *keyring_key_to_ptr(struct key *key)
{
if (key->type == &key_type_keyring)
return (void *)((unsigned long)key | KEYRING_PTR_SUBTYPE);
return key;
}
static struct list_head keyring_name_hash[KEYRING_NAME_HASH_SIZE];
static DEFINE_RWLOCK(keyring_name_lock);
static inline unsigned keyring_hash(const char *desc)
{
unsigned bucket = 0;
for (; *desc; desc++)
bucket += (unsigned char)*desc;
return bucket & (KEYRING_NAME_HASH_SIZE - 1);
}
/*
* The keyring key type definition. Keyrings are simply keys of this type and
* can be treated as ordinary keys in addition to having their own special
* operations.
*/
static int keyring_preparse(struct key_preparsed_payload *prep);
static void keyring_free_preparse(struct key_preparsed_payload *prep);
static int keyring_instantiate(struct key *keyring,
struct key_preparsed_payload *prep);
static void keyring_revoke(struct key *keyring);
static void keyring_destroy(struct key *keyring);
static void keyring_describe(const struct key *keyring, struct seq_file *m);
static long keyring_read(const struct key *keyring,
char __user *buffer, size_t buflen);
struct key_type key_type_keyring = {
.name = "keyring",
.def_datalen = 0,
.preparse = keyring_preparse,
.free_preparse = keyring_free_preparse,
.instantiate = keyring_instantiate,
.revoke = keyring_revoke,
.destroy = keyring_destroy,
.describe = keyring_describe,
.read = keyring_read,
};
EXPORT_SYMBOL(key_type_keyring);
/*
* Semaphore to serialise link/link calls to prevent two link calls in parallel
* introducing a cycle.
*/
static DECLARE_RWSEM(keyring_serialise_link_sem);
/*
* Publish the name of a keyring so that it can be found by name (if it has
* one).
*/
static void keyring_publish_name(struct key *keyring)
{
int bucket;
if (keyring->description) {
bucket = keyring_hash(keyring->description);
write_lock(&keyring_name_lock);
if (!keyring_name_hash[bucket].next)
INIT_LIST_HEAD(&keyring_name_hash[bucket]);
list_add_tail(&keyring->name_link,
&keyring_name_hash[bucket]);
write_unlock(&keyring_name_lock);
}
}
/*
* Preparse a keyring payload
*/
static int keyring_preparse(struct key_preparsed_payload *prep)
{
return prep->datalen != 0 ? -EINVAL : 0;
}
/*
* Free a preparse of a user defined key payload
*/
static void keyring_free_preparse(struct key_preparsed_payload *prep)
{
}
/*
* Initialise a keyring.
*
* Returns 0 on success, -EINVAL if given any data.
*/
static int keyring_instantiate(struct key *keyring,
struct key_preparsed_payload *prep)
{
assoc_array_init(&keyring->keys);
/* make the keyring available by name if it has one */
keyring_publish_name(keyring);
return 0;
}
/*
* Multiply 64-bits by 32-bits to 96-bits and fold back to 64-bit. Ideally we'd
* fold the carry back too, but that requires inline asm.
*/
static u64 mult_64x32_and_fold(u64 x, u32 y)
{
u64 hi = (u64)(u32)(x >> 32) * y;
u64 lo = (u64)(u32)(x) * y;
return lo + ((u64)(u32)hi << 32) + (u32)(hi >> 32);
}
/*
* Hash a key type and description.
*/
static unsigned long hash_key_type_and_desc(const struct keyring_index_key *index_key)
{
const unsigned level_shift = ASSOC_ARRAY_LEVEL_STEP;
const unsigned long fan_mask = ASSOC_ARRAY_FAN_MASK;
const char *description = index_key->description;
unsigned long hash, type;
u32 piece;
u64 acc;
int n, desc_len = index_key->desc_len;
type = (unsigned long)index_key->type;
acc = mult_64x32_and_fold(type, desc_len + 13);
acc = mult_64x32_and_fold(acc, 9207);
for (;;) {
n = desc_len;
if (n <= 0)
break;
if (n > 4)
n = 4;
piece = 0;
memcpy(&piece, description, n);
description += n;
desc_len -= n;
acc = mult_64x32_and_fold(acc, piece);
acc = mult_64x32_and_fold(acc, 9207);
}
/* Fold the hash down to 32 bits if need be. */
hash = acc;
if (ASSOC_ARRAY_KEY_CHUNK_SIZE == 32)
hash ^= acc >> 32;
/* Squidge all the keyrings into a separate part of the tree to
* ordinary keys by making sure the lowest level segment in the hash is
* zero for keyrings and non-zero otherwise.
*/
if (index_key->type != &key_type_keyring && (hash & fan_mask) == 0)
return hash | (hash >> (ASSOC_ARRAY_KEY_CHUNK_SIZE - level_shift)) | 1;
if (index_key->type == &key_type_keyring && (hash & fan_mask) != 0)
return (hash + (hash << level_shift)) & ~fan_mask;
return hash;
}
/*
* Build the next index key chunk.
*
* On 32-bit systems the index key is laid out as:
*
* 0 4 5 9...
* hash desclen typeptr desc[]
*
* On 64-bit systems:
*
* 0 8 9 17...
* hash desclen typeptr desc[]
*
* We return it one word-sized chunk at a time.
*/
static unsigned long keyring_get_key_chunk(const void *data, int level)
{
const struct keyring_index_key *index_key = data;
unsigned long chunk = 0;
long offset = 0;
int desc_len = index_key->desc_len, n = sizeof(chunk);
level /= ASSOC_ARRAY_KEY_CHUNK_SIZE;
switch (level) {
case 0:
return hash_key_type_and_desc(index_key);
case 1:
return ((unsigned long)index_key->type << 8) | desc_len;
case 2:
if (desc_len == 0)
return (u8)((unsigned long)index_key->type >>
(ASSOC_ARRAY_KEY_CHUNK_SIZE - 8));
n--;
offset = 1;
default:
offset += sizeof(chunk) - 1;
offset += (level - 3) * sizeof(chunk);
if (offset >= desc_len)
return 0;
desc_len -= offset;
if (desc_len > n)
desc_len = n;
offset += desc_len;
do {
chunk <<= 8;
chunk |= ((u8*)index_key->description)[--offset];
} while (--desc_len > 0);
if (level == 2) {
chunk <<= 8;
chunk |= (u8)((unsigned long)index_key->type >>
(ASSOC_ARRAY_KEY_CHUNK_SIZE - 8));
}
return chunk;
}
}
static unsigned long keyring_get_object_key_chunk(const void *object, int level)
{
const struct key *key = keyring_ptr_to_key(object);
return keyring_get_key_chunk(&key->index_key, level);
}
static bool keyring_compare_object(const void *object, const void *data)
{
const struct keyring_index_key *index_key = data;
const struct key *key = keyring_ptr_to_key(object);
return key->index_key.type == index_key->type &&
key->index_key.desc_len == index_key->desc_len &&
memcmp(key->index_key.description, index_key->description,
index_key->desc_len) == 0;
}
/*
* Compare the index keys of a pair of objects and determine the bit position
* at which they differ - if they differ.
*/
static int keyring_diff_objects(const void *object, const void *data)
{
const struct key *key_a = keyring_ptr_to_key(object);
const struct keyring_index_key *a = &key_a->index_key;
const struct keyring_index_key *b = data;
unsigned long seg_a, seg_b;
int level, i;
level = 0;
seg_a = hash_key_type_and_desc(a);
seg_b = hash_key_type_and_desc(b);
if ((seg_a ^ seg_b) != 0)
goto differ;
/* The number of bits contributed by the hash is controlled by a
* constant in the assoc_array headers. Everything else thereafter we
* can deal with as being machine word-size dependent.
*/
level += ASSOC_ARRAY_KEY_CHUNK_SIZE / 8;
seg_a = a->desc_len;
seg_b = b->desc_len;
if ((seg_a ^ seg_b) != 0)
goto differ;
/* The next bit may not work on big endian */
level++;
seg_a = (unsigned long)a->type;
seg_b = (unsigned long)b->type;
if ((seg_a ^ seg_b) != 0)
goto differ;
level += sizeof(unsigned long);
if (a->desc_len == 0)
goto same;
i = 0;
if (((unsigned long)a->description | (unsigned long)b->description) &
(sizeof(unsigned long) - 1)) {
do {
seg_a = *(unsigned long *)(a->description + i);
seg_b = *(unsigned long *)(b->description + i);
if ((seg_a ^ seg_b) != 0)
goto differ_plus_i;
i += sizeof(unsigned long);
} while (i < (a->desc_len & (sizeof(unsigned long) - 1)));
}
for (; i < a->desc_len; i++) {
seg_a = *(unsigned char *)(a->description + i);
seg_b = *(unsigned char *)(b->description + i);
if ((seg_a ^ seg_b) != 0)
goto differ_plus_i;
}
same:
return -1;
differ_plus_i:
level += i;
differ:
i = level * 8 + __ffs(seg_a ^ seg_b);
return i;
}
/*
* Free an object after stripping the keyring flag off of the pointer.
*/
static void keyring_free_object(void *object)
{
key_put(keyring_ptr_to_key(object));
}
/*
* Operations for keyring management by the index-tree routines.
*/
static const struct assoc_array_ops keyring_assoc_array_ops = {
.get_key_chunk = keyring_get_key_chunk,
.get_object_key_chunk = keyring_get_object_key_chunk,
.compare_object = keyring_compare_object,
.diff_objects = keyring_diff_objects,
.free_object = keyring_free_object,
};
/*
* Clean up a keyring when it is destroyed. Unpublish its name if it had one
* and dispose of its data.
*
* The garbage collector detects the final key_put(), removes the keyring from
* the serial number tree and then does RCU synchronisation before coming here,
* so we shouldn't need to worry about code poking around here with the RCU
* readlock held by this time.
*/
static void keyring_destroy(struct key *keyring)
{
if (keyring->description) {
write_lock(&keyring_name_lock);
if (keyring->name_link.next != NULL &&
!list_empty(&keyring->name_link))
list_del(&keyring->name_link);
write_unlock(&keyring_name_lock);
}
if (keyring->restrict_link) {
struct key_restriction *keyres = keyring->restrict_link;
key_put(keyres->key);
kfree(keyres);
}
assoc_array_destroy(&keyring->keys, &keyring_assoc_array_ops);
}
/*
* Describe a keyring for /proc.
*/
static void keyring_describe(const struct key *keyring, struct seq_file *m)
{
if (keyring->description)
seq_puts(m, keyring->description);
else
seq_puts(m, "[anon]");
if (key_is_instantiated(keyring)) {
if (keyring->keys.nr_leaves_on_tree != 0)
seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree);
else
seq_puts(m, ": empty");
}
}
struct keyring_read_iterator_context {
size_t buflen;
size_t count;
key_serial_t __user *buffer;
};
static int keyring_read_iterator(const void *object, void *data)
{
struct keyring_read_iterator_context *ctx = data;
const struct key *key = keyring_ptr_to_key(object);
int ret;
kenter("{%s,%d},,{%zu/%zu}",
key->type->name, key->serial, ctx->count, ctx->buflen);
if (ctx->count >= ctx->buflen)
return 1;
ret = put_user(key->serial, ctx->buffer);
if (ret < 0)
return ret;
ctx->buffer++;
ctx->count += sizeof(key->serial);
return 0;
}
/*
* Read a list of key IDs from the keyring's contents in binary form
*
* The keyring's semaphore is read-locked by the caller. This prevents someone
* from modifying it under us - which could cause us to read key IDs multiple
* times.
*/
static long keyring_read(const struct key *keyring,
char __user *buffer, size_t buflen)
{
struct keyring_read_iterator_context ctx;
unsigned long nr_keys;
int ret;
kenter("{%d},,%zu", key_serial(keyring), buflen);
if (buflen & (sizeof(key_serial_t) - 1))
return -EINVAL;
nr_keys = keyring->keys.nr_leaves_on_tree;
if (nr_keys == 0)
return 0;
/* Calculate how much data we could return */
if (!buffer || !buflen)
return nr_keys * sizeof(key_serial_t);
/* Copy the IDs of the subscribed keys into the buffer */
ctx.buffer = (key_serial_t __user *)buffer;
ctx.buflen = buflen;
ctx.count = 0;
ret = assoc_array_iterate(&keyring->keys, keyring_read_iterator, &ctx);
if (ret < 0) {
kleave(" = %d [iterate]", ret);
return ret;
}
kleave(" = %zu [ok]", ctx.count);
return ctx.count;
}
/*
* Allocate a keyring and link into the destination keyring.
*/
struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid,
const struct cred *cred, key_perm_t perm,
unsigned long flags,
struct key_restriction *restrict_link,
struct key *dest)
{
struct key *keyring;
int ret;
keyring = key_alloc(&key_type_keyring, description,
uid, gid, cred, perm, flags, restrict_link);
if (!IS_ERR(keyring)) {
ret = key_instantiate_and_link(keyring, NULL, 0, dest, NULL);
if (ret < 0) {
key_put(keyring);
keyring = ERR_PTR(ret);
}
}
return keyring;
}
EXPORT_SYMBOL(keyring_alloc);
/**
* restrict_link_reject - Give -EPERM to restrict link
* @keyring: The keyring being added to.
* @type: The type of key being added.
* @payload: The payload of the key intended to be added.
* @data: Additional data for evaluating restriction.
*
* Reject the addition of any links to a keyring. It can be overridden by
* passing KEY_ALLOC_BYPASS_RESTRICTION to key_instantiate_and_link() when
* adding a key to a keyring.
*
* This is meant to be stored in a key_restriction structure which is passed
* in the restrict_link parameter to keyring_alloc().
*/
int restrict_link_reject(struct key *keyring,
const struct key_type *type,
const union key_payload *payload,
struct key *restriction_key)
{
return -EPERM;
}
/*
* By default, we keys found by getting an exact match on their descriptions.
*/
bool key_default_cmp(const struct key *key,
const struct key_match_data *match_data)
{
return strcmp(key->description, match_data->raw_data) == 0;
}
/*
* Iteration function to consider each key found.
*/
static int keyring_search_iterator(const void *object, void *iterator_data)
{
struct keyring_search_context *ctx = iterator_data;
const struct key *key = keyring_ptr_to_key(object);
unsigned long kflags = key->flags;
kenter("{%d}", key->serial);
/* ignore keys not of this type */
if (key->type != ctx->index_key.type) {
kleave(" = 0 [!type]");
return 0;
}
/* skip invalidated, revoked and expired keys */
if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
(1 << KEY_FLAG_REVOKED))) {
ctx->result = ERR_PTR(-EKEYREVOKED);
kleave(" = %d [invrev]", ctx->skipped_ret);
goto skipped;
}
if (key->expiry && ctx->now.tv_sec >= key->expiry) {
if (!(ctx->flags & KEYRING_SEARCH_SKIP_EXPIRED))
ctx->result = ERR_PTR(-EKEYEXPIRED);
kleave(" = %d [expire]", ctx->skipped_ret);
goto skipped;
}
}
/* keys that don't match */
if (!ctx->match_data.cmp(key, &ctx->match_data)) {
kleave(" = 0 [!match]");
return 0;
}
/* key must have search permissions */
if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
key_task_permission(make_key_ref(key, ctx->possessed),
ctx->cred, KEY_NEED_SEARCH) < 0) {
ctx->result = ERR_PTR(-EACCES);
kleave(" = %d [!perm]", ctx->skipped_ret);
goto skipped;
}
if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
/* we set a different error code if we pass a negative key */
if (kflags & (1 << KEY_FLAG_NEGATIVE)) {
smp_rmb();
ctx->result = ERR_PTR(key->reject_error);
kleave(" = %d [neg]", ctx->skipped_ret);
goto skipped;
}
}
/* Found */
ctx->result = make_key_ref(key, ctx->possessed);
kleave(" = 1 [found]");
return 1;
skipped:
return ctx->skipped_ret;
}
/*
* Search inside a keyring for a key. We can search by walking to it
* directly based on its index-key or we can iterate over the entire
* tree looking for it, based on the match function.
*/
static int search_keyring(struct key *keyring, struct keyring_search_context *ctx)
{
if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_DIRECT) {
const void *object;
object = assoc_array_find(&keyring->keys,
&keyring_assoc_array_ops,
&ctx->index_key);
return object ? ctx->iterator(object, ctx) : 0;
}
return assoc_array_iterate(&keyring->keys, ctx->iterator, ctx);
}
/*
* Search a tree of keyrings that point to other keyrings up to the maximum
* depth.
*/
static bool search_nested_keyrings(struct key *keyring,
struct keyring_search_context *ctx)
{
struct {
struct key *keyring;
struct assoc_array_node *node;
int slot;
} stack[KEYRING_SEARCH_MAX_DEPTH];
struct assoc_array_shortcut *shortcut;
struct assoc_array_node *node;
struct assoc_array_ptr *ptr;
struct key *key;
int sp = 0, slot;
kenter("{%d},{%s,%s}",
keyring->serial,
ctx->index_key.type->name,
ctx->index_key.description);
#define STATE_CHECKS (KEYRING_SEARCH_NO_STATE_CHECK | KEYRING_SEARCH_DO_STATE_CHECK)
BUG_ON((ctx->flags & STATE_CHECKS) == 0 ||
(ctx->flags & STATE_CHECKS) == STATE_CHECKS);
if (ctx->index_key.description)
ctx->index_key.desc_len = strlen(ctx->index_key.description);
/* Check to see if this top-level keyring is what we are looking for
* and whether it is valid or not.
*/
if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_ITERATE ||
keyring_compare_object(keyring, &ctx->index_key)) {
ctx->skipped_ret = 2;
switch (ctx->iterator(keyring_key_to_ptr(keyring), ctx)) {
case 1:
goto found;
case 2:
return false;
default:
break;
}
}
ctx->skipped_ret = 0;
/* Start processing a new keyring */
descend_to_keyring:
kdebug("descend to %d", keyring->serial);
if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
(1 << KEY_FLAG_REVOKED)))
goto not_this_keyring;
/* Search through the keys in this keyring before its searching its
* subtrees.
*/
if (search_keyring(keyring, ctx))
goto found;
/* Then manually iterate through the keyrings nested in this one.
*
* Start from the root node of the index tree. Because of the way the
* hash function has been set up, keyrings cluster on the leftmost
* branch of the root node (root slot 0) or in the root node itself.
* Non-keyrings avoid the leftmost branch of the root entirely (root
* slots 1-15).
*/
ptr = READ_ONCE(keyring->keys.root);
if (!ptr)
goto not_this_keyring;
if (assoc_array_ptr_is_shortcut(ptr)) {
/* If the root is a shortcut, either the keyring only contains
* keyring pointers (everything clusters behind root slot 0) or
* doesn't contain any keyring pointers.
*/
shortcut = assoc_array_ptr_to_shortcut(ptr);
smp_read_barrier_depends();
if ((shortcut->index_key[0] & ASSOC_ARRAY_FAN_MASK) != 0)
goto not_this_keyring;
ptr = READ_ONCE(shortcut->next_node);
node = assoc_array_ptr_to_node(ptr);
goto begin_node;
}
node = assoc_array_ptr_to_node(ptr);
smp_read_barrier_depends();
ptr = node->slots[0];
if (!assoc_array_ptr_is_meta(ptr))
goto begin_node;
descend_to_node:
/* Descend to a more distal node in this keyring's content tree and go
* through that.
*/
kdebug("descend");
if (assoc_array_ptr_is_shortcut(ptr)) {
shortcut = assoc_array_ptr_to_shortcut(ptr);
smp_read_barrier_depends();
ptr = READ_ONCE(shortcut->next_node);
BUG_ON(!assoc_array_ptr_is_node(ptr));
}
node = assoc_array_ptr_to_node(ptr);
begin_node:
kdebug("begin_node");
smp_read_barrier_depends();
slot = 0;
ascend_to_node:
/* Go through the slots in a node */
for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
ptr = READ_ONCE(node->slots[slot]);
if (assoc_array_ptr_is_meta(ptr) && node->back_pointer)
goto descend_to_node;
if (!keyring_ptr_is_keyring(ptr))
continue;
key = keyring_ptr_to_key(ptr);
if (sp >= KEYRING_SEARCH_MAX_DEPTH) {
if (ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP) {
ctx->result = ERR_PTR(-ELOOP);
return false;
}
goto not_this_keyring;
}
/* Search a nested keyring */
if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
key_task_permission(make_key_ref(key, ctx->possessed),
ctx->cred, KEY_NEED_SEARCH) < 0)
continue;
/* stack the current position */
stack[sp].keyring = keyring;
stack[sp].node = node;
stack[sp].slot = slot;
sp++;
/* begin again with the new keyring */
keyring = key;
goto descend_to_keyring;
}
/* We've dealt with all the slots in the current node, so now we need
* to ascend to the parent and continue processing there.
*/
ptr = READ_ONCE(node->back_pointer);
slot = node->parent_slot;
if (ptr && assoc_array_ptr_is_shortcut(ptr)) {
shortcut = assoc_array_ptr_to_shortcut(ptr);
smp_read_barrier_depends();
ptr = READ_ONCE(shortcut->back_pointer);
slot = shortcut->parent_slot;
}
if (!ptr)
goto not_this_keyring;
node = assoc_array_ptr_to_node(ptr);
smp_read_barrier_depends();
slot++;
/* If we've ascended to the root (zero backpointer), we must have just
* finished processing the leftmost branch rather than the root slots -
* so there can't be any more keyrings for us to find.
*/
if (node->back_pointer) {
kdebug("ascend %d", slot);
goto ascend_to_node;
}
/* The keyring we're looking at was disqualified or didn't contain a
* matching key.
*/
not_this_keyring:
kdebug("not_this_keyring %d", sp);
if (sp <= 0) {
kleave(" = false");
return false;
}
/* Resume the processing of a keyring higher up in the tree */
sp--;
keyring = stack[sp].keyring;
node = stack[sp].node;
slot = stack[sp].slot + 1;
kdebug("ascend to %d [%d]", keyring->serial, slot);
goto ascend_to_node;
/* We found a viable match */
found:
key = key_ref_to_ptr(ctx->result);
key_check(key);
if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME)) {
key->last_used_at = ctx->now.tv_sec;
keyring->last_used_at = ctx->now.tv_sec;
while (sp > 0)
stack[--sp].keyring->last_used_at = ctx->now.tv_sec;
}
kleave(" = true");
return true;
}
/**
* keyring_search_aux - Search a keyring tree for a key matching some criteria
* @keyring_ref: A pointer to the keyring with possession indicator.
* @ctx: The keyring search context.
*
* Search the supplied keyring tree for a key that matches the criteria given.
* The root keyring and any linked keyrings must grant Search permission to the
* caller to be searchable and keys can only be found if they too grant Search
* to the caller. The possession flag on the root keyring pointer controls use
* of the possessor bits in permissions checking of the entire tree. In
* addition, the LSM gets to forbid keyring searches and key matches.
*
* The search is performed as a breadth-then-depth search up to the prescribed
* limit (KEYRING_SEARCH_MAX_DEPTH).
*
* Keys are matched to the type provided and are then filtered by the match
* function, which is given the description to use in any way it sees fit. The
* match function may use any attributes of a key that it wishes to to
* determine the match. Normally the match function from the key type would be
* used.
*
* RCU can be used to prevent the keyring key lists from disappearing without
* the need to take lots of locks.
*
* Returns a pointer to the found key and increments the key usage count if
* successful; -EAGAIN if no matching keys were found, or if expired or revoked
* keys were found; -ENOKEY if only negative keys were found; -ENOTDIR if the
* specified keyring wasn't a keyring.
*
* In the case of a successful return, the possession attribute from
* @keyring_ref is propagated to the returned key reference.
*/
key_ref_t keyring_search_aux(key_ref_t keyring_ref,
struct keyring_search_context *ctx)
{
struct key *keyring;
long err;
ctx->iterator = keyring_search_iterator;
ctx->possessed = is_key_possessed(keyring_ref);
ctx->result = ERR_PTR(-EAGAIN);
keyring = key_ref_to_ptr(keyring_ref);
key_check(keyring);
if (keyring->type != &key_type_keyring)
return ERR_PTR(-ENOTDIR);
if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM)) {
err = key_task_permission(keyring_ref, ctx->cred, KEY_NEED_SEARCH);
if (err < 0)
return ERR_PTR(err);
}
rcu_read_lock();
ctx->now = current_kernel_time();
if (search_nested_keyrings(keyring, ctx))
__key_get(key_ref_to_ptr(ctx->result));
rcu_read_unlock();
return ctx->result;
}
/**
* keyring_search - Search the supplied keyring tree for a matching key
* @keyring: The root of the keyring tree to be searched.
* @type: The type of keyring we want to find.
* @description: The name of the keyring we want to find.
*
* As keyring_search_aux() above, but using the current task's credentials and
* type's default matching function and preferred search method.
*/
key_ref_t keyring_search(key_ref_t keyring,
struct key_type *type,
const char *description)
{
struct keyring_search_context ctx = {
.index_key.type = type,
.index_key.description = description,
.cred = current_cred(),
.match_data.cmp = key_default_cmp,
.match_data.raw_data = description,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
.flags = KEYRING_SEARCH_DO_STATE_CHECK,
};
key_ref_t key;
int ret;
if (type->match_preparse) {
ret = type->match_preparse(&ctx.match_data);
if (ret < 0)
return ERR_PTR(ret);
}
key = keyring_search_aux(keyring, &ctx);
if (type->match_free)
type->match_free(&ctx.match_data);
return key;
}
EXPORT_SYMBOL(keyring_search);
static struct key_restriction *keyring_restriction_alloc(
key_restrict_link_func_t check)
{
struct key_restriction *keyres =
kzalloc(sizeof(struct key_restriction), GFP_KERNEL);
if (!keyres)
return ERR_PTR(-ENOMEM);
keyres->check = check;
return keyres;
}
/*
* Semaphore to serialise restriction setup to prevent reference count
* cycles through restriction key pointers.
*/
static DECLARE_RWSEM(keyring_serialise_restrict_sem);
/*
* Check for restriction cycles that would prevent keyring garbage collection.
* keyring_serialise_restrict_sem must be held.
*/
static bool keyring_detect_restriction_cycle(const struct key *dest_keyring,
struct key_restriction *keyres)
{
while (keyres && keyres->key &&
keyres->key->type == &key_type_keyring) {
if (keyres->key == dest_keyring)
return true;
keyres = keyres->key->restrict_link;
}
return false;
}
/**
* keyring_restrict - Look up and apply a restriction to a keyring
*
* @keyring: The keyring to be restricted
* @restriction: The restriction options to apply to the keyring
*/
int keyring_restrict(key_ref_t keyring_ref, const char *type,
const char *restriction)
{
struct key *keyring;
struct key_type *restrict_type = NULL;
struct key_restriction *restrict_link;
int ret = 0;
keyring = key_ref_to_ptr(keyring_ref);
key_check(keyring);
if (keyring->type != &key_type_keyring)
return -ENOTDIR;
if (!type) {
restrict_link = keyring_restriction_alloc(restrict_link_reject);
} else {
restrict_type = key_type_lookup(type);
if (IS_ERR(restrict_type))
return PTR_ERR(restrict_type);
if (!restrict_type->lookup_restriction) {
ret = -ENOENT;
goto error;
}
restrict_link = restrict_type->lookup_restriction(restriction);
}
if (IS_ERR(restrict_link)) {
ret = PTR_ERR(restrict_link);
goto error;
}
down_write(&keyring->sem);
down_write(&keyring_serialise_restrict_sem);
if (keyring->restrict_link)
ret = -EEXIST;
else if (keyring_detect_restriction_cycle(keyring, restrict_link))
ret = -EDEADLK;
else
keyring->restrict_link = restrict_link;
up_write(&keyring_serialise_restrict_sem);
up_write(&keyring->sem);
if (ret < 0) {
key_put(restrict_link->key);
kfree(restrict_link);
}
error:
if (restrict_type)
key_type_put(restrict_type);
return ret;
}
EXPORT_SYMBOL(keyring_restrict);
/*
* Search the given keyring for a key that might be updated.
*
* The caller must guarantee that the keyring is a keyring and that the
* permission is granted to modify the keyring as no check is made here. The
* caller must also hold a lock on the keyring semaphore.
*
* Returns a pointer to the found key with usage count incremented if
* successful and returns NULL if not found. Revoked and invalidated keys are
* skipped over.
*
* If successful, the possession indicator is propagated from the keyring ref
* to the returned key reference.
*/
key_ref_t find_key_to_update(key_ref_t keyring_ref,
const struct keyring_index_key *index_key)
{
struct key *keyring, *key;
const void *object;
keyring = key_ref_to_ptr(keyring_ref);
kenter("{%d},{%s,%s}",
keyring->serial, index_key->type->name, index_key->description);
object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops,
index_key);
if (object)
goto found;
kleave(" = NULL");
return NULL;
found:
key = keyring_ptr_to_key(object);
if (key->flags & ((1 << KEY_FLAG_INVALIDATED) |
(1 << KEY_FLAG_REVOKED))) {
kleave(" = NULL [x]");
return NULL;
}
__key_get(key);
kleave(" = {%d}", key->serial);
return make_key_ref(key, is_key_possessed(keyring_ref));
}
/*
* Find a keyring with the specified name.
*
* Only keyrings that have nonzero refcount, are not revoked, and are owned by a
* user in the current user namespace are considered. If @uid_keyring is %true,
* the keyring additionally must have been allocated as a user or user session
* keyring; otherwise, it must grant Search permission directly to the caller.
*
* Returns a pointer to the keyring with the keyring's refcount having being
* incremented on success. -ENOKEY is returned if a key could not be found.
*/
struct key *find_keyring_by_name(const char *name, bool uid_keyring)
{
struct key *keyring;
int bucket;
if (!name)
return ERR_PTR(-EINVAL);
bucket = keyring_hash(name);
read_lock(&keyring_name_lock);
if (keyring_name_hash[bucket].next) {
/* search this hash bucket for a keyring with a matching name
* that's readable and that hasn't been revoked */
list_for_each_entry(keyring,
&keyring_name_hash[bucket],
name_link
) {
if (!kuid_has_mapping(current_user_ns(), keyring->user->uid))
continue;
if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
continue;
if (strcmp(keyring->description, name) != 0)
continue;
if (uid_keyring) {
if (!test_bit(KEY_FLAG_UID_KEYRING,
&keyring->flags))
continue;
} else {
if (key_permission(make_key_ref(keyring, 0),
KEY_NEED_SEARCH) < 0)
continue;
}
/* we've got a match but we might end up racing with
* key_cleanup() if the keyring is currently 'dead'
* (ie. it has a zero usage count) */
if (!refcount_inc_not_zero(&keyring->usage))
continue;
keyring->last_used_at = current_kernel_time().tv_sec;
goto out;
}
}
keyring = ERR_PTR(-ENOKEY);
out:
read_unlock(&keyring_name_lock);
return keyring;
}
static int keyring_detect_cycle_iterator(const void *object,
void *iterator_data)
{
struct keyring_search_context *ctx = iterator_data;
const struct key *key = keyring_ptr_to_key(object);
kenter("{%d}", key->serial);
/* We might get a keyring with matching index-key that is nonetheless a
* different keyring. */
if (key != ctx->match_data.raw_data)
return 0;
ctx->result = ERR_PTR(-EDEADLK);
return 1;
}
/*
* See if a cycle will will be created by inserting acyclic tree B in acyclic
* tree A at the topmost level (ie: as a direct child of A).
*
* Since we are adding B to A at the top level, checking for cycles should just
* be a matter of seeing if node A is somewhere in tree B.
*/
static int keyring_detect_cycle(struct key *A, struct key *B)
{
struct keyring_search_context ctx = {
.index_key = A->index_key,
.match_data.raw_data = A,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
.iterator = keyring_detect_cycle_iterator,
.flags = (KEYRING_SEARCH_NO_STATE_CHECK |
KEYRING_SEARCH_NO_UPDATE_TIME |
KEYRING_SEARCH_NO_CHECK_PERM |
KEYRING_SEARCH_DETECT_TOO_DEEP),
};
rcu_read_lock();
search_nested_keyrings(B, &ctx);
rcu_read_unlock();
return PTR_ERR(ctx.result) == -EAGAIN ? 0 : PTR_ERR(ctx.result);
}
/*
* Preallocate memory so that a key can be linked into to a keyring.
*/
int __key_link_begin(struct key *keyring,
const struct keyring_index_key *index_key,
struct assoc_array_edit **_edit)
__acquires(&keyring->sem)
__acquires(&keyring_serialise_link_sem)
{
struct assoc_array_edit *edit;
int ret;
kenter("%d,%s,%s,",
keyring->serial, index_key->type->name, index_key->description);
BUG_ON(index_key->desc_len == 0);
if (keyring->type != &key_type_keyring)
return -ENOTDIR;
down_write(&keyring->sem);
ret = -EKEYREVOKED;
if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
goto error_krsem;
/* serialise link/link calls to prevent parallel calls causing a cycle
* when linking two keyring in opposite orders */
if (index_key->type == &key_type_keyring)
down_write(&keyring_serialise_link_sem);
/* Create an edit script that will insert/replace the key in the
* keyring tree.
*/
edit = assoc_array_insert(&keyring->keys,
&keyring_assoc_array_ops,
index_key,
NULL);
if (IS_ERR(edit)) {
ret = PTR_ERR(edit);
goto error_sem;
}
/* If we're not replacing a link in-place then we're going to need some
* extra quota.
*/
if (!edit->dead_leaf) {
ret = key_payload_reserve(keyring,
keyring->datalen + KEYQUOTA_LINK_BYTES);
if (ret < 0)
goto error_cancel;
}
*_edit = edit;
kleave(" = 0");
return 0;
error_cancel:
assoc_array_cancel_edit(edit);
error_sem:
if (index_key->type == &key_type_keyring)
up_write(&keyring_serialise_link_sem);
error_krsem:
up_write(&keyring->sem);
kleave(" = %d", ret);
return ret;
}
/*
* Check already instantiated keys aren't going to be a problem.
*
* The caller must have called __key_link_begin(). Don't need to call this for
* keys that were created since __key_link_begin() was called.
*/
int __key_link_check_live_key(struct key *keyring, struct key *key)
{
if (key->type == &key_type_keyring)
/* check that we aren't going to create a cycle by linking one
* keyring to another */
return keyring_detect_cycle(keyring, key);
return 0;
}
/*
* Link a key into to a keyring.
*
* Must be called with __key_link_begin() having being called. Discards any
* already extant link to matching key if there is one, so that each keyring
* holds at most one link to any given key of a particular type+description
* combination.
*/
void __key_link(struct key *key, struct assoc_array_edit **_edit)
{
__key_get(key);
assoc_array_insert_set_object(*_edit, keyring_key_to_ptr(key));
assoc_array_apply_edit(*_edit);
*_edit = NULL;
}
/*
* Finish linking a key into to a keyring.
*
* Must be called with __key_link_begin() having being called.
*/
void __key_link_end(struct key *keyring,
const struct keyring_index_key *index_key,
struct assoc_array_edit *edit)
__releases(&keyring->sem)
__releases(&keyring_serialise_link_sem)
{
BUG_ON(index_key->type == NULL);
kenter("%d,%s,", keyring->serial, index_key->type->name);
if (index_key->type == &key_type_keyring)
up_write(&keyring_serialise_link_sem);
if (edit) {
if (!edit->dead_leaf) {
key_payload_reserve(keyring,
keyring->datalen - KEYQUOTA_LINK_BYTES);
}
assoc_array_cancel_edit(edit);
}
up_write(&keyring->sem);
}
/*
* Check addition of keys to restricted keyrings.
*/
static int __key_link_check_restriction(struct key *keyring, struct key *key)
{
if (!keyring->restrict_link || !keyring->restrict_link->check)
return 0;
return keyring->restrict_link->check(keyring, key->type, &key->payload,
keyring->restrict_link->key);
}
/**
* key_link - Link a key to a keyring
* @keyring: The keyring to make the link in.
* @key: The key to link to.
*
* Make a link in a keyring to a key, such that the keyring holds a reference
* on that key and the key can potentially be found by searching that keyring.
*
* This function will write-lock the keyring's semaphore and will consume some
* of the user's key data quota to hold the link.
*
* Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,
* -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is
* full, -EDQUOT if there is insufficient key data quota remaining to add
* another link or -ENOMEM if there's insufficient memory.
*
* It is assumed that the caller has checked that it is permitted for a link to
* be made (the keyring should have Write permission and the key Link
* permission).
*/
int key_link(struct key *keyring, struct key *key)
{
struct assoc_array_edit *edit;
int ret;
kenter("{%d,%d}", keyring->serial, refcount_read(&keyring->usage));
key_check(keyring);
key_check(key);
ret = __key_link_begin(keyring, &key->index_key, &edit);
if (ret == 0) {
kdebug("begun {%d,%d}", keyring->serial, refcount_read(&keyring->usage));
ret = __key_link_check_restriction(keyring, key);
if (ret == 0)
ret = __key_link_check_live_key(keyring, key);
if (ret == 0)
__key_link(key, &edit);
__key_link_end(keyring, &key->index_key, edit);
}
kleave(" = %d {%d,%d}", ret, keyring->serial, refcount_read(&keyring->usage));
return ret;
}
EXPORT_SYMBOL(key_link);
/**
* key_unlink - Unlink the first link to a key from a keyring.
* @keyring: The keyring to remove the link from.
* @key: The key the link is to.
*
* Remove a link from a keyring to a key.
*
* This function will write-lock the keyring's semaphore.
*
* Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if
* the key isn't linked to by the keyring or -ENOMEM if there's insufficient
* memory.
*
* It is assumed that the caller has checked that it is permitted for a link to
* be removed (the keyring should have Write permission; no permissions are
* required on the key).
*/
int key_unlink(struct key *keyring, struct key *key)
{
struct assoc_array_edit *edit;
int ret;
key_check(keyring);
key_check(key);
if (keyring->type != &key_type_keyring)
return -ENOTDIR;
down_write(&keyring->sem);
edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops,
&key->index_key);
if (IS_ERR(edit)) {
ret = PTR_ERR(edit);
goto error;
}
ret = -ENOENT;
if (edit == NULL)
goto error;
assoc_array_apply_edit(edit);
key_payload_reserve(keyring, keyring->datalen - KEYQUOTA_LINK_BYTES);
ret = 0;
error:
up_write(&keyring->sem);
return ret;
}
EXPORT_SYMBOL(key_unlink);
/**
* keyring_clear - Clear a keyring
* @keyring: The keyring to clear.
*
* Clear the contents of the specified keyring.
*
* Returns 0 if successful or -ENOTDIR if the keyring isn't a keyring.
*/
int keyring_clear(struct key *keyring)
{
struct assoc_array_edit *edit;
int ret;
if (keyring->type != &key_type_keyring)
return -ENOTDIR;
down_write(&keyring->sem);
edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
if (IS_ERR(edit)) {
ret = PTR_ERR(edit);
} else {
if (edit)
assoc_array_apply_edit(edit);
key_payload_reserve(keyring, 0);
ret = 0;
}
up_write(&keyring->sem);
return ret;
}
EXPORT_SYMBOL(keyring_clear);
/*
* Dispose of the links from a revoked keyring.
*
* This is called with the key sem write-locked.
*/
static void keyring_revoke(struct key *keyring)
{
struct assoc_array_edit *edit;
edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
if (!IS_ERR(edit)) {
if (edit)
assoc_array_apply_edit(edit);
key_payload_reserve(keyring, 0);
}
}
static bool keyring_gc_select_iterator(void *object, void *iterator_data)
{
struct key *key = keyring_ptr_to_key(object);
time_t *limit = iterator_data;
if (key_is_dead(key, *limit))
return false;
key_get(key);
return true;
}
static int keyring_gc_check_iterator(const void *object, void *iterator_data)
{
const struct key *key = keyring_ptr_to_key(object);
time_t *limit = iterator_data;
key_check(key);
return key_is_dead(key, *limit);
}
/*
* Garbage collect pointers from a keyring.
*
* Not called with any locks held. The keyring's key struct will not be
* deallocated under us as only our caller may deallocate it.
*/
void keyring_gc(struct key *keyring, time_t limit)
{
int result;
kenter("%x{%s}", keyring->serial, keyring->description ?: "");
if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
(1 << KEY_FLAG_REVOKED)))
goto dont_gc;
/* scan the keyring looking for dead keys */
rcu_read_lock();
result = assoc_array_iterate(&keyring->keys,
keyring_gc_check_iterator, &limit);
rcu_read_unlock();
if (result == true)
goto do_gc;
dont_gc:
kleave(" [no gc]");
return;
do_gc:
down_write(&keyring->sem);
assoc_array_gc(&keyring->keys, &keyring_assoc_array_ops,
keyring_gc_select_iterator, &limit);
up_write(&keyring->sem);
kleave(" [gc]");
}
/*
* Garbage collect restriction pointers from a keyring.
*
* Keyring restrictions are associated with a key type, and must be cleaned
* up if the key type is unregistered. The restriction is altered to always
* reject additional keys so a keyring cannot be opened up by unregistering
* a key type.
*
* Not called with any keyring locks held. The keyring's key struct will not
* be deallocated under us as only our caller may deallocate it.
*
* The caller is required to hold key_types_sem and dead_type->sem. This is
* fulfilled by key_gc_keytype() holding the locks on behalf of
* key_garbage_collector(), which it invokes on a workqueue.
*/
void keyring_restriction_gc(struct key *keyring, struct key_type *dead_type)
{
struct key_restriction *keyres;
kenter("%x{%s}", keyring->serial, keyring->description ?: "");
/*
* keyring->restrict_link is only assigned at key allocation time
* or with the key type locked, so the only values that could be
* concurrently assigned to keyring->restrict_link are for key
* types other than dead_type. Given this, it's ok to check
* the key type before acquiring keyring->sem.
*/
if (!dead_type || !keyring->restrict_link ||
keyring->restrict_link->keytype != dead_type) {
kleave(" [no restriction gc]");
return;
}
/* Lock the keyring to ensure that a link is not in progress */
down_write(&keyring->sem);
keyres = keyring->restrict_link;
keyres->check = restrict_link_reject;
key_put(keyres->key);
keyres->key = NULL;
keyres->keytype = NULL;
up_write(&keyring->sem);
kleave(" [restriction gc]");
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2891_7 |
crossvul-cpp_data_good_1448_1 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mod_lua.h"
#include "lua_apr.h"
#include "lua_dbd.h"
#include "lua_passwd.h"
#include "scoreboard.h"
#include "util_md5.h"
#include "util_script.h"
#include "util_varbuf.h"
#include "apr_date.h"
#include "apr_pools.h"
#include "apr_thread_mutex.h"
#include "apr_tables.h"
#include "util_cookies.h"
#define APR_WANT_BYTEFUNC
#include "apr_want.h"
extern apr_global_mutex_t* lua_ivm_mutex;
extern apr_shm_t *lua_ivm_shm;
APLOG_USE_MODULE(lua);
#define POST_MAX_VARS 500
#ifndef MODLUA_MAX_REG_MATCH
#define MODLUA_MAX_REG_MATCH 25
#endif
typedef char *(*req_field_string_f) (request_rec * r);
typedef int (*req_field_int_f) (request_rec * r);
typedef req_table_t *(*req_field_apr_table_f) (request_rec * r);
void ap_lua_rstack_dump(lua_State *L, request_rec *r, const char *msg)
{
int i;
int top = lua_gettop(L);
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(01484) "Lua Stack Dump: [%s]", msg);
for (i = 1; i <= top; i++) {
int t = lua_type(L, i);
switch (t) {
case LUA_TSTRING:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
"%d: '%s'", i, lua_tostring(L, i));
break;
}
case LUA_TUSERDATA:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "%d: userdata",
i);
break;
}
case LUA_TLIGHTUSERDATA:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
"%d: lightuserdata", i);
break;
}
case LUA_TNIL:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "%d: NIL", i);
break;
}
case LUA_TNONE:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "%d: None", i);
break;
}
case LUA_TBOOLEAN:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
"%d: %s", i, lua_toboolean(L,
i) ? "true" :
"false");
break;
}
case LUA_TNUMBER:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
"%d: %g", i, lua_tonumber(L, i));
break;
}
case LUA_TTABLE:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
"%d: <table>", i);
break;
}
case LUA_TFUNCTION:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
"%d: <function>", i);
break;
}
default:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
"%d: unknown: -[%s]-", i, lua_typename(L, i));
break;
}
}
}
}
/**
* Verify that the thing at index is a request_rec wrapping
* userdata thingamajig and return it if it is. if it is not
* lua will enter its error handling routine.
*/
static request_rec *ap_lua_check_request_rec(lua_State *L, int index)
{
request_rec *r;
luaL_checkudata(L, index, "Apache2.Request");
r = (request_rec *) lua_unboxpointer(L, index);
return r;
}
/* ------------------ request methods -------------------- */
/* helper callback for req_parseargs */
static int req_aprtable2luatable_cb(void *l, const char *key,
const char *value)
{
int t;
lua_State *L = (lua_State *) l; /* [table<s,t>, table<s,s>] */
/* rstack_dump(L, RRR, "start of cb"); */
/* L is [table<s,t>, table<s,s>] */
/* build complex */
lua_getfield(L, -1, key); /* [VALUE, table<s,t>, table<s,s>] */
/* rstack_dump(L, RRR, "after getfield"); */
t = lua_type(L, -1);
switch (t) {
case LUA_TNIL:
case LUA_TNONE:{
lua_pop(L, 1); /* [table<s,t>, table<s,s>] */
lua_newtable(L); /* [array, table<s,t>, table<s,s>] */
lua_pushnumber(L, 1); /* [1, array, table<s,t>, table<s,s>] */
lua_pushstring(L, value); /* [string, 1, array, table<s,t>, table<s,s>] */
lua_settable(L, -3); /* [array, table<s,t>, table<s,s>] */
lua_setfield(L, -2, key); /* [table<s,t>, table<s,s>] */
break;
}
case LUA_TTABLE:{
/* [array, table<s,t>, table<s,s>] */
int size = lua_rawlen(L, -1);
lua_pushnumber(L, size + 1); /* [#, array, table<s,t>, table<s,s>] */
lua_pushstring(L, value); /* [string, #, array, table<s,t>, table<s,s>] */
lua_settable(L, -3); /* [array, table<s,t>, table<s,s>] */
lua_setfield(L, -2, key); /* [table<s,t>, table<s,s>] */
break;
}
}
/* L is [table<s,t>, table<s,s>] */
/* build simple */
lua_getfield(L, -2, key); /* [VALUE, table<s,s>, table<s,t>] */
if (lua_isnoneornil(L, -1)) { /* only set if not already set */
lua_pop(L, 1); /* [table<s,s>, table<s,t>]] */
lua_pushstring(L, value); /* [string, table<s,s>, table<s,t>] */
lua_setfield(L, -3, key); /* [table<s,s>, table<s,t>] */
}
else {
lua_pop(L, 1);
}
return 1;
}
/* helper callback for req_parseargs */
static int req_aprtable2luatable_cb_len(void *l, const char *key,
const char *value, size_t len)
{
int t;
lua_State *L = (lua_State *) l; /* [table<s,t>, table<s,s>] */
/* rstack_dump(L, RRR, "start of cb"); */
/* L is [table<s,t>, table<s,s>] */
/* build complex */
lua_getfield(L, -1, key); /* [VALUE, table<s,t>, table<s,s>] */
/* rstack_dump(L, RRR, "after getfield"); */
t = lua_type(L, -1);
switch (t) {
case LUA_TNIL:
case LUA_TNONE:{
lua_pop(L, 1); /* [table<s,t>, table<s,s>] */
lua_newtable(L); /* [array, table<s,t>, table<s,s>] */
lua_pushnumber(L, 1); /* [1, array, table<s,t>, table<s,s>] */
lua_pushlstring(L, value, len); /* [string, 1, array, table<s,t>, table<s,s>] */
lua_settable(L, -3); /* [array, table<s,t>, table<s,s>] */
lua_setfield(L, -2, key); /* [table<s,t>, table<s,s>] */
break;
}
case LUA_TTABLE:{
/* [array, table<s,t>, table<s,s>] */
int size = lua_rawlen(L, -1);
lua_pushnumber(L, size + 1); /* [#, array, table<s,t>, table<s,s>] */
lua_pushlstring(L, value, len); /* [string, #, array, table<s,t>, table<s,s>] */
lua_settable(L, -3); /* [array, table<s,t>, table<s,s>] */
lua_setfield(L, -2, key); /* [table<s,t>, table<s,s>] */
break;
}
}
/* L is [table<s,t>, table<s,s>] */
/* build simple */
lua_getfield(L, -2, key); /* [VALUE, table<s,s>, table<s,t>] */
if (lua_isnoneornil(L, -1)) { /* only set if not already set */
lua_pop(L, 1); /* [table<s,s>, table<s,t>]] */
lua_pushlstring(L, value, len); /* [string, table<s,s>, table<s,t>] */
lua_setfield(L, -3, key); /* [table<s,s>, table<s,t>] */
}
else {
lua_pop(L, 1);
}
return 1;
}
/*
=======================================================================================================================
lua_read_body(request_rec *r, const char **rbuf, apr_off_t *size): Reads any additional form data sent in POST/PUT
requests. Used for multipart POST data.
=======================================================================================================================
*/
static int lua_read_body(request_rec *r, const char **rbuf, apr_off_t *size,
apr_off_t maxsize)
{
int rc = OK;
if ((rc = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) {
return (rc);
}
if (ap_should_client_block(r)) {
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
char argsbuffer[HUGE_STRING_LEN];
apr_off_t rsize, len_read, rpos = 0;
apr_off_t length = r->remaining;
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
if (maxsize != 0 && length > maxsize) {
return APR_EINCOMPLETE; /* Only room for incomplete data chunk :( */
}
*rbuf = (const char *) apr_pcalloc(r->pool, (apr_size_t) (length + 1));
*size = length;
while ((len_read = ap_get_client_block(r, argsbuffer, sizeof(argsbuffer))) > 0) {
if ((rpos + len_read) > length) {
rsize = length - rpos;
}
else {
rsize = len_read;
}
memcpy((char *) *rbuf + rpos, argsbuffer, (size_t) rsize);
rpos += rsize;
}
}
return (rc);
}
/*
* =======================================================================================================================
* lua_write_body: Reads any additional form data sent in POST/PUT requests
* and writes to a file.
* =======================================================================================================================
*/
static apr_status_t lua_write_body(request_rec *r, apr_file_t *file, apr_off_t *size)
{
apr_status_t rc = OK;
if ((rc = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
return rc;
if (ap_should_client_block(r)) {
char argsbuffer[HUGE_STRING_LEN];
apr_off_t rsize,
len_read,
rpos = 0;
apr_off_t length = r->remaining;
*size = length;
while ((len_read =
ap_get_client_block(r, argsbuffer,
sizeof(argsbuffer))) > 0) {
if ((rpos + len_read) > length)
rsize = (apr_size_t) length - rpos;
else
rsize = len_read;
rc = apr_file_write_full(file, argsbuffer, (apr_size_t) rsize,
NULL);
if (rc != APR_SUCCESS)
return rc;
rpos += rsize;
}
}
return rc;
}
/* r:parseargs() returning a lua table */
static int req_parseargs(lua_State *L)
{
apr_table_t *form_table;
request_rec *r = ap_lua_check_request_rec(L, 1);
lua_newtable(L);
lua_newtable(L); /* [table, table] */
ap_args_to_table(r, &form_table);
apr_table_do(req_aprtable2luatable_cb, L, form_table, NULL);
return 2; /* [table<string, string>, table<string, array<string>>] */
}
/* ap_lua_binstrstr: Binary strstr function for uploaded data with NULL bytes */
static char* ap_lua_binstrstr (const char * haystack, size_t hsize, const char* needle, size_t nsize)
{
size_t p;
if (haystack == NULL) return NULL;
if (needle == NULL) return NULL;
if (hsize < nsize) return NULL;
for (p = 0; p <= (hsize - nsize); ++p) {
if (memcmp(haystack + p, needle, nsize) == 0) {
return (char*) (haystack + p);
}
}
return NULL;
}
/* r:parsebody(): Parses regular (url-enocded) or multipart POST data and returns two tables*/
static int req_parsebody(lua_State *L)
{
apr_array_header_t *pairs;
apr_off_t len;
int res;
apr_size_t size;
apr_size_t max_post_size;
char *multipart;
const char *contentType;
request_rec *r = ap_lua_check_request_rec(L, 1);
max_post_size = (apr_size_t) luaL_optint(L, 2, MAX_STRING_LEN);
multipart = apr_pcalloc(r->pool, 256);
contentType = apr_table_get(r->headers_in, "Content-Type");
lua_newtable(L);
lua_newtable(L); /* [table, table] */
if (contentType != NULL && (sscanf(contentType, "multipart/form-data; boundary=%250c", multipart) == 1)) {
char *buffer, *key, *filename;
char *start = 0, *end = 0, *crlf = 0;
const char *data;
int i;
size_t vlen = 0;
size_t len = 0;
if (lua_read_body(r, &data, (apr_off_t*) &size, max_post_size) != OK) {
return 2;
}
len = strlen(multipart);
i = 0;
for
(
start = strstr((char *) data, multipart);
start != NULL;
start = end
) {
i++;
if (i == POST_MAX_VARS) break;
crlf = strstr((char *) start, "\r\n\r\n");
if (!crlf) break;
end = ap_lua_binstrstr(crlf, (size - (crlf - data)), multipart, len);
if (end == NULL) break;
key = (char *) apr_pcalloc(r->pool, 256);
filename = (char *) apr_pcalloc(r->pool, 256);
vlen = end - crlf - 8;
buffer = (char *) apr_pcalloc(r->pool, vlen+1);
memcpy(buffer, crlf + 4, vlen);
sscanf(start + len + 2,
"Content-Disposition: form-data; name=\"%255[^\"]\"; filename=\"%255[^\"]\"",
key, filename);
if (strlen(key)) {
req_aprtable2luatable_cb_len(L, key, buffer, vlen);
}
}
}
else {
char *buffer;
res = ap_parse_form_data(r, NULL, &pairs, -1, max_post_size);
if (res == OK) {
while(pairs && !apr_is_empty_array(pairs)) {
ap_form_pair_t *pair = (ap_form_pair_t *) apr_array_pop(pairs);
apr_brigade_length(pair->value, 1, &len);
size = (apr_size_t) len;
buffer = apr_palloc(r->pool, size + 1);
apr_brigade_flatten(pair->value, buffer, &size);
buffer[len] = 0;
req_aprtable2luatable_cb(L, pair->name, buffer);
}
}
}
return 2; /* [table<string, string>, table<string, array<string>>] */
}
/*
* lua_ap_requestbody; r:requestbody([filename]) - Reads or stores the request
* body
*/
static int lua_ap_requestbody(lua_State *L)
{
const char *filename;
request_rec *r;
apr_off_t maxSize;
r = ap_lua_check_request_rec(L, 1);
filename = luaL_optstring(L, 2, 0);
maxSize = luaL_optint(L, 3, 0);
if (r) {
apr_off_t size;
if (maxSize > 0 && r->remaining > maxSize) {
lua_pushnil(L);
lua_pushliteral(L, "Request body was larger than the permitted size.");
return 2;
}
if (r->method_number != M_POST && r->method_number != M_PUT)
return (0);
if (!filename) {
const char *data;
if (lua_read_body(r, &data, &size, maxSize) != OK)
return (0);
lua_pushlstring(L, data, (size_t) size);
lua_pushinteger(L, (lua_Integer) size);
return (2);
} else {
apr_status_t rc;
apr_file_t *file;
rc = apr_file_open(&file, filename, APR_CREATE | APR_FOPEN_WRITE,
APR_FPROT_OS_DEFAULT, r->pool);
lua_settop(L, 0);
if (rc == APR_SUCCESS) {
rc = lua_write_body(r, file, &size);
apr_file_close(file);
if (rc != OK) {
lua_pushboolean(L, 0);
return 1;
}
lua_pushinteger(L, (lua_Integer) size);
return (1);
} else
lua_pushboolean(L, 0);
return (1);
}
}
return (0);
}
/* wrap ap_rputs as r:puts(String) */
static int req_puts(lua_State *L)
{
request_rec *r = ap_lua_check_request_rec(L, 1);
int argc = lua_gettop(L);
int i;
for (i = 2; i <= argc; i++) {
ap_rputs(luaL_checkstring(L, i), r);
}
return 0;
}
/* wrap ap_rwrite as r:write(String) */
static int req_write(lua_State *L)
{
request_rec *r = ap_lua_check_request_rec(L, 1);
size_t n;
int rv;
const char *buf = luaL_checklstring(L, 2, &n);
rv = ap_rwrite((void *) buf, n, r);
lua_pushinteger(L, rv);
return 1;
}
/* r:addoutputfilter(name|function) */
static int req_add_output_filter(lua_State *L)
{
request_rec *r = ap_lua_check_request_rec(L, 1);
const char *name = luaL_checkstring(L, 2);
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01485) "adding output filter %s",
name);
ap_add_output_filter(name, L, r, r->connection);
return 0;
}
/* wrap ap_construct_url as r:construct_url(String) */
static int req_construct_url(lua_State *L)
{
request_rec *r = ap_lua_check_request_rec(L, 1);
const char *name = luaL_checkstring(L, 2);
lua_pushstring(L, ap_construct_url(r->pool, name, r));
return 1;
}
/* wrap ap_escape_html r:escape_html(String) */
static int req_escape_html(lua_State *L)
{
request_rec *r = ap_lua_check_request_rec(L, 1);
const char *s = luaL_checkstring(L, 2);
lua_pushstring(L, ap_escape_html(r->pool, s));
return 1;
}
/* wrap optional ssl_var_lookup as r:ssl_var_lookup(String) */
static int req_ssl_var_lookup(lua_State *L)
{
request_rec *r = ap_lua_check_request_rec(L, 1);
const char *s = luaL_checkstring(L, 2);
const char *res = ap_lua_ssl_val(r->pool, r->server, r->connection, r,
(char *)s);
lua_pushstring(L, res);
return 1;
}
/* BEGIN dispatch mathods for request_rec fields */
/* not really a field, but we treat it like one */
static const char *req_document_root(request_rec *r)
{
return ap_document_root(r);
}
static const char *req_context_prefix(request_rec *r)
{
return ap_context_prefix(r);
}
static const char *req_context_document_root(request_rec *r)
{
return ap_context_document_root(r);
}
static char *req_uri_field(request_rec *r)
{
return r->uri;
}
static const char *req_method_field(request_rec *r)
{
return r->method;
}
static const char *req_handler_field(request_rec *r)
{
return r->handler;
}
static const char *req_proxyreq_field(request_rec *r)
{
switch (r->proxyreq) {
case PROXYREQ_NONE: return "PROXYREQ_NONE";
case PROXYREQ_PROXY: return "PROXYREQ_PROXY";
case PROXYREQ_REVERSE: return "PROXYREQ_REVERSE";
case PROXYREQ_RESPONSE: return "PROXYREQ_RESPONSE";
default: return NULL;
}
}
static const char *req_hostname_field(request_rec *r)
{
return r->hostname;
}
static const char *req_args_field(request_rec *r)
{
return r->args;
}
static const char *req_path_info_field(request_rec *r)
{
return r->path_info;
}
static const char *req_canonical_filename_field(request_rec *r)
{
return r->canonical_filename;
}
static const char *req_filename_field(request_rec *r)
{
return r->filename;
}
static const char *req_user_field(request_rec *r)
{
return r->user;
}
static const char *req_unparsed_uri_field(request_rec *r)
{
return r->unparsed_uri;
}
static const char *req_ap_auth_type_field(request_rec *r)
{
return r->ap_auth_type;
}
static const char *req_content_encoding_field(request_rec *r)
{
return r->content_encoding;
}
static const char *req_content_type_field(request_rec *r)
{
return r->content_type;
}
static const char *req_range_field(request_rec *r)
{
return r->range;
}
static const char *req_protocol_field(request_rec *r)
{
return r->protocol;
}
static const char *req_the_request_field(request_rec *r)
{
return r->the_request;
}
static const char *req_log_id_field(request_rec *r)
{
return r->log_id;
}
static const char *req_useragent_ip_field(request_rec *r)
{
return r->useragent_ip;
}
static int req_remaining_field(request_rec *r)
{
return r->remaining;
}
static int req_status_field(request_rec *r)
{
return r->status;
}
static int req_assbackwards_field(request_rec *r)
{
return r->assbackwards;
}
static req_table_t* req_headers_in(request_rec *r)
{
req_table_t* t = apr_palloc(r->pool, sizeof(req_table_t));
t->r = r;
t->t = r->headers_in;
t->n = "headers_in";
return t;
}
static req_table_t* req_headers_out(request_rec *r)
{
req_table_t* t = apr_palloc(r->pool, sizeof(req_table_t));
t->r = r;
t->t = r->headers_out;
t->n = "headers_out";
return t;
}
static req_table_t* req_err_headers_out(request_rec *r)
{
req_table_t* t = apr_palloc(r->pool, sizeof(req_table_t));
t->r = r;
t->t = r->err_headers_out;
t->n = "err_headers_out";
return t;
}
static req_table_t* req_subprocess_env(request_rec *r)
{
req_table_t* t = apr_palloc(r->pool, sizeof(req_table_t));
t->r = r;
t->t = r->subprocess_env;
t->n = "subprocess_env";
return t;
}
static req_table_t* req_notes(request_rec *r)
{
req_table_t* t = apr_palloc(r->pool, sizeof(req_table_t));
t->r = r;
t->t = r->notes;
t->n = "notes";
return t;
}
static int req_ssl_is_https_field(request_rec *r)
{
return ap_lua_ssl_is_https(r->connection);
}
static int req_ap_get_server_port(request_rec *r)
{
return (int) ap_get_server_port(r);
}
static int lua_ap_rflush (lua_State *L) {
int returnValue;
request_rec *r;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
returnValue = ap_rflush(r);
lua_pushboolean(L, (returnValue == 0));
return 1;
}
static const char* lua_ap_options(request_rec* r)
{
int opts;
opts = ap_allow_options(r);
return apr_psprintf(r->pool, "%s %s %s %s %s %s", (opts&OPT_INDEXES) ? "Indexes" : "", (opts&OPT_INCLUDES) ? "Includes" : "", (opts&OPT_SYM_LINKS) ? "FollowSymLinks" : "", (opts&OPT_EXECCGI) ? "ExecCGI" : "", (opts&OPT_MULTI) ? "MultiViews" : "", (opts&OPT_ALL) == OPT_ALL ? "All" : "" );
}
static const char* lua_ap_allowoverrides(request_rec* r)
{
int opts;
opts = ap_allow_overrides(r);
if ( (opts & OR_ALL) == OR_ALL) {
return "All";
}
else if (opts == OR_NONE) {
return "None";
}
return apr_psprintf(r->pool, "%s %s %s %s %s", (opts & OR_LIMIT) ? "Limit" : "", (opts & OR_OPTIONS) ? "Options" : "", (opts & OR_FILEINFO) ? "FileInfo" : "", (opts & OR_AUTHCFG) ? "AuthCfg" : "", (opts & OR_INDEXES) ? "Indexes" : "" );
}
static int lua_ap_started(request_rec* r)
{
return (int)(ap_scoreboard_image->global->restart_time / 1000000);
}
static const char* lua_ap_basic_auth_pw(request_rec* r)
{
const char* pw = NULL;
ap_get_basic_auth_pw(r, &pw);
return pw ? pw : "";
}
static int lua_ap_limit_req_body(request_rec* r)
{
return (int) ap_get_limit_req_body(r);
}
static int lua_ap_is_initial_req(request_rec *r)
{
return ap_is_initial_req(r);
}
static int lua_ap_some_auth_required(request_rec *r)
{
return ap_some_auth_required(r);
}
static int lua_ap_sendfile(lua_State *L)
{
apr_finfo_t file_info;
const char *filename;
request_rec *r;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TSTRING);
r = ap_lua_check_request_rec(L, 1);
filename = lua_tostring(L, 2);
apr_stat(&file_info, filename, APR_FINFO_MIN, r->pool);
if (file_info.filetype == APR_NOFILE || file_info.filetype == APR_DIR) {
lua_pushboolean(L, 0);
}
else {
apr_size_t sent;
apr_status_t rc;
apr_file_t *file;
rc = apr_file_open(&file, filename, APR_READ, APR_OS_DEFAULT,
r->pool);
if (rc == APR_SUCCESS) {
ap_send_fd(file, r, 0, (apr_size_t)file_info.size, &sent);
apr_file_close(file);
lua_pushinteger(L, sent);
}
else {
lua_pushboolean(L, 0);
}
}
return (1);
}
/*
* lua_apr_b64encode; r:encode_base64(string) - encodes a string to Base64
* format
*/
static int lua_apr_b64encode(lua_State *L)
{
const char *plain;
char *encoded;
size_t plain_len, encoded_len;
request_rec *r;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
plain = lua_tolstring(L, 2, &plain_len);
encoded_len = apr_base64_encode_len(plain_len);
if (encoded_len) {
encoded = apr_palloc(r->pool, encoded_len);
encoded_len = apr_base64_encode(encoded, plain, plain_len);
if (encoded_len > 0 && encoded[encoded_len - 1] == '\0')
encoded_len--;
lua_pushlstring(L, encoded, encoded_len);
return 1;
}
return 0;
}
/*
* lua_apr_b64decode; r:decode_base64(string) - decodes a Base64 string
*/
static int lua_apr_b64decode(lua_State *L)
{
const char *encoded;
char *plain;
size_t encoded_len, decoded_len;
request_rec *r;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
encoded = lua_tolstring(L, 2, &encoded_len);
decoded_len = apr_base64_decode_len(encoded);
if (decoded_len) {
plain = apr_palloc(r->pool, decoded_len);
decoded_len = apr_base64_decode(plain, encoded);
if (decoded_len > 0 && plain[decoded_len - 1] == '\0')
decoded_len--;
lua_pushlstring(L, plain, decoded_len);
return 1;
}
return 0;
}
/*
* lua_ap_unescape; r:unescape(string) - Unescapes an URL-encoded string
*/
static int lua_ap_unescape(lua_State *L)
{
const char *escaped;
char *plain;
size_t x,
y;
request_rec *r;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
escaped = lua_tolstring(L, 2, &x);
plain = apr_pstrdup(r->pool, escaped);
y = ap_unescape_urlencoded(plain);
if (!y) {
lua_pushstring(L, plain);
return 1;
}
return 0;
}
/*
* lua_ap_escape; r:escape(string) - URL-escapes a string
*/
static int lua_ap_escape(lua_State *L)
{
const char *plain;
char *escaped;
size_t x;
request_rec *r;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
plain = lua_tolstring(L, 2, &x);
escaped = ap_escape_urlencoded(r->pool, plain);
lua_pushstring(L, escaped);
return 1;
}
/*
* lua_apr_md5; r:md5(string) - Calculates an MD5 digest of a string
*/
static int lua_apr_md5(lua_State *L)
{
const char *buffer;
char *result;
size_t len;
request_rec *r;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
buffer = lua_tolstring(L, 2, &len);
result = ap_md5_binary(r->pool, (const unsigned char *)buffer, len);
lua_pushstring(L, result);
return 1;
}
/*
* lua_apr_sha1; r:sha1(string) - Calculates the SHA1 digest of a string
*/
static int lua_apr_sha1(lua_State *L)
{
unsigned char digest[APR_SHA1_DIGESTSIZE];
apr_sha1_ctx_t sha1;
const char *buffer;
char *result;
size_t len;
request_rec *r;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
result = apr_pcalloc(r->pool, sizeof(digest) * 2 + 1);
buffer = lua_tolstring(L, 2, &len);
apr_sha1_init(&sha1);
apr_sha1_update(&sha1, buffer, len);
apr_sha1_final(digest, &sha1);
ap_bin2hex(digest, sizeof(digest), result);
lua_pushstring(L, result);
return 1;
}
/*
* lua_apr_htpassword; r:htpassword(string [, algorithm [, cost]]) - Creates
* a htpassword hash from a string
*/
static int lua_apr_htpassword(lua_State *L)
{
passwd_ctx ctx = { 0 };
request_rec *r;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
ctx.passwd = apr_pstrdup(r->pool, lua_tostring(L, 2));
ctx.alg = luaL_optinteger(L, 3, ALG_APMD5);
ctx.cost = luaL_optinteger(L, 4, 0);
ctx.pool = r->pool;
ctx.out = apr_pcalloc(r->pool, MAX_PASSWD_LEN);
ctx.out_len = MAX_PASSWD_LEN;
if (mk_password_hash(&ctx)) {
lua_pushboolean(L, 0);
lua_pushstring(L, ctx.errstr);
return 2;
} else {
lua_pushstring(L, ctx.out);
}
return 1;
}
/*
* lua_apr_touch; r:touch(string [, time]) - Sets mtime of a file
*/
static int lua_apr_touch(lua_State *L)
{
request_rec *r;
const char *path;
apr_status_t status;
apr_time_t mtime;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
path = lua_tostring(L, 2);
mtime = (apr_time_t)luaL_optnumber(L, 3, (lua_Number)apr_time_now());
status = apr_file_mtime_set(path, mtime, r->pool);
lua_pushboolean(L, (status == 0));
return 1;
}
/*
* lua_apr_mkdir; r:mkdir(string [, permissions]) - Creates a directory
*/
static int lua_apr_mkdir(lua_State *L)
{
request_rec *r;
const char *path;
apr_status_t status;
apr_fileperms_t perms;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
path = lua_tostring(L, 2);
perms = luaL_optinteger(L, 3, APR_OS_DEFAULT);
status = apr_dir_make(path, perms, r->pool);
lua_pushboolean(L, (status == 0));
return 1;
}
/*
* lua_apr_mkrdir; r:mkrdir(string [, permissions]) - Creates directories
* recursive
*/
static int lua_apr_mkrdir(lua_State *L)
{
request_rec *r;
const char *path;
apr_status_t status;
apr_fileperms_t perms;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
path = lua_tostring(L, 2);
perms = luaL_optinteger(L, 3, APR_OS_DEFAULT);
status = apr_dir_make_recursive(path, perms, r->pool);
lua_pushboolean(L, (status == 0));
return 1;
}
/*
* lua_apr_rmdir; r:rmdir(string) - Removes a directory
*/
static int lua_apr_rmdir(lua_State *L)
{
request_rec *r;
const char *path;
apr_status_t status;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
path = lua_tostring(L, 2);
status = apr_dir_remove(path, r->pool);
lua_pushboolean(L, (status == 0));
return 1;
}
/*
* lua_apr_date_parse_rfc; r.date_parse_rfc(string) - Parses a DateTime string
*/
static int lua_apr_date_parse_rfc(lua_State *L)
{
const char *input;
apr_time_t result;
luaL_checktype(L, 1, LUA_TSTRING);
input = lua_tostring(L, 1);
result = apr_date_parse_rfc(input);
if (result == 0)
return 0;
lua_pushnumber(L, (lua_Number)(result / APR_USEC_PER_SEC));
return 1;
}
/*
* lua_ap_mpm_query; r:mpm_query(info) - Queries for MPM info
*/
static int lua_ap_mpm_query(lua_State *L)
{
int x,
y;
x = lua_tointeger(L, 1);
ap_mpm_query(x, &y);
lua_pushinteger(L, y);
return 1;
}
/*
* lua_ap_expr; r:expr(string) - Evaluates an expr statement.
*/
static int lua_ap_expr(lua_State *L)
{
request_rec *r;
int x = 0;
const char *expr,
*err;
ap_expr_info_t res;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TSTRING);
r = ap_lua_check_request_rec(L, 1);
expr = lua_tostring(L, 2);
res.filename = NULL;
res.flags = 0;
res.line_number = 0;
res.module_index = APLOG_MODULE_INDEX;
err = ap_expr_parse(r->pool, r->pool, &res, expr, NULL);
if (!err) {
x = ap_expr_exec(r, &res, &err);
lua_pushboolean(L, x);
if (x < 0) {
lua_pushstring(L, err);
return 2;
}
return 1;
} else {
lua_pushboolean(L, 0);
lua_pushstring(L, err);
return 2;
}
lua_pushboolean(L, 0);
return 1;
}
/*
* lua_ap_regex; r:regex(string, pattern [, flags])
* - Evaluates a regex and returns captures if matched
*/
static int lua_ap_regex(lua_State *L)
{
request_rec *r;
int i,
rv,
flags;
const char *pattern,
*source;
char *err;
ap_regex_t regex;
ap_regmatch_t matches[MODLUA_MAX_REG_MATCH+1];
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TSTRING);
luaL_checktype(L, 3, LUA_TSTRING);
r = ap_lua_check_request_rec(L, 1);
source = lua_tostring(L, 2);
pattern = lua_tostring(L, 3);
flags = luaL_optinteger(L, 4, 0);
rv = ap_regcomp(®ex, pattern, flags);
if (rv) {
lua_pushboolean(L, 0);
err = apr_palloc(r->pool, 256);
ap_regerror(rv, ®ex, err, 256);
lua_pushstring(L, err);
return 2;
}
if (regex.re_nsub > MODLUA_MAX_REG_MATCH) {
lua_pushboolean(L, 0);
err = apr_palloc(r->pool, 64);
apr_snprintf(err, 64,
"regcomp found %d matches; only %d allowed.",
regex.re_nsub, MODLUA_MAX_REG_MATCH);
lua_pushstring(L, err);
return 2;
}
rv = ap_regexec(®ex, source, MODLUA_MAX_REG_MATCH, matches, 0);
if (rv == AP_REG_NOMATCH) {
lua_pushboolean(L, 0);
return 1;
}
lua_newtable(L);
for (i = 0; i <= regex.re_nsub; i++) {
lua_pushinteger(L, i);
if (matches[i].rm_so >= 0 && matches[i].rm_eo >= 0)
lua_pushstring(L,
apr_pstrndup(r->pool, source + matches[i].rm_so,
matches[i].rm_eo - matches[i].rm_so));
else
lua_pushnil(L);
lua_settable(L, -3);
}
return 1;
}
/*
* lua_ap_scoreboard_process; r:scoreboard_process(a) - returns scoreboard info
*/
static int lua_ap_scoreboard_process(lua_State *L)
{
int i;
process_score *ps_record;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TNUMBER);
i = lua_tointeger(L, 2);
ps_record = ap_get_scoreboard_process(i);
if (ps_record) {
lua_newtable(L);
lua_pushstring(L, "connections");
lua_pushnumber(L, ps_record->connections);
lua_settable(L, -3);
lua_pushstring(L, "keepalive");
lua_pushnumber(L, ps_record->keep_alive);
lua_settable(L, -3);
lua_pushstring(L, "lingering_close");
lua_pushnumber(L, ps_record->lingering_close);
lua_settable(L, -3);
lua_pushstring(L, "pid");
lua_pushnumber(L, ps_record->pid);
lua_settable(L, -3);
lua_pushstring(L, "suspended");
lua_pushnumber(L, ps_record->suspended);
lua_settable(L, -3);
lua_pushstring(L, "write_completion");
lua_pushnumber(L, ps_record->write_completion);
lua_settable(L, -3);
lua_pushstring(L, "not_accepting");
lua_pushnumber(L, ps_record->not_accepting);
lua_settable(L, -3);
lua_pushstring(L, "quiescing");
lua_pushnumber(L, ps_record->quiescing);
lua_settable(L, -3);
return 1;
}
return 0;
}
/*
* lua_ap_scoreboard_worker; r:scoreboard_worker(proc, thread) - Returns thread
* info
*/
static int lua_ap_scoreboard_worker(lua_State *L)
{
int i, j;
worker_score *ws_record = NULL;
request_rec *r = NULL;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TNUMBER);
luaL_checktype(L, 3, LUA_TNUMBER);
r = ap_lua_check_request_rec(L, 1);
if (!r) return 0;
i = lua_tointeger(L, 2);
j = lua_tointeger(L, 3);
ws_record = apr_palloc(r->pool, sizeof *ws_record);
ap_copy_scoreboard_worker(ws_record, i, j);
if (ws_record) {
lua_newtable(L);
lua_pushstring(L, "access_count");
lua_pushnumber(L, ws_record->access_count);
lua_settable(L, -3);
lua_pushstring(L, "bytes_served");
lua_pushnumber(L, (lua_Number) ws_record->bytes_served);
lua_settable(L, -3);
lua_pushstring(L, "client");
lua_pushstring(L, ws_record->client);
lua_settable(L, -3);
lua_pushstring(L, "conn_bytes");
lua_pushnumber(L, (lua_Number) ws_record->conn_bytes);
lua_settable(L, -3);
lua_pushstring(L, "conn_count");
lua_pushnumber(L, ws_record->conn_count);
lua_settable(L, -3);
lua_pushstring(L, "generation");
lua_pushnumber(L, ws_record->generation);
lua_settable(L, -3);
lua_pushstring(L, "last_used");
lua_pushnumber(L, (lua_Number) ws_record->last_used);
lua_settable(L, -3);
lua_pushstring(L, "pid");
lua_pushnumber(L, ws_record->pid);
lua_settable(L, -3);
lua_pushstring(L, "request");
lua_pushstring(L, ws_record->request);
lua_settable(L, -3);
lua_pushstring(L, "start_time");
lua_pushnumber(L, (lua_Number) ws_record->start_time);
lua_settable(L, -3);
lua_pushstring(L, "status");
lua_pushnumber(L, ws_record->status);
lua_settable(L, -3);
lua_pushstring(L, "stop_time");
lua_pushnumber(L, (lua_Number) ws_record->stop_time);
lua_settable(L, -3);
lua_pushstring(L, "tid");
lua_pushinteger(L, (lua_Integer) ws_record->tid);
lua_settable(L, -3);
lua_pushstring(L, "vhost");
lua_pushstring(L, ws_record->vhost);
lua_settable(L, -3);
#ifdef HAVE_TIMES
lua_pushstring(L, "stimes");
lua_pushnumber(L, ws_record->times.tms_stime);
lua_settable(L, -3);
lua_pushstring(L, "utimes");
lua_pushnumber(L, ws_record->times.tms_utime);
lua_settable(L, -3);
#endif
return 1;
}
return 0;
}
/*
* lua_ap_clock; r:clock() - Returns timestamp with microsecond precision
*/
static int lua_ap_clock(lua_State *L)
{
apr_time_t now;
now = apr_time_now();
lua_pushnumber(L, (lua_Number) now);
return 1;
}
/*
* lua_ap_add_input_filter; r:add_input_filter(name) - Adds an input filter to
* the chain
*/
static int lua_ap_add_input_filter(lua_State *L)
{
request_rec *r;
const char *filterName;
ap_filter_rec_t *filter;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TSTRING);
r = ap_lua_check_request_rec(L, 1);
filterName = lua_tostring(L, 2);
filter = ap_get_input_filter_handle(filterName);
if (filter) {
ap_add_input_filter_handle(filter, NULL, r, r->connection);
lua_pushboolean(L, 1);
} else
lua_pushboolean(L, 0);
return 1;
}
/*
* lua_ap_module_info; r:module_info(mod_name) - Returns information about a
* loaded module
*/
static int lua_ap_module_info(lua_State *L)
{
const char *moduleName;
module *mod;
luaL_checktype(L, 1, LUA_TSTRING);
moduleName = lua_tostring(L, 1);
mod = ap_find_linked_module(moduleName);
if (mod && mod->cmds) {
const command_rec *cmd;
lua_newtable(L);
lua_pushstring(L, "commands");
lua_newtable(L);
for (cmd = mod->cmds; cmd->name; ++cmd) {
lua_pushstring(L, cmd->name);
lua_pushstring(L, cmd->errmsg);
lua_settable(L, -3);
}
lua_settable(L, -3);
return 1;
}
return 0;
}
/*
* lua_ap_runtime_dir_relative: r:runtime_dir_relative(file): Returns the
* filename as relative to the runtime dir
*/
static int lua_ap_runtime_dir_relative(lua_State *L)
{
request_rec *r;
const char *file;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
file = luaL_optstring(L, 2, ".");
lua_pushstring(L, ap_runtime_dir_relative(r->pool, file));
return 1;
}
/*
* lua_ap_set_document_root; r:set_document_root(path) - sets the current doc
* root for the request
*/
static int lua_ap_set_document_root(lua_State *L)
{
request_rec *r;
const char *root;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TSTRING);
r = ap_lua_check_request_rec(L, 1);
root = lua_tostring(L, 2);
ap_set_document_root(r, root);
return 0;
}
/*
* lua_ap_getdir; r:get_direntries(directory) - Gets all entries of a
* directory and returns the directory info as a table
*/
static int lua_ap_getdir(lua_State *L)
{
request_rec *r;
apr_dir_t *thedir;
apr_finfo_t file_info;
apr_status_t status;
const char *directory;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TSTRING);
r = ap_lua_check_request_rec(L, 1);
directory = lua_tostring(L, 2);
if (apr_dir_open(&thedir, directory, r->pool) == APR_SUCCESS) {
int i = 0;
lua_newtable(L);
do {
status = apr_dir_read(&file_info, APR_FINFO_NAME, thedir);
if (APR_STATUS_IS_INCOMPLETE(status)) {
continue; /* ignore un-stat()able files */
}
else if (status != APR_SUCCESS) {
break;
}
lua_pushinteger(L, ++i);
lua_pushstring(L, file_info.name);
lua_settable(L, -3);
} while (1);
apr_dir_close(thedir);
return 1;
}
else {
return 0;
}
}
/*
* lua_ap_stat; r:stat(filename [, wanted]) - Runs stat on a file and
* returns the file info as a table
*/
static int lua_ap_stat(lua_State *L)
{
request_rec *r;
const char *filename;
apr_finfo_t file_info;
apr_int32_t wanted;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TSTRING);
r = ap_lua_check_request_rec(L, 1);
filename = lua_tostring(L, 2);
wanted = luaL_optinteger(L, 3, APR_FINFO_MIN);
if (apr_stat(&file_info, filename, wanted, r->pool) == OK) {
lua_newtable(L);
if (wanted & APR_FINFO_MTIME) {
lua_pushstring(L, "mtime");
lua_pushnumber(L, (lua_Number) file_info.mtime);
lua_settable(L, -3);
}
if (wanted & APR_FINFO_ATIME) {
lua_pushstring(L, "atime");
lua_pushnumber(L, (lua_Number) file_info.atime);
lua_settable(L, -3);
}
if (wanted & APR_FINFO_CTIME) {
lua_pushstring(L, "ctime");
lua_pushnumber(L, (lua_Number) file_info.ctime);
lua_settable(L, -3);
}
if (wanted & APR_FINFO_SIZE) {
lua_pushstring(L, "size");
lua_pushnumber(L, (lua_Number) file_info.size);
lua_settable(L, -3);
}
if (wanted & APR_FINFO_TYPE) {
lua_pushstring(L, "filetype");
lua_pushinteger(L, file_info.filetype);
lua_settable(L, -3);
}
if (wanted & APR_FINFO_PROT) {
lua_pushstring(L, "protection");
lua_pushinteger(L, file_info.protection);
lua_settable(L, -3);
}
return 1;
}
else {
return 0;
}
}
/*
* lua_ap_loaded_modules; r:loaded_modules() - Returns a list of loaded modules
*/
static int lua_ap_loaded_modules(lua_State *L)
{
int i;
lua_newtable(L);
for (i = 0; ap_loaded_modules[i] && ap_loaded_modules[i]->name; i++) {
lua_pushinteger(L, i + 1);
lua_pushstring(L, ap_loaded_modules[i]->name);
lua_settable(L, -3);
}
return 1;
}
/*
* lua_ap_server_info; r:server_info() - Returns server info, such as the
* executable filename, server root, mpm etc
*/
static int lua_ap_server_info(lua_State *L)
{
lua_newtable(L);
lua_pushstring(L, "server_executable");
lua_pushstring(L, ap_server_argv0);
lua_settable(L, -3);
lua_pushstring(L, "server_root");
lua_pushstring(L, ap_server_root);
lua_settable(L, -3);
lua_pushstring(L, "scoreboard_fname");
lua_pushstring(L, ap_scoreboard_fname);
lua_settable(L, -3);
lua_pushstring(L, "server_mpm");
lua_pushstring(L, ap_show_mpm());
lua_settable(L, -3);
return 1;
}
/*
* === Auto-scraped functions ===
*/
/**
* ap_set_context_info: Set context_prefix and context_document_root.
* @param r The request
* @param prefix the URI prefix, without trailing slash
* @param document_root the corresponding directory on disk, without trailing
* slash
* @note If one of prefix of document_root is NULL, the corrsponding
* property will not be changed.
*/
static int lua_ap_set_context_info(lua_State *L)
{
request_rec *r;
const char *prefix;
const char *document_root;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
prefix = lua_tostring(L, 2);
luaL_checktype(L, 3, LUA_TSTRING);
document_root = lua_tostring(L, 3);
ap_set_context_info(r, prefix, document_root);
return 0;
}
/**
* ap_os_escape_path (apr_pool_t *p, const char *path, int partial)
* convert an OS path to a URL in an OS dependant way.
* @param p The pool to allocate from
* @param path The path to convert
* @param partial if set, assume that the path will be appended to something
* with a '/' in it (and thus does not prefix "./")
* @return The converted URL
*/
static int lua_ap_os_escape_path(lua_State *L)
{
char *returnValue;
request_rec *r;
const char *path;
int partial = 0;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
path = lua_tostring(L, 2);
if (lua_isboolean(L, 3))
partial = lua_toboolean(L, 3);
returnValue = ap_os_escape_path(r->pool, path, partial);
lua_pushstring(L, returnValue);
return 1;
}
/**
* ap_escape_logitem (apr_pool_t *p, const char *str)
* Escape a string for logging
* @param p The pool to allocate from
* @param str The string to escape
* @return The escaped string
*/
static int lua_ap_escape_logitem(lua_State *L)
{
char *returnValue;
request_rec *r;
const char *str;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
str = lua_tostring(L, 2);
returnValue = ap_escape_logitem(r->pool, str);
lua_pushstring(L, returnValue);
return 1;
}
/**
* ap_strcmp_match (const char *str, const char *expected)
* Determine if a string matches a patterm containing the wildcards '?' or '*'
* @param str The string to check
* @param expected The pattern to match against
* @param ignoreCase Whether to ignore case when matching
* @return 1 if the two strings match, 0 otherwise
*/
static int lua_ap_strcmp_match(lua_State *L)
{
int returnValue;
const char *str;
const char *expected;
int ignoreCase = 0;
luaL_checktype(L, 1, LUA_TSTRING);
str = lua_tostring(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
expected = lua_tostring(L, 2);
if (lua_isboolean(L, 3))
ignoreCase = lua_toboolean(L, 3);
if (!ignoreCase)
returnValue = ap_strcmp_match(str, expected);
else
returnValue = ap_strcasecmp_match(str, expected);
lua_pushboolean(L, (!returnValue));
return 1;
}
/**
* ap_set_keepalive (request_rec *r)
* Set the keepalive status for this request
* @param r The current request
* @return 1 if keepalive can be set, 0 otherwise
*/
static int lua_ap_set_keepalive(lua_State *L)
{
int returnValue;
request_rec *r;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
returnValue = ap_set_keepalive(r);
lua_pushboolean(L, returnValue);
return 1;
}
/**
* ap_make_etag (request_rec *r, int force_weak)
* Construct an entity tag from the resource information. If it's a real
* file, build in some of the file characteristics.
* @param r The current request
* @param force_weak Force the entity tag to be weak - it could be modified
* again in as short an interval.
* @return The entity tag
*/
static int lua_ap_make_etag(lua_State *L)
{
char *returnValue;
request_rec *r;
int force_weak;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TBOOLEAN);
force_weak = luaL_optint(L, 2, 0);
returnValue = ap_make_etag(r, force_weak);
lua_pushstring(L, returnValue);
return 1;
}
/**
* ap_send_interim_response (request_rec *r, int send_headers)
* Send an interim (HTTP 1xx) response immediately.
* @param r The request
* @param send_headers Whether to send&clear headers in r->headers_out
*/
static int lua_ap_send_interim_response(lua_State *L)
{
request_rec *r;
int send_headers = 0;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
if (lua_isboolean(L, 2))
send_headers = lua_toboolean(L, 2);
ap_send_interim_response(r, send_headers);
return 0;
}
/**
* ap_custom_response (request_rec *r, int status, const char *string)
* Install a custom response handler for a given status
* @param r The current request
* @param status The status for which the custom response should be used
* @param string The custom response. This can be a static string, a file
* or a URL
*/
static int lua_ap_custom_response(lua_State *L)
{
request_rec *r;
int status;
const char *string;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TNUMBER);
status = lua_tointeger(L, 2);
luaL_checktype(L, 3, LUA_TSTRING);
string = lua_tostring(L, 3);
ap_custom_response(r, status, string);
return 0;
}
/**
* ap_exists_config_define (const char *name)
* Check for a definition from the server command line
* @param name The define to check for
* @return 1 if defined, 0 otherwise
*/
static int lua_ap_exists_config_define(lua_State *L)
{
int returnValue;
const char *name;
luaL_checktype(L, 1, LUA_TSTRING);
name = lua_tostring(L, 1);
returnValue = ap_exists_config_define(name);
lua_pushboolean(L, returnValue);
return 1;
}
static int lua_ap_get_server_name_for_url(lua_State *L)
{
const char *servername;
request_rec *r;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
servername = ap_get_server_name_for_url(r);
lua_pushstring(L, servername);
return 1;
}
/* ap_state_query (int query_code) item starts a new field */
static int lua_ap_state_query(lua_State *L)
{
int returnValue;
int query_code;
luaL_checktype(L, 1, LUA_TNUMBER);
query_code = lua_tointeger(L, 1);
returnValue = ap_state_query(query_code);
lua_pushinteger(L, returnValue);
return 1;
}
/*
* lua_ap_usleep; r:usleep(microseconds)
* - Sleep for the specified number of microseconds.
*/
static int lua_ap_usleep(lua_State *L)
{
apr_interval_time_t msec;
luaL_checktype(L, 1, LUA_TNUMBER);
msec = (apr_interval_time_t)lua_tonumber(L, 1);
apr_sleep(msec);
return 0;
}
/* END dispatch methods for request_rec fields */
static int req_dispatch(lua_State *L)
{
apr_hash_t *dispatch;
req_fun_t *rft;
request_rec *r = ap_lua_check_request_rec(L, 1);
const char *name = luaL_checkstring(L, 2);
lua_pop(L, 2);
lua_getfield(L, LUA_REGISTRYINDEX, "Apache2.Request.dispatch");
dispatch = lua_touserdata(L, 1);
lua_pop(L, 1);
rft = apr_hash_get(dispatch, name, APR_HASH_KEY_STRING);
if (rft) {
switch (rft->type) {
case APL_REQ_FUNTYPE_TABLE:{
req_table_t *rs;
req_field_apr_table_f func = (req_field_apr_table_f)rft->fun;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01486)
"request_rec->dispatching %s -> apr table",
name);
rs = (*func)(r);
ap_lua_push_apr_table(L, rs);
return 1;
}
case APL_REQ_FUNTYPE_LUACFUN:{
lua_CFunction func = (lua_CFunction)rft->fun;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01487)
"request_rec->dispatching %s -> lua_CFunction",
name);
lua_pushcfunction(L, func);
return 1;
}
case APL_REQ_FUNTYPE_STRING:{
req_field_string_f func = (req_field_string_f)rft->fun;
char *rs;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01488)
"request_rec->dispatching %s -> string", name);
rs = (*func) (r);
lua_pushstring(L, rs);
return 1;
}
case APL_REQ_FUNTYPE_INT:{
req_field_int_f func = (req_field_int_f)rft->fun;
int rs;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01489)
"request_rec->dispatching %s -> int", name);
rs = (*func) (r);
lua_pushinteger(L, rs);
return 1;
}
case APL_REQ_FUNTYPE_BOOLEAN:{
req_field_int_f func = (req_field_int_f)rft->fun;
int rs;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01490)
"request_rec->dispatching %s -> boolean", name);
rs = (*func) (r);
lua_pushboolean(L, rs);
return 1;
}
}
}
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01491) "nothing for %s", name);
return 0;
}
/* helper function for the logging functions below */
static int req_log_at(lua_State *L, int level)
{
const char *msg;
request_rec *r = ap_lua_check_request_rec(L, 1);
lua_Debug dbg;
lua_getstack(L, 1, &dbg);
lua_getinfo(L, "Sl", &dbg);
msg = luaL_checkstring(L, 2);
ap_log_rerror(dbg.source, dbg.currentline, APLOG_MODULE_INDEX, level, 0,
r, "%s", msg);
return 0;
}
/* r:debug(String) and friends which use apache logging */
static int req_emerg(lua_State *L)
{
return req_log_at(L, APLOG_EMERG);
}
static int req_alert(lua_State *L)
{
return req_log_at(L, APLOG_ALERT);
}
static int req_crit(lua_State *L)
{
return req_log_at(L, APLOG_CRIT);
}
static int req_err(lua_State *L)
{
return req_log_at(L, APLOG_ERR);
}
static int req_warn(lua_State *L)
{
return req_log_at(L, APLOG_WARNING);
}
static int req_notice(lua_State *L)
{
return req_log_at(L, APLOG_NOTICE);
}
static int req_info(lua_State *L)
{
return req_log_at(L, APLOG_INFO);
}
static int req_debug(lua_State *L)
{
return req_log_at(L, APLOG_DEBUG);
}
static int lua_ivm_get(lua_State *L)
{
const char *key, *raw_key;
apr_pool_t *pool;
lua_ivm_object *object = NULL;
request_rec *r = ap_lua_check_request_rec(L, 1);
key = luaL_checkstring(L, 2);
raw_key = apr_pstrcat(r->pool, "lua_ivm_", key, NULL);
apr_global_mutex_lock(lua_ivm_mutex);
pool = *((apr_pool_t**) apr_shm_baseaddr_get(lua_ivm_shm));
apr_pool_userdata_get((void **)&object, raw_key, pool);
if (object) {
if (object->type == LUA_TBOOLEAN) lua_pushboolean(L, (int) object->number);
else if (object->type == LUA_TNUMBER) lua_pushnumber(L, object->number);
else if (object->type == LUA_TSTRING) lua_pushlstring(L, object->vb.buf, object->size);
apr_global_mutex_unlock(lua_ivm_mutex);
return 1;
}
else {
apr_global_mutex_unlock(lua_ivm_mutex);
return 0;
}
}
static int lua_ivm_set(lua_State *L)
{
const char *key, *raw_key;
const char *value = NULL;
apr_pool_t *pool;
size_t str_len;
lua_ivm_object *object = NULL;
request_rec *r = ap_lua_check_request_rec(L, 1);
key = luaL_checkstring(L, 2);
luaL_checkany(L, 3);
raw_key = apr_pstrcat(r->pool, "lua_ivm_", key, NULL);
apr_global_mutex_lock(lua_ivm_mutex);
pool = *((apr_pool_t**) apr_shm_baseaddr_get(lua_ivm_shm));
apr_pool_userdata_get((void **)&object, raw_key, pool);
if (!object) {
object = apr_pcalloc(pool, sizeof(lua_ivm_object));
ap_varbuf_init(pool, &object->vb, 2);
object->size = 1;
object->vb_size = 1;
}
object->type = lua_type(L, 3);
if (object->type == LUA_TNUMBER) object->number = lua_tonumber(L, 3);
else if (object->type == LUA_TBOOLEAN) object->number = lua_tonumber(L, 3);
else if (object->type == LUA_TSTRING) {
value = lua_tolstring(L, 3, &str_len);
str_len++; /* add trailing \0 */
if ( str_len > object->vb_size) {
ap_varbuf_grow(&object->vb, str_len);
object->vb_size = str_len;
}
object->size = str_len-1;
memset(object->vb.buf, 0, str_len);
memcpy(object->vb.buf, value, str_len-1);
}
apr_pool_userdata_set(object, raw_key, NULL, pool);
apr_global_mutex_unlock(lua_ivm_mutex);
return 0;
}
static int lua_get_cookie(lua_State *L)
{
const char *key, *cookie;
request_rec *r = ap_lua_check_request_rec(L, 1);
key = luaL_checkstring(L, 2);
cookie = NULL;
ap_cookie_read(r, key, &cookie, 0);
if (cookie != NULL) {
lua_pushstring(L, cookie);
return 1;
}
return 0;
}
static int lua_set_cookie(lua_State *L)
{
const char *key, *value, *out, *path = "", *domain = "";
const char *strexpires = "", *strdomain = "", *strpath = "";
int secure = 0, expires = 0, httponly = 0;
char cdate[APR_RFC822_DATE_LEN+1];
apr_status_t rv;
request_rec *r = ap_lua_check_request_rec(L, 1);
/* New >= 2.4.8 method: */
if (lua_istable(L, 2)) {
/* key */
lua_pushstring(L, "key");
lua_gettable(L, -2);
key = luaL_checkstring(L, -1);
lua_pop(L, 1);
/* value */
lua_pushstring(L, "value");
lua_gettable(L, -2);
value = luaL_checkstring(L, -1);
lua_pop(L, 1);
/* expiry */
lua_pushstring(L, "expires");
lua_gettable(L, -2);
expires = luaL_optint(L, -1, 0);
lua_pop(L, 1);
/* secure */
lua_pushstring(L, "secure");
lua_gettable(L, -2);
if (lua_isboolean(L, -1)) {
secure = lua_toboolean(L, -1);
}
lua_pop(L, 1);
/* httponly */
lua_pushstring(L, "httponly");
lua_gettable(L, -2);
if (lua_isboolean(L, -1)) {
httponly = lua_toboolean(L, -1);
}
lua_pop(L, 1);
/* path */
lua_pushstring(L, "path");
lua_gettable(L, -2);
path = luaL_optstring(L, -1, "/");
lua_pop(L, 1);
/* domain */
lua_pushstring(L, "domain");
lua_gettable(L, -2);
domain = luaL_optstring(L, -1, "");
lua_pop(L, 1);
}
/* Old <= 2.4.7 method: */
else {
key = luaL_checkstring(L, 2);
value = luaL_checkstring(L, 3);
secure = 0;
if (lua_isboolean(L, 4)) {
secure = lua_toboolean(L, 4);
}
expires = luaL_optinteger(L, 5, 0);
}
/* Calculate expiry if set */
if (expires > 0) {
rv = apr_rfc822_date(cdate, apr_time_from_sec(expires));
if (rv == APR_SUCCESS) {
strexpires = apr_psprintf(r->pool, "Expires=%s;", cdate);
}
}
/* Create path segment */
if (path != NULL && strlen(path) > 0) {
strpath = apr_psprintf(r->pool, "Path=%s;", path);
}
/* Create domain segment */
if (domain != NULL && strlen(domain) > 0) {
/* Domain does NOT like quotes in most browsers, so let's avoid that */
strdomain = apr_psprintf(r->pool, "Domain=%s;", domain);
}
/* URL-encode key/value */
value = ap_escape_urlencoded(r->pool, value);
key = ap_escape_urlencoded(r->pool, key);
/* Create the header */
out = apr_psprintf(r->pool, "%s=%s; %s %s %s %s %s", key, value,
secure ? "Secure;" : "",
expires ? strexpires : "",
httponly ? "HttpOnly;" : "",
strlen(strdomain) ? strdomain : "",
strlen(strpath) ? strpath : "");
apr_table_add(r->err_headers_out, "Set-Cookie", out);
return 0;
}
static apr_uint64_t ap_ntoh64(const apr_uint64_t *input)
{
apr_uint64_t rval;
unsigned char *data = (unsigned char *)&rval;
if (APR_IS_BIGENDIAN) {
return *input;
}
data[0] = *input >> 56;
data[1] = *input >> 48;
data[2] = *input >> 40;
data[3] = *input >> 32;
data[4] = *input >> 24;
data[5] = *input >> 16;
data[6] = *input >> 8;
data[7] = *input >> 0;
return rval;
}
static int lua_websocket_greet(lua_State *L)
{
const char *key = NULL;
unsigned char digest[APR_SHA1_DIGESTSIZE];
apr_sha1_ctx_t sha1;
char *encoded;
int encoded_len;
request_rec *r = ap_lua_check_request_rec(L, 1);
key = apr_table_get(r->headers_in, "Sec-WebSocket-Key");
if (key != NULL) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Websocket: Got websocket key: %s", key);
key = apr_pstrcat(r->pool, key, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
NULL);
apr_sha1_init(&sha1);
apr_sha1_update(&sha1, key, strlen(key));
apr_sha1_final(digest, &sha1);
encoded_len = apr_base64_encode_len(APR_SHA1_DIGESTSIZE);
if (encoded_len) {
encoded = apr_palloc(r->pool, encoded_len);
encoded_len = apr_base64_encode(encoded, (char*) digest, APR_SHA1_DIGESTSIZE);
r->status = 101;
apr_table_set(r->headers_out, "Upgrade", "websocket");
apr_table_set(r->headers_out, "Connection", "Upgrade");
apr_table_set(r->headers_out, "Sec-WebSocket-Accept", encoded);
/* Trick httpd into NOT using the chunked filter, IMPORTANT!!!111*/
apr_table_set(r->headers_out, "Transfer-Encoding", "chunked");
r->clength = 0;
r->bytes_sent = 0;
r->read_chunked = 0;
ap_rflush(r);
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Websocket: Upgraded from HTTP to Websocket");
lua_pushboolean(L, 1);
return 1;
}
}
ap_log_rerror(APLOG_MARK, APLOG_NOTICE, 0, r, APLOGNO(02666)
"Websocket: Upgrade from HTTP to Websocket failed");
return 0;
}
static apr_status_t lua_websocket_readbytes(conn_rec* c, char* buffer,
apr_off_t len)
{
apr_bucket_brigade *brigade = apr_brigade_create(c->pool, c->bucket_alloc);
apr_status_t rv;
rv = ap_get_brigade(c->input_filters, brigade, AP_MODE_READBYTES,
APR_BLOCK_READ, len);
if (rv == APR_SUCCESS) {
if (!APR_BRIGADE_EMPTY(brigade)) {
apr_bucket* bucket = APR_BRIGADE_FIRST(brigade);
const char* data = NULL;
apr_size_t data_length = 0;
rv = apr_bucket_read(bucket, &data, &data_length, APR_BLOCK_READ);
if (rv == APR_SUCCESS) {
memcpy(buffer, data, len);
}
apr_bucket_delete(bucket);
}
}
apr_brigade_cleanup(brigade);
return rv;
}
static int lua_websocket_peek(lua_State *L)
{
apr_status_t rv;
apr_bucket_brigade *brigade;
request_rec *r = ap_lua_check_request_rec(L, 1);
brigade = apr_brigade_create(r->connection->pool,
r->connection->bucket_alloc);
rv = ap_get_brigade(r->connection->input_filters, brigade,
AP_MODE_READBYTES, APR_NONBLOCK_READ, 1);
if (rv == APR_SUCCESS) {
lua_pushboolean(L, 1);
}
else {
lua_pushboolean(L, 0);
}
apr_brigade_cleanup(brigade);
return 1;
}
static int lua_websocket_read(lua_State *L)
{
apr_socket_t *sock;
apr_status_t rv;
int do_read = 1;
int n = 0;
apr_size_t len = 1;
apr_size_t plen = 0;
unsigned short payload_short = 0;
apr_uint64_t payload_long = 0;
unsigned char *mask_bytes;
char byte;
int plaintext;
request_rec *r = ap_lua_check_request_rec(L, 1);
plaintext = ap_lua_ssl_is_https(r->connection) ? 0 : 1;
mask_bytes = apr_pcalloc(r->pool, 4);
sock = ap_get_conn_socket(r->connection);
while (do_read) {
do_read = 0;
/* Get opcode and FIN bit */
if (plaintext) {
rv = apr_socket_recv(sock, &byte, &len);
}
else {
rv = lua_websocket_readbytes(r->connection, &byte, 1);
}
if (rv == APR_SUCCESS) {
unsigned char ubyte, fin, opcode, mask, payload;
ubyte = (unsigned char)byte;
/* fin bit is the first bit */
fin = ubyte >> (CHAR_BIT - 1);
/* opcode is the last four bits (there's 3 reserved bits we don't care about) */
opcode = ubyte & 0xf;
/* Get the payload length and mask bit */
if (plaintext) {
rv = apr_socket_recv(sock, &byte, &len);
}
else {
rv = lua_websocket_readbytes(r->connection, &byte, 1);
}
if (rv == APR_SUCCESS) {
ubyte = (unsigned char)byte;
/* Mask is the first bit */
mask = ubyte >> (CHAR_BIT - 1);
/* Payload is the last 7 bits */
payload = ubyte & 0x7f;
plen = payload;
/* Extended payload? */
if (payload == 126) {
len = 2;
if (plaintext) {
/* XXX: apr_socket_recv does not receive len bits, only up to len bits! */
rv = apr_socket_recv(sock, (char*) &payload_short, &len);
}
else {
rv = lua_websocket_readbytes(r->connection,
(char*) &payload_short, 2);
}
payload_short = ntohs(payload_short);
if (rv == APR_SUCCESS) {
plen = payload_short;
}
else {
return 0;
}
}
/* Super duper extended payload? */
if (payload == 127) {
len = 8;
if (plaintext) {
rv = apr_socket_recv(sock, (char*) &payload_long, &len);
}
else {
rv = lua_websocket_readbytes(r->connection,
(char*) &payload_long, 8);
}
if (rv == APR_SUCCESS) {
plen = ap_ntoh64(&payload_long);
}
else {
return 0;
}
}
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Websocket: Reading %" APR_SIZE_T_FMT " (%s) bytes, masking is %s. %s",
plen,
(payload >= 126) ? "extra payload" : "no extra payload",
mask ? "on" : "off",
fin ? "This is a final frame" : "more to follow");
if (mask) {
len = 4;
if (plaintext) {
rv = apr_socket_recv(sock, (char*) mask_bytes, &len);
}
else {
rv = lua_websocket_readbytes(r->connection,
(char*) mask_bytes, 4);
}
if (rv != APR_SUCCESS) {
return 0;
}
}
if (plen < (HUGE_STRING_LEN*1024) && plen > 0) {
apr_size_t remaining = plen;
apr_size_t received;
apr_off_t at = 0;
char *buffer = apr_palloc(r->pool, plen+1);
buffer[plen] = 0;
if (plaintext) {
while (remaining > 0) {
received = remaining;
rv = apr_socket_recv(sock, buffer+at, &received);
if (received > 0 ) {
remaining -= received;
at += received;
}
}
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
"Websocket: Frame contained %" APR_OFF_T_FMT " bytes, pushed to Lua stack",
at);
}
else {
rv = lua_websocket_readbytes(r->connection, buffer,
remaining);
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
"Websocket: SSL Frame contained %" APR_SIZE_T_FMT " bytes, "\
"pushed to Lua stack",
remaining);
}
if (mask) {
for (n = 0; n < plen; n++) {
buffer[n] ^= mask_bytes[n%4];
}
}
lua_pushlstring(L, buffer, (size_t) plen); /* push to stack */
lua_pushboolean(L, fin); /* push FIN bit to stack as boolean */
return 2;
}
/* Decide if we need to react to the opcode or not */
if (opcode == 0x09) { /* ping */
char frame[2];
plen = 2;
frame[0] = 0x8A;
frame[1] = 0;
apr_socket_send(sock, frame, &plen); /* Pong! */
do_read = 1;
}
}
}
}
return 0;
}
static int lua_websocket_write(lua_State *L)
{
const char *string;
apr_status_t rv;
size_t len;
int raw = 0;
char prelude;
request_rec *r = ap_lua_check_request_rec(L, 1);
if (lua_isboolean(L, 3)) {
raw = lua_toboolean(L, 3);
}
string = lua_tolstring(L, 2, &len);
if (raw != 1) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Websocket: Writing framed message to client");
prelude = 0x81; /* text frame, FIN */
ap_rputc(prelude, r);
if (len < 126) {
ap_rputc(len, r);
}
else if (len < 65535) {
apr_uint16_t slen = len;
ap_rputc(126, r);
slen = htons(slen);
ap_rwrite((char*) &slen, 2, r);
}
else {
apr_uint64_t llen = len;
ap_rputc(127, r);
llen = ap_ntoh64(&llen); /* ntoh doubles as hton */
ap_rwrite((char*) &llen, 8, r);
}
}
else {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Websocket: Writing raw message to client");
}
ap_rwrite(string, len, r);
rv = ap_rflush(r);
if (rv == APR_SUCCESS) {
lua_pushboolean(L, 1);
}
else {
lua_pushboolean(L, 0);
}
return 1;
}
static int lua_websocket_close(lua_State *L)
{
apr_socket_t *sock;
char prelude[2];
request_rec *r = ap_lua_check_request_rec(L, 1);
sock = ap_get_conn_socket(r->connection);
/* Send a header that says: socket is closing. */
prelude[0] = 0x88; /* closing socket opcode */
prelude[1] = 0; /* zero length frame */
ap_rwrite(prelude, 2, r);
/* Close up tell the MPM and filters to back off */
apr_socket_close(sock);
r->output_filters = NULL;
r->connection->keepalive = AP_CONN_CLOSE;
return 0;
}
static int lua_websocket_ping(lua_State *L)
{
apr_socket_t *sock;
apr_size_t plen;
char prelude[2];
apr_status_t rv;
request_rec *r = ap_lua_check_request_rec(L, 1);
sock = ap_get_conn_socket(r->connection);
/* Send a header that says: PING. */
prelude[0] = 0x89; /* ping opcode */
prelude[1] = 0;
plen = 2;
apr_socket_send(sock, prelude, &plen);
/* Get opcode and FIN bit from pong */
plen = 2;
rv = apr_socket_recv(sock, prelude, &plen);
if (rv == APR_SUCCESS) {
unsigned char opcode = prelude[0];
unsigned char len = prelude[1];
unsigned char mask = len >> 7;
if (mask) len -= 128;
plen = len;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Websocket: Got PONG opcode: %x", opcode);
if (opcode == 0x8A) {
lua_pushboolean(L, 1);
}
else {
lua_pushboolean(L, 0);
}
if (plen > 0) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
"Websocket: Reading %" APR_SIZE_T_FMT " bytes of PONG", plen);
return 1;
}
if (mask) {
plen = 2;
apr_socket_recv(sock, prelude, &plen);
plen = 2;
apr_socket_recv(sock, prelude, &plen);
}
}
else {
lua_pushboolean(L, 0);
}
return 1;
}
#define APLUA_REQ_TRACE(lev) static int req_trace##lev(lua_State *L) \
{ \
return req_log_at(L, APLOG_TRACE##lev); \
}
APLUA_REQ_TRACE(1)
APLUA_REQ_TRACE(2)
APLUA_REQ_TRACE(3)
APLUA_REQ_TRACE(4)
APLUA_REQ_TRACE(5)
APLUA_REQ_TRACE(6)
APLUA_REQ_TRACE(7)
APLUA_REQ_TRACE(8)
/* handle r.status = 201 */
static int req_newindex(lua_State *L)
{
const char *key;
/* request_rec* r = lua_touserdata(L, lua_upvalueindex(1)); */
/* const char* key = luaL_checkstring(L, -2); */
request_rec *r = ap_lua_check_request_rec(L, 1);
key = luaL_checkstring(L, 2);
if (0 == strcmp("args", key)) {
const char *value = luaL_checkstring(L, 3);
r->args = apr_pstrdup(r->pool, value);
return 0;
}
if (0 == strcmp("content_type", key)) {
const char *value = luaL_checkstring(L, 3);
ap_set_content_type(r, apr_pstrdup(r->pool, value));
return 0;
}
if (0 == strcmp("filename", key)) {
const char *value = luaL_checkstring(L, 3);
r->filename = apr_pstrdup(r->pool, value);
return 0;
}
if (0 == strcmp("handler", key)) {
const char *value = luaL_checkstring(L, 3);
r->handler = apr_pstrdup(r->pool, value);
return 0;
}
if (0 == strcmp("proxyreq", key)) {
int value = luaL_checkinteger(L, 3);
r->proxyreq = value;
return 0;
}
if (0 == strcmp("status", key)) {
int code = luaL_checkinteger(L, 3);
r->status = code;
return 0;
}
if (0 == strcmp("uri", key)) {
const char *value = luaL_checkstring(L, 3);
r->uri = apr_pstrdup(r->pool, value);
return 0;
}
if (0 == strcmp("user", key)) {
const char *value = luaL_checkstring(L, 3);
r->user = apr_pstrdup(r->pool, value);
return 0;
}
lua_pushstring(L,
apr_psprintf(r->pool,
"Property [%s] may not be set on a request_rec",
key));
lua_error(L);
return 0;
}
/* helper function for walking config trees */
static void read_cfg_tree(lua_State *L, request_rec *r, ap_directive_t *rcfg) {
int x = 0;
const char* value;
ap_directive_t *cfg;
lua_newtable(L);
for (cfg = rcfg; cfg; cfg = cfg->next) {
x++;
lua_pushnumber(L, x);
lua_newtable(L);
value = apr_psprintf(r->pool, "%s %s", cfg->directive, cfg->args);
lua_pushstring(L, "directive");
lua_pushstring(L, value);
lua_settable(L, -3);
lua_pushstring(L, "file");
lua_pushstring(L, cfg->filename);
lua_settable(L, -3);
lua_pushstring(L, "line");
lua_pushnumber(L, cfg->line_num);
lua_settable(L, -3);
if (cfg->first_child) {
lua_pushstring(L, "children");
read_cfg_tree(L, r, cfg->first_child);
lua_settable(L, -3);
}
lua_settable(L, -3);
}
}
static int lua_ap_get_config(lua_State *L) {
request_rec *r = ap_lua_check_request_rec(L, 1);
read_cfg_tree(L, r, ap_conftree);
return 1;
}
/* Hack, hack, hack...! TODO: Make this actually work properly */
static int lua_ap_get_active_config(lua_State *L) {
ap_directive_t *subdir;
ap_directive_t *dir = ap_conftree;
request_rec *r = ap_lua_check_request_rec(L, 1);
for (dir = ap_conftree; dir; dir = dir->next) {
if (ap_strcasestr(dir->directive, "<virtualhost") && dir->first_child) {
for (subdir = dir->first_child; subdir; subdir = subdir->next) {
if (ap_strcasecmp_match(subdir->directive, "servername") &&
!ap_strcasecmp_match(r->hostname, subdir->args)) {
read_cfg_tree(L, r, dir->first_child);
return 1;
}
if (ap_strcasecmp_match(subdir->directive, "serveralias") &&
!ap_strcasecmp_match(r->hostname, subdir->args)) {
read_cfg_tree(L, r, dir->first_child);
return 1;
}
}
}
}
return 0;
}
static const struct luaL_Reg request_methods[] = {
{"__index", req_dispatch},
{"__newindex", req_newindex},
/* {"__newindex", req_set_field}, */
{NULL, NULL}
};
static const struct luaL_Reg connection_methods[] = {
{NULL, NULL}
};
static const char* lua_ap_auth_name(request_rec* r)
{
const char *name;
name = ap_auth_name(r);
return name ? name : "";
}
static const char* lua_ap_get_server_name(request_rec* r)
{
const char *name;
name = ap_get_server_name(r);
return name ? name : "localhost";
}
static const struct luaL_Reg server_methods[] = {
{NULL, NULL}
};
static req_fun_t *makefun(const void *fun, int type, apr_pool_t *pool)
{
req_fun_t *rft = apr_palloc(pool, sizeof(req_fun_t));
rft->fun = fun;
rft->type = type;
return rft;
}
void ap_lua_load_request_lmodule(lua_State *L, apr_pool_t *p)
{
apr_hash_t *dispatch = apr_hash_make(p);
apr_hash_set(dispatch, "puts", APR_HASH_KEY_STRING,
makefun(&req_puts, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "write", APR_HASH_KEY_STRING,
makefun(&req_write, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "document_root", APR_HASH_KEY_STRING,
makefun(&req_document_root, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "context_prefix", APR_HASH_KEY_STRING,
makefun(&req_context_prefix, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "context_document_root", APR_HASH_KEY_STRING,
makefun(&req_context_document_root, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "parseargs", APR_HASH_KEY_STRING,
makefun(&req_parseargs, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "parsebody", APR_HASH_KEY_STRING,
makefun(&req_parsebody, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "debug", APR_HASH_KEY_STRING,
makefun(&req_debug, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "info", APR_HASH_KEY_STRING,
makefun(&req_info, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "notice", APR_HASH_KEY_STRING,
makefun(&req_notice, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "warn", APR_HASH_KEY_STRING,
makefun(&req_warn, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "err", APR_HASH_KEY_STRING,
makefun(&req_err, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "crit", APR_HASH_KEY_STRING,
makefun(&req_crit, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "alert", APR_HASH_KEY_STRING,
makefun(&req_alert, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "emerg", APR_HASH_KEY_STRING,
makefun(&req_emerg, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "trace1", APR_HASH_KEY_STRING,
makefun(&req_trace1, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "trace2", APR_HASH_KEY_STRING,
makefun(&req_trace2, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "trace3", APR_HASH_KEY_STRING,
makefun(&req_trace3, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "trace4", APR_HASH_KEY_STRING,
makefun(&req_trace4, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "trace5", APR_HASH_KEY_STRING,
makefun(&req_trace5, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "trace6", APR_HASH_KEY_STRING,
makefun(&req_trace6, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "trace7", APR_HASH_KEY_STRING,
makefun(&req_trace7, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "trace8", APR_HASH_KEY_STRING,
makefun(&req_trace8, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "add_output_filter", APR_HASH_KEY_STRING,
makefun(&req_add_output_filter, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "construct_url", APR_HASH_KEY_STRING,
makefun(&req_construct_url, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "escape_html", APR_HASH_KEY_STRING,
makefun(&req_escape_html, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "ssl_var_lookup", APR_HASH_KEY_STRING,
makefun(&req_ssl_var_lookup, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "is_https", APR_HASH_KEY_STRING,
makefun(&req_ssl_is_https_field, APL_REQ_FUNTYPE_BOOLEAN, p));
apr_hash_set(dispatch, "assbackwards", APR_HASH_KEY_STRING,
makefun(&req_assbackwards_field, APL_REQ_FUNTYPE_BOOLEAN, p));
apr_hash_set(dispatch, "status", APR_HASH_KEY_STRING,
makefun(&req_status_field, APL_REQ_FUNTYPE_INT, p));
apr_hash_set(dispatch, "protocol", APR_HASH_KEY_STRING,
makefun(&req_protocol_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "range", APR_HASH_KEY_STRING,
makefun(&req_range_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "content_type", APR_HASH_KEY_STRING,
makefun(&req_content_type_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "content_encoding", APR_HASH_KEY_STRING,
makefun(&req_content_encoding_field, APL_REQ_FUNTYPE_STRING,
p));
apr_hash_set(dispatch, "ap_auth_type", APR_HASH_KEY_STRING,
makefun(&req_ap_auth_type_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "unparsed_uri", APR_HASH_KEY_STRING,
makefun(&req_unparsed_uri_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "user", APR_HASH_KEY_STRING,
makefun(&req_user_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "filename", APR_HASH_KEY_STRING,
makefun(&req_filename_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "canonical_filename", APR_HASH_KEY_STRING,
makefun(&req_canonical_filename_field,
APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "path_info", APR_HASH_KEY_STRING,
makefun(&req_path_info_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "args", APR_HASH_KEY_STRING,
makefun(&req_args_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "handler", APR_HASH_KEY_STRING,
makefun(&req_handler_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "hostname", APR_HASH_KEY_STRING,
makefun(&req_hostname_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "uri", APR_HASH_KEY_STRING,
makefun(&req_uri_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "the_request", APR_HASH_KEY_STRING,
makefun(&req_the_request_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "log_id", APR_HASH_KEY_STRING,
makefun(&req_log_id_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "useragent_ip", APR_HASH_KEY_STRING,
makefun(&req_useragent_ip_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "method", APR_HASH_KEY_STRING,
makefun(&req_method_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "proxyreq", APR_HASH_KEY_STRING,
makefun(&req_proxyreq_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "headers_in", APR_HASH_KEY_STRING,
makefun(&req_headers_in, APL_REQ_FUNTYPE_TABLE, p));
apr_hash_set(dispatch, "headers_out", APR_HASH_KEY_STRING,
makefun(&req_headers_out, APL_REQ_FUNTYPE_TABLE, p));
apr_hash_set(dispatch, "err_headers_out", APR_HASH_KEY_STRING,
makefun(&req_err_headers_out, APL_REQ_FUNTYPE_TABLE, p));
apr_hash_set(dispatch, "notes", APR_HASH_KEY_STRING,
makefun(&req_notes, APL_REQ_FUNTYPE_TABLE, p));
apr_hash_set(dispatch, "subprocess_env", APR_HASH_KEY_STRING,
makefun(&req_subprocess_env, APL_REQ_FUNTYPE_TABLE, p));
apr_hash_set(dispatch, "flush", APR_HASH_KEY_STRING,
makefun(&lua_ap_rflush, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "port", APR_HASH_KEY_STRING,
makefun(&req_ap_get_server_port, APL_REQ_FUNTYPE_INT, p));
apr_hash_set(dispatch, "banner", APR_HASH_KEY_STRING,
makefun(&ap_get_server_banner, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "options", APR_HASH_KEY_STRING,
makefun(&lua_ap_options, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "allowoverrides", APR_HASH_KEY_STRING,
makefun(&lua_ap_allowoverrides, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "started", APR_HASH_KEY_STRING,
makefun(&lua_ap_started, APL_REQ_FUNTYPE_INT, p));
apr_hash_set(dispatch, "basic_auth_pw", APR_HASH_KEY_STRING,
makefun(&lua_ap_basic_auth_pw, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "limit_req_body", APR_HASH_KEY_STRING,
makefun(&lua_ap_limit_req_body, APL_REQ_FUNTYPE_INT, p));
apr_hash_set(dispatch, "server_built", APR_HASH_KEY_STRING,
makefun(&ap_get_server_built, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "is_initial_req", APR_HASH_KEY_STRING,
makefun(&lua_ap_is_initial_req, APL_REQ_FUNTYPE_BOOLEAN, p));
apr_hash_set(dispatch, "remaining", APR_HASH_KEY_STRING,
makefun(&req_remaining_field, APL_REQ_FUNTYPE_INT, p));
apr_hash_set(dispatch, "some_auth_required", APR_HASH_KEY_STRING,
makefun(&lua_ap_some_auth_required, APL_REQ_FUNTYPE_BOOLEAN, p));
apr_hash_set(dispatch, "server_name", APR_HASH_KEY_STRING,
makefun(&lua_ap_get_server_name, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "auth_name", APR_HASH_KEY_STRING,
makefun(&lua_ap_auth_name, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "sendfile", APR_HASH_KEY_STRING,
makefun(&lua_ap_sendfile, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "dbacquire", APR_HASH_KEY_STRING,
makefun(&lua_db_acquire, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "stat", APR_HASH_KEY_STRING,
makefun(&lua_ap_stat, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "get_direntries", APR_HASH_KEY_STRING,
makefun(&lua_ap_getdir, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "regex", APR_HASH_KEY_STRING,
makefun(&lua_ap_regex, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "usleep", APR_HASH_KEY_STRING,
makefun(&lua_ap_usleep, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "base64_encode", APR_HASH_KEY_STRING,
makefun(&lua_apr_b64encode, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "base64_decode", APR_HASH_KEY_STRING,
makefun(&lua_apr_b64decode, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "md5", APR_HASH_KEY_STRING,
makefun(&lua_apr_md5, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "sha1", APR_HASH_KEY_STRING,
makefun(&lua_apr_sha1, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "htpassword", APR_HASH_KEY_STRING,
makefun(&lua_apr_htpassword, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "touch", APR_HASH_KEY_STRING,
makefun(&lua_apr_touch, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "mkdir", APR_HASH_KEY_STRING,
makefun(&lua_apr_mkdir, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "mkrdir", APR_HASH_KEY_STRING,
makefun(&lua_apr_mkrdir, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "rmdir", APR_HASH_KEY_STRING,
makefun(&lua_apr_rmdir, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "date_parse_rfc", APR_HASH_KEY_STRING,
makefun(&lua_apr_date_parse_rfc, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "escape", APR_HASH_KEY_STRING,
makefun(&lua_ap_escape, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "unescape", APR_HASH_KEY_STRING,
makefun(&lua_ap_unescape, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "mpm_query", APR_HASH_KEY_STRING,
makefun(&lua_ap_mpm_query, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "expr", APR_HASH_KEY_STRING,
makefun(&lua_ap_expr, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "scoreboard_process", APR_HASH_KEY_STRING,
makefun(&lua_ap_scoreboard_process, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "scoreboard_worker", APR_HASH_KEY_STRING,
makefun(&lua_ap_scoreboard_worker, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "clock", APR_HASH_KEY_STRING,
makefun(&lua_ap_clock, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "requestbody", APR_HASH_KEY_STRING,
makefun(&lua_ap_requestbody, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "add_input_filter", APR_HASH_KEY_STRING,
makefun(&lua_ap_add_input_filter, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "module_info", APR_HASH_KEY_STRING,
makefun(&lua_ap_module_info, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "loaded_modules", APR_HASH_KEY_STRING,
makefun(&lua_ap_loaded_modules, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "runtime_dir_relative", APR_HASH_KEY_STRING,
makefun(&lua_ap_runtime_dir_relative, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "server_info", APR_HASH_KEY_STRING,
makefun(&lua_ap_server_info, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "set_document_root", APR_HASH_KEY_STRING,
makefun(&lua_ap_set_document_root, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "set_context_info", APR_HASH_KEY_STRING,
makefun(&lua_ap_set_context_info, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "os_escape_path", APR_HASH_KEY_STRING,
makefun(&lua_ap_os_escape_path, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "escape_logitem", APR_HASH_KEY_STRING,
makefun(&lua_ap_escape_logitem, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "strcmp_match", APR_HASH_KEY_STRING,
makefun(&lua_ap_strcmp_match, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "set_keepalive", APR_HASH_KEY_STRING,
makefun(&lua_ap_set_keepalive, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "make_etag", APR_HASH_KEY_STRING,
makefun(&lua_ap_make_etag, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "send_interim_response", APR_HASH_KEY_STRING,
makefun(&lua_ap_send_interim_response, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "custom_response", APR_HASH_KEY_STRING,
makefun(&lua_ap_custom_response, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "exists_config_define", APR_HASH_KEY_STRING,
makefun(&lua_ap_exists_config_define, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "state_query", APR_HASH_KEY_STRING,
makefun(&lua_ap_state_query, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "get_server_name_for_url", APR_HASH_KEY_STRING,
makefun(&lua_ap_get_server_name_for_url, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "ivm_get", APR_HASH_KEY_STRING,
makefun(&lua_ivm_get, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "ivm_set", APR_HASH_KEY_STRING,
makefun(&lua_ivm_set, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "getcookie", APR_HASH_KEY_STRING,
makefun(&lua_get_cookie, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "setcookie", APR_HASH_KEY_STRING,
makefun(&lua_set_cookie, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "wsupgrade", APR_HASH_KEY_STRING,
makefun(&lua_websocket_greet, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "wsread", APR_HASH_KEY_STRING,
makefun(&lua_websocket_read, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "wspeek", APR_HASH_KEY_STRING,
makefun(&lua_websocket_peek, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "wswrite", APR_HASH_KEY_STRING,
makefun(&lua_websocket_write, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "wsclose", APR_HASH_KEY_STRING,
makefun(&lua_websocket_close, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "wsping", APR_HASH_KEY_STRING,
makefun(&lua_websocket_ping, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "config", APR_HASH_KEY_STRING,
makefun(&lua_ap_get_config, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "activeconfig", APR_HASH_KEY_STRING,
makefun(&lua_ap_get_active_config, APL_REQ_FUNTYPE_LUACFUN, p));
lua_pushlightuserdata(L, dispatch);
lua_setfield(L, LUA_REGISTRYINDEX, "Apache2.Request.dispatch");
luaL_newmetatable(L, "Apache2.Request"); /* [metatable] */
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_register(L, NULL, request_methods); /* [metatable] */
lua_pop(L, 2);
luaL_newmetatable(L, "Apache2.Connection"); /* [metatable] */
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_register(L, NULL, connection_methods); /* [metatable] */
lua_pop(L, 2);
luaL_newmetatable(L, "Apache2.Server"); /* [metatable] */
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_register(L, NULL, server_methods); /* [metatable] */
lua_pop(L, 2);
}
void ap_lua_push_connection(lua_State *L, conn_rec *c)
{
req_table_t* t;
lua_boxpointer(L, c);
luaL_getmetatable(L, "Apache2.Connection");
lua_setmetatable(L, -2);
luaL_getmetatable(L, "Apache2.Connection");
t = apr_pcalloc(c->pool, sizeof(req_table_t));
t->t = c->notes;
t->r = NULL;
t->n = "notes";
ap_lua_push_apr_table(L, t);
lua_setfield(L, -2, "notes");
lua_pushstring(L, c->client_ip);
lua_setfield(L, -2, "client_ip");
lua_pop(L, 1);
}
void ap_lua_push_server(lua_State *L, server_rec *s)
{
lua_boxpointer(L, s);
luaL_getmetatable(L, "Apache2.Server");
lua_setmetatable(L, -2);
luaL_getmetatable(L, "Apache2.Server");
lua_pushstring(L, s->server_hostname);
lua_setfield(L, -2, "server_hostname");
lua_pop(L, 1);
}
void ap_lua_push_request(lua_State *L, request_rec *r)
{
lua_boxpointer(L, r);
luaL_getmetatable(L, "Apache2.Request");
lua_setmetatable(L, -2);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_1448_1 |
crossvul-cpp_data_bad_243_0 | /**
* @file
* Send/receive commands to/from an IMAP server
*
* @authors
* Copyright (C) 1996-1998,2010,2012 Michael R. Elkins <me@mutt.org>
* Copyright (C) 1996-1999 Brandon Long <blong@fiction.net>
* Copyright (C) 1999-2009,2011 Brendan Cully <brendan@kublai.com>
*
* @copyright
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @page imap_command Send/receive commands to/from an IMAP server
*
* Send/receive commands to/from an IMAP server
*/
#include "config.h"
#include <ctype.h>
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "imap_private.h"
#include "mutt/mutt.h"
#include "conn/conn.h"
#include "buffy.h"
#include "context.h"
#include "globals.h"
#include "header.h"
#include "imap/imap.h"
#include "mailbox.h"
#include "message.h"
#include "mutt_account.h"
#include "mutt_menu.h"
#include "mutt_socket.h"
#include "mx.h"
#include "options.h"
#include "protos.h"
#include "url.h"
#define IMAP_CMD_BUFSIZE 512
/**
* Capabilities - Server capabilities strings that we understand
*
* @note This must be kept in the same order as ImapCaps.
*
* @note Gmail documents one string but use another, so we support both.
*/
static const char *const Capabilities[] = {
"IMAP4", "IMAP4rev1", "STATUS", "ACL",
"NAMESPACE", "AUTH=CRAM-MD5", "AUTH=GSSAPI", "AUTH=ANONYMOUS",
"STARTTLS", "LOGINDISABLED", "IDLE", "SASL-IR",
"ENABLE", "X-GM-EXT-1", "X-GM-EXT1", NULL,
};
/**
* cmd_queue_full - Is the IMAP command queue full?
* @param idata Server data
* @retval true Queue is full
*/
static bool cmd_queue_full(struct ImapData *idata)
{
if ((idata->nextcmd + 1) % idata->cmdslots == idata->lastcmd)
return true;
return false;
}
/**
* cmd_new - Create and queue a new command control block
* @param idata IMAP data
* @retval NULL if the pipeline is full
* @retval ptr New command
*/
static struct ImapCommand *cmd_new(struct ImapData *idata)
{
struct ImapCommand *cmd = NULL;
if (cmd_queue_full(idata))
{
mutt_debug(3, "IMAP command queue full\n");
return NULL;
}
cmd = idata->cmds + idata->nextcmd;
idata->nextcmd = (idata->nextcmd + 1) % idata->cmdslots;
snprintf(cmd->seq, sizeof(cmd->seq), "a%04u", idata->seqno++);
if (idata->seqno > 9999)
idata->seqno = 0;
cmd->state = IMAP_CMD_NEW;
return cmd;
}
/**
* cmd_queue - Add a IMAP command to the queue
* @param idata Server data
* @param cmdstr Command string
* @param flags Server flags, e.g. #IMAP_CMD_POLL
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*
* If the queue is full, attempts to drain it.
*/
static int cmd_queue(struct ImapData *idata, const char *cmdstr, int flags)
{
if (cmd_queue_full(idata))
{
mutt_debug(3, "Draining IMAP command pipeline\n");
const int rc = imap_exec(idata, NULL, IMAP_CMD_FAIL_OK | (flags & IMAP_CMD_POLL));
if (rc < 0 && rc != -2)
return rc;
}
struct ImapCommand *cmd = cmd_new(idata);
if (!cmd)
return IMAP_CMD_BAD;
if (mutt_buffer_printf(idata->cmdbuf, "%s %s\r\n", cmd->seq, cmdstr) < 0)
return IMAP_CMD_BAD;
return 0;
}
/**
* cmd_handle_fatal - When ImapData is in fatal state, do what we can
* @param idata Server data
*/
static void cmd_handle_fatal(struct ImapData *idata)
{
idata->status = IMAP_FATAL;
if ((idata->state >= IMAP_SELECTED) && (idata->reopen & IMAP_REOPEN_ALLOW))
{
mx_fastclose_mailbox(idata->ctx);
mutt_socket_close(idata->conn);
mutt_error(_("Mailbox %s@%s closed"), idata->conn->account.login,
idata->conn->account.host);
idata->state = IMAP_DISCONNECTED;
}
imap_close_connection(idata);
if (!idata->recovering)
{
idata->recovering = true;
if (imap_conn_find(&idata->conn->account, 0))
mutt_clear_error();
idata->recovering = false;
}
}
/**
* cmd_start - Start a new IMAP command
* @param idata Server data
* @param cmdstr Command string
* @param flags Command flags, e.g. #IMAP_CMD_QUEUE
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*/
static int cmd_start(struct ImapData *idata, const char *cmdstr, int flags)
{
int rc;
if (idata->status == IMAP_FATAL)
{
cmd_handle_fatal(idata);
return -1;
}
if (cmdstr && ((rc = cmd_queue(idata, cmdstr, flags)) < 0))
return rc;
if (flags & IMAP_CMD_QUEUE)
return 0;
if (idata->cmdbuf->dptr == idata->cmdbuf->data)
return IMAP_CMD_BAD;
rc = mutt_socket_send_d(idata->conn, idata->cmdbuf->data,
(flags & IMAP_CMD_PASS) ? IMAP_LOG_PASS : IMAP_LOG_CMD);
idata->cmdbuf->dptr = idata->cmdbuf->data;
/* unidle when command queue is flushed */
if (idata->state == IMAP_IDLE)
idata->state = IMAP_SELECTED;
return (rc < 0) ? IMAP_CMD_BAD : 0;
}
/**
* cmd_status - parse response line for tagged OK/NO/BAD
* @param s Status string from server
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*/
static int cmd_status(const char *s)
{
s = imap_next_word((char *) s);
if (mutt_str_strncasecmp("OK", s, 2) == 0)
return IMAP_CMD_OK;
if (mutt_str_strncasecmp("NO", s, 2) == 0)
return IMAP_CMD_NO;
return IMAP_CMD_BAD;
}
/**
* cmd_parse_expunge - Parse expunge command
* @param idata Server data
* @param s String containing MSN of message to expunge
*
* cmd_parse_expunge: mark headers with new sequence ID and mark idata to be
* reopened at our earliest convenience
*/
static void cmd_parse_expunge(struct ImapData *idata, const char *s)
{
unsigned int exp_msn;
struct Header *h = NULL;
mutt_debug(2, "Handling EXPUNGE\n");
if (mutt_str_atoui(s, &exp_msn) < 0 || exp_msn < 1 || exp_msn > idata->max_msn)
return;
h = idata->msn_index[exp_msn - 1];
if (h)
{
/* imap_expunge_mailbox() will rewrite h->index.
* It needs to resort using SORT_ORDER anyway, so setting to INT_MAX
* makes the code simpler and possibly more efficient. */
h->index = INT_MAX;
HEADER_DATA(h)->msn = 0;
}
/* decrement seqno of those above. */
for (unsigned int cur = exp_msn; cur < idata->max_msn; cur++)
{
h = idata->msn_index[cur];
if (h)
HEADER_DATA(h)->msn--;
idata->msn_index[cur - 1] = h;
}
idata->msn_index[idata->max_msn - 1] = NULL;
idata->max_msn--;
idata->reopen |= IMAP_EXPUNGE_PENDING;
}
/**
* cmd_parse_fetch - Load fetch response into ImapData
* @param idata Server data
* @param s String containing MSN of message to fetch
*
* Currently only handles unanticipated FETCH responses, and only FLAGS data.
* We get these if another client has changed flags for a mailbox we've
* selected. Of course, a lot of code here duplicates code in message.c.
*/
static void cmd_parse_fetch(struct ImapData *idata, char *s)
{
unsigned int msn, uid;
struct Header *h = NULL;
int server_changes = 0;
mutt_debug(3, "Handling FETCH\n");
if (mutt_str_atoui(s, &msn) < 0 || msn < 1 || msn > idata->max_msn)
{
mutt_debug(3, "#1 FETCH response ignored for this message\n");
return;
}
h = idata->msn_index[msn - 1];
if (!h || !h->active)
{
mutt_debug(3, "#2 FETCH response ignored for this message\n");
return;
}
mutt_debug(2, "Message UID %u updated\n", HEADER_DATA(h)->uid);
/* skip FETCH */
s = imap_next_word(s);
s = imap_next_word(s);
if (*s != '(')
{
mutt_debug(1, "Malformed FETCH response\n");
return;
}
s++;
while (*s)
{
SKIPWS(s);
if (mutt_str_strncasecmp("FLAGS", s, 5) == 0)
{
imap_set_flags(idata, h, s, &server_changes);
if (server_changes)
{
/* If server flags could conflict with neomutt's flags, reopen the mailbox. */
if (h->changed)
idata->reopen |= IMAP_EXPUNGE_PENDING;
else
idata->check_status = IMAP_FLAGS_PENDING;
}
return;
}
else if (mutt_str_strncasecmp("UID", s, 3) == 0)
{
s += 3;
SKIPWS(s);
if (mutt_str_atoui(s, &uid) < 0)
{
mutt_debug(2, "Illegal UID. Skipping update.\n");
return;
}
if (uid != HEADER_DATA(h)->uid)
{
mutt_debug(2, "FETCH UID vs MSN mismatch. Skipping update.\n");
return;
}
s = imap_next_word(s);
}
else if (*s == ')')
s++; /* end of request */
else if (*s)
{
mutt_debug(2, "Only handle FLAGS updates\n");
return;
}
}
}
/**
* cmd_parse_capability - set capability bits according to CAPABILITY response
* @param idata Server data
* @param s Command string with capabilities
*/
static void cmd_parse_capability(struct ImapData *idata, char *s)
{
mutt_debug(3, "Handling CAPABILITY\n");
s = imap_next_word(s);
char *bracket = strchr(s, ']');
if (bracket)
*bracket = '\0';
FREE(&idata->capstr);
idata->capstr = mutt_str_strdup(s);
memset(idata->capabilities, 0, sizeof(idata->capabilities));
while (*s)
{
for (int i = 0; i < CAPMAX; i++)
{
if (mutt_str_word_casecmp(Capabilities[i], s) == 0)
{
mutt_bit_set(idata->capabilities, i);
mutt_debug(4, " Found capability \"%s\": %d\n", Capabilities[i], i);
break;
}
}
s = imap_next_word(s);
}
}
/**
* cmd_parse_list - Parse a server LIST command (list mailboxes)
* @param idata Server data
* @param s Command string with folder list
*/
static void cmd_parse_list(struct ImapData *idata, char *s)
{
struct ImapList *list = NULL;
struct ImapList lb;
char delimbuf[5]; /* worst case: "\\"\0 */
unsigned int litlen;
if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST)
list = (struct ImapList *) idata->cmddata;
else
list = &lb;
memset(list, 0, sizeof(struct ImapList));
/* flags */
s = imap_next_word(s);
if (*s != '(')
{
mutt_debug(1, "Bad LIST response\n");
return;
}
s++;
while (*s)
{
if (mutt_str_strncasecmp(s, "\\NoSelect", 9) == 0)
list->noselect = true;
else if (mutt_str_strncasecmp(s, "\\NoInferiors", 12) == 0)
list->noinferiors = true;
/* See draft-gahrns-imap-child-mailbox-?? */
else if (mutt_str_strncasecmp(s, "\\HasNoChildren", 14) == 0)
list->noinferiors = true;
s = imap_next_word(s);
if (*(s - 2) == ')')
break;
}
/* Delimiter */
if (mutt_str_strncasecmp(s, "NIL", 3) != 0)
{
delimbuf[0] = '\0';
mutt_str_strcat(delimbuf, 5, s);
imap_unquote_string(delimbuf);
list->delim = delimbuf[0];
}
/* Name */
s = imap_next_word(s);
/* Notes often responds with literals here. We need a real tokenizer. */
if (imap_get_literal_count(s, &litlen) == 0)
{
if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE)
{
idata->status = IMAP_FATAL;
return;
}
list->name = idata->buf;
}
else
{
imap_unmunge_mbox_name(idata, s);
list->name = s;
}
if (list->name[0] == '\0')
{
idata->delim = list->delim;
mutt_debug(3, "Root delimiter: %c\n", idata->delim);
}
}
/**
* cmd_parse_lsub - Parse a server LSUB (list subscribed mailboxes)
* @param idata Server data
* @param s Command string with folder list
*/
static void cmd_parse_lsub(struct ImapData *idata, char *s)
{
char buf[STRING];
char errstr[STRING];
struct Buffer err, token;
struct Url url;
struct ImapList list;
if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST)
{
/* caller will handle response itself */
cmd_parse_list(idata, s);
return;
}
if (!ImapCheckSubscribed)
return;
idata->cmdtype = IMAP_CT_LIST;
idata->cmddata = &list;
cmd_parse_list(idata, s);
idata->cmddata = NULL;
/* noselect is for a gmail quirk (#3445) */
if (!list.name || list.noselect)
return;
mutt_debug(3, "Subscribing to %s\n", list.name);
mutt_str_strfcpy(buf, "mailboxes \"", sizeof(buf));
mutt_account_tourl(&idata->conn->account, &url);
/* escape \ and " */
imap_quote_string(errstr, sizeof(errstr), list.name, true);
url.path = errstr + 1;
url.path[strlen(url.path) - 1] = '\0';
if (mutt_str_strcmp(url.user, ImapUser) == 0)
url.user = NULL;
url_tostring(&url, buf + 11, sizeof(buf) - 11, 0);
mutt_str_strcat(buf, sizeof(buf), "\"");
mutt_buffer_init(&token);
mutt_buffer_init(&err);
err.data = errstr;
err.dsize = sizeof(errstr);
if (mutt_parse_rc_line(buf, &token, &err))
mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr);
FREE(&token.data);
}
/**
* cmd_parse_myrights - Set rights bits according to MYRIGHTS response
* @param idata Server data
* @param s Command string with rights info
*/
static void cmd_parse_myrights(struct ImapData *idata, const char *s)
{
mutt_debug(2, "Handling MYRIGHTS\n");
s = imap_next_word((char *) s);
s = imap_next_word((char *) s);
/* zero out current rights set */
memset(idata->ctx->rights, 0, sizeof(idata->ctx->rights));
while (*s && !isspace((unsigned char) *s))
{
switch (*s)
{
case 'a':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_ADMIN);
break;
case 'e':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_EXPUNGE);
break;
case 'i':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_INSERT);
break;
case 'k':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_CREATE);
break;
case 'l':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_LOOKUP);
break;
case 'p':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_POST);
break;
case 'r':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_READ);
break;
case 's':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_SEEN);
break;
case 't':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELETE);
break;
case 'w':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_WRITE);
break;
case 'x':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELMX);
break;
/* obsolete rights */
case 'c':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_CREATE);
mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELMX);
break;
case 'd':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELETE);
mutt_bit_set(idata->ctx->rights, MUTT_ACL_EXPUNGE);
break;
default:
mutt_debug(1, "Unknown right: %c\n", *s);
}
s++;
}
}
/**
* cmd_parse_search - store SEARCH response for later use
* @param idata Server data
* @param s Command string with search results
*/
static void cmd_parse_search(struct ImapData *idata, const char *s)
{
unsigned int uid;
struct Header *h = NULL;
mutt_debug(2, "Handling SEARCH\n");
while ((s = imap_next_word((char *) s)) && *s != '\0')
{
if (mutt_str_atoui(s, &uid) < 0)
continue;
h = (struct Header *) mutt_hash_int_find(idata->uid_hash, uid);
if (h)
h->matched = true;
}
}
/**
* cmd_parse_status - Parse status from server
* @param idata Server data
* @param s Command string with status info
*
* first cut: just do buffy update. Later we may wish to cache all mailbox
* information, even that not desired by buffy
*/
static void cmd_parse_status(struct ImapData *idata, char *s)
{
char *value = NULL;
struct Buffy *inc = NULL;
struct ImapMbox mx;
struct ImapStatus *status = NULL;
unsigned int olduv, oldun;
unsigned int litlen;
short new = 0;
short new_msg_count = 0;
char *mailbox = imap_next_word(s);
/* We need a real tokenizer. */
if (imap_get_literal_count(mailbox, &litlen) == 0)
{
if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE)
{
idata->status = IMAP_FATAL;
return;
}
mailbox = idata->buf;
s = mailbox + litlen;
*s = '\0';
s++;
SKIPWS(s);
}
else
{
s = imap_next_word(mailbox);
*(s - 1) = '\0';
imap_unmunge_mbox_name(idata, mailbox);
}
status = imap_mboxcache_get(idata, mailbox, 1);
olduv = status->uidvalidity;
oldun = status->uidnext;
if (*s++ != '(')
{
mutt_debug(1, "Error parsing STATUS\n");
return;
}
while (*s && *s != ')')
{
value = imap_next_word(s);
errno = 0;
const unsigned long ulcount = strtoul(value, &value, 10);
if (((errno == ERANGE) && (ulcount == ULONG_MAX)) || ((unsigned int) ulcount != ulcount))
{
mutt_debug(1, "Error parsing STATUS number\n");
return;
}
const unsigned int count = (unsigned int) ulcount;
if (mutt_str_strncmp("MESSAGES", s, 8) == 0)
{
status->messages = count;
new_msg_count = 1;
}
else if (mutt_str_strncmp("RECENT", s, 6) == 0)
status->recent = count;
else if (mutt_str_strncmp("UIDNEXT", s, 7) == 0)
status->uidnext = count;
else if (mutt_str_strncmp("UIDVALIDITY", s, 11) == 0)
status->uidvalidity = count;
else if (mutt_str_strncmp("UNSEEN", s, 6) == 0)
status->unseen = count;
s = value;
if (*s && *s != ')')
s = imap_next_word(s);
}
mutt_debug(3, "%s (UIDVALIDITY: %u, UIDNEXT: %u) %d messages, %d recent, %d unseen\n",
status->name, status->uidvalidity, status->uidnext,
status->messages, status->recent, status->unseen);
/* caller is prepared to handle the result herself */
if (idata->cmddata && idata->cmdtype == IMAP_CT_STATUS)
{
memcpy(idata->cmddata, status, sizeof(struct ImapStatus));
return;
}
mutt_debug(3, "Running default STATUS handler\n");
/* should perhaps move this code back to imap_buffy_check */
for (inc = Incoming; inc; inc = inc->next)
{
if (inc->magic != MUTT_IMAP)
continue;
if (imap_parse_path(inc->path, &mx) < 0)
{
mutt_debug(1, "Error parsing mailbox %s, skipping\n", inc->path);
continue;
}
if (imap_account_match(&idata->conn->account, &mx.account))
{
if (mx.mbox)
{
value = mutt_str_strdup(mx.mbox);
imap_fix_path(idata, mx.mbox, value, mutt_str_strlen(value) + 1);
FREE(&mx.mbox);
}
else
value = mutt_str_strdup("INBOX");
if (value && (imap_mxcmp(mailbox, value) == 0))
{
mutt_debug(3, "Found %s in buffy list (OV: %u ON: %u U: %d)\n", mailbox,
olduv, oldun, status->unseen);
if (MailCheckRecent)
{
if (olduv && olduv == status->uidvalidity)
{
if (oldun < status->uidnext)
new = (status->unseen > 0);
}
else if (!olduv && !oldun)
{
/* first check per session, use recent. might need a flag for this. */
new = (status->recent > 0);
}
else
new = (status->unseen > 0);
}
else
new = (status->unseen > 0);
#ifdef USE_SIDEBAR
if ((inc->new != new) || (inc->msg_count != status->messages) ||
(inc->msg_unread != status->unseen))
{
mutt_menu_set_current_redraw(REDRAW_SIDEBAR);
}
#endif
inc->new = new;
if (new_msg_count)
inc->msg_count = status->messages;
inc->msg_unread = status->unseen;
if (inc->new)
{
/* force back to keep detecting new mail until the mailbox is
opened */
status->uidnext = oldun;
}
FREE(&value);
return;
}
FREE(&value);
}
FREE(&mx.mbox);
}
}
/**
* cmd_parse_enabled - Record what the server has enabled
* @param idata Server data
* @param s Command string containing acceptable encodings
*/
static void cmd_parse_enabled(struct ImapData *idata, const char *s)
{
mutt_debug(2, "Handling ENABLED\n");
while ((s = imap_next_word((char *) s)) && *s != '\0')
{
if ((mutt_str_strncasecmp(s, "UTF8=ACCEPT", 11) == 0) ||
(mutt_str_strncasecmp(s, "UTF8=ONLY", 9) == 0))
{
idata->unicode = 1;
}
}
}
/**
* cmd_handle_untagged - fallback parser for otherwise unhandled messages
* @param idata Server data
* @retval 0 Success
* @retval -1 Failure
*/
static int cmd_handle_untagged(struct ImapData *idata)
{
unsigned int count = 0;
char *s = imap_next_word(idata->buf);
char *pn = imap_next_word(s);
if ((idata->state >= IMAP_SELECTED) && isdigit((unsigned char) *s))
{
pn = s;
s = imap_next_word(s);
/* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the
* connection, so update that one.
*/
if (mutt_str_strncasecmp("EXISTS", s, 6) == 0)
{
mutt_debug(2, "Handling EXISTS\n");
/* new mail arrived */
if (mutt_str_atoui(pn, &count) < 0)
{
mutt_debug(1, "Malformed EXISTS: '%s'\n", pn);
}
if (!(idata->reopen & IMAP_EXPUNGE_PENDING) && count < idata->max_msn)
{
/* Notes 6.0.3 has a tendency to report fewer messages exist than
* it should. */
mutt_debug(1, "Message count is out of sync\n");
return 0;
}
/* at least the InterChange server sends EXISTS messages freely,
* even when there is no new mail */
else if (count == idata->max_msn)
mutt_debug(3, "superfluous EXISTS message.\n");
else
{
if (!(idata->reopen & IMAP_EXPUNGE_PENDING))
{
mutt_debug(2, "New mail in %s - %d messages total.\n", idata->mailbox, count);
idata->reopen |= IMAP_NEWMAIL_PENDING;
}
idata->new_mail_count = count;
}
}
/* pn vs. s: need initial seqno */
else if (mutt_str_strncasecmp("EXPUNGE", s, 7) == 0)
cmd_parse_expunge(idata, pn);
else if (mutt_str_strncasecmp("FETCH", s, 5) == 0)
cmd_parse_fetch(idata, pn);
}
else if (mutt_str_strncasecmp("CAPABILITY", s, 10) == 0)
cmd_parse_capability(idata, s);
else if (mutt_str_strncasecmp("OK [CAPABILITY", s, 14) == 0)
cmd_parse_capability(idata, pn);
else if (mutt_str_strncasecmp("OK [CAPABILITY", pn, 14) == 0)
cmd_parse_capability(idata, imap_next_word(pn));
else if (mutt_str_strncasecmp("LIST", s, 4) == 0)
cmd_parse_list(idata, s);
else if (mutt_str_strncasecmp("LSUB", s, 4) == 0)
cmd_parse_lsub(idata, s);
else if (mutt_str_strncasecmp("MYRIGHTS", s, 8) == 0)
cmd_parse_myrights(idata, s);
else if (mutt_str_strncasecmp("SEARCH", s, 6) == 0)
cmd_parse_search(idata, s);
else if (mutt_str_strncasecmp("STATUS", s, 6) == 0)
cmd_parse_status(idata, s);
else if (mutt_str_strncasecmp("ENABLED", s, 7) == 0)
cmd_parse_enabled(idata, s);
else if (mutt_str_strncasecmp("BYE", s, 3) == 0)
{
mutt_debug(2, "Handling BYE\n");
/* check if we're logging out */
if (idata->status == IMAP_BYE)
return 0;
/* server shut down our connection */
s += 3;
SKIPWS(s);
mutt_error("%s", s);
cmd_handle_fatal(idata);
return -1;
}
else if (ImapServernoise && (mutt_str_strncasecmp("NO", s, 2) == 0))
{
mutt_debug(2, "Handling untagged NO\n");
/* Display the warning message from the server */
mutt_error("%s", s + 3);
}
return 0;
}
/**
* imap_cmd_start - Given an IMAP command, send it to the server
* @param idata Server data
* @param cmdstr Command string to send
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*
* If cmdstr is NULL, sends queued commands.
*/
int imap_cmd_start(struct ImapData *idata, const char *cmdstr)
{
return cmd_start(idata, cmdstr, 0);
}
/**
* imap_cmd_step - Reads server responses from an IMAP command
* @param idata Server data
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*
* detects tagged completion response, handles untagged messages, can read
* arbitrarily large strings (using malloc, so don't make it _too_ large!).
*/
int imap_cmd_step(struct ImapData *idata)
{
size_t len = 0;
int c;
int rc;
int stillrunning = 0;
struct ImapCommand *cmd = NULL;
if (idata->status == IMAP_FATAL)
{
cmd_handle_fatal(idata);
return IMAP_CMD_BAD;
}
/* read into buffer, expanding buffer as necessary until we have a full
* line */
do
{
if (len == idata->blen)
{
mutt_mem_realloc(&idata->buf, idata->blen + IMAP_CMD_BUFSIZE);
idata->blen = idata->blen + IMAP_CMD_BUFSIZE;
mutt_debug(3, "grew buffer to %u bytes\n", idata->blen);
}
/* back up over '\0' */
if (len)
len--;
c = mutt_socket_readln(idata->buf + len, idata->blen - len, idata->conn);
if (c <= 0)
{
mutt_debug(1, "Error reading server response.\n");
cmd_handle_fatal(idata);
return IMAP_CMD_BAD;
}
len += c;
}
/* if we've read all the way to the end of the buffer, we haven't read a
* full line (mutt_socket_readln strips the \r, so we always have at least
* one character free when we've read a full line) */
while (len == idata->blen);
/* don't let one large string make cmd->buf hog memory forever */
if ((idata->blen > IMAP_CMD_BUFSIZE) && (len <= IMAP_CMD_BUFSIZE))
{
mutt_mem_realloc(&idata->buf, IMAP_CMD_BUFSIZE);
idata->blen = IMAP_CMD_BUFSIZE;
mutt_debug(3, "shrank buffer to %u bytes\n", idata->blen);
}
idata->lastread = time(NULL);
/* handle untagged messages. The caller still gets its shot afterwards. */
if (((mutt_str_strncmp(idata->buf, "* ", 2) == 0) ||
(mutt_str_strncmp(imap_next_word(idata->buf), "OK [", 4) == 0)) &&
cmd_handle_untagged(idata))
{
return IMAP_CMD_BAD;
}
/* server demands a continuation response from us */
if (idata->buf[0] == '+')
return IMAP_CMD_RESPOND;
/* Look for tagged command completions.
*
* Some response handlers can end up recursively calling
* imap_cmd_step() and end up handling all tagged command
* completions.
* (e.g. FETCH->set_flag->set_header_color->~h pattern match.)
*
* Other callers don't even create an idata->cmds entry.
*
* For both these cases, we default to returning OK */
rc = IMAP_CMD_OK;
c = idata->lastcmd;
do
{
cmd = &idata->cmds[c];
if (cmd->state == IMAP_CMD_NEW)
{
if (mutt_str_strncmp(idata->buf, cmd->seq, SEQLEN) == 0)
{
if (!stillrunning)
{
/* first command in queue has finished - move queue pointer up */
idata->lastcmd = (idata->lastcmd + 1) % idata->cmdslots;
}
cmd->state = cmd_status(idata->buf);
/* bogus - we don't know which command result to return here. Caller
* should provide a tag. */
rc = cmd->state;
}
else
stillrunning++;
}
c = (c + 1) % idata->cmdslots;
} while (c != idata->nextcmd);
if (stillrunning)
rc = IMAP_CMD_CONTINUE;
else
{
mutt_debug(3, "IMAP queue drained\n");
imap_cmd_finish(idata);
}
return rc;
}
/**
* imap_code - Was the command successful
* @param s IMAP command status
* @retval 1 Command result was OK
* @retval 0 If NO or BAD
*/
bool imap_code(const char *s)
{
return (cmd_status(s) == IMAP_CMD_OK);
}
/**
* imap_cmd_trailer - Extra information after tagged command response if any
* @param idata Server data
* @retval ptr Extra command information (pointer into idata->buf)
* @retval "" Error (static string)
*/
const char *imap_cmd_trailer(struct ImapData *idata)
{
static const char *notrailer = "";
const char *s = idata->buf;
if (!s)
{
mutt_debug(2, "not a tagged response\n");
return notrailer;
}
s = imap_next_word((char *) s);
if (!s || ((mutt_str_strncasecmp(s, "OK", 2) != 0) &&
(mutt_str_strncasecmp(s, "NO", 2) != 0) &&
(mutt_str_strncasecmp(s, "BAD", 3) != 0)))
{
mutt_debug(2, "not a command completion: %s\n", idata->buf);
return notrailer;
}
s = imap_next_word((char *) s);
if (!s)
return notrailer;
return s;
}
/**
* imap_exec - Execute a command and wait for the response from the server
* @param idata IMAP data
* @param cmdstr Command to execute
* @param flags Flags (see below)
* @retval 0 Success
* @retval -1 Failure
* @retval -2 OK Failure
*
* Also, handle untagged responses.
*
* Flags:
* * IMAP_CMD_FAIL_OK: the calling procedure can handle failure.
* This is used for checking for a mailbox on append and login
* * IMAP_CMD_PASS: command contains a password. Suppress logging.
* * IMAP_CMD_QUEUE: only queue command, do not execute.
* * IMAP_CMD_POLL: poll the socket for a response before running imap_cmd_step.
*/
int imap_exec(struct ImapData *idata, const char *cmdstr, int flags)
{
int rc;
rc = cmd_start(idata, cmdstr, flags);
if (rc < 0)
{
cmd_handle_fatal(idata);
return -1;
}
if (flags & IMAP_CMD_QUEUE)
return 0;
if ((flags & IMAP_CMD_POLL) && (ImapPollTimeout > 0) &&
(mutt_socket_poll(idata->conn, ImapPollTimeout)) == 0)
{
mutt_error(_("Connection to %s timed out"), idata->conn->account.host);
cmd_handle_fatal(idata);
return -1;
}
/* Allow interruptions, particularly useful if there are network problems. */
mutt_sig_allow_interrupt(1);
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
mutt_sig_allow_interrupt(0);
if (rc == IMAP_CMD_NO && (flags & IMAP_CMD_FAIL_OK))
return -2;
if (rc != IMAP_CMD_OK)
{
if ((flags & IMAP_CMD_FAIL_OK) && idata->status != IMAP_FATAL)
return -2;
mutt_debug(1, "command failed: %s\n", idata->buf);
return -1;
}
return 0;
}
/**
* imap_cmd_finish - Attempt to perform cleanup
* @param idata Server data
*
* Attempts to perform cleanup (eg fetch new mail if detected, do expunge).
* Called automatically by imap_cmd_step(), but may be called at any time.
* Called by imap_check_mailbox() just before the index is refreshed, for
* instance.
*/
void imap_cmd_finish(struct ImapData *idata)
{
if (idata->status == IMAP_FATAL)
{
cmd_handle_fatal(idata);
return;
}
if (!(idata->state >= IMAP_SELECTED) || idata->ctx->closing)
return;
if (idata->reopen & IMAP_REOPEN_ALLOW)
{
unsigned int count = idata->new_mail_count;
if (!(idata->reopen & IMAP_EXPUNGE_PENDING) &&
(idata->reopen & IMAP_NEWMAIL_PENDING) && count > idata->max_msn)
{
/* read new mail messages */
mutt_debug(2, "Fetching new mail\n");
/* check_status: curs_main uses imap_check_mailbox to detect
* whether the index needs updating */
idata->check_status = IMAP_NEWMAIL_PENDING;
imap_read_headers(idata, idata->max_msn + 1, count);
}
else if (idata->reopen & IMAP_EXPUNGE_PENDING)
{
mutt_debug(2, "Expunging mailbox\n");
imap_expunge_mailbox(idata);
/* Detect whether we've gotten unexpected EXPUNGE messages */
if ((idata->reopen & IMAP_EXPUNGE_PENDING) && !(idata->reopen & IMAP_EXPUNGE_EXPECTED))
idata->check_status = IMAP_EXPUNGE_PENDING;
idata->reopen &=
~(IMAP_EXPUNGE_PENDING | IMAP_NEWMAIL_PENDING | IMAP_EXPUNGE_EXPECTED);
}
}
idata->status = false;
}
/**
* imap_cmd_idle - Enter the IDLE state
* @param idata Server data
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*/
int imap_cmd_idle(struct ImapData *idata)
{
int rc;
if (cmd_start(idata, "IDLE", IMAP_CMD_POLL) < 0)
{
cmd_handle_fatal(idata);
return -1;
}
if ((ImapPollTimeout > 0) && (mutt_socket_poll(idata->conn, ImapPollTimeout)) == 0)
{
mutt_error(_("Connection to %s timed out"), idata->conn->account.host);
cmd_handle_fatal(idata);
return -1;
}
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
if (rc == IMAP_CMD_RESPOND)
{
/* successfully entered IDLE state */
idata->state = IMAP_IDLE;
/* queue automatic exit when next command is issued */
mutt_buffer_printf(idata->cmdbuf, "DONE\r\n");
rc = IMAP_CMD_OK;
}
if (rc != IMAP_CMD_OK)
{
mutt_debug(1, "error starting IDLE\n");
return -1;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_243_0 |
crossvul-cpp_data_good_5114_0 | /* netscreen.c
*
* Juniper NetScreen snoop output parser
* Created by re-using a lot of code from cosine.c
* Copyright (c) 2007 by Sake Blok <sake@euronet.nl>
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include "wtap-int.h"
#include "netscreen.h"
#include "file_wrappers.h"
#include <stdlib.h>
#include <string.h>
/* XXX TODO:
*
* o Construct a list of interfaces, with interface names, give
* them link-layer types based on the interface name and packet
* data, and supply interface IDs with each packet (i.e., make
* this supply a pcap-ng-style set of interfaces and associate
* packets with interfaces). This is probably the right way
* to "Pass the interface names and the traffic direction to either
* the frame-structure, a pseudo-header or use PPI." See the
* message at
*
* http://www.wireshark.org/lists/wireshark-dev/200708/msg00029.html
*
* to see whether any further discussion is still needed. I suspect
* it doesn't; pcap-NG existed at the time, as per the final
* message in that thread:
*
* http://www.wireshark.org/lists/wireshark-dev/200708/msg00039.html
*
* but I don't think we fully *supported* it at that point. Now
* that we do, we have the infrastructure to support this, except
* that we currently have no way to translate interface IDs to
* interface names in the "frame" dissector or to supply interface
* information as part of the packet metadata from Wiretap modules.
* That should be fixed so that we can show interface information,
* such as the interface name, in packet dissections from, for example,
* pcap-NG captures.
*/
static gboolean info_line(const gchar *line);
static gint64 netscreen_seek_next_packet(wtap *wth, int *err, gchar **err_info,
char *hdr);
static gboolean netscreen_check_file_type(wtap *wth, int *err,
gchar **err_info);
static gboolean netscreen_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset);
static gboolean netscreen_seek_read(wtap *wth, gint64 seek_off,
struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info);
static gboolean parse_netscreen_packet(FILE_T fh, struct wtap_pkthdr *phdr,
Buffer* buf, char *line, int *err, gchar **err_info);
static int parse_single_hex_dump_line(char* rec, guint8 *buf,
guint byte_offset);
/* Returns TRUE if the line appears to be a line with protocol info.
Otherwise it returns FALSE. */
static gboolean info_line(const gchar *line)
{
int i=NETSCREEN_SPACES_ON_INFO_LINE;
while (i-- > 0) {
if (g_ascii_isspace(*line)) {
line++;
continue;
} else {
return FALSE;
}
}
return TRUE;
}
/* Seeks to the beginning of the next packet, and returns the
byte offset. Copy the header line to hdr. Returns -1 on failure,
and sets "*err" to the error and sets "*err_info" to null or an
additional error string. */
static gint64 netscreen_seek_next_packet(wtap *wth, int *err, gchar **err_info,
char *hdr)
{
gint64 cur_off;
char buf[NETSCREEN_LINE_LENGTH];
while (1) {
cur_off = file_tell(wth->fh);
if (cur_off == -1) {
/* Error */
*err = file_error(wth->fh, err_info);
return -1;
}
if (file_gets(buf, sizeof(buf), wth->fh) == NULL) {
/* EOF or error. */
*err = file_error(wth->fh, err_info);
break;
}
if (strstr(buf, NETSCREEN_REC_MAGIC_STR1) ||
strstr(buf, NETSCREEN_REC_MAGIC_STR2)) {
g_strlcpy(hdr, buf, NETSCREEN_LINE_LENGTH);
return cur_off;
}
}
return -1;
}
/* Look through the first part of a file to see if this is
* NetScreen snoop output.
*
* Returns TRUE if it is, FALSE if it isn't or if we get an I/O error;
* if we get an I/O error, "*err" will be set to a non-zero value and
* "*err_info" is set to null or an additional error string.
*/
static gboolean netscreen_check_file_type(wtap *wth, int *err, gchar **err_info)
{
char buf[NETSCREEN_LINE_LENGTH];
guint reclen, line;
buf[NETSCREEN_LINE_LENGTH-1] = '\0';
for (line = 0; line < NETSCREEN_HEADER_LINES_TO_CHECK; line++) {
if (file_gets(buf, NETSCREEN_LINE_LENGTH, wth->fh) == NULL) {
/* EOF or error. */
*err = file_error(wth->fh, err_info);
return FALSE;
}
reclen = (guint) strlen(buf);
if (reclen < strlen(NETSCREEN_HDR_MAGIC_STR1) ||
reclen < strlen(NETSCREEN_HDR_MAGIC_STR2)) {
continue;
}
if (strstr(buf, NETSCREEN_HDR_MAGIC_STR1) ||
strstr(buf, NETSCREEN_HDR_MAGIC_STR2)) {
return TRUE;
}
}
*err = 0;
return FALSE;
}
wtap_open_return_val netscreen_open(wtap *wth, int *err, gchar **err_info)
{
/* Look for a NetScreen snoop header line */
if (!netscreen_check_file_type(wth, err, err_info)) {
if (*err != 0 && *err != WTAP_ERR_SHORT_READ)
return WTAP_OPEN_ERROR;
return WTAP_OPEN_NOT_MINE;
}
if (file_seek(wth->fh, 0L, SEEK_SET, err) == -1) /* rewind */
return WTAP_OPEN_ERROR;
wth->file_encap = WTAP_ENCAP_UNKNOWN;
wth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_NETSCREEN;
wth->snapshot_length = 0; /* not known */
wth->subtype_read = netscreen_read;
wth->subtype_seek_read = netscreen_seek_read;
wth->file_tsprec = WTAP_TSPREC_DSEC;
return WTAP_OPEN_MINE;
}
/* Find the next packet and parse it; called from wtap_read(). */
static gboolean netscreen_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset)
{
gint64 offset;
char line[NETSCREEN_LINE_LENGTH];
/* Find the next packet */
offset = netscreen_seek_next_packet(wth, err, err_info, line);
if (offset < 0)
return FALSE;
/* Parse the header and convert the ASCII hex dump to binary data */
if (!parse_netscreen_packet(wth->fh, &wth->phdr,
wth->frame_buffer, line, err, err_info))
return FALSE;
/*
* If the per-file encapsulation isn't known, set it to this
* packet's encapsulation.
*
* If it *is* known, and it isn't this packet's encapsulation,
* set it to WTAP_ENCAP_PER_PACKET, as this file doesn't
* have a single encapsulation for all packets in the file.
*/
if (wth->file_encap == WTAP_ENCAP_UNKNOWN)
wth->file_encap = wth->phdr.pkt_encap;
else {
if (wth->file_encap != wth->phdr.pkt_encap)
wth->file_encap = WTAP_ENCAP_PER_PACKET;
}
*data_offset = offset;
return TRUE;
}
/* Used to read packets in random-access fashion */
static gboolean
netscreen_seek_read(wtap *wth, gint64 seek_off,
struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
char line[NETSCREEN_LINE_LENGTH];
if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1) {
return FALSE;
}
if (file_gets(line, NETSCREEN_LINE_LENGTH, wth->random_fh) == NULL) {
*err = file_error(wth->random_fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
return parse_netscreen_packet(wth->random_fh, phdr, buf, line,
err, err_info);
}
/* Parses a packet record header. There are a few possible formats:
*
* XXX list extra formats here!
6843828.0: trust(o) len=98:00121ebbd132->00600868d659/0800
192.168.1.1 -> 192.168.1.10/6
vhl=45, tos=00, id=37739, frag=0000, ttl=64 tlen=84
tcp:ports 2222->2333, seq=3452113890, ack=1540618280, flag=5018/ACK
00 60 08 68 d6 59 00 12 1e bb d1 32 08 00 45 00 .`.h.Y.....2..E.
00 54 93 6b 00 00 40 06 63 dd c0 a8 01 01 c0 a8 .T.k..@.c.......
01 0a 08 ae 09 1d cd c3 13 e2 5b d3 f8 28 50 18 ..........[..(P.
1f d4 79 21 00 00 e7 76 89 64 16 e2 19 0a 80 09 ..y!...v.d......
31 e7 04 28 04 58 f3 d9 b1 9f 3d 65 1a db d8 61 1..(.X....=e...a
2c 21 b6 d3 20 60 0c 8c 35 98 88 cf 20 91 0e a9 ,!...`..5.......
1d 0b ..
*/
static gboolean
parse_netscreen_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer* buf,
char *line, int *err, gchar **err_info)
{
int sec;
int dsec;
char cap_int[NETSCREEN_MAX_INT_NAME_LENGTH];
char direction[2];
guint pkt_len;
char cap_src[13];
char cap_dst[13];
guint8 *pd;
gchar *p;
int n, i = 0;
guint offset = 0;
gchar dststr[13];
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
if (sscanf(line, "%9d.%9d: %15[a-z0-9/:.-](%1[io]) len=%9u:%12s->%12s/",
&sec, &dsec, cap_int, direction, &pkt_len, cap_src, cap_dst) < 5) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: Can't parse packet-header");
return -1;
}
if (pkt_len > WTAP_MAX_PACKET_SIZE) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup_printf("netscreen: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
/*
* If direction[0] is 'o', the direction is NETSCREEN_EGRESS,
* otherwise it's NETSCREEN_INGRESS.
*/
phdr->ts.secs = sec;
phdr->ts.nsecs = dsec * 100000000;
phdr->len = pkt_len;
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
while(1) {
/* The last packet is not delimited by an empty line, but by EOF
* So accept EOF as a valid delimiter too
*/
if (file_gets(line, NETSCREEN_LINE_LENGTH, fh) == NULL) {
break;
}
/*
* Skip blanks.
* The number of blanks is not fixed - for wireless
* interfaces, there may be 14 extra spaces before
* the hex data.
*/
for (p = &line[0]; g_ascii_isspace(*p); p++)
;
/* packets are delimited with empty lines */
if (*p == '\0') {
break;
}
n = parse_single_hex_dump_line(p, pd, offset);
/* the smallest packet has a length of 6 bytes, if
* the first hex-data is less then check whether
* it is a info-line and act accordingly
*/
if (offset == 0 && n < 6) {
if (info_line(line)) {
if (++i <= NETSCREEN_MAX_INFOLINES) {
continue;
}
} else {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: cannot parse hex-data");
return FALSE;
}
}
/* If there is no more data and the line was not empty,
* then there must be an error in the file
*/
if (n == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: cannot parse hex-data");
return FALSE;
}
/* Adjust the offset to the data that was just added to the buffer */
offset += n;
/* If there was more hex-data than was announced in the len=x
* header, then then there must be an error in the file
*/
if (offset > pkt_len) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: too much hex-data");
return FALSE;
}
}
/*
* Determine the encapsulation type, based on the
* first 4 characters of the interface name
*
* XXX convert this to a 'case' structure when adding more
* (non-ethernet) interfacetypes
*/
if (strncmp(cap_int, "adsl", 4) == 0) {
/* The ADSL interface can be bridged with or without
* PPP encapsulation. Check whether the first six bytes
* of the hex data are the same as the destination mac
* address in the header. If they are, assume ethernet
* LinkLayer or else PPP
*/
g_snprintf(dststr, 13, "%02x%02x%02x%02x%02x%02x",
pd[0], pd[1], pd[2], pd[3], pd[4], pd[5]);
if (strncmp(dststr, cap_dst, 12) == 0)
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
else
phdr->pkt_encap = WTAP_ENCAP_PPP;
}
else if (strncmp(cap_int, "seri", 4) == 0)
phdr->pkt_encap = WTAP_ENCAP_PPP;
else
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
phdr->caplen = offset;
return TRUE;
}
/* Take a string representing one line from a hex dump, with leading white
* space removed, and converts the text to binary data. We place the bytes
* in the buffer at the specified offset.
*
* Returns number of bytes successfully read, -1 if bad. */
static int
parse_single_hex_dump_line(char* rec, guint8 *buf, guint byte_offset)
{
int num_items_scanned;
guint8 character;
guint8 byte;
for (num_items_scanned = 0; num_items_scanned < 16; num_items_scanned++) {
character = *rec++;
if (character >= '0' && character <= '9')
byte = character - '0' + 0;
else if (character >= 'A' && character <= 'F')
byte = character - 'A' + 0xA;
else if (character >= 'a' && character <= 'f')
byte = character - 'a' + 0xa;
else if (character == ' ' || character == '\r' || character == '\n' || character == '\0') {
/* Nothing more to parse */
break;
} else
return -1; /* not a hex digit, space before ASCII dump, or EOL */
byte <<= 4;
character = *rec++ & 0xFF;
if (character >= '0' && character <= '9')
byte += character - '0' + 0;
else if (character >= 'A' && character <= 'F')
byte += character - 'A' + 0xA;
else if (character >= 'a' && character <= 'f')
byte += character - 'a' + 0xa;
else
return -1; /* not a hex digit */
buf[byte_offset + num_items_scanned] = byte;
character = *rec++ & 0xFF;
if (character == '\0' || character == '\r' || character == '\n') {
/* Nothing more to parse */
break;
} else if (character != ' ') {
/* not space before ASCII dump */
return -1;
}
}
if (num_items_scanned == 0)
return -1;
return num_items_scanned;
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5114_0 |
crossvul-cpp_data_bad_5608_2 | /*
* ModSecurity for Apache 2.x, http://www.modsecurity.org/
* Copyright (c) 2004-2011 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* You may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*/
#include "msc_xml.h"
/**
* Initialise XML parser.
*/
int xml_init(modsec_rec *msr, char **error_msg) {
if (error_msg == NULL) return -1;
*error_msg = NULL;
msr->xml = apr_pcalloc(msr->mp, sizeof(xml_data));
if (msr->xml == NULL) return -1;
return 1;
}
#if 0
static void xml_receive_sax_error(void *data, const char *msg, ...) {
modsec_rec *msr = (modsec_rec *)data;
char message[256];
if (msr == NULL) return;
apr_snprintf(message, sizeof(message), "%s (line %d offset %d)",
log_escape_nq(msr->mp, msr->xml->parsing_ctx->lastError.message),
msr->xml->parsing_ctx->lastError.line,
msr->xml->parsing_ctx->lastError.int2);
msr_log(msr, 5, "XML: Parsing error: %s", message);
}
#endif
/**
* Feed one chunk of data to the XML parser.
*/
int xml_process_chunk(modsec_rec *msr, const char *buf, unsigned int size, char **error_msg) {
if (error_msg == NULL) return -1;
*error_msg = NULL;
/* We want to initialise our parsing context here, to
* enable us to pass it the first chunk of data so that
* it can attempt to auto-detect the encoding.
*/
if (msr->xml->parsing_ctx == NULL) {
/* First invocation. */
msr_log(msr, 4, "XML: Initialising parser.");
/* NOTE When Sax interface is used libxml will not
* create the document object, but we need it.
msr->xml->sax_handler = (xmlSAXHandler *)apr_pcalloc(msr->mp, sizeof(xmlSAXHandler));
if (msr->xml->sax_handler == NULL) return -1;
msr->xml->sax_handler->error = xml_receive_sax_error;
msr->xml->sax_handler->warning = xml_receive_sax_error;
msr->xml->parsing_ctx = xmlCreatePushParserCtxt(msr->xml->sax_handler, msr,
buf, size, "body.xml");
*/
msr->xml->parsing_ctx = xmlCreatePushParserCtxt(NULL, NULL, buf, size, "body.xml");
if (msr->xml->parsing_ctx == NULL) {
*error_msg = apr_psprintf(msr->mp, "XML: Failed to create parsing context.");
return -1;
}
} else {
/* Not a first invocation. */
xmlParseChunk(msr->xml->parsing_ctx, buf, size, 0);
if (msr->xml->parsing_ctx->wellFormed != 1) {
*error_msg = apr_psprintf(msr->mp, "XML: Failed parsing document.");
return -1;
}
}
return 1;
}
/**
* Finalise XML parsing.
*/
int xml_complete(modsec_rec *msr, char **error_msg) {
if (error_msg == NULL) return -1;
*error_msg = NULL;
/* Only if we have a context, meaning we've done some work. */
if (msr->xml->parsing_ctx != NULL) {
/* This is how we signalise the end of parsing to libxml. */
xmlParseChunk(msr->xml->parsing_ctx, NULL, 0, 1);
/* Preserve the results for our reference. */
msr->xml->well_formed = msr->xml->parsing_ctx->wellFormed;
msr->xml->doc = msr->xml->parsing_ctx->myDoc;
/* Clean up everything else. */
xmlFreeParserCtxt(msr->xml->parsing_ctx);
msr->xml->parsing_ctx = NULL;
msr_log(msr, 4, "XML: Parsing complete (well_formed %u).", msr->xml->well_formed);
if (msr->xml->well_formed != 1) {
*error_msg = apr_psprintf(msr->mp, "XML: Failed parsing document.");
return -1;
}
}
return 1;
}
/**
* Frees the resources used for XML parsing.
*/
apr_status_t xml_cleanup(modsec_rec *msr) {
if (msr->xml->doc != NULL) {
xmlFreeDoc(msr->xml->doc);
msr->xml->doc = NULL;
}
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5608_2 |
crossvul-cpp_data_good_2891_13 | /* user_defined.c: user defined key type
*
* Copyright (C) 2004 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/seq_file.h>
#include <linux/err.h>
#include <keys/user-type.h>
#include <linux/uaccess.h>
#include "internal.h"
static int logon_vet_description(const char *desc);
/*
* user defined keys take an arbitrary string as the description and an
* arbitrary blob of data as the payload
*/
struct key_type key_type_user = {
.name = "user",
.preparse = user_preparse,
.free_preparse = user_free_preparse,
.instantiate = generic_key_instantiate,
.update = user_update,
.revoke = user_revoke,
.destroy = user_destroy,
.describe = user_describe,
.read = user_read,
};
EXPORT_SYMBOL_GPL(key_type_user);
/*
* This key type is essentially the same as key_type_user, but it does
* not define a .read op. This is suitable for storing username and
* password pairs in the keyring that you do not want to be readable
* from userspace.
*/
struct key_type key_type_logon = {
.name = "logon",
.preparse = user_preparse,
.free_preparse = user_free_preparse,
.instantiate = generic_key_instantiate,
.update = user_update,
.revoke = user_revoke,
.destroy = user_destroy,
.describe = user_describe,
.vet_description = logon_vet_description,
};
EXPORT_SYMBOL_GPL(key_type_logon);
/*
* Preparse a user defined key payload
*/
int user_preparse(struct key_preparsed_payload *prep)
{
struct user_key_payload *upayload;
size_t datalen = prep->datalen;
if (datalen <= 0 || datalen > 32767 || !prep->data)
return -EINVAL;
upayload = kmalloc(sizeof(*upayload) + datalen, GFP_KERNEL);
if (!upayload)
return -ENOMEM;
/* attach the data */
prep->quotalen = datalen;
prep->payload.data[0] = upayload;
upayload->datalen = datalen;
memcpy(upayload->data, prep->data, datalen);
return 0;
}
EXPORT_SYMBOL_GPL(user_preparse);
/*
* Free a preparse of a user defined key payload
*/
void user_free_preparse(struct key_preparsed_payload *prep)
{
kzfree(prep->payload.data[0]);
}
EXPORT_SYMBOL_GPL(user_free_preparse);
static void user_free_payload_rcu(struct rcu_head *head)
{
struct user_key_payload *payload;
payload = container_of(head, struct user_key_payload, rcu);
kzfree(payload);
}
/*
* update a user defined key
* - the key's semaphore is write-locked
*/
int user_update(struct key *key, struct key_preparsed_payload *prep)
{
struct user_key_payload *zap = NULL;
int ret;
/* check the quota and attach the new data */
ret = key_payload_reserve(key, prep->datalen);
if (ret < 0)
return ret;
/* attach the new data, displacing the old */
key->expiry = prep->expiry;
if (key_is_positive(key))
zap = dereference_key_locked(key);
rcu_assign_keypointer(key, prep->payload.data[0]);
prep->payload.data[0] = NULL;
if (zap)
call_rcu(&zap->rcu, user_free_payload_rcu);
return ret;
}
EXPORT_SYMBOL_GPL(user_update);
/*
* dispose of the links from a revoked keyring
* - called with the key sem write-locked
*/
void user_revoke(struct key *key)
{
struct user_key_payload *upayload = user_key_payload_locked(key);
/* clear the quota */
key_payload_reserve(key, 0);
if (upayload) {
rcu_assign_keypointer(key, NULL);
call_rcu(&upayload->rcu, user_free_payload_rcu);
}
}
EXPORT_SYMBOL(user_revoke);
/*
* dispose of the data dangling from the corpse of a user key
*/
void user_destroy(struct key *key)
{
struct user_key_payload *upayload = key->payload.data[0];
kzfree(upayload);
}
EXPORT_SYMBOL_GPL(user_destroy);
/*
* describe the user key
*/
void user_describe(const struct key *key, struct seq_file *m)
{
seq_puts(m, key->description);
if (key_is_positive(key))
seq_printf(m, ": %u", key->datalen);
}
EXPORT_SYMBOL_GPL(user_describe);
/*
* read the key data
* - the key's semaphore is read-locked
*/
long user_read(const struct key *key, char __user *buffer, size_t buflen)
{
const struct user_key_payload *upayload;
long ret;
upayload = user_key_payload_locked(key);
ret = upayload->datalen;
/* we can return the data as is */
if (buffer && buflen > 0) {
if (buflen > upayload->datalen)
buflen = upayload->datalen;
if (copy_to_user(buffer, upayload->data, buflen) != 0)
ret = -EFAULT;
}
return ret;
}
EXPORT_SYMBOL_GPL(user_read);
/* Vet the description for a "logon" key */
static int logon_vet_description(const char *desc)
{
char *p;
/* require a "qualified" description string */
p = strchr(desc, ':');
if (!p)
return -EINVAL;
/* also reject description with ':' as first char */
if (p == desc)
return -EINVAL;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2891_13 |
crossvul-cpp_data_bad_3661_0 | /*
* An implementation of key value pair (KVP) functionality for Linux.
*
*
* Copyright (C) 2010, Novell, Inc.
* Author : K. Y. Srinivasan <ksrinivasan@novell.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <sys/utsname.h>
#include <linux/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#include <linux/connector.h>
#include <linux/hyperv.h>
#include <linux/netlink.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <syslog.h>
#include <sys/stat.h>
#include <fcntl.h>
/*
* KVP protocol: The user mode component first registers with the
* the kernel component. Subsequently, the kernel component requests, data
* for the specified keys. In response to this message the user mode component
* fills in the value corresponding to the specified key. We overload the
* sequence field in the cn_msg header to define our KVP message types.
*
* We use this infrastructure for also supporting queries from user mode
* application for state that may be maintained in the KVP kernel component.
*
*/
enum key_index {
FullyQualifiedDomainName = 0,
IntegrationServicesVersion, /*This key is serviced in the kernel*/
NetworkAddressIPv4,
NetworkAddressIPv6,
OSBuildNumber,
OSName,
OSMajorVersion,
OSMinorVersion,
OSVersion,
ProcessorArchitecture
};
static char kvp_send_buffer[4096];
static char kvp_recv_buffer[4096];
static struct sockaddr_nl addr;
static char *os_name = "";
static char *os_major = "";
static char *os_minor = "";
static char *processor_arch;
static char *os_build;
static char *lic_version;
static struct utsname uts_buf;
#define MAX_FILE_NAME 100
#define ENTRIES_PER_BLOCK 50
struct kvp_record {
__u8 key[HV_KVP_EXCHANGE_MAX_KEY_SIZE];
__u8 value[HV_KVP_EXCHANGE_MAX_VALUE_SIZE];
};
struct kvp_file_state {
int fd;
int num_blocks;
struct kvp_record *records;
int num_records;
__u8 fname[MAX_FILE_NAME];
};
static struct kvp_file_state kvp_file_info[KVP_POOL_COUNT];
static void kvp_acquire_lock(int pool)
{
struct flock fl = {F_WRLCK, SEEK_SET, 0, 0, 0};
fl.l_pid = getpid();
if (fcntl(kvp_file_info[pool].fd, F_SETLKW, &fl) == -1) {
syslog(LOG_ERR, "Failed to acquire the lock pool: %d", pool);
exit(-1);
}
}
static void kvp_release_lock(int pool)
{
struct flock fl = {F_UNLCK, SEEK_SET, 0, 0, 0};
fl.l_pid = getpid();
if (fcntl(kvp_file_info[pool].fd, F_SETLK, &fl) == -1) {
perror("fcntl");
syslog(LOG_ERR, "Failed to release the lock pool: %d", pool);
exit(-1);
}
}
static void kvp_update_file(int pool)
{
FILE *filep;
size_t bytes_written;
/*
* We are going to write our in-memory registry out to
* disk; acquire the lock first.
*/
kvp_acquire_lock(pool);
filep = fopen(kvp_file_info[pool].fname, "w");
if (!filep) {
kvp_release_lock(pool);
syslog(LOG_ERR, "Failed to open file, pool: %d", pool);
exit(-1);
}
bytes_written = fwrite(kvp_file_info[pool].records,
sizeof(struct kvp_record),
kvp_file_info[pool].num_records, filep);
fflush(filep);
kvp_release_lock(pool);
}
static void kvp_update_mem_state(int pool)
{
FILE *filep;
size_t records_read = 0;
struct kvp_record *record = kvp_file_info[pool].records;
struct kvp_record *readp;
int num_blocks = kvp_file_info[pool].num_blocks;
int alloc_unit = sizeof(struct kvp_record) * ENTRIES_PER_BLOCK;
kvp_acquire_lock(pool);
filep = fopen(kvp_file_info[pool].fname, "r");
if (!filep) {
kvp_release_lock(pool);
syslog(LOG_ERR, "Failed to open file, pool: %d", pool);
exit(-1);
}
while (!feof(filep)) {
readp = &record[records_read];
records_read += fread(readp, sizeof(struct kvp_record),
ENTRIES_PER_BLOCK * num_blocks,
filep);
if (!feof(filep)) {
/*
* We have more data to read.
*/
num_blocks++;
record = realloc(record, alloc_unit * num_blocks);
if (record == NULL) {
syslog(LOG_ERR, "malloc failed");
exit(-1);
}
continue;
}
break;
}
kvp_file_info[pool].num_blocks = num_blocks;
kvp_file_info[pool].records = record;
kvp_file_info[pool].num_records = records_read;
kvp_release_lock(pool);
}
static int kvp_file_init(void)
{
int ret, fd;
FILE *filep;
size_t records_read;
__u8 *fname;
struct kvp_record *record;
struct kvp_record *readp;
int num_blocks;
int i;
int alloc_unit = sizeof(struct kvp_record) * ENTRIES_PER_BLOCK;
if (access("/var/opt/hyperv", F_OK)) {
if (mkdir("/var/opt/hyperv", S_IRUSR | S_IWUSR | S_IROTH)) {
syslog(LOG_ERR, " Failed to create /var/opt/hyperv");
exit(-1);
}
}
for (i = 0; i < KVP_POOL_COUNT; i++) {
fname = kvp_file_info[i].fname;
records_read = 0;
num_blocks = 1;
sprintf(fname, "/var/opt/hyperv/.kvp_pool_%d", i);
fd = open(fname, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IROTH);
if (fd == -1)
return 1;
filep = fopen(fname, "r");
if (!filep)
return 1;
record = malloc(alloc_unit * num_blocks);
if (record == NULL) {
fclose(filep);
return 1;
}
while (!feof(filep)) {
readp = &record[records_read];
records_read += fread(readp, sizeof(struct kvp_record),
ENTRIES_PER_BLOCK,
filep);
if (!feof(filep)) {
/*
* We have more data to read.
*/
num_blocks++;
record = realloc(record, alloc_unit *
num_blocks);
if (record == NULL) {
fclose(filep);
return 1;
}
continue;
}
break;
}
kvp_file_info[i].fd = fd;
kvp_file_info[i].num_blocks = num_blocks;
kvp_file_info[i].records = record;
kvp_file_info[i].num_records = records_read;
fclose(filep);
}
return 0;
}
static int kvp_key_delete(int pool, __u8 *key, int key_size)
{
int i;
int j, k;
int num_records;
struct kvp_record *record;
/*
* First update the in-memory state.
*/
kvp_update_mem_state(pool);
num_records = kvp_file_info[pool].num_records;
record = kvp_file_info[pool].records;
for (i = 0; i < num_records; i++) {
if (memcmp(key, record[i].key, key_size))
continue;
/*
* Found a match; just move the remaining
* entries up.
*/
if (i == num_records) {
kvp_file_info[pool].num_records--;
kvp_update_file(pool);
return 0;
}
j = i;
k = j + 1;
for (; k < num_records; k++) {
strcpy(record[j].key, record[k].key);
strcpy(record[j].value, record[k].value);
j++;
}
kvp_file_info[pool].num_records--;
kvp_update_file(pool);
return 0;
}
return 1;
}
static int kvp_key_add_or_modify(int pool, __u8 *key, int key_size, __u8 *value,
int value_size)
{
int i;
int j, k;
int num_records;
struct kvp_record *record;
int num_blocks;
if ((key_size > HV_KVP_EXCHANGE_MAX_KEY_SIZE) ||
(value_size > HV_KVP_EXCHANGE_MAX_VALUE_SIZE))
return 1;
/*
* First update the in-memory state.
*/
kvp_update_mem_state(pool);
num_records = kvp_file_info[pool].num_records;
record = kvp_file_info[pool].records;
num_blocks = kvp_file_info[pool].num_blocks;
for (i = 0; i < num_records; i++) {
if (memcmp(key, record[i].key, key_size))
continue;
/*
* Found a match; just update the value -
* this is the modify case.
*/
memcpy(record[i].value, value, value_size);
kvp_update_file(pool);
return 0;
}
/*
* Need to add a new entry;
*/
if (num_records == (ENTRIES_PER_BLOCK * num_blocks)) {
/* Need to allocate a larger array for reg entries. */
record = realloc(record, sizeof(struct kvp_record) *
ENTRIES_PER_BLOCK * (num_blocks + 1));
if (record == NULL)
return 1;
kvp_file_info[pool].num_blocks++;
}
memcpy(record[i].value, value, value_size);
memcpy(record[i].key, key, key_size);
kvp_file_info[pool].records = record;
kvp_file_info[pool].num_records++;
kvp_update_file(pool);
return 0;
}
static int kvp_get_value(int pool, __u8 *key, int key_size, __u8 *value,
int value_size)
{
int i;
int num_records;
struct kvp_record *record;
if ((key_size > HV_KVP_EXCHANGE_MAX_KEY_SIZE) ||
(value_size > HV_KVP_EXCHANGE_MAX_VALUE_SIZE))
return 1;
/*
* First update the in-memory state.
*/
kvp_update_mem_state(pool);
num_records = kvp_file_info[pool].num_records;
record = kvp_file_info[pool].records;
for (i = 0; i < num_records; i++) {
if (memcmp(key, record[i].key, key_size))
continue;
/*
* Found a match; just copy the value out.
*/
memcpy(value, record[i].value, value_size);
return 0;
}
return 1;
}
static void kvp_pool_enumerate(int pool, int index, __u8 *key, int key_size,
__u8 *value, int value_size)
{
struct kvp_record *record;
/*
* First update our in-memory database.
*/
kvp_update_mem_state(pool);
record = kvp_file_info[pool].records;
if (index >= kvp_file_info[pool].num_records) {
/*
* This is an invalid index; terminate enumeration;
* - a NULL value will do the trick.
*/
strcpy(value, "");
return;
}
memcpy(key, record[index].key, key_size);
memcpy(value, record[index].value, value_size);
}
void kvp_get_os_info(void)
{
FILE *file;
char *p, buf[512];
uname(&uts_buf);
os_build = uts_buf.release;
processor_arch = uts_buf.machine;
/*
* The current windows host (win7) expects the build
* string to be of the form: x.y.z
* Strip additional information we may have.
*/
p = strchr(os_build, '-');
if (p)
*p = '\0';
file = fopen("/etc/SuSE-release", "r");
if (file != NULL)
goto kvp_osinfo_found;
file = fopen("/etc/redhat-release", "r");
if (file != NULL)
goto kvp_osinfo_found;
/*
* Add code for other supported platforms.
*/
/*
* We don't have information about the os.
*/
os_name = uts_buf.sysname;
return;
kvp_osinfo_found:
/* up to three lines */
p = fgets(buf, sizeof(buf), file);
if (p) {
p = strchr(buf, '\n');
if (p)
*p = '\0';
p = strdup(buf);
if (!p)
goto done;
os_name = p;
/* second line */
p = fgets(buf, sizeof(buf), file);
if (p) {
p = strchr(buf, '\n');
if (p)
*p = '\0';
p = strdup(buf);
if (!p)
goto done;
os_major = p;
/* third line */
p = fgets(buf, sizeof(buf), file);
if (p) {
p = strchr(buf, '\n');
if (p)
*p = '\0';
p = strdup(buf);
if (p)
os_minor = p;
}
}
}
done:
fclose(file);
return;
}
static int
kvp_get_ip_address(int family, char *buffer, int length)
{
struct ifaddrs *ifap;
struct ifaddrs *curp;
int ipv4_len = strlen("255.255.255.255") + 1;
int ipv6_len = strlen("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")+1;
int offset = 0;
const char *str;
char tmp[50];
int error = 0;
/*
* On entry into this function, the buffer is capable of holding the
* maximum key value (2048 bytes).
*/
if (getifaddrs(&ifap)) {
strcpy(buffer, "getifaddrs failed\n");
return 1;
}
curp = ifap;
while (curp != NULL) {
if ((curp->ifa_addr != NULL) &&
(curp->ifa_addr->sa_family == family)) {
if (family == AF_INET) {
struct sockaddr_in *addr =
(struct sockaddr_in *) curp->ifa_addr;
str = inet_ntop(family, &addr->sin_addr,
tmp, 50);
if (str == NULL) {
strcpy(buffer, "inet_ntop failed\n");
error = 1;
goto getaddr_done;
}
if (offset == 0)
strcpy(buffer, tmp);
else
strcat(buffer, tmp);
strcat(buffer, ";");
offset += strlen(str) + 1;
if ((length - offset) < (ipv4_len + 1))
goto getaddr_done;
} else {
/*
* We only support AF_INET and AF_INET6
* and the list of addresses is separated by a ";".
*/
struct sockaddr_in6 *addr =
(struct sockaddr_in6 *) curp->ifa_addr;
str = inet_ntop(family,
&addr->sin6_addr.s6_addr,
tmp, 50);
if (str == NULL) {
strcpy(buffer, "inet_ntop failed\n");
error = 1;
goto getaddr_done;
}
if (offset == 0)
strcpy(buffer, tmp);
else
strcat(buffer, tmp);
strcat(buffer, ";");
offset += strlen(str) + 1;
if ((length - offset) < (ipv6_len + 1))
goto getaddr_done;
}
}
curp = curp->ifa_next;
}
getaddr_done:
freeifaddrs(ifap);
return error;
}
static int
kvp_get_domain_name(char *buffer, int length)
{
struct addrinfo hints, *info ;
int error = 0;
gethostname(buffer, length);
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET; /*Get only ipv4 addrinfo. */
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;
error = getaddrinfo(buffer, NULL, &hints, &info);
if (error != 0) {
strcpy(buffer, "getaddrinfo failed\n");
return error;
}
strcpy(buffer, info->ai_canonname);
freeaddrinfo(info);
return error;
}
static int
netlink_send(int fd, struct cn_msg *msg)
{
struct nlmsghdr *nlh;
unsigned int size;
struct msghdr message;
char buffer[64];
struct iovec iov[2];
size = NLMSG_SPACE(sizeof(struct cn_msg) + msg->len);
nlh = (struct nlmsghdr *)buffer;
nlh->nlmsg_seq = 0;
nlh->nlmsg_pid = getpid();
nlh->nlmsg_type = NLMSG_DONE;
nlh->nlmsg_len = NLMSG_LENGTH(size - sizeof(*nlh));
nlh->nlmsg_flags = 0;
iov[0].iov_base = nlh;
iov[0].iov_len = sizeof(*nlh);
iov[1].iov_base = msg;
iov[1].iov_len = size;
memset(&message, 0, sizeof(message));
message.msg_name = &addr;
message.msg_namelen = sizeof(addr);
message.msg_iov = iov;
message.msg_iovlen = 2;
return sendmsg(fd, &message, 0);
}
int main(void)
{
int fd, len, sock_opt;
int error;
struct cn_msg *message;
struct pollfd pfd;
struct nlmsghdr *incoming_msg;
struct cn_msg *incoming_cn_msg;
struct hv_kvp_msg *hv_msg;
char *p;
char *key_value;
char *key_name;
daemon(1, 0);
openlog("KVP", 0, LOG_USER);
syslog(LOG_INFO, "KVP starting; pid is:%d", getpid());
/*
* Retrieve OS release information.
*/
kvp_get_os_info();
if (kvp_file_init()) {
syslog(LOG_ERR, "Failed to initialize the pools");
exit(-1);
}
fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
if (fd < 0) {
syslog(LOG_ERR, "netlink socket creation failed; error:%d", fd);
exit(-1);
}
addr.nl_family = AF_NETLINK;
addr.nl_pad = 0;
addr.nl_pid = 0;
addr.nl_groups = CN_KVP_IDX;
error = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
if (error < 0) {
syslog(LOG_ERR, "bind failed; error:%d", error);
close(fd);
exit(-1);
}
sock_opt = addr.nl_groups;
setsockopt(fd, 270, 1, &sock_opt, sizeof(sock_opt));
/*
* Register ourselves with the kernel.
*/
message = (struct cn_msg *)kvp_send_buffer;
message->id.idx = CN_KVP_IDX;
message->id.val = CN_KVP_VAL;
hv_msg = (struct hv_kvp_msg *)message->data;
hv_msg->kvp_hdr.operation = KVP_OP_REGISTER;
message->ack = 0;
message->len = sizeof(struct hv_kvp_msg);
len = netlink_send(fd, message);
if (len < 0) {
syslog(LOG_ERR, "netlink_send failed; error:%d", len);
close(fd);
exit(-1);
}
pfd.fd = fd;
while (1) {
pfd.events = POLLIN;
pfd.revents = 0;
poll(&pfd, 1, -1);
len = recv(fd, kvp_recv_buffer, sizeof(kvp_recv_buffer), 0);
if (len < 0) {
syslog(LOG_ERR, "recv failed; error:%d", len);
close(fd);
return -1;
}
incoming_msg = (struct nlmsghdr *)kvp_recv_buffer;
incoming_cn_msg = (struct cn_msg *)NLMSG_DATA(incoming_msg);
hv_msg = (struct hv_kvp_msg *)incoming_cn_msg->data;
switch (hv_msg->kvp_hdr.operation) {
case KVP_OP_REGISTER:
/*
* Driver is registering with us; stash away the version
* information.
*/
p = (char *)hv_msg->body.kvp_register.version;
lic_version = malloc(strlen(p) + 1);
if (lic_version) {
strcpy(lic_version, p);
syslog(LOG_INFO, "KVP LIC Version: %s",
lic_version);
} else {
syslog(LOG_ERR, "malloc failed");
}
continue;
/*
* The current protocol with the kernel component uses a
* NULL key name to pass an error condition.
* For the SET, GET and DELETE operations,
* use the existing protocol to pass back error.
*/
case KVP_OP_SET:
if (kvp_key_add_or_modify(hv_msg->kvp_hdr.pool,
hv_msg->body.kvp_set.data.key,
hv_msg->body.kvp_set.data.key_size,
hv_msg->body.kvp_set.data.value,
hv_msg->body.kvp_set.data.value_size))
strcpy(hv_msg->body.kvp_set.data.key, "");
break;
case KVP_OP_GET:
if (kvp_get_value(hv_msg->kvp_hdr.pool,
hv_msg->body.kvp_set.data.key,
hv_msg->body.kvp_set.data.key_size,
hv_msg->body.kvp_set.data.value,
hv_msg->body.kvp_set.data.value_size))
strcpy(hv_msg->body.kvp_set.data.key, "");
break;
case KVP_OP_DELETE:
if (kvp_key_delete(hv_msg->kvp_hdr.pool,
hv_msg->body.kvp_delete.key,
hv_msg->body.kvp_delete.key_size))
strcpy(hv_msg->body.kvp_delete.key, "");
break;
default:
break;
}
if (hv_msg->kvp_hdr.operation != KVP_OP_ENUMERATE)
goto kvp_done;
/*
* If the pool is KVP_POOL_AUTO, dynamically generate
* both the key and the value; if not read from the
* appropriate pool.
*/
if (hv_msg->kvp_hdr.pool != KVP_POOL_AUTO) {
kvp_pool_enumerate(hv_msg->kvp_hdr.pool,
hv_msg->body.kvp_enum_data.index,
hv_msg->body.kvp_enum_data.data.key,
HV_KVP_EXCHANGE_MAX_KEY_SIZE,
hv_msg->body.kvp_enum_data.data.value,
HV_KVP_EXCHANGE_MAX_VALUE_SIZE);
goto kvp_done;
}
hv_msg = (struct hv_kvp_msg *)incoming_cn_msg->data;
key_name = (char *)hv_msg->body.kvp_enum_data.data.key;
key_value = (char *)hv_msg->body.kvp_enum_data.data.value;
switch (hv_msg->body.kvp_enum_data.index) {
case FullyQualifiedDomainName:
kvp_get_domain_name(key_value,
HV_KVP_EXCHANGE_MAX_VALUE_SIZE);
strcpy(key_name, "FullyQualifiedDomainName");
break;
case IntegrationServicesVersion:
strcpy(key_name, "IntegrationServicesVersion");
strcpy(key_value, lic_version);
break;
case NetworkAddressIPv4:
kvp_get_ip_address(AF_INET, key_value,
HV_KVP_EXCHANGE_MAX_VALUE_SIZE);
strcpy(key_name, "NetworkAddressIPv4");
break;
case NetworkAddressIPv6:
kvp_get_ip_address(AF_INET6, key_value,
HV_KVP_EXCHANGE_MAX_VALUE_SIZE);
strcpy(key_name, "NetworkAddressIPv6");
break;
case OSBuildNumber:
strcpy(key_value, os_build);
strcpy(key_name, "OSBuildNumber");
break;
case OSName:
strcpy(key_value, os_name);
strcpy(key_name, "OSName");
break;
case OSMajorVersion:
strcpy(key_value, os_major);
strcpy(key_name, "OSMajorVersion");
break;
case OSMinorVersion:
strcpy(key_value, os_minor);
strcpy(key_name, "OSMinorVersion");
break;
case OSVersion:
strcpy(key_value, os_build);
strcpy(key_name, "OSVersion");
break;
case ProcessorArchitecture:
strcpy(key_value, processor_arch);
strcpy(key_name, "ProcessorArchitecture");
break;
default:
strcpy(key_value, "Unknown Key");
/*
* We use a null key name to terminate enumeration.
*/
strcpy(key_name, "");
break;
}
/*
* Send the value back to the kernel. The response is
* already in the receive buffer. Update the cn_msg header to
* reflect the key value that has been added to the message
*/
kvp_done:
incoming_cn_msg->id.idx = CN_KVP_IDX;
incoming_cn_msg->id.val = CN_KVP_VAL;
incoming_cn_msg->ack = 0;
incoming_cn_msg->len = sizeof(struct hv_kvp_msg);
len = netlink_send(fd, incoming_cn_msg);
if (len < 0) {
syslog(LOG_ERR, "net_link send failed; error:%d", len);
exit(-1);
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3661_0 |
crossvul-cpp_data_bad_2976_1 | /*
* Salsa20: Salsa20 stream cipher algorithm
*
* Copyright (c) 2007 Tan Swee Heng <thesweeheng@gmail.com>
*
* Derived from:
* - salsa20.c: Public domain C code by Daniel J. Bernstein <djb@cr.yp.to>
*
* Salsa20 is a stream cipher candidate in eSTREAM, the ECRYPT Stream
* Cipher Project. It is designed by Daniel J. Bernstein <djb@cr.yp.to>.
* More information about eSTREAM and Salsa20 can be found here:
* http://www.ecrypt.eu.org/stream/
* http://cr.yp.to/snuffle.html
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/crypto.h>
#include <linux/types.h>
#include <linux/bitops.h>
#include <crypto/algapi.h>
#include <asm/byteorder.h>
#define SALSA20_IV_SIZE 8U
#define SALSA20_MIN_KEY_SIZE 16U
#define SALSA20_MAX_KEY_SIZE 32U
/*
* Start of code taken from D. J. Bernstein's reference implementation.
* With some modifications and optimizations made to suit our needs.
*/
/*
salsa20-ref.c version 20051118
D. J. Bernstein
Public domain.
*/
#define U32TO8_LITTLE(p, v) \
{ (p)[0] = (v >> 0) & 0xff; (p)[1] = (v >> 8) & 0xff; \
(p)[2] = (v >> 16) & 0xff; (p)[3] = (v >> 24) & 0xff; }
#define U8TO32_LITTLE(p) \
(((u32)((p)[0]) ) | ((u32)((p)[1]) << 8) | \
((u32)((p)[2]) << 16) | ((u32)((p)[3]) << 24) )
struct salsa20_ctx
{
u32 input[16];
};
static void salsa20_wordtobyte(u8 output[64], const u32 input[16])
{
u32 x[16];
int i;
memcpy(x, input, sizeof(x));
for (i = 20; i > 0; i -= 2) {
x[ 4] ^= rol32((x[ 0] + x[12]), 7);
x[ 8] ^= rol32((x[ 4] + x[ 0]), 9);
x[12] ^= rol32((x[ 8] + x[ 4]), 13);
x[ 0] ^= rol32((x[12] + x[ 8]), 18);
x[ 9] ^= rol32((x[ 5] + x[ 1]), 7);
x[13] ^= rol32((x[ 9] + x[ 5]), 9);
x[ 1] ^= rol32((x[13] + x[ 9]), 13);
x[ 5] ^= rol32((x[ 1] + x[13]), 18);
x[14] ^= rol32((x[10] + x[ 6]), 7);
x[ 2] ^= rol32((x[14] + x[10]), 9);
x[ 6] ^= rol32((x[ 2] + x[14]), 13);
x[10] ^= rol32((x[ 6] + x[ 2]), 18);
x[ 3] ^= rol32((x[15] + x[11]), 7);
x[ 7] ^= rol32((x[ 3] + x[15]), 9);
x[11] ^= rol32((x[ 7] + x[ 3]), 13);
x[15] ^= rol32((x[11] + x[ 7]), 18);
x[ 1] ^= rol32((x[ 0] + x[ 3]), 7);
x[ 2] ^= rol32((x[ 1] + x[ 0]), 9);
x[ 3] ^= rol32((x[ 2] + x[ 1]), 13);
x[ 0] ^= rol32((x[ 3] + x[ 2]), 18);
x[ 6] ^= rol32((x[ 5] + x[ 4]), 7);
x[ 7] ^= rol32((x[ 6] + x[ 5]), 9);
x[ 4] ^= rol32((x[ 7] + x[ 6]), 13);
x[ 5] ^= rol32((x[ 4] + x[ 7]), 18);
x[11] ^= rol32((x[10] + x[ 9]), 7);
x[ 8] ^= rol32((x[11] + x[10]), 9);
x[ 9] ^= rol32((x[ 8] + x[11]), 13);
x[10] ^= rol32((x[ 9] + x[ 8]), 18);
x[12] ^= rol32((x[15] + x[14]), 7);
x[13] ^= rol32((x[12] + x[15]), 9);
x[14] ^= rol32((x[13] + x[12]), 13);
x[15] ^= rol32((x[14] + x[13]), 18);
}
for (i = 0; i < 16; ++i)
x[i] += input[i];
for (i = 0; i < 16; ++i)
U32TO8_LITTLE(output + 4 * i,x[i]);
}
static const char sigma[16] = "expand 32-byte k";
static const char tau[16] = "expand 16-byte k";
static void salsa20_keysetup(struct salsa20_ctx *ctx, const u8 *k, u32 kbytes)
{
const char *constants;
ctx->input[1] = U8TO32_LITTLE(k + 0);
ctx->input[2] = U8TO32_LITTLE(k + 4);
ctx->input[3] = U8TO32_LITTLE(k + 8);
ctx->input[4] = U8TO32_LITTLE(k + 12);
if (kbytes == 32) { /* recommended */
k += 16;
constants = sigma;
} else { /* kbytes == 16 */
constants = tau;
}
ctx->input[11] = U8TO32_LITTLE(k + 0);
ctx->input[12] = U8TO32_LITTLE(k + 4);
ctx->input[13] = U8TO32_LITTLE(k + 8);
ctx->input[14] = U8TO32_LITTLE(k + 12);
ctx->input[0] = U8TO32_LITTLE(constants + 0);
ctx->input[5] = U8TO32_LITTLE(constants + 4);
ctx->input[10] = U8TO32_LITTLE(constants + 8);
ctx->input[15] = U8TO32_LITTLE(constants + 12);
}
static void salsa20_ivsetup(struct salsa20_ctx *ctx, const u8 *iv)
{
ctx->input[6] = U8TO32_LITTLE(iv + 0);
ctx->input[7] = U8TO32_LITTLE(iv + 4);
ctx->input[8] = 0;
ctx->input[9] = 0;
}
static void salsa20_encrypt_bytes(struct salsa20_ctx *ctx, u8 *dst,
const u8 *src, unsigned int bytes)
{
u8 buf[64];
if (dst != src)
memcpy(dst, src, bytes);
while (bytes) {
salsa20_wordtobyte(buf, ctx->input);
ctx->input[8]++;
if (!ctx->input[8])
ctx->input[9]++;
if (bytes <= 64) {
crypto_xor(dst, buf, bytes);
return;
}
crypto_xor(dst, buf, 64);
bytes -= 64;
dst += 64;
}
}
/*
* End of code taken from D. J. Bernstein's reference implementation.
*/
static int setkey(struct crypto_tfm *tfm, const u8 *key,
unsigned int keysize)
{
struct salsa20_ctx *ctx = crypto_tfm_ctx(tfm);
salsa20_keysetup(ctx, key, keysize);
return 0;
}
static int encrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct blkcipher_walk walk;
struct crypto_blkcipher *tfm = desc->tfm;
struct salsa20_ctx *ctx = crypto_blkcipher_ctx(tfm);
int err;
blkcipher_walk_init(&walk, dst, src, nbytes);
err = blkcipher_walk_virt_block(desc, &walk, 64);
salsa20_ivsetup(ctx, walk.iv);
if (likely(walk.nbytes == nbytes))
{
salsa20_encrypt_bytes(ctx, walk.dst.virt.addr,
walk.src.virt.addr, nbytes);
return blkcipher_walk_done(desc, &walk, 0);
}
while (walk.nbytes >= 64) {
salsa20_encrypt_bytes(ctx, walk.dst.virt.addr,
walk.src.virt.addr,
walk.nbytes - (walk.nbytes % 64));
err = blkcipher_walk_done(desc, &walk, walk.nbytes % 64);
}
if (walk.nbytes) {
salsa20_encrypt_bytes(ctx, walk.dst.virt.addr,
walk.src.virt.addr, walk.nbytes);
err = blkcipher_walk_done(desc, &walk, 0);
}
return err;
}
static struct crypto_alg alg = {
.cra_name = "salsa20",
.cra_driver_name = "salsa20-generic",
.cra_priority = 100,
.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER,
.cra_type = &crypto_blkcipher_type,
.cra_blocksize = 1,
.cra_ctxsize = sizeof(struct salsa20_ctx),
.cra_alignmask = 3,
.cra_module = THIS_MODULE,
.cra_u = {
.blkcipher = {
.setkey = setkey,
.encrypt = encrypt,
.decrypt = encrypt,
.min_keysize = SALSA20_MIN_KEY_SIZE,
.max_keysize = SALSA20_MAX_KEY_SIZE,
.ivsize = SALSA20_IV_SIZE,
}
}
};
static int __init salsa20_generic_mod_init(void)
{
return crypto_register_alg(&alg);
}
static void __exit salsa20_generic_mod_fini(void)
{
crypto_unregister_alg(&alg);
}
module_init(salsa20_generic_mod_init);
module_exit(salsa20_generic_mod_fini);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION ("Salsa20 stream cipher algorithm");
MODULE_ALIAS_CRYPTO("salsa20");
MODULE_ALIAS_CRYPTO("salsa20-generic");
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2976_1 |
crossvul-cpp_data_good_5315_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP RRRR OOO FFFFF IIIII L EEEEE %
% P P R R O O F I L E %
% PPPP RRRR O O FFF I L EEE %
% P R R O O F I L E %
% P R R OOO F IIIII LLLLL EEEEE %
% %
% %
% MagickCore Image Profile Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/colorspace-private.h"
#include "magick/configure.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/hashmap.h"
#include "magick/image.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/option-private.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantum.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/splay-tree.h"
#include "magick/string_.h"
#include "magick/thread-private.h"
#include "magick/token.h"
#include "magick/utility.h"
#if defined(MAGICKCORE_LCMS_DELEGATE)
#if defined(MAGICKCORE_HAVE_LCMS_LCMS2_H)
#include <wchar.h>
#include <lcms/lcms2.h>
#else
#include <wchar.h>
#include "lcms2.h"
#endif
#endif
/*
Forward declarations
*/
static MagickBooleanType
SetImageProfileInternal(Image *,const char *,const StringInfo *,
const MagickBooleanType);
static void
WriteTo8BimProfile(Image *,const char*,const StringInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e I m a g e P r o f i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneImageProfiles() clones one or more image profiles.
%
% The format of the CloneImageProfiles method is:
%
% MagickBooleanType CloneImageProfiles(Image *image,
% const Image *clone_image)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o clone_image: the clone image.
%
*/
MagickExport MagickBooleanType CloneImageProfiles(Image *image,
const Image *clone_image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(clone_image != (const Image *) NULL);
assert(clone_image->signature == MagickSignature);
image->color_profile.length=clone_image->color_profile.length;
image->color_profile.info=clone_image->color_profile.info;
image->iptc_profile.length=clone_image->iptc_profile.length;
image->iptc_profile.info=clone_image->iptc_profile.info;
if (clone_image->profiles != (void *) NULL)
{
if (image->profiles != (void *) NULL)
DestroyImageProfiles(image);
image->profiles=CloneSplayTree((SplayTreeInfo *) clone_image->profiles,
(void *(*)(void *)) ConstantString,(void *(*)(void *)) CloneStringInfo);
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e l e t e I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DeleteImageProfile() deletes a profile from the image by its name.
%
% The format of the DeleteImageProfile method is:
%
% MagickBooleanTyupe DeleteImageProfile(Image *image,const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name.
%
*/
MagickExport MagickBooleanType DeleteImageProfile(Image *image,const char *name)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return(MagickFalse);
if (LocaleCompare(name,"icc") == 0)
{
/*
Continue to support deprecated color profile for now.
*/
image->color_profile.length=0;
image->color_profile.info=(unsigned char *) NULL;
}
if (LocaleCompare(name,"iptc") == 0)
{
/*
Continue to support deprecated IPTC profile for now.
*/
image->iptc_profile.length=0;
image->iptc_profile.info=(unsigned char *) NULL;
}
WriteTo8BimProfile(image,name,(StringInfo *) NULL);
return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->profiles,name));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y I m a g e P r o f i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImageProfiles() releases memory associated with an image profile map.
%
% The format of the DestroyProfiles method is:
%
% void DestroyImageProfiles(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void DestroyImageProfiles(Image *image)
{
if (image->profiles != (SplayTreeInfo *) NULL)
image->profiles=DestroySplayTree((SplayTreeInfo *) image->profiles);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageProfile() gets a profile associated with an image by name.
%
% The format of the GetImageProfile method is:
%
% const StringInfo *GetImageProfile(const Image *image,const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name.
%
*/
MagickExport const StringInfo *GetImageProfile(const Image *image,
const char *name)
{
const StringInfo
*profile;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return((StringInfo *) NULL);
profile=(const StringInfo *) GetValueFromSplayTree((SplayTreeInfo *)
image->profiles,name);
return(profile);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t N e x t I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetNextImageProfile() gets the next profile name for an image.
%
% The format of the GetNextImageProfile method is:
%
% char *GetNextImageProfile(const Image *image)
%
% A description of each parameter follows:
%
% o hash_info: the hash info.
%
*/
MagickExport char *GetNextImageProfile(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return((char *) NULL);
return((char *) GetNextKeyInSplayTree((SplayTreeInfo *) image->profiles));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P r o f i l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ProfileImage() associates, applies, or removes an ICM, IPTC, or generic
% profile with / to / from an image. If the profile is NULL, it is removed
% from the image otherwise added or applied. Use a name of '*' and a profile
% of NULL to remove all profiles from the image.
%
% ICC and ICM profiles are handled as follows: If the image does not have
% an associated color profile, the one you provide is associated with the
% image and the image pixels are not transformed. Otherwise, the colorspace
% transform defined by the existing and new profile are applied to the image
% pixels and the new profile is associated with the image.
%
% The format of the ProfileImage method is:
%
% MagickBooleanType ProfileImage(Image *image,const char *name,
% const void *datum,const size_t length,const MagickBooleanType clone)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: Name of profile to add or remove: ICC, IPTC, or generic profile.
%
% o datum: the profile data.
%
% o length: the length of the profile.
%
% o clone: should be MagickFalse.
%
*/
#if defined(MAGICKCORE_LCMS_DELEGATE)
static unsigned short **DestroyPixelThreadSet(unsigned short **pixels)
{
register ssize_t
i;
assert(pixels != (unsigned short **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (pixels[i] != (unsigned short *) NULL)
pixels[i]=(unsigned short *) RelinquishMagickMemory(pixels[i]);
pixels=(unsigned short **) RelinquishMagickMemory(pixels);
return(pixels);
}
static unsigned short **AcquirePixelThreadSet(const size_t columns,
const size_t channels)
{
register ssize_t
i;
unsigned short
**pixels;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(unsigned short **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (unsigned short **) NULL)
return((unsigned short **) NULL);
(void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
for (i=0; i < (ssize_t) number_threads; i++)
{
pixels[i]=(unsigned short *) AcquireQuantumMemory(columns,channels*
sizeof(**pixels));
if (pixels[i] == (unsigned short *) NULL)
return(DestroyPixelThreadSet(pixels));
}
return(pixels);
}
static cmsHTRANSFORM *DestroyTransformThreadSet(cmsHTRANSFORM *transform)
{
register ssize_t
i;
assert(transform != (cmsHTRANSFORM *) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (transform[i] != (cmsHTRANSFORM) NULL)
cmsDeleteTransform(transform[i]);
transform=(cmsHTRANSFORM *) RelinquishMagickMemory(transform);
return(transform);
}
static cmsHTRANSFORM *AcquireTransformThreadSet(Image *image,
const cmsHPROFILE source_profile,const cmsUInt32Number source_type,
const cmsHPROFILE target_profile,const cmsUInt32Number target_type,
const int intent,const cmsUInt32Number flags)
{
cmsHTRANSFORM
*transform;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
transform=(cmsHTRANSFORM *) AcquireQuantumMemory(number_threads,
sizeof(*transform));
if (transform == (cmsHTRANSFORM *) NULL)
return((cmsHTRANSFORM *) NULL);
(void) ResetMagickMemory(transform,0,number_threads*sizeof(*transform));
for (i=0; i < (ssize_t) number_threads; i++)
{
transform[i]=cmsCreateTransformTHR((cmsContext) image,source_profile,
source_type,target_profile,target_type,intent,flags);
if (transform[i] == (cmsHTRANSFORM) NULL)
return(DestroyTransformThreadSet(transform));
}
return(transform);
}
#endif
#if defined(MAGICKCORE_LCMS_DELEGATE)
static void LCMSExceptionHandler(cmsContext context,cmsUInt32Number severity,
const char *message)
{
Image
*image;
(void) LogMagickEvent(TransformEvent,GetMagickModule(),"lcms: #%u, %s",
severity,message != (char *) NULL ? message : "no message");
image=(Image *) context;
if (image != (Image *) NULL)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ImageWarning,"UnableToTransformColorspace","`%s'",image->filename);
}
#endif
static MagickBooleanType SetsRGBImageProfile(Image *image)
{
static unsigned char
sRGBProfile[] =
{
0x00, 0x00, 0x0c, 0x8c, 0x61, 0x72, 0x67, 0x6c, 0x02, 0x20, 0x00, 0x00,
0x6d, 0x6e, 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20,
0x07, 0xde, 0x00, 0x01, 0x00, 0x06, 0x00, 0x16, 0x00, 0x0f, 0x00, 0x3a,
0x61, 0x63, 0x73, 0x70, 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00,
0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6,
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x61, 0x72, 0x67, 0x6c,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11,
0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x99,
0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0xec, 0x00, 0x00, 0x00, 0x67,
0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54, 0x00, 0x00, 0x00, 0x70,
0x64, 0x6d, 0x64, 0x64, 0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88,
0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x03, 0x4c, 0x00, 0x00, 0x00, 0x0c,
0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x58, 0x00, 0x00, 0x00, 0x67,
0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x00, 0x24,
0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xe4, 0x00, 0x00, 0x00, 0x14,
0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x24,
0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x04, 0x1c, 0x00, 0x00, 0x00, 0x14,
0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x04, 0x30, 0x00, 0x00, 0x00, 0x14,
0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00, 0x14,
0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x58, 0x00, 0x00, 0x00, 0x14,
0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x6c, 0x00, 0x00, 0x00, 0x14,
0x72, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c,
0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c,
0x62, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c,
0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f,
0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36,
0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76,
0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77,
0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39,
0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c,
0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31,
0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75,
0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77,
0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20,
0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66,
0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, 0x43, 0x72, 0x65, 0x61,
0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x47, 0x72, 0x61, 0x65, 0x6d,
0x65, 0x20, 0x57, 0x2e, 0x20, 0x47, 0x69, 0x6c, 0x6c, 0x2e, 0x20, 0x52,
0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x74, 0x6f,
0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x20,
0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x2e, 0x20, 0x4e, 0x6f, 0x20, 0x57,
0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x2c, 0x20, 0x55, 0x73, 0x65,
0x20, 0x61, 0x74, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e,
0x20, 0x72, 0x69, 0x73, 0x6b, 0x2e, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20,
0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69,
0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74,
0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e,
0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e,
0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e,
0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47,
0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61,
0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43,
0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44,
0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63,
0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20,
0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00,
0x43, 0x52, 0x54, 0x20, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36,
0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36,
0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0x7c,
0x00, 0x14, 0x5f, 0x30, 0x00, 0x10, 0xce, 0x02, 0x00, 0x03, 0xed, 0xb2,
0x00, 0x04, 0x13, 0x0a, 0x00, 0x03, 0x5c, 0x67, 0x00, 0x00, 0x00, 0x01,
0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x0a, 0x3d,
0x00, 0x50, 0x00, 0x00, 0x00, 0x57, 0x1e, 0xb8, 0x6d, 0x65, 0x61, 0x73,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02, 0x58, 0x59, 0x5a, 0x20,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00,
0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0xa0,
0x00, 0x00, 0x38, 0xf5, 0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x97, 0x00, 0x00, 0xb7, 0x87,
0x00, 0x00, 0x18, 0xd9, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x24, 0x9f, 0x00, 0x00, 0x0f, 0x84, 0x00, 0x00, 0xb6, 0xc4,
0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f, 0x00, 0x14, 0x00, 0x19,
0x00, 0x1e, 0x00, 0x23, 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37,
0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a, 0x00, 0x4f, 0x00, 0x54,
0x00, 0x59, 0x00, 0x5e, 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72,
0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86, 0x00, 0x8b, 0x00, 0x90,
0x00, 0x95, 0x00, 0x9a, 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae,
0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1, 0x00, 0xc6, 0x00, 0xcb,
0x00, 0xd0, 0x00, 0xd5, 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb,
0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01, 0x01, 0x07, 0x01, 0x0d,
0x01, 0x13, 0x01, 0x19, 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32,
0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c, 0x01, 0x52, 0x01, 0x59,
0x01, 0x60, 0x01, 0x67, 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83,
0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1, 0x01, 0xa9, 0x01, 0xb1,
0x01, 0xb9, 0x01, 0xc1, 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1,
0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03, 0x02, 0x0c, 0x02, 0x14,
0x02, 0x1d, 0x02, 0x26, 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b,
0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71, 0x02, 0x7a, 0x02, 0x84,
0x02, 0x8e, 0x02, 0x98, 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1,
0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb, 0x02, 0xf5, 0x03, 0x00,
0x03, 0x0b, 0x03, 0x16, 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43,
0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72, 0x03, 0x7e, 0x03, 0x8a,
0x03, 0x96, 0x03, 0xa2, 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3,
0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06, 0x04, 0x13, 0x04, 0x20,
0x04, 0x2d, 0x04, 0x3b, 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71,
0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8, 0x04, 0xb6, 0x04, 0xc4,
0x04, 0xd3, 0x04, 0xe1, 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c,
0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58, 0x05, 0x67, 0x05, 0x77,
0x05, 0x86, 0x05, 0x96, 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5,
0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16, 0x06, 0x27, 0x06, 0x37,
0x06, 0x48, 0x06, 0x59, 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d,
0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3, 0x06, 0xf5, 0x07, 0x07,
0x07, 0x19, 0x07, 0x2b, 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74,
0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf, 0x07, 0xd2, 0x07, 0xe5,
0x07, 0xf8, 0x08, 0x0b, 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a,
0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa, 0x08, 0xbe, 0x08, 0xd2,
0x08, 0xe7, 0x08, 0xfb, 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f,
0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4, 0x09, 0xba, 0x09, 0xcf,
0x09, 0xe5, 0x09, 0xfb, 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54,
0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae, 0x0a, 0xc5, 0x0a, 0xdc,
0x0a, 0xf3, 0x0b, 0x0b, 0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69,
0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8, 0x0b, 0xe1, 0x0b, 0xf9,
0x0c, 0x12, 0x0c, 0x2a, 0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e,
0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3, 0x0d, 0x0d, 0x0d, 0x26,
0x0d, 0x40, 0x0d, 0x5a, 0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3,
0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e, 0x0e, 0x49, 0x0e, 0x64,
0x0e, 0x7f, 0x0e, 0x9b, 0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09,
0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a, 0x0f, 0x96, 0x0f, 0xb3,
0x0f, 0xcf, 0x0f, 0xec, 0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61,
0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7, 0x10, 0xf5, 0x11, 0x13,
0x11, 0x31, 0x11, 0x4f, 0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9,
0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45, 0x12, 0x64, 0x12, 0x84,
0x12, 0xa3, 0x12, 0xc3, 0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43,
0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5, 0x13, 0xe5, 0x14, 0x06,
0x14, 0x27, 0x14, 0x49, 0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce,
0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56, 0x15, 0x78, 0x15, 0x9b,
0x15, 0xbd, 0x15, 0xe0, 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c,
0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa, 0x17, 0x1d, 0x17, 0x41,
0x17, 0x65, 0x17, 0x89, 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b,
0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf, 0x18, 0xd5, 0x18, 0xfa,
0x19, 0x20, 0x19, 0x45, 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd,
0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77, 0x1a, 0x9e, 0x1a, 0xc5,
0x1a, 0xec, 0x1b, 0x14, 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2,
0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52, 0x1c, 0x7b, 0x1c, 0xa3,
0x1c, 0xcc, 0x1c, 0xf5, 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99,
0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40, 0x1e, 0x6a, 0x1e, 0x94,
0x1e, 0xbe, 0x1e, 0xe9, 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94,
0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41, 0x20, 0x6c, 0x20, 0x98,
0x20, 0xc4, 0x20, 0xf0, 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1,
0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55, 0x22, 0x82, 0x22, 0xaf,
0x22, 0xdd, 0x23, 0x0a, 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2,
0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c, 0x24, 0xab, 0x24, 0xda,
0x25, 0x09, 0x25, 0x38, 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7,
0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7, 0x26, 0xe8, 0x27, 0x18,
0x27, 0x49, 0x27, 0x7a, 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f,
0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06, 0x29, 0x38, 0x29, 0x6b,
0x29, 0x9d, 0x29, 0xd0, 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b,
0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69, 0x2b, 0x9d, 0x2b, 0xd1,
0x2c, 0x05, 0x2c, 0x39, 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c,
0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1, 0x2e, 0x16, 0x2e, 0x4c,
0x2e, 0x82, 0x2e, 0xb7, 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91,
0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c, 0x30, 0xa4, 0x30, 0xdb,
0x31, 0x12, 0x31, 0x4a, 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a,
0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d, 0x33, 0x46, 0x33, 0x7f,
0x33, 0xb8, 0x33, 0xf1, 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8,
0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2, 0x35, 0xfd, 0x36, 0x37,
0x36, 0x72, 0x36, 0xae, 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c,
0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c, 0x38, 0xc8, 0x39, 0x05,
0x39, 0x42, 0x39, 0x7f, 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74,
0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b, 0x3b, 0xaa, 0x3b, 0xe8,
0x3c, 0x27, 0x3c, 0x65, 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61,
0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60, 0x3e, 0xa0, 0x3e, 0xe0,
0x3f, 0x21, 0x3f, 0x61, 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64,
0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a, 0x41, 0xac, 0x41, 0xee,
0x42, 0x30, 0x42, 0x72, 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d,
0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a, 0x44, 0xce, 0x45, 0x12,
0x45, 0x55, 0x45, 0x9a, 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab,
0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0, 0x48, 0x05, 0x48, 0x4b,
0x48, 0x91, 0x48, 0xd7, 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0,
0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c, 0x4b, 0x53, 0x4b, 0x9a,
0x4b, 0xe2, 0x4c, 0x2a, 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a,
0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e, 0x4e, 0xb7, 0x4f, 0x00,
0x4f, 0x49, 0x4f, 0x93, 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb,
0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6, 0x52, 0x31, 0x52, 0x7c,
0x52, 0xc7, 0x53, 0x13, 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42,
0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75, 0x55, 0xc2, 0x56, 0x0f,
0x56, 0x5c, 0x56, 0xa9, 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0,
0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a, 0x59, 0x69, 0x59, 0xb8,
0x5a, 0x07, 0x5a, 0x56, 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95,
0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6, 0x5d, 0x27, 0x5d, 0x78,
0x5d, 0xc9, 0x5e, 0x1a, 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61,
0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa, 0x60, 0xfc, 0x61, 0x4f,
0x61, 0xa2, 0x61, 0xf5, 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43,
0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94, 0x64, 0xe9, 0x65, 0x3d,
0x65, 0x92, 0x65, 0xe7, 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d,
0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96, 0x68, 0xec, 0x69, 0x43,
0x69, 0x9a, 0x69, 0xf1, 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f,
0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf, 0x6d, 0x08, 0x6d, 0x60,
0x6d, 0xb9, 0x6e, 0x12, 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78,
0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0, 0x71, 0x3a, 0x71, 0x95,
0x71, 0xf0, 0x72, 0x4b, 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8,
0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28, 0x75, 0x85, 0x75, 0xe1,
0x76, 0x3e, 0x76, 0x9b, 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11,
0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89, 0x79, 0xe7, 0x7a, 0x46,
0x7a, 0xa5, 0x7b, 0x04, 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81,
0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01, 0x7e, 0x62, 0x7e, 0xc2,
0x7f, 0x23, 0x7f, 0x84, 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a,
0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92, 0x82, 0xf4, 0x83, 0x57,
0x83, 0xba, 0x84, 0x1d, 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab,
0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b, 0x87, 0x9f, 0x88, 0x04,
0x88, 0x69, 0x88, 0xce, 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64,
0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc, 0x8c, 0x63, 0x8c, 0xca,
0x8d, 0x31, 0x8d, 0x98, 0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36,
0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6, 0x91, 0x3f, 0x91, 0xa8,
0x92, 0x11, 0x92, 0x7a, 0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20,
0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9, 0x96, 0x34, 0x96, 0x9f,
0x97, 0x0a, 0x97, 0x75, 0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24,
0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5, 0x9b, 0x42, 0x9b, 0xaf,
0x9c, 0x1c, 0x9c, 0x89, 0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40,
0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa, 0xa0, 0x69, 0xa0, 0xd8,
0xa1, 0x47, 0xa1, 0xb6, 0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76,
0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38, 0xa5, 0xa9, 0xa6, 0x1a,
0xa6, 0x8b, 0xa6, 0xfd, 0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4,
0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f, 0xab, 0x02, 0xab, 0x75,
0xab, 0xe9, 0xac, 0x5c, 0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d,
0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00, 0xb0, 0x75, 0xb0, 0xea,
0xb1, 0x60, 0xb1, 0xd6, 0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae,
0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a, 0xb6, 0x01, 0xb6, 0x79,
0xb6, 0xf0, 0xb7, 0x68, 0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a,
0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e, 0xbb, 0xa7, 0xbc, 0x21,
0xbc, 0x9b, 0xbd, 0x15, 0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff,
0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec, 0xc1, 0x67, 0xc1, 0xe3,
0xc2, 0x5f, 0xc2, 0xdb, 0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce,
0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3, 0xc7, 0x41, 0xc7, 0xbf,
0xc8, 0x3d, 0xc8, 0xbc, 0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7,
0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5, 0xcd, 0x35, 0xcd, 0xb5,
0xce, 0x36, 0xce, 0xb6, 0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba,
0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1, 0xd3, 0x44, 0xd3, 0xc6,
0xd4, 0x49, 0xd4, 0xcb, 0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8,
0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8, 0xd9, 0x6c, 0xd9, 0xf1,
0xda, 0x76, 0xda, 0xfb, 0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10,
0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29, 0xdf, 0xaf, 0xe0, 0x36,
0xe0, 0xbd, 0xe1, 0x44, 0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63,
0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84, 0xe6, 0x0d, 0xe6, 0x96,
0xe7, 0x1f, 0xe7, 0xa9, 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0,
0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb, 0xec, 0x86, 0xed, 0x11,
0xed, 0x9c, 0xee, 0x28, 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58,
0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c, 0xf3, 0x19, 0xf3, 0xa7,
0xf4, 0x34, 0xf4, 0xc2, 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb,
0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38, 0xf9, 0xc7, 0xfa, 0x57,
0xfa, 0xe7, 0xfb, 0x77, 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba,
0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff
};
StringInfo
*profile;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (GetImageProfile(image,"icc") != (const StringInfo *) NULL)
return(MagickFalse);
profile=AcquireStringInfo(sizeof(sRGBProfile));
SetStringInfoDatum(profile,sRGBProfile);
status=SetImageProfile(image,"icc",profile);
profile=DestroyStringInfo(profile);
return(status);
}
MagickExport MagickBooleanType ProfileImage(Image *image,const char *name,
const void *datum,const size_t length,
const MagickBooleanType magick_unused(clone))
{
#define ProfileImageTag "Profile/Image"
#define ThrowProfileException(severity,tag,context) \
{ \
if (source_profile != (cmsHPROFILE) NULL) \
(void) cmsCloseProfile(source_profile); \
if (target_profile != (cmsHPROFILE) NULL) \
(void) cmsCloseProfile(target_profile); \
ThrowBinaryException(severity,tag,context); \
}
MagickBooleanType
status;
StringInfo
*profile;
magick_unreferenced(clone);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(name != (const char *) NULL);
if ((datum == (const void *) NULL) || (length == 0))
{
char
*next;
/*
Delete image profile(s).
*/
ResetImageProfileIterator(image);
for (next=GetNextImageProfile(image); next != (const char *) NULL; )
{
if (IsOptionMember(next,name) != MagickFalse)
{
(void) DeleteImageProfile(image,next);
ResetImageProfileIterator(image);
}
next=GetNextImageProfile(image);
}
return(MagickTrue);
}
/*
Add a ICC, IPTC, or generic profile to the image.
*/
status=MagickTrue;
profile=AcquireStringInfo((size_t) length);
SetStringInfoDatum(profile,(unsigned char *) datum);
if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"icm") != 0))
status=SetImageProfile(image,name,profile);
else
{
const StringInfo
*icc_profile;
icc_profile=GetImageProfile(image,"icc");
if ((icc_profile != (const StringInfo *) NULL) &&
(CompareStringInfo(icc_profile,profile) == 0))
{
const char
*value;
value=GetImageProperty(image,"exif:ColorSpace");
(void) value;
if (LocaleCompare(value,"1") != 0)
(void) SetsRGBImageProfile(image);
value=GetImageProperty(image,"exif:InteroperabilityIndex");
if (LocaleCompare(value,"R98.") != 0)
(void) SetsRGBImageProfile(image);
/* Future.
value=GetImageProperty(image,"exif:InteroperabilityIndex");
if (LocaleCompare(value,"R03.") != 0)
(void) SetAdobeRGB1998ImageProfile(image);
*/
icc_profile=GetImageProfile(image,"icc");
}
if ((icc_profile != (const StringInfo *) NULL) &&
(CompareStringInfo(icc_profile,profile) == 0))
{
profile=DestroyStringInfo(profile);
return(MagickTrue);
}
#if !defined(MAGICKCORE_LCMS_DELEGATE)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (LCMS)",
image->filename);
#else
{
cmsHPROFILE
source_profile;
/*
Transform pixel colors as defined by the color profiles.
*/
cmsSetLogErrorHandler(LCMSExceptionHandler);
source_profile=cmsOpenProfileFromMemTHR((cmsContext) image,
GetStringInfoDatum(profile),(cmsUInt32Number)
GetStringInfoLength(profile));
if (source_profile == (cmsHPROFILE) NULL)
ThrowBinaryException(ResourceLimitError,
"ColorspaceColorProfileMismatch",name);
if ((cmsGetDeviceClass(source_profile) != cmsSigLinkClass) &&
(icc_profile == (StringInfo *) NULL))
status=SetImageProfile(image,name,profile);
else
{
CacheView
*image_view;
ColorspaceType
source_colorspace,
target_colorspace;
cmsColorSpaceSignature
signature;
cmsHPROFILE
target_profile;
cmsHTRANSFORM
*magick_restrict transform;
cmsUInt32Number
flags,
source_type,
target_type;
ExceptionInfo
*exception;
int
intent;
MagickBooleanType
status;
MagickOffsetType
progress;
size_t
source_channels,
target_channels;
ssize_t
y;
unsigned short
**magick_restrict source_pixels,
**magick_restrict target_pixels;
exception=(&image->exception);
target_profile=(cmsHPROFILE) NULL;
if (icc_profile != (StringInfo *) NULL)
{
target_profile=source_profile;
source_profile=cmsOpenProfileFromMemTHR((cmsContext) image,
GetStringInfoDatum(icc_profile),(cmsUInt32Number)
GetStringInfoLength(icc_profile));
if (source_profile == (cmsHPROFILE) NULL)
ThrowProfileException(ResourceLimitError,
"ColorspaceColorProfileMismatch",name);
}
switch (cmsGetColorSpace(source_profile))
{
case cmsSigCmykData:
{
source_colorspace=CMYKColorspace;
source_type=(cmsUInt32Number) TYPE_CMYK_16;
source_channels=4;
break;
}
case cmsSigGrayData:
{
source_colorspace=GRAYColorspace;
source_type=(cmsUInt32Number) TYPE_GRAY_16;
source_channels=1;
break;
}
case cmsSigLabData:
{
source_colorspace=LabColorspace;
source_type=(cmsUInt32Number) TYPE_Lab_16;
source_channels=3;
break;
}
case cmsSigLuvData:
{
source_colorspace=YUVColorspace;
source_type=(cmsUInt32Number) TYPE_YUV_16;
source_channels=3;
break;
}
case cmsSigRgbData:
{
source_colorspace=sRGBColorspace;
source_type=(cmsUInt32Number) TYPE_RGB_16;
source_channels=3;
break;
}
case cmsSigXYZData:
{
source_colorspace=XYZColorspace;
source_type=(cmsUInt32Number) TYPE_XYZ_16;
source_channels=3;
break;
}
case cmsSigYCbCrData:
{
source_colorspace=YCbCrColorspace;
source_type=(cmsUInt32Number) TYPE_YCbCr_16;
source_channels=3;
break;
}
default:
{
source_colorspace=UndefinedColorspace;
source_type=(cmsUInt32Number) TYPE_RGB_16;
source_channels=3;
break;
}
}
signature=cmsGetPCS(source_profile);
if (target_profile != (cmsHPROFILE) NULL)
signature=cmsGetColorSpace(target_profile);
switch (signature)
{
case cmsSigCmykData:
{
target_colorspace=CMYKColorspace;
target_type=(cmsUInt32Number) TYPE_CMYK_16;
target_channels=4;
break;
}
case cmsSigLabData:
{
target_colorspace=LabColorspace;
target_type=(cmsUInt32Number) TYPE_Lab_16;
target_channels=3;
break;
}
case cmsSigGrayData:
{
target_colorspace=GRAYColorspace;
target_type=(cmsUInt32Number) TYPE_GRAY_16;
target_channels=1;
break;
}
case cmsSigLuvData:
{
target_colorspace=YUVColorspace;
target_type=(cmsUInt32Number) TYPE_YUV_16;
target_channels=3;
break;
}
case cmsSigRgbData:
{
target_colorspace=sRGBColorspace;
target_type=(cmsUInt32Number) TYPE_RGB_16;
target_channels=3;
break;
}
case cmsSigXYZData:
{
target_colorspace=XYZColorspace;
target_type=(cmsUInt32Number) TYPE_XYZ_16;
target_channels=3;
break;
}
case cmsSigYCbCrData:
{
target_colorspace=YCbCrColorspace;
target_type=(cmsUInt32Number) TYPE_YCbCr_16;
target_channels=3;
break;
}
default:
{
target_colorspace=UndefinedColorspace;
target_type=(cmsUInt32Number) TYPE_RGB_16;
target_channels=3;
break;
}
}
if ((source_colorspace == UndefinedColorspace) ||
(target_colorspace == UndefinedColorspace))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
if ((source_colorspace == GRAYColorspace) &&
(SetImageGray(image,exception) == MagickFalse))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
if ((source_colorspace == CMYKColorspace) &&
(image->colorspace != CMYKColorspace))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
if ((source_colorspace == XYZColorspace) &&
(image->colorspace != XYZColorspace))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
if ((source_colorspace == YCbCrColorspace) &&
(image->colorspace != YCbCrColorspace))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
if ((source_colorspace != CMYKColorspace) &&
(source_colorspace != GRAYColorspace) &&
(source_colorspace != LabColorspace) &&
(source_colorspace != XYZColorspace) &&
(source_colorspace != YCbCrColorspace) &&
(IssRGBCompatibleColorspace(image->colorspace) == MagickFalse))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
switch (image->rendering_intent)
{
case AbsoluteIntent: intent=INTENT_ABSOLUTE_COLORIMETRIC; break;
case PerceptualIntent: intent=INTENT_PERCEPTUAL; break;
case RelativeIntent: intent=INTENT_RELATIVE_COLORIMETRIC; break;
case SaturationIntent: intent=INTENT_SATURATION; break;
default: intent=INTENT_PERCEPTUAL; break;
}
flags=cmsFLAGS_HIGHRESPRECALC;
#if defined(cmsFLAGS_BLACKPOINTCOMPENSATION)
if (image->black_point_compensation != MagickFalse)
flags|=cmsFLAGS_BLACKPOINTCOMPENSATION;
#endif
transform=AcquireTransformThreadSet(image,source_profile,
source_type,target_profile,target_type,intent,flags);
if (transform == (cmsHTRANSFORM *) NULL)
ThrowProfileException(ImageError,"UnableToCreateColorTransform",
name);
/*
Transform image as dictated by the source & target image profiles.
*/
source_pixels=AcquirePixelThreadSet(image->columns,source_channels);
target_pixels=AcquirePixelThreadSet(image->columns,target_channels);
if ((source_pixels == (unsigned short **) NULL) ||
(target_pixels == (unsigned short **) NULL))
{
transform=DestroyTransformThreadSet(transform);
ThrowProfileException(ResourceLimitError,
"MemoryAllocationFailed",image->filename);
}
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
target_pixels=DestroyPixelThreadSet(target_pixels);
source_pixels=DestroyPixelThreadSet(source_pixels);
transform=DestroyTransformThreadSet(transform);
if (source_profile != (cmsHPROFILE) NULL)
(void) cmsCloseProfile(source_profile);
if (target_profile != (cmsHPROFILE) NULL)
(void) cmsCloseProfile(target_profile);
return(MagickFalse);
}
if (target_colorspace == CMYKColorspace)
(void) SetImageColorspace(image,target_colorspace);
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
register unsigned short
*p;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
p=source_pixels[id];
for (x=0; x < (ssize_t) image->columns; x++)
{
*p++=ScaleQuantumToShort(GetPixelRed(q));
if (source_channels > 1)
{
*p++=ScaleQuantumToShort(GetPixelGreen(q));
*p++=ScaleQuantumToShort(GetPixelBlue(q));
}
if (source_channels > 3)
*p++=ScaleQuantumToShort(GetPixelIndex(indexes+x));
q++;
}
cmsDoTransform(transform[id],source_pixels[id],target_pixels[id],
(unsigned int) image->columns);
p=target_pixels[id];
q-=image->columns;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleShortToQuantum(*p));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
p++;
if (target_channels > 1)
{
SetPixelGreen(q,ScaleShortToQuantum(*p));
p++;
SetPixelBlue(q,ScaleShortToQuantum(*p));
p++;
}
if (target_channels > 3)
{
SetPixelIndex(indexes+x,ScaleShortToQuantum(*p));
p++;
}
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ProfileImage)
#endif
proceed=SetImageProgress(image,ProfileImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
(void) SetImageColorspace(image,target_colorspace);
switch (signature)
{
case cmsSigRgbData:
{
image->type=image->matte == MagickFalse ? TrueColorType :
TrueColorMatteType;
break;
}
case cmsSigCmykData:
{
image->type=image->matte == MagickFalse ? ColorSeparationType :
ColorSeparationMatteType;
break;
}
case cmsSigGrayData:
{
image->type=image->matte == MagickFalse ? GrayscaleType :
GrayscaleMatteType;
break;
}
default:
break;
}
target_pixels=DestroyPixelThreadSet(target_pixels);
source_pixels=DestroyPixelThreadSet(source_pixels);
transform=DestroyTransformThreadSet(transform);
if (cmsGetDeviceClass(source_profile) != cmsSigLinkClass)
status=SetImageProfile(image,name,profile);
if (target_profile != (cmsHPROFILE) NULL)
(void) cmsCloseProfile(target_profile);
}
(void) cmsCloseProfile(source_profile);
}
#endif
}
profile=DestroyStringInfo(profile);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e m o v e I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RemoveImageProfile() removes a named profile from the image and returns its
% value.
%
% The format of the RemoveImageProfile method is:
%
% void *RemoveImageProfile(Image *image,const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name.
%
*/
MagickExport StringInfo *RemoveImageProfile(Image *image,const char *name)
{
StringInfo
*profile;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return((StringInfo *) NULL);
if (LocaleCompare(name,"icc") == 0)
{
/*
Continue to support deprecated color profile for now.
*/
image->color_profile.length=0;
image->color_profile.info=(unsigned char *) NULL;
}
if (LocaleCompare(name,"iptc") == 0)
{
/*
Continue to support deprecated IPTC profile for now.
*/
image->iptc_profile.length=0;
image->iptc_profile.info=(unsigned char *) NULL;
}
WriteTo8BimProfile(image,name,(StringInfo *) NULL);
profile=(StringInfo *) RemoveNodeFromSplayTree((SplayTreeInfo *)
image->profiles,name);
return(profile);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s e t P r o f i l e I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetImageProfileIterator() resets the image profile iterator. Use it in
% conjunction with GetNextImageProfile() to iterate over all the profiles
% associated with an image.
%
% The format of the ResetImageProfileIterator method is:
%
% ResetImageProfileIterator(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void ResetImageProfileIterator(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return;
ResetSplayTreeIterator((SplayTreeInfo *) image->profiles);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageProfile() adds a named profile to the image. If a profile with the
% same name already exists, it is replaced. This method differs from the
% ProfileImage() method in that it does not apply CMS color profiles.
%
% The format of the SetImageProfile method is:
%
% MagickBooleanType SetImageProfile(Image *image,const char *name,
% const StringInfo *profile)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name, for example icc, exif, and 8bim (8bim is the
% Photoshop wrapper for iptc profiles).
%
% o profile: A StringInfo structure that contains the named profile.
%
*/
static void *DestroyProfile(void *profile)
{
return((void *) DestroyStringInfo((StringInfo *) profile));
}
static inline const unsigned char *ReadResourceByte(const unsigned char *p,
unsigned char *quantum)
{
*quantum=(*p++);
return(p);
}
static inline const unsigned char *ReadResourceLong(const unsigned char *p,
unsigned int *quantum)
{
*quantum=(size_t) (*p++ << 24);
*quantum|=(size_t) (*p++ << 16);
*quantum|=(size_t) (*p++ << 8);
*quantum|=(size_t) (*p++ << 0);
return(p);
}
static inline const unsigned char *ReadResourceShort(const unsigned char *p,
unsigned short *quantum)
{
*quantum=(unsigned short) (*p++ << 8);
*quantum|=(unsigned short) (*p++ << 0);
return(p);
}
static inline void WriteResourceLong(unsigned char *p,
const unsigned int quantum)
{
unsigned char
buffer[4];
buffer[0]=(unsigned char) (quantum >> 24);
buffer[1]=(unsigned char) (quantum >> 16);
buffer[2]=(unsigned char) (quantum >> 8);
buffer[3]=(unsigned char) quantum;
(void) CopyMagickMemory(p,buffer,4);
}
static void WriteTo8BimProfile(Image *image,const char *name,
const StringInfo *profile)
{
const unsigned char
*datum,
*q;
register const unsigned char
*p;
size_t
length;
StringInfo
*profile_8bim;
ssize_t
count;
unsigned char
length_byte;
unsigned int
value;
unsigned short
id,
profile_id;
if (LocaleCompare(name,"icc") == 0)
profile_id=0x040f;
else
if (LocaleCompare(name,"iptc") == 0)
profile_id=0x0404;
else
if (LocaleCompare(name,"xmp") == 0)
profile_id=0x0424;
else
return;
profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *)
image->profiles,"8bim");
if (profile_8bim == (StringInfo *) NULL)
return;
datum=GetStringInfoDatum(profile_8bim);
length=GetStringInfoLength(profile_8bim);
for (p=datum; p < (datum+length-16); )
{
q=p;
if (LocaleNCompare((char *) p,"8BIM",4) != 0)
break;
p+=4;
p=ReadResourceShort(p,&id);
p=ReadResourceByte(p,&length_byte);
p+=length_byte;
if (((length_byte+1) & 0x01) != 0)
p++;
if (p > (datum+length-4))
break;
p=ReadResourceLong(p,&value);
count=(ssize_t) value;
if ((count & 0x01) != 0)
count++;
if ((count < 0) || (p > (datum+length-count)) ||
(count > (ssize_t) length))
break;
if (id != profile_id)
p+=count;
else
{
size_t
extent,
offset;
ssize_t
extract_extent;
StringInfo
*extract_profile;
extract_extent=0;
extent=(datum+length)-(p+count);
if (profile == (StringInfo *) NULL)
{
offset=(q-datum);
extract_profile=AcquireStringInfo(offset+extent);
(void) CopyMagickMemory(extract_profile->datum,datum,offset);
}
else
{
offset=(p-datum);
extract_extent=profile->length;
if ((extract_extent & 0x01) != 0)
extract_extent++;
extract_profile=AcquireStringInfo(offset+extract_extent+extent);
(void) CopyMagickMemory(extract_profile->datum,datum,offset-4);
(void) WriteResourceLong(extract_profile->datum+offset-4,
(unsigned int) profile->length);
(void) CopyMagickMemory(extract_profile->datum+offset,
profile->datum,profile->length);
}
(void) CopyMagickMemory(extract_profile->datum+offset+extract_extent,
p+count,extent);
(void) AddValueToSplayTree((SplayTreeInfo *) image->profiles,
ConstantString("8bim"),CloneStringInfo(extract_profile));
extract_profile=DestroyStringInfo(extract_profile);
break;
}
}
}
static void GetProfilesFromResourceBlock(Image *image,
const StringInfo *resource_block)
{
const unsigned char
*datum;
register const unsigned char
*p;
size_t
length;
ssize_t
count;
StringInfo
*profile;
unsigned char
length_byte;
unsigned int
value;
unsigned short
id;
datum=GetStringInfoDatum(resource_block);
length=GetStringInfoLength(resource_block);
for (p=datum; p < (datum+length-16); )
{
if (LocaleNCompare((char *) p,"8BIM",4) != 0)
break;
p+=4;
p=ReadResourceShort(p,&id);
p=ReadResourceByte(p,&length_byte);
p+=length_byte;
if (((length_byte+1) & 0x01) != 0)
p++;
if (p > (datum+length-4))
break;
p=ReadResourceLong(p,&value);
count=(ssize_t) value;
if ((p > (datum+length-count)) || (count > (ssize_t) length) ||
(count < 0))
break;
switch (id)
{
case 0x03ed:
{
unsigned int
resolution;
unsigned short
units;
/*
Resolution.
*/
p=ReadResourceLong(p,&resolution);
image->x_resolution=((double) resolution)/65536.0;
p=ReadResourceShort(p,&units)+2;
p=ReadResourceLong(p,&resolution)+4;
image->y_resolution=((double) resolution)/65536.0;
/*
Values are always stored as pixels per inch.
*/
if ((ResolutionType) units != PixelsPerCentimeterResolution)
image->units=PixelsPerInchResolution;
else
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution/=2.54;
image->y_resolution/=2.54;
}
break;
}
case 0x0404:
{
/*
IPTC Profile
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"iptc",profile,MagickTrue);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
case 0x040c:
{
/*
Thumbnail.
*/
p+=count;
break;
}
case 0x040f:
{
/*
ICC Profile.
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"icc",profile,MagickTrue);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
case 0x0422:
{
/*
EXIF Profile.
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"exif",profile,MagickTrue);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
case 0x0424:
{
/*
XMP Profile.
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"xmp",profile,MagickTrue);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
default:
{
p+=count;
break;
}
}
if ((count & 0x01) != 0)
p++;
}
}
static MagickBooleanType SetImageProfileInternal(Image *image,const char *name,
const StringInfo *profile,const MagickBooleanType recursive)
{
char
key[MaxTextExtent],
property[MaxTextExtent];
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
image->profiles=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory,
DestroyProfile);
(void) CopyMagickString(key,name,MaxTextExtent);
LocaleLower(key);
status=AddValueToSplayTree((SplayTreeInfo *) image->profiles,
ConstantString(key),CloneStringInfo(profile));
if ((status != MagickFalse) &&
((LocaleCompare(name,"icc") == 0) || (LocaleCompare(name,"icm") == 0)))
{
const StringInfo
*icc_profile;
/*
Continue to support deprecated color profile member.
*/
icc_profile=GetImageProfile(image,name);
if (icc_profile != (const StringInfo *) NULL)
{
image->color_profile.length=GetStringInfoLength(icc_profile);
image->color_profile.info=GetStringInfoDatum(icc_profile);
}
}
if ((status != MagickFalse) &&
((LocaleCompare(name,"iptc") == 0) || (LocaleCompare(name,"8bim") == 0)))
{
const StringInfo
*iptc_profile;
/*
Continue to support deprecated IPTC profile member.
*/
iptc_profile=GetImageProfile(image,name);
if (iptc_profile != (const StringInfo *) NULL)
{
image->iptc_profile.length=GetStringInfoLength(iptc_profile);
image->iptc_profile.info=GetStringInfoDatum(iptc_profile);
}
}
if (status != MagickFalse)
{
if (LocaleCompare(name,"8bim") == 0)
GetProfilesFromResourceBlock(image,profile);
else if (recursive == MagickFalse)
WriteTo8BimProfile(image,name,profile);
}
/*
Inject profile into image properties.
*/
(void) FormatLocaleString(property,MaxTextExtent,"%s:*",name);
(void) GetImageProperty(image,property);
return(status);
}
MagickExport MagickBooleanType SetImageProfile(Image *image,const char *name,
const StringInfo *profile)
{
return(SetImageProfileInternal(image,name,profile,MagickFalse));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S y n c I m a g e P r o f i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncImageProfiles() synchronizes image properties with the image profiles.
% Currently we only support updating the EXIF resolution and orientation.
%
% The format of the SyncImageProfiles method is:
%
% MagickBooleanType SyncImageProfiles(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static inline int ReadProfileByte(unsigned char **p,size_t *length)
{
int
c;
if (*length < 1)
return(EOF);
c=(int) (*(*p)++);
(*length)--;
return(c);
}
static inline unsigned short ReadProfileShort(const EndianType endian,
unsigned char *buffer)
{
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) ((buffer[1] << 8) | buffer[0]);
return((unsigned short) (value & 0xffff));
}
value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) |
((unsigned char *) buffer)[1]);
return((unsigned short) (value & 0xffff));
}
static inline unsigned int ReadProfileLong(const EndianType endian,
unsigned char *buffer)
{
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) |
(buffer[1] << 8 ) | (buffer[0]));
return((unsigned int) (value & 0xffffffff));
}
value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) |
(buffer[2] << 8) | buffer[3]);
return((unsigned int) (value & 0xffffffff));
}
static inline unsigned int ReadProfileMSBLong(unsigned char **p,size_t *length)
{
unsigned int
value;
if (*length < 4)
return(0);
value=ReadProfileLong(MSBEndian,*p);
(*length)-=4;
*p+=4;
return(value);
}
static inline unsigned short ReadProfileMSBShort(unsigned char **p,
size_t *length)
{
unsigned short
value;
if (*length < 2)
return(0);
value=ReadProfileShort(MSBEndian,*p);
(*length)-=2;
*p+=2;
return(value);
}
static inline void WriteProfileLong(const EndianType endian,
const size_t value,unsigned char *p)
{
unsigned char
buffer[4];
if (endian == LSBEndian)
{
buffer[0]=(unsigned char) value;
buffer[1]=(unsigned char) (value >> 8);
buffer[2]=(unsigned char) (value >> 16);
buffer[3]=(unsigned char) (value >> 24);
(void) CopyMagickMemory(p,buffer,4);
return;
}
buffer[0]=(unsigned char) (value >> 24);
buffer[1]=(unsigned char) (value >> 16);
buffer[2]=(unsigned char) (value >> 8);
buffer[3]=(unsigned char) value;
(void) CopyMagickMemory(p,buffer,4);
}
static void WriteProfileShort(const EndianType endian,
const unsigned short value,unsigned char *p)
{
unsigned char
buffer[2];
if (endian == LSBEndian)
{
buffer[0]=(unsigned char) value;
buffer[1]=(unsigned char) (value >> 8);
(void) CopyMagickMemory(p,buffer,2);
return;
}
buffer[0]=(unsigned char) (value >> 8);
buffer[1]=(unsigned char) value;
(void) CopyMagickMemory(p,buffer,2);
}
static MagickBooleanType Sync8BimProfile(Image *image,StringInfo *profile)
{
size_t
length;
ssize_t
count;
unsigned char
*p;
unsigned short
id;
length=GetStringInfoLength(profile);
p=GetStringInfoDatum(profile);
while (length != 0)
{
if (ReadProfileByte(&p,&length) != 0x38)
continue;
if (ReadProfileByte(&p,&length) != 0x42)
continue;
if (ReadProfileByte(&p,&length) != 0x49)
continue;
if (ReadProfileByte(&p,&length) != 0x4D)
continue;
if (length < 7)
return(MagickFalse);
id=ReadProfileMSBShort(&p,&length);
count=(ssize_t) ReadProfileByte(&p,&length);
if ((count > (ssize_t) length) || (count < 0))
return(MagickFalse);
p+=count;
if ((*p & 0x01) == 0)
(void) ReadProfileByte(&p,&length);
count=(ssize_t) ReadProfileMSBLong(&p,&length);
if ((count > (ssize_t) length) || (count < 0))
return(MagickFalse);
if ((id == 0x3ED) && (count == 16))
{
if (image->units == PixelsPerCentimeterResolution)
WriteProfileLong(MSBEndian, (unsigned int) (image->x_resolution*2.54*
65536.0),p);
else
WriteProfileLong(MSBEndian, (unsigned int) (image->x_resolution*
65536.0),p);
WriteProfileShort(MSBEndian,(unsigned short) image->units,p+4);
if (image->units == PixelsPerCentimeterResolution)
WriteProfileLong(MSBEndian, (unsigned int) (image->y_resolution*2.54*
65536.0),p+8);
else
WriteProfileLong(MSBEndian, (unsigned int) (image->y_resolution*
65536.0),p+8);
WriteProfileShort(MSBEndian,(unsigned short) image->units,p+12);
}
p+=count;
length-=count;
}
return(MagickTrue);
}
static MagickBooleanType SyncExifProfile(Image *image, StringInfo *profile)
{
#define MaxDirectoryStack 16
#define EXIF_DELIMITER "\n"
#define EXIF_NUM_FORMATS 12
#define TAG_EXIF_OFFSET 0x8769
#define TAG_INTEROP_OFFSET 0xa005
typedef struct _DirectoryInfo
{
unsigned char
*directory;
size_t
entry;
} DirectoryInfo;
DirectoryInfo
directory_stack[MaxDirectoryStack];
EndianType
endian;
size_t
entry,
length,
number_entries;
SplayTreeInfo
*exif_resources;
ssize_t
id,
level,
offset;
static int
format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};
unsigned char
*directory,
*exif;
/*
Set EXIF resolution tag.
*/
length=GetStringInfoLength(profile);
exif=GetStringInfoDatum(profile);
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadProfileShort(LSBEndian,exif);
if ((id != 0x4949) && (id != 0x4D4D))
{
while (length != 0)
{
if (ReadProfileByte(&exif,&length) != 0x45)
continue;
if (ReadProfileByte(&exif,&length) != 0x78)
continue;
if (ReadProfileByte(&exif,&length) != 0x69)
continue;
if (ReadProfileByte(&exif,&length) != 0x66)
continue;
if (ReadProfileByte(&exif,&length) != 0x00)
continue;
if (ReadProfileByte(&exif,&length) != 0x00)
continue;
break;
}
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadProfileShort(LSBEndian,exif);
}
endian=LSBEndian;
if (id == 0x4949)
endian=LSBEndian;
else
if (id == 0x4D4D)
endian=MSBEndian;
else
return(MagickFalse);
if (ReadProfileShort(endian,exif+2) != 0x002a)
return(MagickFalse);
/*
This the offset to the first IFD.
*/
offset=(ssize_t) ((int) ReadProfileLong(endian,exif+4));
if ((offset < 0) || ((size_t) offset >= length))
return(MagickFalse);
directory=exif+offset;
level=0;
entry=0;
exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL,
(void *(*)(void *)) NULL,(void *(*)(void *)) NULL);
do
{
if (level > 0)
{
level--;
directory=directory_stack[level].directory;
entry=directory_stack[level].entry;
}
if ((directory < exif) || (directory > (exif+length-2)))
break;
/*
Determine how many entries there are in the current IFD.
*/
number_entries=ReadProfileShort(endian,directory);
for ( ; entry < number_entries; entry++)
{
register unsigned char
*p,
*q;
size_t
number_bytes;
ssize_t
components,
format,
tag_value;
q=(unsigned char *) (directory+2+(12*entry));
if (GetValueFromSplayTree(exif_resources,q) == q)
break;
(void) AddValueToSplayTree(exif_resources,q,q);
tag_value=(ssize_t) ReadProfileShort(endian,q);
format=(ssize_t) ReadProfileShort(endian,q+2);
if ((format-1) >= EXIF_NUM_FORMATS)
break;
components=(ssize_t) ((int) ReadProfileLong(endian,q+4));
number_bytes=(size_t) components*format_bytes[format];
if ((ssize_t) number_bytes < components)
break; /* prevent overflow */
if (number_bytes <= 4)
p=q+8;
else
{
ssize_t
offset;
/*
The directory entry contains an offset.
*/
offset=(ssize_t) ((int) ReadProfileLong(endian,q+8));
if ((ssize_t) (offset+number_bytes) < offset)
continue; /* prevent overflow */
if ((size_t) (offset+number_bytes) > length)
continue;
p=(unsigned char *) (exif+offset);
}
switch (tag_value)
{
case 0x011a:
{
(void) WriteProfileLong(endian,(size_t) (image->x_resolution+0.5),p);
(void) WriteProfileLong(endian,1UL,p+4);
break;
}
case 0x011b:
{
(void) WriteProfileLong(endian,(size_t) (image->y_resolution+0.5),p);
(void) WriteProfileLong(endian,1UL,p+4);
break;
}
case 0x0112:
{
if (number_bytes == 4)
{
(void) WriteProfileLong(endian,(size_t) image->orientation,p);
break;
}
(void) WriteProfileShort(endian,(unsigned short) image->orientation,
p);
break;
}
case 0x0128:
{
if (number_bytes == 4)
{
(void) WriteProfileLong(endian,(size_t) (image->units+1),p);
break;
}
(void) WriteProfileShort(endian,(unsigned short) (image->units+1),p);
break;
}
default:
break;
}
if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET))
{
ssize_t
offset;
offset=(ssize_t) ((int) ReadProfileLong(endian,p));
if (((size_t) offset < length) && (level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=directory;
entry++;
directory_stack[level].entry=entry;
level++;
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
level++;
if ((directory+2+(12*number_entries)) > (exif+length))
break;
offset=(ssize_t) ((int) ReadProfileLong(endian,directory+2+(12*
number_entries)));
if ((offset != 0) && ((size_t) offset < length) &&
(level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
level++;
}
}
break;
}
}
} while (level > 0);
exif_resources=DestroySplayTree(exif_resources);
return(MagickTrue);
}
MagickExport MagickBooleanType SyncImageProfiles(Image *image)
{
MagickBooleanType
status;
StringInfo
*profile;
status=MagickTrue;
profile=(StringInfo *) GetImageProfile(image,"8BIM");
if (profile != (StringInfo *) NULL)
if (Sync8BimProfile(image,profile) == MagickFalse)
status=MagickFalse;
profile=(StringInfo *) GetImageProfile(image,"EXIF");
if (profile != (StringInfo *) NULL)
if (SyncExifProfile(image,profile) == MagickFalse)
status=MagickFalse;
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5315_0 |
crossvul-cpp_data_bad_1562_0 | #include <gio/gio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include "libabrt.h"
#include "abrt-polkit.h"
#include "abrt_glib.h"
#include <libreport/dump_dir.h>
#include "problem_api.h"
static GMainLoop *loop;
static guint g_timeout_source;
/* default, settable with -t: */
static unsigned g_timeout_value = 120;
/* ---------------------------------------------------------------------------------------------------- */
static GDBusNodeInfo *introspection_data = NULL;
/* Introspection data for the service we are exporting */
static const gchar introspection_xml[] =
"<node>"
" <interface name='"ABRT_DBUS_IFACE"'>"
" <method name='NewProblem'>"
" <arg type='a{ss}' name='problem_data' direction='in'/>"
" <arg type='s' name='problem_id' direction='out'/>"
" </method>"
" <method name='GetProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetAllProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetForeignProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetInfo'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='as' name='element_names' direction='in'/>"
" <arg type='a{ss}' name='response' direction='out'/>"
" </method>"
" <method name='SetElement'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" <arg type='s' name='value' direction='in'/>"
" </method>"
" <method name='DeleteElement'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" </method>"
" <method name='ChownProblemDir'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" </method>"
" <method name='DeleteProblem'>"
" <arg type='as' name='problem_dir' direction='in'/>"
" </method>"
" <method name='FindProblemByElementInTimeRange'>"
" <arg type='s' name='element' direction='in'/>"
" <arg type='s' name='value' direction='in'/>"
" <arg type='x' name='timestamp_from' direction='in'/>"
" <arg type='x' name='timestamp_to' direction='in'/>"
" <arg type='b' name='all_users' direction='in'/>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='Quit' />"
" </interface>"
"</node>";
/* ---------------------------------------------------------------------------------------------------- */
/* forward */
static gboolean on_timeout_cb(gpointer user_data);
static void reset_timeout(void)
{
if (g_timeout_source > 0)
{
log_info("Removing timeout");
g_source_remove(g_timeout_source);
}
log_info("Setting a new timeout");
g_timeout_source = g_timeout_add_seconds(g_timeout_value, on_timeout_cb, NULL);
}
static uid_t get_caller_uid(GDBusConnection *connection, GDBusMethodInvocation *invocation, const char *caller)
{
GError *error = NULL;
guint caller_uid;
GDBusProxy * proxy = g_dbus_proxy_new_sync(connection,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
NULL,
&error);
GVariant *result = g_dbus_proxy_call_sync(proxy,
"GetConnectionUnixUser",
g_variant_new ("(s)", caller),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
if (result == NULL)
{
/* we failed to get the uid, so return (uid_t) -1 to indicate the error
*/
if (error)
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidUser",
error->message);
g_error_free(error);
}
else
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidUser",
_("Unknown error"));
}
return (uid_t) -1;
}
g_variant_get(result, "(u)", &caller_uid);
g_variant_unref(result);
log_info("Caller uid: %i", caller_uid);
return caller_uid;
}
static bool allowed_problem_dir(const char *dir_name)
{
//HACK HACK HACK! Disabled for now until we fix clients (abrt-gui) to not pass /home/user/.cache/abrt/spool
#if 0
unsigned len = strlen(g_settings_dump_location);
/* If doesn't start with "g_settings_dump_location[/]"... */
if (strncmp(dir_name, g_settings_dump_location, len) != 0
|| (dir_name[len] != '/' && dir_name[len] != '\0')
/* or contains "/." anywhere (-> might contain ".." component) */
|| strstr(dir_name + len, "/.")
) {
return false;
}
#endif
return true;
}
static char *handle_new_problem(GVariant *problem_info, uid_t caller_uid, char **error)
{
problem_data_t *pd = problem_data_new();
GVariantIter *iter;
g_variant_get(problem_info, "a{ss}", &iter);
gchar *key, *value;
while (g_variant_iter_loop(iter, "{ss}", &key, &value))
{
problem_data_add_text_editable(pd, key, value);
}
if (caller_uid != 0 || problem_data_get_content_or_NULL(pd, FILENAME_UID) == NULL)
{ /* set uid field to caller's uid if caller is not root or root doesn't pass own uid */
log_info("Adding UID %d to problem data", caller_uid);
char buf[sizeof(uid_t) * 3 + 2];
snprintf(buf, sizeof(buf), "%d", caller_uid);
problem_data_add_text_noteditable(pd, FILENAME_UID, buf);
}
/* At least it should generate local problem identifier UUID */
problem_data_add_basics(pd);
char *problem_id = problem_data_save(pd);
if (problem_id)
notify_new_path(problem_id);
else if (error)
*error = xasprintf("Cannot create a new problem");
problem_data_free(pd);
return problem_id;
}
static void return_InvalidProblemDir_error(GDBusMethodInvocation *invocation, const char *dir_name)
{
char *msg = xasprintf(_("'%s' is not a valid problem directory"), dir_name);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidProblemDir",
msg);
free(msg);
}
/*
* Checks element's rights and does not open directory if element is protected.
* Checks problem's rights and does not open directory if user hasn't got
* access to a problem.
*
* Returns a dump directory opend for writing or NULL.
*
* If any operation from the above listed fails, immediately returns D-Bus
* error to a D-Bus caller.
*/
static struct dump_dir *open_directory_for_modification_of_element(
GDBusMethodInvocation *invocation,
uid_t caller_uid,
const char *problem_id,
const char *element)
{
static const char *const protected_elements[] = {
FILENAME_TIME,
FILENAME_UID,
NULL,
};
for (const char *const *protected = protected_elements; *protected; ++protected)
{
if (strcmp(*protected, element) == 0)
{
log_notice("'%s' element of '%s' can't be modified", element, problem_id);
char *error = xasprintf(_("'%s' element can't be modified"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ProtectedElement",
error);
free(error);
return NULL;
}
}
if (!dump_dir_accessible_by_uid(problem_id, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("'%s' is not a valid problem directory", problem_id);
return_InvalidProblemDir_error(invocation, problem_id);
}
else
{
log_notice("UID(%d) is not Authorized to access '%s'", caller_uid, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
}
return NULL;
}
struct dump_dir *dd = dd_opendir(problem_id, /* flags : */ 0);
if (!dd)
{ /* This should not happen because of the access check above */
log_notice("Can't access the problem '%s' for modification", problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("Can't access the problem for modification"));
return NULL;
}
return dd;
}
/*
* Lists problems which have given element and were seen in given time interval
*/
struct field_and_time_range {
GList *list;
const char *element;
const char *value;
unsigned long timestamp_from;
unsigned long timestamp_to;
};
static int add_dirname_to_GList_if_matches(struct dump_dir *dd, void *arg)
{
struct field_and_time_range *me = arg;
char *field_data = dd_load_text(dd, me->element);
int brk = (strcmp(field_data, me->value) != 0);
free(field_data);
if (brk)
return 0;
field_data = dd_load_text(dd, FILENAME_LAST_OCCURRENCE);
long val = atol(field_data);
free(field_data);
if (val < me->timestamp_from || val > me->timestamp_to)
return 0;
me->list = g_list_prepend(me->list, xstrdup(dd->dd_dirname));
return 0;
}
static GList *get_problem_dirs_for_element_in_time(uid_t uid,
const char *element,
const char *value,
unsigned long timestamp_from,
unsigned long timestamp_to)
{
if (timestamp_to == 0) /* not sure this is possible, but... */
timestamp_to = time(NULL);
struct field_and_time_range me = {
.list = NULL,
.element = element,
.value = value,
.timestamp_from = timestamp_from,
.timestamp_to = timestamp_to,
};
for_each_problem_in_dir(g_settings_dump_location, uid, add_dirname_to_GList_if_matches, &me);
return g_list_reverse(me.list);
}
static void handle_method_call(GDBusConnection *connection,
const gchar *caller,
const gchar *object_path,
const gchar *interface_name,
const gchar *method_name,
GVariant *parameters,
GDBusMethodInvocation *invocation,
gpointer user_data)
{
reset_timeout();
uid_t caller_uid;
GVariant *response;
caller_uid = get_caller_uid(connection, invocation, caller);
log_notice("caller_uid:%ld method:'%s'", (long)caller_uid, method_name);
if (caller_uid == (uid_t) -1)
return;
if (g_strcmp0(method_name, "NewProblem") == 0)
{
char *error = NULL;
char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error);
if (!problem_id)
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
free(error);
return;
}
/* else */
response = g_variant_new("(s)", problem_id);
g_dbus_method_invocation_return_value(invocation, response);
free(problem_id);
return;
}
if (g_strcmp0(method_name, "GetProblems") == 0)
{
GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
//I was told that g_dbus_method frees the response
//g_variant_unref(response);
return;
}
if (g_strcmp0(method_name, "GetAllProblems") == 0)
{
/*
- so, we have UID,
- if it's 0, then we don't have to check anything and just return all directories
- if uid != 0 then we want to ask for authorization
*/
if (caller_uid != 0)
{
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes)
caller_uid = 0;
}
GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "GetForeignProblems") == 0)
{
GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "ChownProblemDir") == 0)
{
const gchar *problem_dir;
g_variant_get(parameters, "(&s)", &problem_dir);
log_notice("problem_dir:'%s'", problem_dir);
if (!allowed_problem_dir(problem_dir))
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int ddstat = dump_dir_stat_for_uid(problem_dir, caller_uid);
if (ddstat < 0)
{
if (errno == ENOTDIR)
{
log_notice("requested directory does not exist '%s'", problem_dir);
}
else
{
perror_msg("can't get stat of '%s'", problem_dir);
}
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
if (ddstat & DD_STAT_OWNED_BY_UID)
{ //caller seems to be in group with access to this dir, so no action needed
log_notice("caller has access to the requested directory %s", problem_dir);
g_dbus_method_invocation_return_value(invocation, NULL);
return;
}
if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 &&
polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{
log_notice("not authorized");
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
return;
}
struct dump_dir *dd = dd_opendir(problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);
if (!dd)
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int chown_res = dd_chown(dd, caller_uid);
if (chown_res != 0)
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ChownError",
_("Chowning directory failed. Check system logs for more details."));
else
g_dbus_method_invocation_return_value(invocation, NULL);
dd_close(dd);
return;
}
if (g_strcmp0(method_name, "GetInfo") == 0)
{
/* Parameter tuple is (sas) */
/* Get 1st param - problem dir name */
const gchar *problem_dir;
g_variant_get_child(parameters, 0, "&s", &problem_dir);
log_notice("problem_dir:'%s'", problem_dir);
if (!allowed_problem_dir(problem_dir))
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
if (!dump_dir_accessible_by_uid(problem_dir, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("Requested directory does not exist '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{
log_notice("not authorized");
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
return;
}
}
struct dump_dir *dd = dd_opendir(problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);
if (!dd)
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
/* Get 2nd param - vector of element names */
GVariant *array = g_variant_get_child_value(parameters, 1);
GList *elements = string_list_from_variant(array);
g_variant_unref(array);
GVariantBuilder *builder = NULL;
for (GList *l = elements; l; l = l->next)
{
const char *element_name = (const char*)l->data;
char *value = dd_load_text_ext(dd, element_name, 0
| DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE
| DD_FAIL_QUIETLY_ENOENT
| DD_FAIL_QUIETLY_EACCES);
log_notice("element '%s' %s", element_name, value ? "fetched" : "not found");
if (value)
{
if (!builder)
builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
/* g_variant_builder_add makes a copy. No need to xstrdup here */
g_variant_builder_add(builder, "{ss}", element_name, value);
free(value);
}
}
list_free_with_free(elements);
dd_close(dd);
/* It is OK to call g_variant_new("(a{ss})", NULL) because */
/* G_VARIANT_TYPE_TUPLE allows NULL value */
GVariant *response = g_variant_new("(a{ss})", builder);
if (builder)
g_variant_builder_unref(builder);
log_info("GetInfo: returning value for '%s'", problem_dir);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "SetElement") == 0)
{
const char *problem_id;
const char *element;
const char *value;
g_variant_get(parameters, "(&s&s&s)", &problem_id, &element, &value);
if (element == NULL || element[0] == '\0' || strlen(element) > 64)
{
log_notice("'%s' is not a valid element name of '%s'", element, problem_id);
char *error = xasprintf(_("'%s' is not a valid element name"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidElement",
error);
free(error);
return;
}
struct dump_dir *dd = open_directory_for_modification_of_element(
invocation, caller_uid, problem_id, element);
if (!dd)
/* Already logged from open_directory_for_modification_of_element() */
return;
/* Is it good idea to make it static? Is it possible to change the max size while a single run? */
const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024);
const long item_size = dd_get_item_size(dd, element);
if (item_size < 0)
{
log_notice("Can't get size of '%s/%s'", problem_id, element);
char *error = xasprintf(_("Can't get size of '%s'"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
return;
}
const double requested_size = (double)strlen(value) - item_size;
/* Don't want to check the size limit in case of reducing of size */
if (requested_size > 0
&& requested_size > (max_dir_size - get_dirsize(g_settings_dump_location)))
{
log_notice("No problem space left in '%s' (requested Bytes %f)", problem_id, requested_size);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("No problem space left"));
}
else
{
dd_save_text(dd, element, value);
g_dbus_method_invocation_return_value(invocation, NULL);
}
dd_close(dd);
return;
}
if (g_strcmp0(method_name, "DeleteElement") == 0)
{
const char *problem_id;
const char *element;
g_variant_get(parameters, "(&s&s)", &problem_id, &element);
struct dump_dir *dd = open_directory_for_modification_of_element(
invocation, caller_uid, problem_id, element);
if (!dd)
/* Already logged from open_directory_for_modification_of_element() */
return;
const int res = dd_delete_item(dd, element);
dd_close(dd);
if (res != 0)
{
log_notice("Can't delete the element '%s' from the problem directory '%s'", element, problem_id);
char *error = xasprintf(_("Can't delete the element '%s' from the problem directory '%s'"), element, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
free(error);
return;
}
g_dbus_method_invocation_return_value(invocation, NULL);
return;
}
if (g_strcmp0(method_name, "DeleteProblem") == 0)
{
/* Dbus parameters are always tuples.
* In this case, it's (as) - a tuple of one element (array of strings).
* Need to fetch the array:
*/
GVariant *array = g_variant_get_child_value(parameters, 0);
GList *problem_dirs = string_list_from_variant(array);
g_variant_unref(array);
for (GList *l = problem_dirs; l; l = l->next)
{
const char *dir_name = (const char*)l->data;
log_notice("dir_name:'%s'", dir_name);
if (!allowed_problem_dir(dir_name))
{
return_InvalidProblemDir_error(invocation, dir_name);
goto ret;
}
}
for (GList *l = problem_dirs; l; l = l->next)
{
const char *dir_name = (const char*)l->data;
if (!dump_dir_accessible_by_uid(dir_name, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("Requested directory does not exist '%s'", dir_name);
continue;
}
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{ // if user didn't provide correct credentials, just move to the next dir
continue;
}
}
delete_dump_dir(dir_name);
}
g_dbus_method_invocation_return_value(invocation, NULL);
ret:
list_free_with_free(problem_dirs);
return;
}
if (g_strcmp0(method_name, "FindProblemByElementInTimeRange") == 0)
{
const gchar *element;
const gchar *value;
glong timestamp_from;
glong timestamp_to;
gboolean all;
g_variant_get_child(parameters, 0, "&s", &element);
g_variant_get_child(parameters, 1, "&s", &value);
g_variant_get_child(parameters, 2, "x", ×tamp_from);
g_variant_get_child(parameters, 3, "x", ×tamp_to);
g_variant_get_child(parameters, 4, "b", &all);
if (all && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes)
caller_uid = 0;
GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from,
timestamp_to);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "Quit") == 0)
{
g_dbus_method_invocation_return_value(invocation, NULL);
g_main_loop_quit(loop);
return;
}
}
static gboolean on_timeout_cb(gpointer user_data)
{
g_main_loop_quit(loop);
return TRUE;
}
static const GDBusInterfaceVTable interface_vtable =
{
.method_call = handle_method_call,
.get_property = NULL,
.set_property = NULL,
};
static void on_bus_acquired(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
guint registration_id;
registration_id = g_dbus_connection_register_object(connection,
ABRT_DBUS_OBJECT,
introspection_data->interfaces[0],
&interface_vtable,
NULL, /* user_data */
NULL, /* user_data_free_func */
NULL); /* GError** */
g_assert(registration_id > 0);
reset_timeout();
}
/* not used
static void on_name_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
}
*/
static void on_name_lost(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
g_print(_("The name '%s' has been lost, please check if other "
"service owning the name is not running.\n"), name);
exit(1);
}
int main(int argc, char *argv[])
{
/* I18n */
setlocale(LC_ALL, "");
#if ENABLE_NLS
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
#endif
guint owner_id;
abrt_init(argv);
const char *program_usage_string = _(
"& [options]"
);
enum {
OPT_v = 1 << 0,
OPT_t = 1 << 1,
};
/* Keep enum above and order of options below in sync! */
struct options program_options[] = {
OPT__VERBOSE(&g_verbose),
OPT_INTEGER('t', NULL, &g_timeout_value, _("Exit after NUM seconds of inactivity")),
OPT_END()
};
/*unsigned opts =*/ parse_opts(argc, argv, program_options, program_usage_string);
export_abrt_envvars(0);
/* When dbus daemon starts us, it doesn't set PATH
* (I saw it set only DBUS_STARTER_ADDRESS and DBUS_STARTER_BUS_TYPE).
* In this case, set something sane:
*/
const char *env_path = getenv("PATH");
if (!env_path || !env_path[0])
putenv((char*)"PATH=/usr/sbin:/usr/bin:/sbin:/bin");
msg_prefix = "abrt-dbus"; /* for log(), error_msg() and such */
if (getuid() != 0)
error_msg_and_die(_("This program must be run as root."));
glib_init();
/* We are lazy here - we don't want to manually provide
* the introspection data structures - so we just build
* them from XML.
*/
introspection_data = g_dbus_node_info_new_for_xml(introspection_xml, NULL);
g_assert(introspection_data != NULL);
owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
ABRT_DBUS_NAME,
G_BUS_NAME_OWNER_FLAGS_NONE,
on_bus_acquired,
NULL,
on_name_lost,
NULL,
NULL);
/* initialize the g_settings_dump_location */
load_abrt_conf();
loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(loop);
log_notice("Cleaning up");
g_bus_unown_name(owner_id);
g_dbus_node_info_unref(introspection_data);
free_abrt_conf_data();
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1562_0 |
crossvul-cpp_data_good_3581_3 | /*
* linux/kernel/fork.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
/*
* 'fork.c' contains the help-routines for the 'fork' system call
* (see also entry.S and others).
* Fork is rather simple, once you get the hang of it, but the memory
* management can be a bitch. See 'mm/memory.c': 'copy_page_range()'
*/
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/unistd.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/completion.h>
#include <linux/personality.h>
#include <linux/mempolicy.h>
#include <linux/sem.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/iocontext.h>
#include <linux/key.h>
#include <linux/binfmts.h>
#include <linux/mman.h>
#include <linux/mmu_notifier.h>
#include <linux/fs.h>
#include <linux/nsproxy.h>
#include <linux/capability.h>
#include <linux/cpu.h>
#include <linux/cgroup.h>
#include <linux/security.h>
#include <linux/hugetlb.h>
#include <linux/swap.h>
#include <linux/syscalls.h>
#include <linux/jiffies.h>
#include <linux/tracehook.h>
#include <linux/futex.h>
#include <linux/compat.h>
#include <linux/task_io_accounting_ops.h>
#include <linux/rcupdate.h>
#include <linux/ptrace.h>
#include <linux/mount.h>
#include <linux/audit.h>
#include <linux/memcontrol.h>
#include <linux/ftrace.h>
#include <linux/profile.h>
#include <linux/rmap.h>
#include <linux/ksm.h>
#include <linux/acct.h>
#include <linux/tsacct_kern.h>
#include <linux/cn_proc.h>
#include <linux/freezer.h>
#include <linux/delayacct.h>
#include <linux/taskstats_kern.h>
#include <linux/random.h>
#include <linux/tty.h>
#include <linux/proc_fs.h>
#include <linux/blkdev.h>
#include <linux/fs_struct.h>
#include <linux/magic.h>
#include <linux/perf_event.h>
#include <linux/posix-timers.h>
#include <asm/pgtable.h>
#include <asm/pgalloc.h>
#include <asm/uaccess.h>
#include <asm/mmu_context.h>
#include <asm/cacheflush.h>
#include <asm/tlbflush.h>
#include <trace/events/sched.h>
/*
* Protected counters by write_lock_irq(&tasklist_lock)
*/
unsigned long total_forks; /* Handle normal Linux uptimes. */
int nr_threads; /* The idle threads do not count.. */
int max_threads; /* tunable limit on nr_threads */
DEFINE_PER_CPU(unsigned long, process_counts) = 0;
__cacheline_aligned DEFINE_RWLOCK(tasklist_lock); /* outer */
int nr_processes(void)
{
int cpu;
int total = 0;
for_each_possible_cpu(cpu)
total += per_cpu(process_counts, cpu);
return total;
}
#ifndef __HAVE_ARCH_TASK_STRUCT_ALLOCATOR
# define alloc_task_struct() kmem_cache_alloc(task_struct_cachep, GFP_KERNEL)
# define free_task_struct(tsk) kmem_cache_free(task_struct_cachep, (tsk))
static struct kmem_cache *task_struct_cachep;
#endif
#ifndef __HAVE_ARCH_THREAD_INFO_ALLOCATOR
static inline struct thread_info *alloc_thread_info(struct task_struct *tsk)
{
#ifdef CONFIG_DEBUG_STACK_USAGE
gfp_t mask = GFP_KERNEL | __GFP_ZERO;
#else
gfp_t mask = GFP_KERNEL;
#endif
return (struct thread_info *)__get_free_pages(mask, THREAD_SIZE_ORDER);
}
static inline void free_thread_info(struct thread_info *ti)
{
free_pages((unsigned long)ti, THREAD_SIZE_ORDER);
}
#endif
/* SLAB cache for signal_struct structures (tsk->signal) */
static struct kmem_cache *signal_cachep;
/* SLAB cache for sighand_struct structures (tsk->sighand) */
struct kmem_cache *sighand_cachep;
/* SLAB cache for files_struct structures (tsk->files) */
struct kmem_cache *files_cachep;
/* SLAB cache for fs_struct structures (tsk->fs) */
struct kmem_cache *fs_cachep;
/* SLAB cache for vm_area_struct structures */
struct kmem_cache *vm_area_cachep;
/* SLAB cache for mm_struct structures (tsk->mm) */
static struct kmem_cache *mm_cachep;
static void account_kernel_stack(struct thread_info *ti, int account)
{
struct zone *zone = page_zone(virt_to_page(ti));
mod_zone_page_state(zone, NR_KERNEL_STACK, account);
}
void free_task(struct task_struct *tsk)
{
prop_local_destroy_single(&tsk->dirties);
account_kernel_stack(tsk->stack, -1);
free_thread_info(tsk->stack);
rt_mutex_debug_task_free(tsk);
ftrace_graph_exit_task(tsk);
free_task_struct(tsk);
}
EXPORT_SYMBOL(free_task);
void __put_task_struct(struct task_struct *tsk)
{
WARN_ON(!tsk->exit_state);
WARN_ON(atomic_read(&tsk->usage));
WARN_ON(tsk == current);
exit_creds(tsk);
delayacct_tsk_free(tsk);
if (!profile_handoff_task(tsk))
free_task(tsk);
}
/*
* macro override instead of weak attribute alias, to workaround
* gcc 4.1.0 and 4.1.1 bugs with weak attribute and empty functions.
*/
#ifndef arch_task_cache_init
#define arch_task_cache_init()
#endif
void __init fork_init(unsigned long mempages)
{
#ifndef __HAVE_ARCH_TASK_STRUCT_ALLOCATOR
#ifndef ARCH_MIN_TASKALIGN
#define ARCH_MIN_TASKALIGN L1_CACHE_BYTES
#endif
/* create a slab on which task_structs can be allocated */
task_struct_cachep =
kmem_cache_create("task_struct", sizeof(struct task_struct),
ARCH_MIN_TASKALIGN, SLAB_PANIC | SLAB_NOTRACK, NULL);
#endif
/* do the arch specific task caches init */
arch_task_cache_init();
/*
* The default maximum number of threads is set to a safe
* value: the thread structures can take up at most half
* of memory.
*/
max_threads = mempages / (8 * THREAD_SIZE / PAGE_SIZE);
/*
* we need to allow at least 20 threads to boot a system
*/
if(max_threads < 20)
max_threads = 20;
init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
init_task.signal->rlim[RLIMIT_SIGPENDING] =
init_task.signal->rlim[RLIMIT_NPROC];
}
int __attribute__((weak)) arch_dup_task_struct(struct task_struct *dst,
struct task_struct *src)
{
*dst = *src;
return 0;
}
static struct task_struct *dup_task_struct(struct task_struct *orig)
{
struct task_struct *tsk;
struct thread_info *ti;
unsigned long *stackend;
int err;
prepare_to_copy(orig);
tsk = alloc_task_struct();
if (!tsk)
return NULL;
ti = alloc_thread_info(tsk);
if (!ti) {
free_task_struct(tsk);
return NULL;
}
err = arch_dup_task_struct(tsk, orig);
if (err)
goto out;
tsk->stack = ti;
err = prop_local_init_single(&tsk->dirties);
if (err)
goto out;
setup_thread_stack(tsk, orig);
stackend = end_of_stack(tsk);
*stackend = STACK_END_MAGIC; /* for overflow detection */
#ifdef CONFIG_CC_STACKPROTECTOR
tsk->stack_canary = get_random_int();
#endif
/* One for us, one for whoever does the "release_task()" (usually parent) */
atomic_set(&tsk->usage,2);
atomic_set(&tsk->fs_excl, 0);
#ifdef CONFIG_BLK_DEV_IO_TRACE
tsk->btrace_seq = 0;
#endif
tsk->splice_pipe = NULL;
account_kernel_stack(ti, 1);
return tsk;
out:
free_thread_info(ti);
free_task_struct(tsk);
return NULL;
}
#ifdef CONFIG_MMU
static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
{
struct vm_area_struct *mpnt, *tmp, **pprev;
struct rb_node **rb_link, *rb_parent;
int retval;
unsigned long charge;
struct mempolicy *pol;
down_write(&oldmm->mmap_sem);
flush_cache_dup_mm(oldmm);
/*
* Not linked in yet - no deadlock potential:
*/
down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
mm->locked_vm = 0;
mm->mmap = NULL;
mm->mmap_cache = NULL;
mm->free_area_cache = oldmm->mmap_base;
mm->cached_hole_size = ~0UL;
mm->map_count = 0;
cpumask_clear(mm_cpumask(mm));
mm->mm_rb = RB_ROOT;
rb_link = &mm->mm_rb.rb_node;
rb_parent = NULL;
pprev = &mm->mmap;
retval = ksm_fork(mm, oldmm);
if (retval)
goto out;
for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
struct file *file;
if (mpnt->vm_flags & VM_DONTCOPY) {
long pages = vma_pages(mpnt);
mm->total_vm -= pages;
vm_stat_account(mm, mpnt->vm_flags, mpnt->vm_file,
-pages);
continue;
}
charge = 0;
if (mpnt->vm_flags & VM_ACCOUNT) {
unsigned int len = (mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT;
if (security_vm_enough_memory(len))
goto fail_nomem;
charge = len;
}
tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
if (!tmp)
goto fail_nomem;
*tmp = *mpnt;
pol = mpol_dup(vma_policy(mpnt));
retval = PTR_ERR(pol);
if (IS_ERR(pol))
goto fail_nomem_policy;
vma_set_policy(tmp, pol);
tmp->vm_flags &= ~VM_LOCKED;
tmp->vm_mm = mm;
tmp->vm_next = NULL;
anon_vma_link(tmp);
file = tmp->vm_file;
if (file) {
struct inode *inode = file->f_path.dentry->d_inode;
struct address_space *mapping = file->f_mapping;
get_file(file);
if (tmp->vm_flags & VM_DENYWRITE)
atomic_dec(&inode->i_writecount);
spin_lock(&mapping->i_mmap_lock);
if (tmp->vm_flags & VM_SHARED)
mapping->i_mmap_writable++;
tmp->vm_truncate_count = mpnt->vm_truncate_count;
flush_dcache_mmap_lock(mapping);
/* insert tmp into the share list, just after mpnt */
vma_prio_tree_add(tmp, mpnt);
flush_dcache_mmap_unlock(mapping);
spin_unlock(&mapping->i_mmap_lock);
}
/*
* Clear hugetlb-related page reserves for children. This only
* affects MAP_PRIVATE mappings. Faults generated by the child
* are not guaranteed to succeed, even if read-only
*/
if (is_vm_hugetlb_page(tmp))
reset_vma_resv_huge_pages(tmp);
/*
* Link in the new vma and copy the page table entries.
*/
*pprev = tmp;
pprev = &tmp->vm_next;
__vma_link_rb(mm, tmp, rb_link, rb_parent);
rb_link = &tmp->vm_rb.rb_right;
rb_parent = &tmp->vm_rb;
mm->map_count++;
retval = copy_page_range(mm, oldmm, mpnt);
if (tmp->vm_ops && tmp->vm_ops->open)
tmp->vm_ops->open(tmp);
if (retval)
goto out;
}
/* a new mm has just been created */
arch_dup_mmap(oldmm, mm);
retval = 0;
out:
up_write(&mm->mmap_sem);
flush_tlb_mm(oldmm);
up_write(&oldmm->mmap_sem);
return retval;
fail_nomem_policy:
kmem_cache_free(vm_area_cachep, tmp);
fail_nomem:
retval = -ENOMEM;
vm_unacct_memory(charge);
goto out;
}
static inline int mm_alloc_pgd(struct mm_struct * mm)
{
mm->pgd = pgd_alloc(mm);
if (unlikely(!mm->pgd))
return -ENOMEM;
return 0;
}
static inline void mm_free_pgd(struct mm_struct * mm)
{
pgd_free(mm, mm->pgd);
}
#else
#define dup_mmap(mm, oldmm) (0)
#define mm_alloc_pgd(mm) (0)
#define mm_free_pgd(mm)
#endif /* CONFIG_MMU */
__cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
#define allocate_mm() (kmem_cache_alloc(mm_cachep, GFP_KERNEL))
#define free_mm(mm) (kmem_cache_free(mm_cachep, (mm)))
static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
static int __init coredump_filter_setup(char *s)
{
default_dump_filter =
(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
MMF_DUMP_FILTER_MASK;
return 1;
}
__setup("coredump_filter=", coredump_filter_setup);
#include <linux/init_task.h>
static void mm_init_aio(struct mm_struct *mm)
{
#ifdef CONFIG_AIO
spin_lock_init(&mm->ioctx_lock);
INIT_HLIST_HEAD(&mm->ioctx_list);
#endif
}
static struct mm_struct * mm_init(struct mm_struct * mm, struct task_struct *p)
{
atomic_set(&mm->mm_users, 1);
atomic_set(&mm->mm_count, 1);
init_rwsem(&mm->mmap_sem);
INIT_LIST_HEAD(&mm->mmlist);
mm->flags = (current->mm) ?
(current->mm->flags & MMF_INIT_MASK) : default_dump_filter;
mm->core_state = NULL;
mm->nr_ptes = 0;
set_mm_counter(mm, file_rss, 0);
set_mm_counter(mm, anon_rss, 0);
spin_lock_init(&mm->page_table_lock);
mm->free_area_cache = TASK_UNMAPPED_BASE;
mm->cached_hole_size = ~0UL;
mm_init_aio(mm);
mm_init_owner(mm, p);
if (likely(!mm_alloc_pgd(mm))) {
mm->def_flags = 0;
mmu_notifier_mm_init(mm);
return mm;
}
free_mm(mm);
return NULL;
}
/*
* Allocate and initialize an mm_struct.
*/
struct mm_struct * mm_alloc(void)
{
struct mm_struct * mm;
mm = allocate_mm();
if (mm) {
memset(mm, 0, sizeof(*mm));
mm = mm_init(mm, current);
}
return mm;
}
/*
* Called when the last reference to the mm
* is dropped: either by a lazy thread or by
* mmput. Free the page directory and the mm.
*/
void __mmdrop(struct mm_struct *mm)
{
BUG_ON(mm == &init_mm);
mm_free_pgd(mm);
destroy_context(mm);
mmu_notifier_mm_destroy(mm);
free_mm(mm);
}
EXPORT_SYMBOL_GPL(__mmdrop);
/*
* Decrement the use count and release all resources for an mm.
*/
void mmput(struct mm_struct *mm)
{
might_sleep();
if (atomic_dec_and_test(&mm->mm_users)) {
exit_aio(mm);
ksm_exit(mm);
exit_mmap(mm);
set_mm_exe_file(mm, NULL);
if (!list_empty(&mm->mmlist)) {
spin_lock(&mmlist_lock);
list_del(&mm->mmlist);
spin_unlock(&mmlist_lock);
}
put_swap_token(mm);
if (mm->binfmt)
module_put(mm->binfmt->module);
mmdrop(mm);
}
}
EXPORT_SYMBOL_GPL(mmput);
/**
* get_task_mm - acquire a reference to the task's mm
*
* Returns %NULL if the task has no mm. Checks PF_KTHREAD (meaning
* this kernel workthread has transiently adopted a user mm with use_mm,
* to do its AIO) is not set and if so returns a reference to it, after
* bumping up the use count. User must release the mm via mmput()
* after use. Typically used by /proc and ptrace.
*/
struct mm_struct *get_task_mm(struct task_struct *task)
{
struct mm_struct *mm;
task_lock(task);
mm = task->mm;
if (mm) {
if (task->flags & PF_KTHREAD)
mm = NULL;
else
atomic_inc(&mm->mm_users);
}
task_unlock(task);
return mm;
}
EXPORT_SYMBOL_GPL(get_task_mm);
/* Please note the differences between mmput and mm_release.
* mmput is called whenever we stop holding onto a mm_struct,
* error success whatever.
*
* mm_release is called after a mm_struct has been removed
* from the current process.
*
* This difference is important for error handling, when we
* only half set up a mm_struct for a new process and need to restore
* the old one. Because we mmput the new mm_struct before
* restoring the old one. . .
* Eric Biederman 10 January 1998
*/
void mm_release(struct task_struct *tsk, struct mm_struct *mm)
{
struct completion *vfork_done = tsk->vfork_done;
/* Get rid of any futexes when releasing the mm */
#ifdef CONFIG_FUTEX
if (unlikely(tsk->robust_list)) {
exit_robust_list(tsk);
tsk->robust_list = NULL;
}
#ifdef CONFIG_COMPAT
if (unlikely(tsk->compat_robust_list)) {
compat_exit_robust_list(tsk);
tsk->compat_robust_list = NULL;
}
#endif
if (unlikely(!list_empty(&tsk->pi_state_list)))
exit_pi_state_list(tsk);
#endif
/* Get rid of any cached register state */
deactivate_mm(tsk, mm);
/* notify parent sleeping on vfork() */
if (vfork_done) {
tsk->vfork_done = NULL;
complete(vfork_done);
}
/*
* If we're exiting normally, clear a user-space tid field if
* requested. We leave this alone when dying by signal, to leave
* the value intact in a core dump, and to save the unnecessary
* trouble otherwise. Userland only wants this done for a sys_exit.
*/
if (tsk->clear_child_tid) {
if (!(tsk->flags & PF_SIGNALED) &&
atomic_read(&mm->mm_users) > 1) {
/*
* We don't check the error code - if userspace has
* not set up a proper pointer then tough luck.
*/
put_user(0, tsk->clear_child_tid);
sys_futex(tsk->clear_child_tid, FUTEX_WAKE,
1, NULL, NULL, 0);
}
tsk->clear_child_tid = NULL;
}
}
/*
* Allocate a new mm structure and copy contents from the
* mm structure of the passed in task structure.
*/
struct mm_struct *dup_mm(struct task_struct *tsk)
{
struct mm_struct *mm, *oldmm = current->mm;
int err;
if (!oldmm)
return NULL;
mm = allocate_mm();
if (!mm)
goto fail_nomem;
memcpy(mm, oldmm, sizeof(*mm));
/* Initializing for Swap token stuff */
mm->token_priority = 0;
mm->last_interval = 0;
if (!mm_init(mm, tsk))
goto fail_nomem;
if (init_new_context(tsk, mm))
goto fail_nocontext;
dup_mm_exe_file(oldmm, mm);
err = dup_mmap(mm, oldmm);
if (err)
goto free_pt;
mm->hiwater_rss = get_mm_rss(mm);
mm->hiwater_vm = mm->total_vm;
if (mm->binfmt && !try_module_get(mm->binfmt->module))
goto free_pt;
return mm;
free_pt:
/* don't put binfmt in mmput, we haven't got module yet */
mm->binfmt = NULL;
mmput(mm);
fail_nomem:
return NULL;
fail_nocontext:
/*
* If init_new_context() failed, we cannot use mmput() to free the mm
* because it calls destroy_context()
*/
mm_free_pgd(mm);
free_mm(mm);
return NULL;
}
static int copy_mm(unsigned long clone_flags, struct task_struct * tsk)
{
struct mm_struct * mm, *oldmm;
int retval;
tsk->min_flt = tsk->maj_flt = 0;
tsk->nvcsw = tsk->nivcsw = 0;
#ifdef CONFIG_DETECT_HUNG_TASK
tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
#endif
tsk->mm = NULL;
tsk->active_mm = NULL;
/*
* Are we cloning a kernel thread?
*
* We need to steal a active VM for that..
*/
oldmm = current->mm;
if (!oldmm)
return 0;
if (clone_flags & CLONE_VM) {
atomic_inc(&oldmm->mm_users);
mm = oldmm;
goto good_mm;
}
retval = -ENOMEM;
mm = dup_mm(tsk);
if (!mm)
goto fail_nomem;
good_mm:
/* Initializing for Swap token stuff */
mm->token_priority = 0;
mm->last_interval = 0;
tsk->mm = mm;
tsk->active_mm = mm;
return 0;
fail_nomem:
return retval;
}
static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
{
struct fs_struct *fs = current->fs;
if (clone_flags & CLONE_FS) {
/* tsk->fs is already what we want */
write_lock(&fs->lock);
if (fs->in_exec) {
write_unlock(&fs->lock);
return -EAGAIN;
}
fs->users++;
write_unlock(&fs->lock);
return 0;
}
tsk->fs = copy_fs_struct(fs);
if (!tsk->fs)
return -ENOMEM;
return 0;
}
static int copy_files(unsigned long clone_flags, struct task_struct * tsk)
{
struct files_struct *oldf, *newf;
int error = 0;
/*
* A background process may not have any files ...
*/
oldf = current->files;
if (!oldf)
goto out;
if (clone_flags & CLONE_FILES) {
atomic_inc(&oldf->count);
goto out;
}
newf = dup_fd(oldf, &error);
if (!newf)
goto out;
tsk->files = newf;
error = 0;
out:
return error;
}
static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
{
#ifdef CONFIG_BLOCK
struct io_context *ioc = current->io_context;
if (!ioc)
return 0;
/*
* Share io context with parent, if CLONE_IO is set
*/
if (clone_flags & CLONE_IO) {
tsk->io_context = ioc_task_link(ioc);
if (unlikely(!tsk->io_context))
return -ENOMEM;
} else if (ioprio_valid(ioc->ioprio)) {
tsk->io_context = alloc_io_context(GFP_KERNEL, -1);
if (unlikely(!tsk->io_context))
return -ENOMEM;
tsk->io_context->ioprio = ioc->ioprio;
}
#endif
return 0;
}
static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
{
struct sighand_struct *sig;
if (clone_flags & CLONE_SIGHAND) {
atomic_inc(¤t->sighand->count);
return 0;
}
sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
rcu_assign_pointer(tsk->sighand, sig);
if (!sig)
return -ENOMEM;
atomic_set(&sig->count, 1);
memcpy(sig->action, current->sighand->action, sizeof(sig->action));
return 0;
}
void __cleanup_sighand(struct sighand_struct *sighand)
{
if (atomic_dec_and_test(&sighand->count))
kmem_cache_free(sighand_cachep, sighand);
}
/*
* Initialize POSIX timer handling for a thread group.
*/
static void posix_cpu_timers_init_group(struct signal_struct *sig)
{
/* Thread group counters. */
thread_group_cputime_init(sig);
/* Expiration times and increments. */
sig->it[CPUCLOCK_PROF].expires = cputime_zero;
sig->it[CPUCLOCK_PROF].incr = cputime_zero;
sig->it[CPUCLOCK_VIRT].expires = cputime_zero;
sig->it[CPUCLOCK_VIRT].incr = cputime_zero;
/* Cached expiration times. */
sig->cputime_expires.prof_exp = cputime_zero;
sig->cputime_expires.virt_exp = cputime_zero;
sig->cputime_expires.sched_exp = 0;
if (sig->rlim[RLIMIT_CPU].rlim_cur != RLIM_INFINITY) {
sig->cputime_expires.prof_exp =
secs_to_cputime(sig->rlim[RLIMIT_CPU].rlim_cur);
sig->cputimer.running = 1;
}
/* The timer lists. */
INIT_LIST_HEAD(&sig->cpu_timers[0]);
INIT_LIST_HEAD(&sig->cpu_timers[1]);
INIT_LIST_HEAD(&sig->cpu_timers[2]);
}
static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
{
struct signal_struct *sig;
if (clone_flags & CLONE_THREAD)
return 0;
sig = kmem_cache_alloc(signal_cachep, GFP_KERNEL);
tsk->signal = sig;
if (!sig)
return -ENOMEM;
atomic_set(&sig->count, 1);
atomic_set(&sig->live, 1);
init_waitqueue_head(&sig->wait_chldexit);
sig->flags = 0;
if (clone_flags & CLONE_NEWPID)
sig->flags |= SIGNAL_UNKILLABLE;
sig->group_exit_code = 0;
sig->group_exit_task = NULL;
sig->group_stop_count = 0;
sig->curr_target = tsk;
init_sigpending(&sig->shared_pending);
INIT_LIST_HEAD(&sig->posix_timers);
hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
sig->it_real_incr.tv64 = 0;
sig->real_timer.function = it_real_fn;
sig->leader = 0; /* session leadership doesn't inherit */
sig->tty_old_pgrp = NULL;
sig->tty = NULL;
sig->utime = sig->stime = sig->cutime = sig->cstime = cputime_zero;
sig->gtime = cputime_zero;
sig->cgtime = cputime_zero;
sig->nvcsw = sig->nivcsw = sig->cnvcsw = sig->cnivcsw = 0;
sig->min_flt = sig->maj_flt = sig->cmin_flt = sig->cmaj_flt = 0;
sig->inblock = sig->oublock = sig->cinblock = sig->coublock = 0;
sig->maxrss = sig->cmaxrss = 0;
task_io_accounting_init(&sig->ioac);
sig->sum_sched_runtime = 0;
taskstats_tgid_init(sig);
task_lock(current->group_leader);
memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
task_unlock(current->group_leader);
posix_cpu_timers_init_group(sig);
acct_init_pacct(&sig->pacct);
tty_audit_fork(sig);
sig->oom_adj = current->signal->oom_adj;
return 0;
}
void __cleanup_signal(struct signal_struct *sig)
{
thread_group_cputime_free(sig);
tty_kref_put(sig->tty);
kmem_cache_free(signal_cachep, sig);
}
static void copy_flags(unsigned long clone_flags, struct task_struct *p)
{
unsigned long new_flags = p->flags;
new_flags &= ~PF_SUPERPRIV;
new_flags |= PF_FORKNOEXEC;
new_flags |= PF_STARTING;
p->flags = new_flags;
clear_freeze_flag(p);
}
SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
{
current->clear_child_tid = tidptr;
return task_pid_vnr(current);
}
static void rt_mutex_init_task(struct task_struct *p)
{
spin_lock_init(&p->pi_lock);
#ifdef CONFIG_RT_MUTEXES
plist_head_init(&p->pi_waiters, &p->pi_lock);
p->pi_blocked_on = NULL;
#endif
}
#ifdef CONFIG_MM_OWNER
void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
{
mm->owner = p;
}
#endif /* CONFIG_MM_OWNER */
/*
* Initialize POSIX timer handling for a single task.
*/
static void posix_cpu_timers_init(struct task_struct *tsk)
{
tsk->cputime_expires.prof_exp = cputime_zero;
tsk->cputime_expires.virt_exp = cputime_zero;
tsk->cputime_expires.sched_exp = 0;
INIT_LIST_HEAD(&tsk->cpu_timers[0]);
INIT_LIST_HEAD(&tsk->cpu_timers[1]);
INIT_LIST_HEAD(&tsk->cpu_timers[2]);
}
/*
* This creates a new process as a copy of the old one,
* but does not actually start it yet.
*
* It copies the registers, and all the appropriate
* parts of the process environment (as per the clone
* flags). The actual kick-off is left to the caller.
*/
static struct task_struct *copy_process(unsigned long clone_flags,
unsigned long stack_start,
struct pt_regs *regs,
unsigned long stack_size,
int __user *child_tidptr,
struct pid *pid,
int trace)
{
int retval;
struct task_struct *p;
int cgroup_callbacks_done = 0;
if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
return ERR_PTR(-EINVAL);
/*
* Thread groups must share signals as well, and detached threads
* can only be started up within the thread group.
*/
if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
return ERR_PTR(-EINVAL);
/*
* Shared signal handlers imply shared VM. By way of the above,
* thread groups also imply shared VM. Blocking this case allows
* for various simplifications in other code.
*/
if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
return ERR_PTR(-EINVAL);
/*
* Siblings of global init remain as zombies on exit since they are
* not reaped by their parent (swapper). To solve this and to avoid
* multi-rooted process trees, prevent global and container-inits
* from creating siblings.
*/
if ((clone_flags & CLONE_PARENT) &&
current->signal->flags & SIGNAL_UNKILLABLE)
return ERR_PTR(-EINVAL);
retval = security_task_create(clone_flags);
if (retval)
goto fork_out;
retval = -ENOMEM;
p = dup_task_struct(current);
if (!p)
goto fork_out;
ftrace_graph_init_task(p);
rt_mutex_init_task(p);
#ifdef CONFIG_PROVE_LOCKING
DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
#endif
retval = -EAGAIN;
if (atomic_read(&p->real_cred->user->processes) >=
p->signal->rlim[RLIMIT_NPROC].rlim_cur) {
if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE) &&
p->real_cred->user != INIT_USER)
goto bad_fork_free;
}
retval = copy_creds(p, clone_flags);
if (retval < 0)
goto bad_fork_free;
/*
* If multiple threads are within copy_process(), then this check
* triggers too late. This doesn't hurt, the check is only there
* to stop root fork bombs.
*/
retval = -EAGAIN;
if (nr_threads >= max_threads)
goto bad_fork_cleanup_count;
if (!try_module_get(task_thread_info(p)->exec_domain->module))
goto bad_fork_cleanup_count;
p->did_exec = 0;
delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
copy_flags(clone_flags, p);
INIT_LIST_HEAD(&p->children);
INIT_LIST_HEAD(&p->sibling);
rcu_copy_process(p);
p->vfork_done = NULL;
spin_lock_init(&p->alloc_lock);
init_sigpending(&p->pending);
p->utime = cputime_zero;
p->stime = cputime_zero;
p->gtime = cputime_zero;
p->utimescaled = cputime_zero;
p->stimescaled = cputime_zero;
p->prev_utime = cputime_zero;
p->prev_stime = cputime_zero;
p->default_timer_slack_ns = current->timer_slack_ns;
task_io_accounting_init(&p->ioac);
acct_clear_integrals(p);
posix_cpu_timers_init(p);
p->lock_depth = -1; /* -1 = no lock */
do_posix_clock_monotonic_gettime(&p->start_time);
p->real_start_time = p->start_time;
monotonic_to_bootbased(&p->real_start_time);
p->io_context = NULL;
p->audit_context = NULL;
cgroup_fork(p);
#ifdef CONFIG_NUMA
p->mempolicy = mpol_dup(p->mempolicy);
if (IS_ERR(p->mempolicy)) {
retval = PTR_ERR(p->mempolicy);
p->mempolicy = NULL;
goto bad_fork_cleanup_cgroup;
}
mpol_fix_fork_child_flag(p);
#endif
#ifdef CONFIG_TRACE_IRQFLAGS
p->irq_events = 0;
#ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
p->hardirqs_enabled = 1;
#else
p->hardirqs_enabled = 0;
#endif
p->hardirq_enable_ip = 0;
p->hardirq_enable_event = 0;
p->hardirq_disable_ip = _THIS_IP_;
p->hardirq_disable_event = 0;
p->softirqs_enabled = 1;
p->softirq_enable_ip = _THIS_IP_;
p->softirq_enable_event = 0;
p->softirq_disable_ip = 0;
p->softirq_disable_event = 0;
p->hardirq_context = 0;
p->softirq_context = 0;
#endif
#ifdef CONFIG_LOCKDEP
p->lockdep_depth = 0; /* no locks held yet */
p->curr_chain_key = 0;
p->lockdep_recursion = 0;
#endif
#ifdef CONFIG_DEBUG_MUTEXES
p->blocked_on = NULL; /* not blocked yet */
#endif
p->bts = NULL;
p->stack_start = stack_start;
/* Perform scheduler related setup. Assign this task to a CPU. */
sched_fork(p, clone_flags);
retval = perf_event_init_task(p);
if (retval)
goto bad_fork_cleanup_policy;
if ((retval = audit_alloc(p)))
goto bad_fork_cleanup_policy;
/* copy all the process information */
if ((retval = copy_semundo(clone_flags, p)))
goto bad_fork_cleanup_audit;
if ((retval = copy_files(clone_flags, p)))
goto bad_fork_cleanup_semundo;
if ((retval = copy_fs(clone_flags, p)))
goto bad_fork_cleanup_files;
if ((retval = copy_sighand(clone_flags, p)))
goto bad_fork_cleanup_fs;
if ((retval = copy_signal(clone_flags, p)))
goto bad_fork_cleanup_sighand;
if ((retval = copy_mm(clone_flags, p)))
goto bad_fork_cleanup_signal;
if ((retval = copy_namespaces(clone_flags, p)))
goto bad_fork_cleanup_mm;
if ((retval = copy_io(clone_flags, p)))
goto bad_fork_cleanup_namespaces;
retval = copy_thread(clone_flags, stack_start, stack_size, p, regs);
if (retval)
goto bad_fork_cleanup_io;
if (pid != &init_struct_pid) {
retval = -ENOMEM;
pid = alloc_pid(p->nsproxy->pid_ns);
if (!pid)
goto bad_fork_cleanup_io;
if (clone_flags & CLONE_NEWPID) {
retval = pid_ns_prepare_proc(p->nsproxy->pid_ns);
if (retval < 0)
goto bad_fork_free_pid;
}
}
p->pid = pid_nr(pid);
p->tgid = p->pid;
if (clone_flags & CLONE_THREAD)
p->tgid = current->tgid;
if (current->nsproxy != p->nsproxy) {
retval = ns_cgroup_clone(p, pid);
if (retval)
goto bad_fork_free_pid;
}
p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
/*
* Clear TID on mm_release()?
*/
p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr: NULL;
#ifdef CONFIG_FUTEX
p->robust_list = NULL;
#ifdef CONFIG_COMPAT
p->compat_robust_list = NULL;
#endif
INIT_LIST_HEAD(&p->pi_state_list);
p->pi_state_cache = NULL;
#endif
/*
* sigaltstack should be cleared when sharing the same VM
*/
if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
p->sas_ss_sp = p->sas_ss_size = 0;
/*
* Syscall tracing should be turned off in the child regardless
* of CLONE_PTRACE.
*/
clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
#ifdef TIF_SYSCALL_EMU
clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
#endif
clear_all_latency_tracing(p);
/* ok, now we should be set up.. */
p->exit_signal = (clone_flags & CLONE_THREAD) ? -1 : (clone_flags & CSIGNAL);
p->pdeath_signal = 0;
p->exit_state = 0;
/*
* Ok, make it visible to the rest of the system.
* We dont wake it up yet.
*/
p->group_leader = p;
INIT_LIST_HEAD(&p->thread_group);
/* Now that the task is set up, run cgroup callbacks if
* necessary. We need to run them before the task is visible
* on the tasklist. */
cgroup_fork_callbacks(p);
cgroup_callbacks_done = 1;
/* Need tasklist lock for parent etc handling! */
write_lock_irq(&tasklist_lock);
/*
* The task hasn't been attached yet, so its cpus_allowed mask will
* not be changed, nor will its assigned CPU.
*
* The cpus_allowed mask of the parent may have changed after it was
* copied first time - so re-copy it here, then check the child's CPU
* to ensure it is on a valid CPU (and if not, just force it back to
* parent's CPU). This avoids alot of nasty races.
*/
p->cpus_allowed = current->cpus_allowed;
p->rt.nr_cpus_allowed = current->rt.nr_cpus_allowed;
if (unlikely(!cpu_isset(task_cpu(p), p->cpus_allowed) ||
!cpu_online(task_cpu(p))))
set_task_cpu(p, smp_processor_id());
/* CLONE_PARENT re-uses the old parent */
if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
p->real_parent = current->real_parent;
p->parent_exec_id = current->parent_exec_id;
} else {
p->real_parent = current;
p->parent_exec_id = current->self_exec_id;
}
spin_lock(¤t->sighand->siglock);
/*
* Process group and session signals need to be delivered to just the
* parent before the fork or both the parent and the child after the
* fork. Restart if a signal comes in before we add the new process to
* it's process group.
* A fatal signal pending means that current will exit, so the new
* thread can't slip out of an OOM kill (or normal SIGKILL).
*/
recalc_sigpending();
if (signal_pending(current)) {
spin_unlock(¤t->sighand->siglock);
write_unlock_irq(&tasklist_lock);
retval = -ERESTARTNOINTR;
goto bad_fork_free_pid;
}
if (clone_flags & CLONE_THREAD) {
atomic_inc(¤t->signal->count);
atomic_inc(¤t->signal->live);
p->group_leader = current->group_leader;
list_add_tail_rcu(&p->thread_group, &p->group_leader->thread_group);
}
if (likely(p->pid)) {
list_add_tail(&p->sibling, &p->real_parent->children);
tracehook_finish_clone(p, clone_flags, trace);
if (thread_group_leader(p)) {
if (clone_flags & CLONE_NEWPID)
p->nsproxy->pid_ns->child_reaper = p;
p->signal->leader_pid = pid;
tty_kref_put(p->signal->tty);
p->signal->tty = tty_kref_get(current->signal->tty);
attach_pid(p, PIDTYPE_PGID, task_pgrp(current));
attach_pid(p, PIDTYPE_SID, task_session(current));
list_add_tail_rcu(&p->tasks, &init_task.tasks);
__get_cpu_var(process_counts)++;
}
attach_pid(p, PIDTYPE_PID, pid);
nr_threads++;
}
total_forks++;
spin_unlock(¤t->sighand->siglock);
write_unlock_irq(&tasklist_lock);
proc_fork_connector(p);
cgroup_post_fork(p);
perf_event_fork(p);
return p;
bad_fork_free_pid:
if (pid != &init_struct_pid)
free_pid(pid);
bad_fork_cleanup_io:
if (p->io_context)
exit_io_context(p);
bad_fork_cleanup_namespaces:
exit_task_namespaces(p);
bad_fork_cleanup_mm:
if (p->mm)
mmput(p->mm);
bad_fork_cleanup_signal:
if (!(clone_flags & CLONE_THREAD))
__cleanup_signal(p->signal);
bad_fork_cleanup_sighand:
__cleanup_sighand(p->sighand);
bad_fork_cleanup_fs:
exit_fs(p); /* blocking */
bad_fork_cleanup_files:
exit_files(p); /* blocking */
bad_fork_cleanup_semundo:
exit_sem(p);
bad_fork_cleanup_audit:
audit_free(p);
bad_fork_cleanup_policy:
perf_event_free_task(p);
#ifdef CONFIG_NUMA
mpol_put(p->mempolicy);
bad_fork_cleanup_cgroup:
#endif
cgroup_exit(p, cgroup_callbacks_done);
delayacct_tsk_free(p);
module_put(task_thread_info(p)->exec_domain->module);
bad_fork_cleanup_count:
atomic_dec(&p->cred->user->processes);
exit_creds(p);
bad_fork_free:
free_task(p);
fork_out:
return ERR_PTR(retval);
}
noinline struct pt_regs * __cpuinit __attribute__((weak)) idle_regs(struct pt_regs *regs)
{
memset(regs, 0, sizeof(struct pt_regs));
return regs;
}
struct task_struct * __cpuinit fork_idle(int cpu)
{
struct task_struct *task;
struct pt_regs regs;
task = copy_process(CLONE_VM, 0, idle_regs(®s), 0, NULL,
&init_struct_pid, 0);
if (!IS_ERR(task))
init_idle(task, cpu);
return task;
}
/*
* Ok, this is the main fork-routine.
*
* It copies the process, and if successful kick-starts
* it and waits for it to finish using the VM if required.
*/
long do_fork(unsigned long clone_flags,
unsigned long stack_start,
struct pt_regs *regs,
unsigned long stack_size,
int __user *parent_tidptr,
int __user *child_tidptr)
{
struct task_struct *p;
int trace = 0;
long nr;
/*
* Do some preliminary argument and permissions checking before we
* actually start allocating stuff
*/
if (clone_flags & CLONE_NEWUSER) {
if (clone_flags & CLONE_THREAD)
return -EINVAL;
/* hopefully this check will go away when userns support is
* complete
*/
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SETUID) ||
!capable(CAP_SETGID))
return -EPERM;
}
/*
* We hope to recycle these flags after 2.6.26
*/
if (unlikely(clone_flags & CLONE_STOPPED)) {
static int __read_mostly count = 100;
if (count > 0 && printk_ratelimit()) {
char comm[TASK_COMM_LEN];
count--;
printk(KERN_INFO "fork(): process `%s' used deprecated "
"clone flags 0x%lx\n",
get_task_comm(comm, current),
clone_flags & CLONE_STOPPED);
}
}
/*
* When called from kernel_thread, don't do user tracing stuff.
*/
if (likely(user_mode(regs)))
trace = tracehook_prepare_clone(clone_flags);
p = copy_process(clone_flags, stack_start, regs, stack_size,
child_tidptr, NULL, trace);
/*
* Do this prior waking up the new thread - the thread pointer
* might get invalid after that point, if the thread exits quickly.
*/
if (!IS_ERR(p)) {
struct completion vfork;
trace_sched_process_fork(current, p);
nr = task_pid_vnr(p);
if (clone_flags & CLONE_PARENT_SETTID)
put_user(nr, parent_tidptr);
if (clone_flags & CLONE_VFORK) {
p->vfork_done = &vfork;
init_completion(&vfork);
}
audit_finish_fork(p);
tracehook_report_clone(regs, clone_flags, nr, p);
/*
* We set PF_STARTING at creation in case tracing wants to
* use this to distinguish a fully live task from one that
* hasn't gotten to tracehook_report_clone() yet. Now we
* clear it and set the child going.
*/
p->flags &= ~PF_STARTING;
if (unlikely(clone_flags & CLONE_STOPPED)) {
/*
* We'll start up with an immediate SIGSTOP.
*/
sigaddset(&p->pending.signal, SIGSTOP);
set_tsk_thread_flag(p, TIF_SIGPENDING);
__set_task_state(p, TASK_STOPPED);
} else {
wake_up_new_task(p, clone_flags);
}
tracehook_report_clone_complete(trace, regs,
clone_flags, nr, p);
if (clone_flags & CLONE_VFORK) {
freezer_do_not_count();
wait_for_completion(&vfork);
freezer_count();
tracehook_report_vfork_done(p, nr);
}
} else {
nr = PTR_ERR(p);
}
return nr;
}
#ifndef ARCH_MIN_MMSTRUCT_ALIGN
#define ARCH_MIN_MMSTRUCT_ALIGN 0
#endif
static void sighand_ctor(void *data)
{
struct sighand_struct *sighand = data;
spin_lock_init(&sighand->siglock);
init_waitqueue_head(&sighand->signalfd_wqh);
}
void __init proc_caches_init(void)
{
sighand_cachep = kmem_cache_create("sighand_cache",
sizeof(struct sighand_struct), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_DESTROY_BY_RCU|
SLAB_NOTRACK, sighand_ctor);
signal_cachep = kmem_cache_create("signal_cache",
sizeof(struct signal_struct), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
files_cachep = kmem_cache_create("files_cache",
sizeof(struct files_struct), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
fs_cachep = kmem_cache_create("fs_cache",
sizeof(struct fs_struct), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
mm_cachep = kmem_cache_create("mm_struct",
sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN,
SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC);
mmap_init();
}
/*
* Check constraints on flags passed to the unshare system call and
* force unsharing of additional process context as appropriate.
*/
static void check_unshare_flags(unsigned long *flags_ptr)
{
/*
* If unsharing a thread from a thread group, must also
* unshare vm.
*/
if (*flags_ptr & CLONE_THREAD)
*flags_ptr |= CLONE_VM;
/*
* If unsharing vm, must also unshare signal handlers.
*/
if (*flags_ptr & CLONE_VM)
*flags_ptr |= CLONE_SIGHAND;
/*
* If unsharing signal handlers and the task was created
* using CLONE_THREAD, then must unshare the thread
*/
if ((*flags_ptr & CLONE_SIGHAND) &&
(atomic_read(¤t->signal->count) > 1))
*flags_ptr |= CLONE_THREAD;
/*
* If unsharing namespace, must also unshare filesystem information.
*/
if (*flags_ptr & CLONE_NEWNS)
*flags_ptr |= CLONE_FS;
}
/*
* Unsharing of tasks created with CLONE_THREAD is not supported yet
*/
static int unshare_thread(unsigned long unshare_flags)
{
if (unshare_flags & CLONE_THREAD)
return -EINVAL;
return 0;
}
/*
* Unshare the filesystem structure if it is being shared
*/
static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
{
struct fs_struct *fs = current->fs;
if (!(unshare_flags & CLONE_FS) || !fs)
return 0;
/* don't need lock here; in the worst case we'll do useless copy */
if (fs->users == 1)
return 0;
*new_fsp = copy_fs_struct(fs);
if (!*new_fsp)
return -ENOMEM;
return 0;
}
/*
* Unsharing of sighand is not supported yet
*/
static int unshare_sighand(unsigned long unshare_flags, struct sighand_struct **new_sighp)
{
struct sighand_struct *sigh = current->sighand;
if ((unshare_flags & CLONE_SIGHAND) && atomic_read(&sigh->count) > 1)
return -EINVAL;
else
return 0;
}
/*
* Unshare vm if it is being shared
*/
static int unshare_vm(unsigned long unshare_flags, struct mm_struct **new_mmp)
{
struct mm_struct *mm = current->mm;
if ((unshare_flags & CLONE_VM) &&
(mm && atomic_read(&mm->mm_users) > 1)) {
return -EINVAL;
}
return 0;
}
/*
* Unshare file descriptor table if it is being shared
*/
static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
{
struct files_struct *fd = current->files;
int error = 0;
if ((unshare_flags & CLONE_FILES) &&
(fd && atomic_read(&fd->count) > 1)) {
*new_fdp = dup_fd(fd, &error);
if (!*new_fdp)
return error;
}
return 0;
}
/*
* unshare allows a process to 'unshare' part of the process
* context which was originally shared using clone. copy_*
* functions used by do_fork() cannot be used here directly
* because they modify an inactive task_struct that is being
* constructed. Here we are modifying the current, active,
* task_struct.
*/
SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
{
int err = 0;
struct fs_struct *fs, *new_fs = NULL;
struct sighand_struct *new_sigh = NULL;
struct mm_struct *mm, *new_mm = NULL, *active_mm = NULL;
struct files_struct *fd, *new_fd = NULL;
struct nsproxy *new_nsproxy = NULL;
int do_sysvsem = 0;
check_unshare_flags(&unshare_flags);
/* Return -EINVAL for all unsupported flags */
err = -EINVAL;
if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET))
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;
if ((err = unshare_thread(unshare_flags)))
goto bad_unshare_out;
if ((err = unshare_fs(unshare_flags, &new_fs)))
goto bad_unshare_cleanup_thread;
if ((err = unshare_sighand(unshare_flags, &new_sigh)))
goto bad_unshare_cleanup_fs;
if ((err = unshare_vm(unshare_flags, &new_mm)))
goto bad_unshare_cleanup_sigh;
if ((err = unshare_fd(unshare_flags, &new_fd)))
goto bad_unshare_cleanup_vm;
if ((err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
new_fs)))
goto bad_unshare_cleanup_fd;
if (new_fs || new_mm || new_fd || do_sysvsem || new_nsproxy) {
if (do_sysvsem) {
/*
* CLONE_SYSVSEM is equivalent to sys_exit().
*/
exit_sem(current);
}
if (new_nsproxy) {
switch_task_namespaces(current, new_nsproxy);
new_nsproxy = NULL;
}
task_lock(current);
if (new_fs) {
fs = current->fs;
write_lock(&fs->lock);
current->fs = new_fs;
if (--fs->users)
new_fs = NULL;
else
new_fs = fs;
write_unlock(&fs->lock);
}
if (new_mm) {
mm = current->mm;
active_mm = current->active_mm;
current->mm = new_mm;
current->active_mm = new_mm;
activate_mm(active_mm, new_mm);
new_mm = mm;
}
if (new_fd) {
fd = current->files;
current->files = new_fd;
new_fd = fd;
}
task_unlock(current);
}
if (new_nsproxy)
put_nsproxy(new_nsproxy);
bad_unshare_cleanup_fd:
if (new_fd)
put_files_struct(new_fd);
bad_unshare_cleanup_vm:
if (new_mm)
mmput(new_mm);
bad_unshare_cleanup_sigh:
if (new_sigh)
if (atomic_dec_and_test(&new_sigh->count))
kmem_cache_free(sighand_cachep, new_sigh);
bad_unshare_cleanup_fs:
if (new_fs)
free_fs_struct(new_fs);
bad_unshare_cleanup_thread:
bad_unshare_out:
return err;
}
/*
* Helper to unshare the files of the current task.
* We don't want to expose copy_files internals to
* the exec layer of the kernel.
*/
int unshare_files(struct files_struct **displaced)
{
struct task_struct *task = current;
struct files_struct *copy = NULL;
int error;
error = unshare_fd(CLONE_FILES, ©);
if (error || !copy) {
*displaced = NULL;
return error;
}
*displaced = task->files;
task_lock(task);
task->files = copy;
task_unlock(task);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3581_3 |
crossvul-cpp_data_good_5845_23 | /*
* Copyright (C) 2011 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#define pr_fmt(fmt) "llcp: %s: " fmt, __func__
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/nfc.h>
#include "nfc.h"
#include "llcp.h"
static int sock_wait_state(struct sock *sk, int state, unsigned long timeo)
{
DECLARE_WAITQUEUE(wait, current);
int err = 0;
pr_debug("sk %p", sk);
add_wait_queue(sk_sleep(sk), &wait);
set_current_state(TASK_INTERRUPTIBLE);
while (sk->sk_state != state) {
if (!timeo) {
err = -EINPROGRESS;
break;
}
if (signal_pending(current)) {
err = sock_intr_errno(timeo);
break;
}
release_sock(sk);
timeo = schedule_timeout(timeo);
lock_sock(sk);
set_current_state(TASK_INTERRUPTIBLE);
err = sock_error(sk);
if (err)
break;
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(sk_sleep(sk), &wait);
return err;
}
static struct proto llcp_sock_proto = {
.name = "NFC_LLCP",
.owner = THIS_MODULE,
.obj_size = sizeof(struct nfc_llcp_sock),
};
static int llcp_sock_bind(struct socket *sock, struct sockaddr *addr, int alen)
{
struct sock *sk = sock->sk;
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
struct nfc_llcp_local *local;
struct nfc_dev *dev;
struct sockaddr_nfc_llcp llcp_addr;
int len, ret = 0;
if (!addr || addr->sa_family != AF_NFC)
return -EINVAL;
pr_debug("sk %p addr %p family %d\n", sk, addr, addr->sa_family);
memset(&llcp_addr, 0, sizeof(llcp_addr));
len = min_t(unsigned int, sizeof(llcp_addr), alen);
memcpy(&llcp_addr, addr, len);
/* This is going to be a listening socket, dsap must be 0 */
if (llcp_addr.dsap != 0)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state != LLCP_CLOSED) {
ret = -EBADFD;
goto error;
}
dev = nfc_get_device(llcp_addr.dev_idx);
if (dev == NULL) {
ret = -ENODEV;
goto error;
}
local = nfc_llcp_find_local(dev);
if (local == NULL) {
ret = -ENODEV;
goto put_dev;
}
llcp_sock->dev = dev;
llcp_sock->local = nfc_llcp_local_get(local);
llcp_sock->nfc_protocol = llcp_addr.nfc_protocol;
llcp_sock->service_name_len = min_t(unsigned int,
llcp_addr.service_name_len,
NFC_LLCP_MAX_SERVICE_NAME);
llcp_sock->service_name = kmemdup(llcp_addr.service_name,
llcp_sock->service_name_len,
GFP_KERNEL);
llcp_sock->ssap = nfc_llcp_get_sdp_ssap(local, llcp_sock);
if (llcp_sock->ssap == LLCP_SAP_MAX) {
ret = -EADDRINUSE;
goto put_dev;
}
llcp_sock->reserved_ssap = llcp_sock->ssap;
nfc_llcp_sock_link(&local->sockets, sk);
pr_debug("Socket bound to SAP %d\n", llcp_sock->ssap);
sk->sk_state = LLCP_BOUND;
put_dev:
nfc_put_device(dev);
error:
release_sock(sk);
return ret;
}
static int llcp_raw_sock_bind(struct socket *sock, struct sockaddr *addr,
int alen)
{
struct sock *sk = sock->sk;
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
struct nfc_llcp_local *local;
struct nfc_dev *dev;
struct sockaddr_nfc_llcp llcp_addr;
int len, ret = 0;
if (!addr || addr->sa_family != AF_NFC)
return -EINVAL;
pr_debug("sk %p addr %p family %d\n", sk, addr, addr->sa_family);
memset(&llcp_addr, 0, sizeof(llcp_addr));
len = min_t(unsigned int, sizeof(llcp_addr), alen);
memcpy(&llcp_addr, addr, len);
lock_sock(sk);
if (sk->sk_state != LLCP_CLOSED) {
ret = -EBADFD;
goto error;
}
dev = nfc_get_device(llcp_addr.dev_idx);
if (dev == NULL) {
ret = -ENODEV;
goto error;
}
local = nfc_llcp_find_local(dev);
if (local == NULL) {
ret = -ENODEV;
goto put_dev;
}
llcp_sock->dev = dev;
llcp_sock->local = nfc_llcp_local_get(local);
llcp_sock->nfc_protocol = llcp_addr.nfc_protocol;
nfc_llcp_sock_link(&local->raw_sockets, sk);
sk->sk_state = LLCP_BOUND;
put_dev:
nfc_put_device(dev);
error:
release_sock(sk);
return ret;
}
static int llcp_sock_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int ret = 0;
pr_debug("sk %p backlog %d\n", sk, backlog);
lock_sock(sk);
if ((sock->type != SOCK_SEQPACKET && sock->type != SOCK_STREAM) ||
sk->sk_state != LLCP_BOUND) {
ret = -EBADFD;
goto error;
}
sk->sk_max_ack_backlog = backlog;
sk->sk_ack_backlog = 0;
pr_debug("Socket listening\n");
sk->sk_state = LLCP_LISTEN;
error:
release_sock(sk);
return ret;
}
static int nfc_llcp_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
u32 opt;
int err = 0;
pr_debug("%p optname %d\n", sk, optname);
if (level != SOL_NFC)
return -ENOPROTOOPT;
lock_sock(sk);
switch (optname) {
case NFC_LLCP_RW:
if (sk->sk_state == LLCP_CONNECTED ||
sk->sk_state == LLCP_BOUND ||
sk->sk_state == LLCP_LISTEN) {
err = -EINVAL;
break;
}
if (get_user(opt, (u32 __user *) optval)) {
err = -EFAULT;
break;
}
if (opt > LLCP_MAX_RW) {
err = -EINVAL;
break;
}
llcp_sock->rw = (u8) opt;
break;
case NFC_LLCP_MIUX:
if (sk->sk_state == LLCP_CONNECTED ||
sk->sk_state == LLCP_BOUND ||
sk->sk_state == LLCP_LISTEN) {
err = -EINVAL;
break;
}
if (get_user(opt, (u32 __user *) optval)) {
err = -EFAULT;
break;
}
if (opt > LLCP_MAX_MIUX) {
err = -EINVAL;
break;
}
llcp_sock->miux = cpu_to_be16((u16) opt);
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
pr_debug("%p rw %d miux %d\n", llcp_sock,
llcp_sock->rw, llcp_sock->miux);
return err;
}
static int nfc_llcp_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct nfc_llcp_local *local;
struct sock *sk = sock->sk;
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
int len, err = 0;
u16 miux, remote_miu;
u8 rw;
pr_debug("%p optname %d\n", sk, optname);
if (level != SOL_NFC)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
local = llcp_sock->local;
if (!local)
return -ENODEV;
len = min_t(u32, len, sizeof(u32));
lock_sock(sk);
switch (optname) {
case NFC_LLCP_RW:
rw = llcp_sock->rw > LLCP_MAX_RW ? local->rw : llcp_sock->rw;
if (put_user(rw, (u32 __user *) optval))
err = -EFAULT;
break;
case NFC_LLCP_MIUX:
miux = be16_to_cpu(llcp_sock->miux) > LLCP_MAX_MIUX ?
be16_to_cpu(local->miux) : be16_to_cpu(llcp_sock->miux);
if (put_user(miux, (u32 __user *) optval))
err = -EFAULT;
break;
case NFC_LLCP_REMOTE_MIU:
remote_miu = llcp_sock->remote_miu > LLCP_MAX_MIU ?
local->remote_miu : llcp_sock->remote_miu;
if (put_user(remote_miu, (u32 __user *) optval))
err = -EFAULT;
break;
case NFC_LLCP_REMOTE_LTO:
if (put_user(local->remote_lto / 10, (u32 __user *) optval))
err = -EFAULT;
break;
case NFC_LLCP_REMOTE_RW:
if (put_user(llcp_sock->remote_rw, (u32 __user *) optval))
err = -EFAULT;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
if (put_user(len, optlen))
return -EFAULT;
return err;
}
void nfc_llcp_accept_unlink(struct sock *sk)
{
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
pr_debug("state %d\n", sk->sk_state);
list_del_init(&llcp_sock->accept_queue);
sk_acceptq_removed(llcp_sock->parent);
llcp_sock->parent = NULL;
sock_put(sk);
}
void nfc_llcp_accept_enqueue(struct sock *parent, struct sock *sk)
{
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
struct nfc_llcp_sock *llcp_sock_parent = nfc_llcp_sock(parent);
/* Lock will be free from unlink */
sock_hold(sk);
list_add_tail(&llcp_sock->accept_queue,
&llcp_sock_parent->accept_queue);
llcp_sock->parent = parent;
sk_acceptq_added(parent);
}
struct sock *nfc_llcp_accept_dequeue(struct sock *parent,
struct socket *newsock)
{
struct nfc_llcp_sock *lsk, *n, *llcp_parent;
struct sock *sk;
llcp_parent = nfc_llcp_sock(parent);
list_for_each_entry_safe(lsk, n, &llcp_parent->accept_queue,
accept_queue) {
sk = &lsk->sk;
lock_sock(sk);
if (sk->sk_state == LLCP_CLOSED) {
release_sock(sk);
nfc_llcp_accept_unlink(sk);
continue;
}
if (sk->sk_state == LLCP_CONNECTED || !newsock) {
list_del_init(&lsk->accept_queue);
sock_put(sk);
if (newsock)
sock_graft(sk, newsock);
release_sock(sk);
pr_debug("Returning sk state %d\n", sk->sk_state);
sk_acceptq_removed(parent);
return sk;
}
release_sock(sk);
}
return NULL;
}
static int llcp_sock_accept(struct socket *sock, struct socket *newsock,
int flags)
{
DECLARE_WAITQUEUE(wait, current);
struct sock *sk = sock->sk, *new_sk;
long timeo;
int ret = 0;
pr_debug("parent %p\n", sk);
lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
if (sk->sk_state != LLCP_LISTEN) {
ret = -EBADFD;
goto error;
}
timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
/* Wait for an incoming connection. */
add_wait_queue_exclusive(sk_sleep(sk), &wait);
while (!(new_sk = nfc_llcp_accept_dequeue(sk, newsock))) {
set_current_state(TASK_INTERRUPTIBLE);
if (!timeo) {
ret = -EAGAIN;
break;
}
if (signal_pending(current)) {
ret = sock_intr_errno(timeo);
break;
}
release_sock(sk);
timeo = schedule_timeout(timeo);
lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(sk_sleep(sk), &wait);
if (ret)
goto error;
newsock->state = SS_CONNECTED;
pr_debug("new socket %p\n", new_sk);
error:
release_sock(sk);
return ret;
}
static int llcp_sock_getname(struct socket *sock, struct sockaddr *uaddr,
int *len, int peer)
{
struct sock *sk = sock->sk;
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
DECLARE_SOCKADDR(struct sockaddr_nfc_llcp *, llcp_addr, uaddr);
if (llcp_sock == NULL || llcp_sock->dev == NULL)
return -EBADFD;
pr_debug("%p %d %d %d\n", sk, llcp_sock->target_idx,
llcp_sock->dsap, llcp_sock->ssap);
memset(llcp_addr, 0, sizeof(*llcp_addr));
*len = sizeof(struct sockaddr_nfc_llcp);
llcp_addr->sa_family = AF_NFC;
llcp_addr->dev_idx = llcp_sock->dev->idx;
llcp_addr->target_idx = llcp_sock->target_idx;
llcp_addr->nfc_protocol = llcp_sock->nfc_protocol;
llcp_addr->dsap = llcp_sock->dsap;
llcp_addr->ssap = llcp_sock->ssap;
llcp_addr->service_name_len = llcp_sock->service_name_len;
memcpy(llcp_addr->service_name, llcp_sock->service_name,
llcp_addr->service_name_len);
return 0;
}
static inline unsigned int llcp_accept_poll(struct sock *parent)
{
struct nfc_llcp_sock *llcp_sock, *n, *parent_sock;
struct sock *sk;
parent_sock = nfc_llcp_sock(parent);
list_for_each_entry_safe(llcp_sock, n, &parent_sock->accept_queue,
accept_queue) {
sk = &llcp_sock->sk;
if (sk->sk_state == LLCP_CONNECTED)
return POLLIN | POLLRDNORM;
}
return 0;
}
static unsigned int llcp_sock_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
unsigned int mask = 0;
pr_debug("%p\n", sk);
sock_poll_wait(file, sk_sleep(sk), wait);
if (sk->sk_state == LLCP_LISTEN)
return llcp_accept_poll(sk);
if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
mask |= POLLERR |
(sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? POLLPRI : 0);
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
if (sk->sk_state == LLCP_CLOSED)
mask |= POLLHUP;
if (sk->sk_shutdown & RCV_SHUTDOWN)
mask |= POLLRDHUP | POLLIN | POLLRDNORM;
if (sk->sk_shutdown == SHUTDOWN_MASK)
mask |= POLLHUP;
if (sock_writeable(sk) && sk->sk_state == LLCP_CONNECTED)
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
else
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
pr_debug("mask 0x%x\n", mask);
return mask;
}
static int llcp_sock_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct nfc_llcp_local *local;
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
int err = 0;
if (!sk)
return 0;
pr_debug("%p\n", sk);
local = llcp_sock->local;
if (local == NULL) {
err = -ENODEV;
goto out;
}
lock_sock(sk);
/* Send a DISC */
if (sk->sk_state == LLCP_CONNECTED)
nfc_llcp_send_disconnect(llcp_sock);
if (sk->sk_state == LLCP_LISTEN) {
struct nfc_llcp_sock *lsk, *n;
struct sock *accept_sk;
list_for_each_entry_safe(lsk, n, &llcp_sock->accept_queue,
accept_queue) {
accept_sk = &lsk->sk;
lock_sock(accept_sk);
nfc_llcp_send_disconnect(lsk);
nfc_llcp_accept_unlink(accept_sk);
release_sock(accept_sk);
}
}
if (llcp_sock->reserved_ssap < LLCP_SAP_MAX)
nfc_llcp_put_ssap(llcp_sock->local, llcp_sock->ssap);
release_sock(sk);
/* Keep this sock alive and therefore do not remove it from the sockets
* list until the DISC PDU has been actually sent. Otherwise we would
* reply with DM PDUs before sending the DISC one.
*/
if (sk->sk_state == LLCP_DISCONNECTING)
return err;
if (sock->type == SOCK_RAW)
nfc_llcp_sock_unlink(&local->raw_sockets, sk);
else
nfc_llcp_sock_unlink(&local->sockets, sk);
out:
sock_orphan(sk);
sock_put(sk);
return err;
}
static int llcp_sock_connect(struct socket *sock, struct sockaddr *_addr,
int len, int flags)
{
struct sock *sk = sock->sk;
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
struct sockaddr_nfc_llcp *addr = (struct sockaddr_nfc_llcp *)_addr;
struct nfc_dev *dev;
struct nfc_llcp_local *local;
int ret = 0;
pr_debug("sock %p sk %p flags 0x%x\n", sock, sk, flags);
if (!addr || len < sizeof(struct sockaddr_nfc) ||
addr->sa_family != AF_NFC)
return -EINVAL;
if (addr->service_name_len == 0 && addr->dsap == 0)
return -EINVAL;
pr_debug("addr dev_idx=%u target_idx=%u protocol=%u\n", addr->dev_idx,
addr->target_idx, addr->nfc_protocol);
lock_sock(sk);
if (sk->sk_state == LLCP_CONNECTED) {
ret = -EISCONN;
goto error;
}
dev = nfc_get_device(addr->dev_idx);
if (dev == NULL) {
ret = -ENODEV;
goto error;
}
local = nfc_llcp_find_local(dev);
if (local == NULL) {
ret = -ENODEV;
goto put_dev;
}
device_lock(&dev->dev);
if (dev->dep_link_up == false) {
ret = -ENOLINK;
device_unlock(&dev->dev);
goto put_dev;
}
device_unlock(&dev->dev);
if (local->rf_mode == NFC_RF_INITIATOR &&
addr->target_idx != local->target_idx) {
ret = -ENOLINK;
goto put_dev;
}
llcp_sock->dev = dev;
llcp_sock->local = nfc_llcp_local_get(local);
llcp_sock->remote_miu = llcp_sock->local->remote_miu;
llcp_sock->ssap = nfc_llcp_get_local_ssap(local);
if (llcp_sock->ssap == LLCP_SAP_MAX) {
ret = -ENOMEM;
goto put_dev;
}
llcp_sock->reserved_ssap = llcp_sock->ssap;
if (addr->service_name_len == 0)
llcp_sock->dsap = addr->dsap;
else
llcp_sock->dsap = LLCP_SAP_SDP;
llcp_sock->nfc_protocol = addr->nfc_protocol;
llcp_sock->service_name_len = min_t(unsigned int,
addr->service_name_len,
NFC_LLCP_MAX_SERVICE_NAME);
llcp_sock->service_name = kmemdup(addr->service_name,
llcp_sock->service_name_len,
GFP_KERNEL);
nfc_llcp_sock_link(&local->connecting_sockets, sk);
ret = nfc_llcp_send_connect(llcp_sock);
if (ret)
goto sock_unlink;
sk->sk_state = LLCP_CONNECTING;
ret = sock_wait_state(sk, LLCP_CONNECTED,
sock_sndtimeo(sk, flags & O_NONBLOCK));
if (ret && ret != -EINPROGRESS)
goto sock_unlink;
release_sock(sk);
return ret;
sock_unlink:
nfc_llcp_put_ssap(local, llcp_sock->ssap);
nfc_llcp_sock_unlink(&local->connecting_sockets, sk);
put_dev:
nfc_put_device(dev);
error:
release_sock(sk);
return ret;
}
static int llcp_sock_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
int ret;
pr_debug("sock %p sk %p", sock, sk);
ret = sock_error(sk);
if (ret)
return ret;
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
lock_sock(sk);
if (sk->sk_type == SOCK_DGRAM) {
struct sockaddr_nfc_llcp *addr =
(struct sockaddr_nfc_llcp *)msg->msg_name;
if (msg->msg_namelen < sizeof(*addr)) {
release_sock(sk);
return -EINVAL;
}
release_sock(sk);
return nfc_llcp_send_ui_frame(llcp_sock, addr->dsap, addr->ssap,
msg, len);
}
if (sk->sk_state != LLCP_CONNECTED) {
release_sock(sk);
return -ENOTCONN;
}
release_sock(sk);
return nfc_llcp_send_i_frame(llcp_sock, msg, len);
}
static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
int noblock = flags & MSG_DONTWAIT;
struct sock *sk = sock->sk;
unsigned int copied, rlen;
struct sk_buff *skb, *cskb;
int err = 0;
pr_debug("%p %zu\n", sk, len);
lock_sock(sk);
if (sk->sk_state == LLCP_CLOSED &&
skb_queue_empty(&sk->sk_receive_queue)) {
release_sock(sk);
return 0;
}
release_sock(sk);
if (flags & (MSG_OOB))
return -EOPNOTSUPP;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb) {
pr_err("Recv datagram failed state %d %d %d",
sk->sk_state, err, sock_error(sk));
if (sk->sk_shutdown & RCV_SHUTDOWN)
return 0;
return err;
}
rlen = skb->len; /* real length of skb */
copied = min_t(unsigned int, rlen, len);
cskb = skb;
if (skb_copy_datagram_iovec(cskb, 0, msg->msg_iov, copied)) {
if (!(flags & MSG_PEEK))
skb_queue_head(&sk->sk_receive_queue, skb);
return -EFAULT;
}
sock_recv_timestamp(msg, sk, skb);
if (sk->sk_type == SOCK_DGRAM && msg->msg_name) {
struct nfc_llcp_ui_cb *ui_cb = nfc_llcp_ui_skb_cb(skb);
struct sockaddr_nfc_llcp *sockaddr =
(struct sockaddr_nfc_llcp *) msg->msg_name;
msg->msg_namelen = sizeof(struct sockaddr_nfc_llcp);
pr_debug("Datagram socket %d %d\n", ui_cb->dsap, ui_cb->ssap);
memset(sockaddr, 0, sizeof(*sockaddr));
sockaddr->sa_family = AF_NFC;
sockaddr->nfc_protocol = NFC_PROTO_NFC_DEP;
sockaddr->dsap = ui_cb->dsap;
sockaddr->ssap = ui_cb->ssap;
}
/* Mark read part of skb as used */
if (!(flags & MSG_PEEK)) {
/* SOCK_STREAM: re-queue skb if it contains unreceived data */
if (sk->sk_type == SOCK_STREAM ||
sk->sk_type == SOCK_DGRAM ||
sk->sk_type == SOCK_RAW) {
skb_pull(skb, copied);
if (skb->len) {
skb_queue_head(&sk->sk_receive_queue, skb);
goto done;
}
}
kfree_skb(skb);
}
/* XXX Queue backlogged skbs */
done:
/* SOCK_SEQPACKET: return real length if MSG_TRUNC is set */
if (sk->sk_type == SOCK_SEQPACKET && (flags & MSG_TRUNC))
copied = rlen;
return copied;
}
static const struct proto_ops llcp_sock_ops = {
.family = PF_NFC,
.owner = THIS_MODULE,
.bind = llcp_sock_bind,
.connect = llcp_sock_connect,
.release = llcp_sock_release,
.socketpair = sock_no_socketpair,
.accept = llcp_sock_accept,
.getname = llcp_sock_getname,
.poll = llcp_sock_poll,
.ioctl = sock_no_ioctl,
.listen = llcp_sock_listen,
.shutdown = sock_no_shutdown,
.setsockopt = nfc_llcp_setsockopt,
.getsockopt = nfc_llcp_getsockopt,
.sendmsg = llcp_sock_sendmsg,
.recvmsg = llcp_sock_recvmsg,
.mmap = sock_no_mmap,
};
static const struct proto_ops llcp_rawsock_ops = {
.family = PF_NFC,
.owner = THIS_MODULE,
.bind = llcp_raw_sock_bind,
.connect = sock_no_connect,
.release = llcp_sock_release,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = llcp_sock_getname,
.poll = llcp_sock_poll,
.ioctl = sock_no_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = sock_no_sendmsg,
.recvmsg = llcp_sock_recvmsg,
.mmap = sock_no_mmap,
};
static void llcp_sock_destruct(struct sock *sk)
{
struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
pr_debug("%p\n", sk);
if (sk->sk_state == LLCP_CONNECTED)
nfc_put_device(llcp_sock->dev);
skb_queue_purge(&sk->sk_receive_queue);
nfc_llcp_sock_free(llcp_sock);
if (!sock_flag(sk, SOCK_DEAD)) {
pr_err("Freeing alive NFC LLCP socket %p\n", sk);
return;
}
}
struct sock *nfc_llcp_sock_alloc(struct socket *sock, int type, gfp_t gfp)
{
struct sock *sk;
struct nfc_llcp_sock *llcp_sock;
sk = sk_alloc(&init_net, PF_NFC, gfp, &llcp_sock_proto);
if (!sk)
return NULL;
llcp_sock = nfc_llcp_sock(sk);
sock_init_data(sock, sk);
sk->sk_state = LLCP_CLOSED;
sk->sk_protocol = NFC_SOCKPROTO_LLCP;
sk->sk_type = type;
sk->sk_destruct = llcp_sock_destruct;
llcp_sock->ssap = 0;
llcp_sock->dsap = LLCP_SAP_SDP;
llcp_sock->rw = LLCP_MAX_RW + 1;
llcp_sock->miux = cpu_to_be16(LLCP_MAX_MIUX + 1);
llcp_sock->send_n = llcp_sock->send_ack_n = 0;
llcp_sock->recv_n = llcp_sock->recv_ack_n = 0;
llcp_sock->remote_ready = 1;
llcp_sock->reserved_ssap = LLCP_SAP_MAX;
nfc_llcp_socket_remote_param_init(llcp_sock);
skb_queue_head_init(&llcp_sock->tx_queue);
skb_queue_head_init(&llcp_sock->tx_pending_queue);
INIT_LIST_HEAD(&llcp_sock->accept_queue);
if (sock != NULL)
sock->state = SS_UNCONNECTED;
return sk;
}
void nfc_llcp_sock_free(struct nfc_llcp_sock *sock)
{
kfree(sock->service_name);
skb_queue_purge(&sock->tx_queue);
skb_queue_purge(&sock->tx_pending_queue);
list_del_init(&sock->accept_queue);
sock->parent = NULL;
nfc_llcp_local_put(sock->local);
}
static int llcp_sock_create(struct net *net, struct socket *sock,
const struct nfc_protocol *nfc_proto)
{
struct sock *sk;
pr_debug("%p\n", sock);
if (sock->type != SOCK_STREAM &&
sock->type != SOCK_DGRAM &&
sock->type != SOCK_RAW)
return -ESOCKTNOSUPPORT;
if (sock->type == SOCK_RAW)
sock->ops = &llcp_rawsock_ops;
else
sock->ops = &llcp_sock_ops;
sk = nfc_llcp_sock_alloc(sock, sock->type, GFP_ATOMIC);
if (sk == NULL)
return -ENOMEM;
return 0;
}
static const struct nfc_protocol llcp_nfc_proto = {
.id = NFC_SOCKPROTO_LLCP,
.proto = &llcp_sock_proto,
.owner = THIS_MODULE,
.create = llcp_sock_create
};
int __init nfc_llcp_sock_init(void)
{
return nfc_proto_register(&llcp_nfc_proto);
}
void nfc_llcp_sock_exit(void)
{
nfc_proto_unregister(&llcp_nfc_proto);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_23 |
crossvul-cpp_data_good_5844_3 | /*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* The User Datagram Protocol (UDP).
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Arnt Gulbrandsen, <agulbra@nvg.unit.no>
* Alan Cox, <alan@lxorguk.ukuu.org.uk>
* Hirokazu Takahashi, <taka@valinux.co.jp>
*
* Fixes:
* Alan Cox : verify_area() calls
* Alan Cox : stopped close while in use off icmp
* messages. Not a fix but a botch that
* for udp at least is 'valid'.
* Alan Cox : Fixed icmp handling properly
* Alan Cox : Correct error for oversized datagrams
* Alan Cox : Tidied select() semantics.
* Alan Cox : udp_err() fixed properly, also now
* select and read wake correctly on errors
* Alan Cox : udp_send verify_area moved to avoid mem leak
* Alan Cox : UDP can count its memory
* Alan Cox : send to an unknown connection causes
* an ECONNREFUSED off the icmp, but
* does NOT close.
* Alan Cox : Switched to new sk_buff handlers. No more backlog!
* Alan Cox : Using generic datagram code. Even smaller and the PEEK
* bug no longer crashes it.
* Fred Van Kempen : Net2e support for sk->broadcast.
* Alan Cox : Uses skb_free_datagram
* Alan Cox : Added get/set sockopt support.
* Alan Cox : Broadcasting without option set returns EACCES.
* Alan Cox : No wakeup calls. Instead we now use the callbacks.
* Alan Cox : Use ip_tos and ip_ttl
* Alan Cox : SNMP Mibs
* Alan Cox : MSG_DONTROUTE, and 0.0.0.0 support.
* Matt Dillon : UDP length checks.
* Alan Cox : Smarter af_inet used properly.
* Alan Cox : Use new kernel side addressing.
* Alan Cox : Incorrect return on truncated datagram receive.
* Arnt Gulbrandsen : New udp_send and stuff
* Alan Cox : Cache last socket
* Alan Cox : Route cache
* Jon Peatfield : Minor efficiency fix to sendto().
* Mike Shaver : RFC1122 checks.
* Alan Cox : Nonblocking error fix.
* Willy Konynenberg : Transparent proxying support.
* Mike McLagan : Routing by source
* David S. Miller : New socket lookup architecture.
* Last socket cache retained as it
* does have a high hit rate.
* Olaf Kirch : Don't linearise iovec on sendmsg.
* Andi Kleen : Some cleanups, cache destination entry
* for connect.
* Vitaly E. Lavrov : Transparent proxy revived after year coma.
* Melvin Smith : Check msg_name not msg_namelen in sendto(),
* return ENOTCONN for unconnected sockets (POSIX)
* Janos Farkas : don't deliver multi/broadcasts to a different
* bound-to-device socket
* Hirokazu Takahashi : HW checksumming for outgoing UDP
* datagrams.
* Hirokazu Takahashi : sendfile() on UDP works now.
* Arnaldo C. Melo : convert /proc/net/udp to seq_file
* YOSHIFUJI Hideaki @USAGI and: Support IPV6_V6ONLY socket option, which
* Alexey Kuznetsov: allow both IPv4 and IPv6 sockets to bind
* a single port at the same time.
* Derek Atkins <derek@ihtfp.com>: Add Encapulation Support
* James Chapman : Add L2TP encapsulation type.
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#define pr_fmt(fmt) "UDP: " fmt
#include <asm/uaccess.h>
#include <asm/ioctls.h>
#include <linux/bootmem.h>
#include <linux/highmem.h>
#include <linux/swap.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/module.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/igmp.h>
#include <linux/in.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <linux/mm.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/slab.h>
#include <net/tcp_states.h>
#include <linux/skbuff.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <net/net_namespace.h>
#include <net/icmp.h>
#include <net/inet_hashtables.h>
#include <net/route.h>
#include <net/checksum.h>
#include <net/xfrm.h>
#include <trace/events/udp.h>
#include <linux/static_key.h>
#include <trace/events/skb.h>
#include <net/busy_poll.h>
#include "udp_impl.h"
struct udp_table udp_table __read_mostly;
EXPORT_SYMBOL(udp_table);
long sysctl_udp_mem[3] __read_mostly;
EXPORT_SYMBOL(sysctl_udp_mem);
int sysctl_udp_rmem_min __read_mostly;
EXPORT_SYMBOL(sysctl_udp_rmem_min);
int sysctl_udp_wmem_min __read_mostly;
EXPORT_SYMBOL(sysctl_udp_wmem_min);
atomic_long_t udp_memory_allocated;
EXPORT_SYMBOL(udp_memory_allocated);
#define MAX_UDP_PORTS 65536
#define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN)
static int udp_lib_lport_inuse(struct net *net, __u16 num,
const struct udp_hslot *hslot,
unsigned long *bitmap,
struct sock *sk,
int (*saddr_comp)(const struct sock *sk1,
const struct sock *sk2),
unsigned int log)
{
struct sock *sk2;
struct hlist_nulls_node *node;
kuid_t uid = sock_i_uid(sk);
sk_nulls_for_each(sk2, node, &hslot->head)
if (net_eq(sock_net(sk2), net) &&
sk2 != sk &&
(bitmap || udp_sk(sk2)->udp_port_hash == num) &&
(!sk2->sk_reuse || !sk->sk_reuse) &&
(!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
(!sk2->sk_reuseport || !sk->sk_reuseport ||
!uid_eq(uid, sock_i_uid(sk2))) &&
(*saddr_comp)(sk, sk2)) {
if (bitmap)
__set_bit(udp_sk(sk2)->udp_port_hash >> log,
bitmap);
else
return 1;
}
return 0;
}
/*
* Note: we still hold spinlock of primary hash chain, so no other writer
* can insert/delete a socket with local_port == num
*/
static int udp_lib_lport_inuse2(struct net *net, __u16 num,
struct udp_hslot *hslot2,
struct sock *sk,
int (*saddr_comp)(const struct sock *sk1,
const struct sock *sk2))
{
struct sock *sk2;
struct hlist_nulls_node *node;
kuid_t uid = sock_i_uid(sk);
int res = 0;
spin_lock(&hslot2->lock);
udp_portaddr_for_each_entry(sk2, node, &hslot2->head)
if (net_eq(sock_net(sk2), net) &&
sk2 != sk &&
(udp_sk(sk2)->udp_port_hash == num) &&
(!sk2->sk_reuse || !sk->sk_reuse) &&
(!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
(!sk2->sk_reuseport || !sk->sk_reuseport ||
!uid_eq(uid, sock_i_uid(sk2))) &&
(*saddr_comp)(sk, sk2)) {
res = 1;
break;
}
spin_unlock(&hslot2->lock);
return res;
}
/**
* udp_lib_get_port - UDP/-Lite port lookup for IPv4 and IPv6
*
* @sk: socket struct in question
* @snum: port number to look up
* @saddr_comp: AF-dependent comparison of bound local IP addresses
* @hash2_nulladdr: AF-dependent hash value in secondary hash chains,
* with NULL address
*/
int udp_lib_get_port(struct sock *sk, unsigned short snum,
int (*saddr_comp)(const struct sock *sk1,
const struct sock *sk2),
unsigned int hash2_nulladdr)
{
struct udp_hslot *hslot, *hslot2;
struct udp_table *udptable = sk->sk_prot->h.udp_table;
int error = 1;
struct net *net = sock_net(sk);
if (!snum) {
int low, high, remaining;
unsigned int rand;
unsigned short first, last;
DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN);
inet_get_local_port_range(net, &low, &high);
remaining = (high - low) + 1;
rand = net_random();
first = (((u64)rand * remaining) >> 32) + low;
/*
* force rand to be an odd multiple of UDP_HTABLE_SIZE
*/
rand = (rand | 1) * (udptable->mask + 1);
last = first + udptable->mask + 1;
do {
hslot = udp_hashslot(udptable, net, first);
bitmap_zero(bitmap, PORTS_PER_CHAIN);
spin_lock_bh(&hslot->lock);
udp_lib_lport_inuse(net, snum, hslot, bitmap, sk,
saddr_comp, udptable->log);
snum = first;
/*
* Iterate on all possible values of snum for this hash.
* Using steps of an odd multiple of UDP_HTABLE_SIZE
* give us randomization and full range coverage.
*/
do {
if (low <= snum && snum <= high &&
!test_bit(snum >> udptable->log, bitmap) &&
!inet_is_reserved_local_port(snum))
goto found;
snum += rand;
} while (snum != first);
spin_unlock_bh(&hslot->lock);
} while (++first != last);
goto fail;
} else {
hslot = udp_hashslot(udptable, net, snum);
spin_lock_bh(&hslot->lock);
if (hslot->count > 10) {
int exist;
unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum;
slot2 &= udptable->mask;
hash2_nulladdr &= udptable->mask;
hslot2 = udp_hashslot2(udptable, slot2);
if (hslot->count < hslot2->count)
goto scan_primary_hash;
exist = udp_lib_lport_inuse2(net, snum, hslot2,
sk, saddr_comp);
if (!exist && (hash2_nulladdr != slot2)) {
hslot2 = udp_hashslot2(udptable, hash2_nulladdr);
exist = udp_lib_lport_inuse2(net, snum, hslot2,
sk, saddr_comp);
}
if (exist)
goto fail_unlock;
else
goto found;
}
scan_primary_hash:
if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk,
saddr_comp, 0))
goto fail_unlock;
}
found:
inet_sk(sk)->inet_num = snum;
udp_sk(sk)->udp_port_hash = snum;
udp_sk(sk)->udp_portaddr_hash ^= snum;
if (sk_unhashed(sk)) {
sk_nulls_add_node_rcu(sk, &hslot->head);
hslot->count++;
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
spin_lock(&hslot2->lock);
hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
&hslot2->head);
hslot2->count++;
spin_unlock(&hslot2->lock);
}
error = 0;
fail_unlock:
spin_unlock_bh(&hslot->lock);
fail:
return error;
}
EXPORT_SYMBOL(udp_lib_get_port);
static int ipv4_rcv_saddr_equal(const struct sock *sk1, const struct sock *sk2)
{
struct inet_sock *inet1 = inet_sk(sk1), *inet2 = inet_sk(sk2);
return (!ipv6_only_sock(sk2) &&
(!inet1->inet_rcv_saddr || !inet2->inet_rcv_saddr ||
inet1->inet_rcv_saddr == inet2->inet_rcv_saddr));
}
static unsigned int udp4_portaddr_hash(struct net *net, __be32 saddr,
unsigned int port)
{
return jhash_1word((__force u32)saddr, net_hash_mix(net)) ^ port;
}
int udp_v4_get_port(struct sock *sk, unsigned short snum)
{
unsigned int hash2_nulladdr =
udp4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum);
unsigned int hash2_partial =
udp4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0);
/* precompute partial secondary hash */
udp_sk(sk)->udp_portaddr_hash = hash2_partial;
return udp_lib_get_port(sk, snum, ipv4_rcv_saddr_equal, hash2_nulladdr);
}
static inline int compute_score(struct sock *sk, struct net *net, __be32 saddr,
unsigned short hnum,
__be16 sport, __be32 daddr, __be16 dport, int dif)
{
int score = -1;
if (net_eq(sock_net(sk), net) && udp_sk(sk)->udp_port_hash == hnum &&
!ipv6_only_sock(sk)) {
struct inet_sock *inet = inet_sk(sk);
score = (sk->sk_family == PF_INET ? 2 : 1);
if (inet->inet_rcv_saddr) {
if (inet->inet_rcv_saddr != daddr)
return -1;
score += 4;
}
if (inet->inet_daddr) {
if (inet->inet_daddr != saddr)
return -1;
score += 4;
}
if (inet->inet_dport) {
if (inet->inet_dport != sport)
return -1;
score += 4;
}
if (sk->sk_bound_dev_if) {
if (sk->sk_bound_dev_if != dif)
return -1;
score += 4;
}
}
return score;
}
/*
* In this second variant, we check (daddr, dport) matches (inet_rcv_sadd, inet_num)
*/
static inline int compute_score2(struct sock *sk, struct net *net,
__be32 saddr, __be16 sport,
__be32 daddr, unsigned int hnum, int dif)
{
int score = -1;
if (net_eq(sock_net(sk), net) && !ipv6_only_sock(sk)) {
struct inet_sock *inet = inet_sk(sk);
if (inet->inet_rcv_saddr != daddr)
return -1;
if (inet->inet_num != hnum)
return -1;
score = (sk->sk_family == PF_INET ? 2 : 1);
if (inet->inet_daddr) {
if (inet->inet_daddr != saddr)
return -1;
score += 4;
}
if (inet->inet_dport) {
if (inet->inet_dport != sport)
return -1;
score += 4;
}
if (sk->sk_bound_dev_if) {
if (sk->sk_bound_dev_if != dif)
return -1;
score += 4;
}
}
return score;
}
static unsigned int udp_ehashfn(struct net *net, const __be32 laddr,
const __u16 lport, const __be32 faddr,
const __be16 fport)
{
static u32 udp_ehash_secret __read_mostly;
net_get_random_once(&udp_ehash_secret, sizeof(udp_ehash_secret));
return __inet_ehashfn(laddr, lport, faddr, fport,
udp_ehash_secret + net_hash_mix(net));
}
/* called with read_rcu_lock() */
static struct sock *udp4_lib_lookup2(struct net *net,
__be32 saddr, __be16 sport,
__be32 daddr, unsigned int hnum, int dif,
struct udp_hslot *hslot2, unsigned int slot2)
{
struct sock *sk, *result;
struct hlist_nulls_node *node;
int score, badness, matches = 0, reuseport = 0;
u32 hash = 0;
begin:
result = NULL;
badness = 0;
udp_portaddr_for_each_entry_rcu(sk, node, &hslot2->head) {
score = compute_score2(sk, net, saddr, sport,
daddr, hnum, dif);
if (score > badness) {
result = sk;
badness = score;
reuseport = sk->sk_reuseport;
if (reuseport) {
hash = udp_ehashfn(net, daddr, hnum,
saddr, sport);
matches = 1;
}
} else if (score == badness && reuseport) {
matches++;
if (((u64)hash * matches) >> 32 == 0)
result = sk;
hash = next_pseudo_random32(hash);
}
}
/*
* if the nulls value we got at the end of this lookup is
* not the expected one, we must restart lookup.
* We probably met an item that was moved to another chain.
*/
if (get_nulls_value(node) != slot2)
goto begin;
if (result) {
if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2)))
result = NULL;
else if (unlikely(compute_score2(result, net, saddr, sport,
daddr, hnum, dif) < badness)) {
sock_put(result);
goto begin;
}
}
return result;
}
/* UDP is nearly always wildcards out the wazoo, it makes no sense to try
* harder than this. -DaveM
*/
struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr,
__be16 sport, __be32 daddr, __be16 dport,
int dif, struct udp_table *udptable)
{
struct sock *sk, *result;
struct hlist_nulls_node *node;
unsigned short hnum = ntohs(dport);
unsigned int hash2, slot2, slot = udp_hashfn(net, hnum, udptable->mask);
struct udp_hslot *hslot2, *hslot = &udptable->hash[slot];
int score, badness, matches = 0, reuseport = 0;
u32 hash = 0;
rcu_read_lock();
if (hslot->count > 10) {
hash2 = udp4_portaddr_hash(net, daddr, hnum);
slot2 = hash2 & udptable->mask;
hslot2 = &udptable->hash2[slot2];
if (hslot->count < hslot2->count)
goto begin;
result = udp4_lib_lookup2(net, saddr, sport,
daddr, hnum, dif,
hslot2, slot2);
if (!result) {
hash2 = udp4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
slot2 = hash2 & udptable->mask;
hslot2 = &udptable->hash2[slot2];
if (hslot->count < hslot2->count)
goto begin;
result = udp4_lib_lookup2(net, saddr, sport,
htonl(INADDR_ANY), hnum, dif,
hslot2, slot2);
}
rcu_read_unlock();
return result;
}
begin:
result = NULL;
badness = 0;
sk_nulls_for_each_rcu(sk, node, &hslot->head) {
score = compute_score(sk, net, saddr, hnum, sport,
daddr, dport, dif);
if (score > badness) {
result = sk;
badness = score;
reuseport = sk->sk_reuseport;
if (reuseport) {
hash = udp_ehashfn(net, daddr, hnum,
saddr, sport);
matches = 1;
}
} else if (score == badness && reuseport) {
matches++;
if (((u64)hash * matches) >> 32 == 0)
result = sk;
hash = next_pseudo_random32(hash);
}
}
/*
* if the nulls value we got at the end of this lookup is
* not the expected one, we must restart lookup.
* We probably met an item that was moved to another chain.
*/
if (get_nulls_value(node) != slot)
goto begin;
if (result) {
if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2)))
result = NULL;
else if (unlikely(compute_score(result, net, saddr, hnum, sport,
daddr, dport, dif) < badness)) {
sock_put(result);
goto begin;
}
}
rcu_read_unlock();
return result;
}
EXPORT_SYMBOL_GPL(__udp4_lib_lookup);
static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
__be16 sport, __be16 dport,
struct udp_table *udptable)
{
struct sock *sk;
const struct iphdr *iph = ip_hdr(skb);
if (unlikely(sk = skb_steal_sock(skb)))
return sk;
else
return __udp4_lib_lookup(dev_net(skb_dst(skb)->dev), iph->saddr, sport,
iph->daddr, dport, inet_iif(skb),
udptable);
}
struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport,
__be32 daddr, __be16 dport, int dif)
{
return __udp4_lib_lookup(net, saddr, sport, daddr, dport, dif, &udp_table);
}
EXPORT_SYMBOL_GPL(udp4_lib_lookup);
static inline bool __udp_is_mcast_sock(struct net *net, struct sock *sk,
__be16 loc_port, __be32 loc_addr,
__be16 rmt_port, __be32 rmt_addr,
int dif, unsigned short hnum)
{
struct inet_sock *inet = inet_sk(sk);
if (!net_eq(sock_net(sk), net) ||
udp_sk(sk)->udp_port_hash != hnum ||
(inet->inet_daddr && inet->inet_daddr != rmt_addr) ||
(inet->inet_dport != rmt_port && inet->inet_dport) ||
(inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) ||
ipv6_only_sock(sk) ||
(sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif))
return false;
if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif))
return false;
return true;
}
static inline struct sock *udp_v4_mcast_next(struct net *net, struct sock *sk,
__be16 loc_port, __be32 loc_addr,
__be16 rmt_port, __be32 rmt_addr,
int dif)
{
struct hlist_nulls_node *node;
struct sock *s = sk;
unsigned short hnum = ntohs(loc_port);
sk_nulls_for_each_from(s, node) {
if (__udp_is_mcast_sock(net, s,
loc_port, loc_addr,
rmt_port, rmt_addr,
dif, hnum))
goto found;
}
s = NULL;
found:
return s;
}
/*
* This routine is called by the ICMP module when it gets some
* sort of error condition. If err < 0 then the socket should
* be closed and the error returned to the user. If err > 0
* it's just the icmp type << 8 | icmp code.
* Header points to the ip header of the error packet. We move
* on past this. Then (as it used to claim before adjustment)
* header points to the first 8 bytes of the udp header. We need
* to find the appropriate port.
*/
void __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable)
{
struct inet_sock *inet;
const struct iphdr *iph = (const struct iphdr *)skb->data;
struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2));
const int type = icmp_hdr(skb)->type;
const int code = icmp_hdr(skb)->code;
struct sock *sk;
int harderr;
int err;
struct net *net = dev_net(skb->dev);
sk = __udp4_lib_lookup(net, iph->daddr, uh->dest,
iph->saddr, uh->source, skb->dev->ifindex, udptable);
if (sk == NULL) {
ICMP_INC_STATS_BH(net, ICMP_MIB_INERRORS);
return; /* No socket for error */
}
err = 0;
harderr = 0;
inet = inet_sk(sk);
switch (type) {
default:
case ICMP_TIME_EXCEEDED:
err = EHOSTUNREACH;
break;
case ICMP_SOURCE_QUENCH:
goto out;
case ICMP_PARAMETERPROB:
err = EPROTO;
harderr = 1;
break;
case ICMP_DEST_UNREACH:
if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
ipv4_sk_update_pmtu(skb, sk, info);
if (inet->pmtudisc != IP_PMTUDISC_DONT) {
err = EMSGSIZE;
harderr = 1;
break;
}
goto out;
}
err = EHOSTUNREACH;
if (code <= NR_ICMP_UNREACH) {
harderr = icmp_err_convert[code].fatal;
err = icmp_err_convert[code].errno;
}
break;
case ICMP_REDIRECT:
ipv4_sk_redirect(skb, sk);
goto out;
}
/*
* RFC1122: OK. Passes ICMP errors back to application, as per
* 4.1.3.3.
*/
if (!inet->recverr) {
if (!harderr || sk->sk_state != TCP_ESTABLISHED)
goto out;
} else
ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1));
sk->sk_err = err;
sk->sk_error_report(sk);
out:
sock_put(sk);
}
void udp_err(struct sk_buff *skb, u32 info)
{
__udp4_lib_err(skb, info, &udp_table);
}
/*
* Throw away all pending data and cancel the corking. Socket is locked.
*/
void udp_flush_pending_frames(struct sock *sk)
{
struct udp_sock *up = udp_sk(sk);
if (up->pending) {
up->len = 0;
up->pending = 0;
ip_flush_pending_frames(sk);
}
}
EXPORT_SYMBOL(udp_flush_pending_frames);
/**
* udp4_hwcsum - handle outgoing HW checksumming
* @skb: sk_buff containing the filled-in UDP header
* (checksum field must be zeroed out)
* @src: source IP address
* @dst: destination IP address
*/
void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst)
{
struct udphdr *uh = udp_hdr(skb);
struct sk_buff *frags = skb_shinfo(skb)->frag_list;
int offset = skb_transport_offset(skb);
int len = skb->len - offset;
int hlen = len;
__wsum csum = 0;
if (!frags) {
/*
* Only one fragment on the socket.
*/
skb->csum_start = skb_transport_header(skb) - skb->head;
skb->csum_offset = offsetof(struct udphdr, check);
uh->check = ~csum_tcpudp_magic(src, dst, len,
IPPROTO_UDP, 0);
} else {
/*
* HW-checksum won't work as there are two or more
* fragments on the socket so that all csums of sk_buffs
* should be together
*/
do {
csum = csum_add(csum, frags->csum);
hlen -= frags->len;
} while ((frags = frags->next));
csum = skb_checksum(skb, offset, hlen, csum);
skb->ip_summed = CHECKSUM_NONE;
uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);
if (uh->check == 0)
uh->check = CSUM_MANGLED_0;
}
}
EXPORT_SYMBOL_GPL(udp4_hwcsum);
static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4)
{
struct sock *sk = skb->sk;
struct inet_sock *inet = inet_sk(sk);
struct udphdr *uh;
int err = 0;
int is_udplite = IS_UDPLITE(sk);
int offset = skb_transport_offset(skb);
int len = skb->len - offset;
__wsum csum = 0;
/*
* Create a UDP header
*/
uh = udp_hdr(skb);
uh->source = inet->inet_sport;
uh->dest = fl4->fl4_dport;
uh->len = htons(len);
uh->check = 0;
if (is_udplite) /* UDP-Lite */
csum = udplite_csum(skb);
else if (sk->sk_no_check == UDP_CSUM_NOXMIT) { /* UDP csum disabled */
skb->ip_summed = CHECKSUM_NONE;
goto send;
} else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
udp4_hwcsum(skb, fl4->saddr, fl4->daddr);
goto send;
} else
csum = udp_csum(skb);
/* add protocol-dependent pseudo-header */
uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len,
sk->sk_protocol, csum);
if (uh->check == 0)
uh->check = CSUM_MANGLED_0;
send:
err = ip_send_skb(sock_net(sk), skb);
if (err) {
if (err == -ENOBUFS && !inet->recverr) {
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_SNDBUFERRORS, is_udplite);
err = 0;
}
} else
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_OUTDATAGRAMS, is_udplite);
return err;
}
/*
* Push out all pending data as one UDP datagram. Socket is locked.
*/
int udp_push_pending_frames(struct sock *sk)
{
struct udp_sock *up = udp_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
struct sk_buff *skb;
int err = 0;
skb = ip_finish_skb(sk, fl4);
if (!skb)
goto out;
err = udp_send_skb(skb, fl4);
out:
up->len = 0;
up->pending = 0;
return err;
}
EXPORT_SYMBOL(udp_push_pending_frames);
int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len)
{
struct inet_sock *inet = inet_sk(sk);
struct udp_sock *up = udp_sk(sk);
struct flowi4 fl4_stack;
struct flowi4 *fl4;
int ulen = len;
struct ipcm_cookie ipc;
struct rtable *rt = NULL;
int free = 0;
int connected = 0;
__be32 daddr, faddr, saddr;
__be16 dport;
u8 tos;
int err, is_udplite = IS_UDPLITE(sk);
int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
struct sk_buff *skb;
struct ip_options_data opt_copy;
if (len > 0xFFFF)
return -EMSGSIZE;
/*
* Check the flags.
*/
if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
return -EOPNOTSUPP;
ipc.opt = NULL;
ipc.tx_flags = 0;
ipc.ttl = 0;
ipc.tos = -1;
getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
fl4 = &inet->cork.fl.u.ip4;
if (up->pending) {
/*
* There are pending frames.
* The socket lock must be held while it's corked.
*/
lock_sock(sk);
if (likely(up->pending)) {
if (unlikely(up->pending != AF_INET)) {
release_sock(sk);
return -EINVAL;
}
goto do_append_data;
}
release_sock(sk);
}
ulen += sizeof(struct udphdr);
/*
* Get and verify the address.
*/
if (msg->msg_name) {
struct sockaddr_in *usin = (struct sockaddr_in *)msg->msg_name;
if (msg->msg_namelen < sizeof(*usin))
return -EINVAL;
if (usin->sin_family != AF_INET) {
if (usin->sin_family != AF_UNSPEC)
return -EAFNOSUPPORT;
}
daddr = usin->sin_addr.s_addr;
dport = usin->sin_port;
if (dport == 0)
return -EINVAL;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
daddr = inet->inet_daddr;
dport = inet->inet_dport;
/* Open fast path for connected socket.
Route will not be used, if at least one option is set.
*/
connected = 1;
}
ipc.addr = inet->inet_saddr;
ipc.oif = sk->sk_bound_dev_if;
sock_tx_timestamp(sk, &ipc.tx_flags);
if (msg->msg_controllen) {
err = ip_cmsg_send(sock_net(sk), msg, &ipc);
if (err)
return err;
if (ipc.opt)
free = 1;
connected = 0;
}
if (!ipc.opt) {
struct ip_options_rcu *inet_opt;
rcu_read_lock();
inet_opt = rcu_dereference(inet->inet_opt);
if (inet_opt) {
memcpy(&opt_copy, inet_opt,
sizeof(*inet_opt) + inet_opt->opt.optlen);
ipc.opt = &opt_copy.opt;
}
rcu_read_unlock();
}
saddr = ipc.addr;
ipc.addr = faddr = daddr;
if (ipc.opt && ipc.opt->opt.srr) {
if (!daddr)
return -EINVAL;
faddr = ipc.opt->opt.faddr;
connected = 0;
}
tos = get_rttos(&ipc, inet);
if (sock_flag(sk, SOCK_LOCALROUTE) ||
(msg->msg_flags & MSG_DONTROUTE) ||
(ipc.opt && ipc.opt->opt.is_strictroute)) {
tos |= RTO_ONLINK;
connected = 0;
}
if (ipv4_is_multicast(daddr)) {
if (!ipc.oif)
ipc.oif = inet->mc_index;
if (!saddr)
saddr = inet->mc_addr;
connected = 0;
} else if (!ipc.oif)
ipc.oif = inet->uc_index;
if (connected)
rt = (struct rtable *)sk_dst_check(sk, 0);
if (rt == NULL) {
struct net *net = sock_net(sk);
fl4 = &fl4_stack;
flowi4_init_output(fl4, ipc.oif, sk->sk_mark, tos,
RT_SCOPE_UNIVERSE, sk->sk_protocol,
inet_sk_flowi_flags(sk)|FLOWI_FLAG_CAN_SLEEP,
faddr, saddr, dport, inet->inet_sport);
security_sk_classify_flow(sk, flowi4_to_flowi(fl4));
rt = ip_route_output_flow(net, fl4, sk);
if (IS_ERR(rt)) {
err = PTR_ERR(rt);
rt = NULL;
if (err == -ENETUNREACH)
IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES);
goto out;
}
err = -EACCES;
if ((rt->rt_flags & RTCF_BROADCAST) &&
!sock_flag(sk, SOCK_BROADCAST))
goto out;
if (connected)
sk_dst_set(sk, dst_clone(&rt->dst));
}
if (msg->msg_flags&MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
saddr = fl4->saddr;
if (!ipc.addr)
daddr = ipc.addr = fl4->daddr;
/* Lockless fast path for the non-corking case. */
if (!corkreq) {
skb = ip_make_skb(sk, fl4, getfrag, msg->msg_iov, ulen,
sizeof(struct udphdr), &ipc, &rt,
msg->msg_flags);
err = PTR_ERR(skb);
if (!IS_ERR_OR_NULL(skb))
err = udp_send_skb(skb, fl4);
goto out;
}
lock_sock(sk);
if (unlikely(up->pending)) {
/* The socket is already corked while preparing it. */
/* ... which is an evident application bug. --ANK */
release_sock(sk);
LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("cork app bug 2\n"));
err = -EINVAL;
goto out;
}
/*
* Now cork the socket to pend data.
*/
fl4 = &inet->cork.fl.u.ip4;
fl4->daddr = daddr;
fl4->saddr = saddr;
fl4->fl4_dport = dport;
fl4->fl4_sport = inet->inet_sport;
up->pending = AF_INET;
do_append_data:
up->len += ulen;
err = ip_append_data(sk, fl4, getfrag, msg->msg_iov, ulen,
sizeof(struct udphdr), &ipc, &rt,
corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
if (err)
udp_flush_pending_frames(sk);
else if (!corkreq)
err = udp_push_pending_frames(sk);
else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
up->pending = 0;
release_sock(sk);
out:
ip_rt_put(rt);
if (free)
kfree(ipc.opt);
if (!err)
return len;
/*
* ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting
* ENOBUFS might not be good (it's not tunable per se), but otherwise
* we don't have a good statistic (IpOutDiscards but it can be too many
* things). We could add another new stat but at least for now that
* seems like overkill.
*/
if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_SNDBUFERRORS, is_udplite);
}
return err;
do_confirm:
dst_confirm(&rt->dst);
if (!(msg->msg_flags&MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto out;
}
EXPORT_SYMBOL(udp_sendmsg);
int udp_sendpage(struct sock *sk, struct page *page, int offset,
size_t size, int flags)
{
struct inet_sock *inet = inet_sk(sk);
struct udp_sock *up = udp_sk(sk);
int ret;
if (!up->pending) {
struct msghdr msg = { .msg_flags = flags|MSG_MORE };
/* Call udp_sendmsg to specify destination address which
* sendpage interface can't pass.
* This will succeed only when the socket is connected.
*/
ret = udp_sendmsg(NULL, sk, &msg, 0);
if (ret < 0)
return ret;
}
lock_sock(sk);
if (unlikely(!up->pending)) {
release_sock(sk);
LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("udp cork app bug 3\n"));
return -EINVAL;
}
ret = ip_append_page(sk, &inet->cork.fl.u.ip4,
page, offset, size, flags);
if (ret == -EOPNOTSUPP) {
release_sock(sk);
return sock_no_sendpage(sk->sk_socket, page, offset,
size, flags);
}
if (ret < 0) {
udp_flush_pending_frames(sk);
goto out;
}
up->len += size;
if (!(up->corkflag || (flags&MSG_MORE)))
ret = udp_push_pending_frames(sk);
if (!ret)
ret = size;
out:
release_sock(sk);
return ret;
}
/**
* first_packet_length - return length of first packet in receive queue
* @sk: socket
*
* Drops all bad checksum frames, until a valid one is found.
* Returns the length of found skb, or 0 if none is found.
*/
static unsigned int first_packet_length(struct sock *sk)
{
struct sk_buff_head list_kill, *rcvq = &sk->sk_receive_queue;
struct sk_buff *skb;
unsigned int res;
__skb_queue_head_init(&list_kill);
spin_lock_bh(&rcvq->lock);
while ((skb = skb_peek(rcvq)) != NULL &&
udp_lib_checksum_complete(skb)) {
UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS,
IS_UDPLITE(sk));
UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS,
IS_UDPLITE(sk));
atomic_inc(&sk->sk_drops);
__skb_unlink(skb, rcvq);
__skb_queue_tail(&list_kill, skb);
}
res = skb ? skb->len : 0;
spin_unlock_bh(&rcvq->lock);
if (!skb_queue_empty(&list_kill)) {
bool slow = lock_sock_fast(sk);
__skb_queue_purge(&list_kill);
sk_mem_reclaim_partial(sk);
unlock_sock_fast(sk, slow);
}
return res;
}
/*
* IOCTL requests applicable to the UDP protocol
*/
int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
{
switch (cmd) {
case SIOCOUTQ:
{
int amount = sk_wmem_alloc_get(sk);
return put_user(amount, (int __user *)arg);
}
case SIOCINQ:
{
unsigned int amount = first_packet_length(sk);
if (amount)
/*
* We will only return the amount
* of this packet since that is all
* that will be read.
*/
amount -= sizeof(struct udphdr);
return put_user(amount, (int __user *)arg);
}
default:
return -ENOIOCTLCMD;
}
return 0;
}
EXPORT_SYMBOL(udp_ioctl);
/*
* This should be easy, if there is something there we
* return it, otherwise we block.
*/
int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len, int noblock, int flags, int *addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
bool slow;
if (flags & MSG_ERRQUEUE)
return ip_recv_error(sk, msg, len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
if (udp_lib_checksum_complete(skb))
goto csum_copy_err;
}
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr),
msg->msg_iov, copied);
else {
err = skb_copy_and_csum_datagram_iovec(skb,
sizeof(struct udphdr),
msg->msg_iov);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udp_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
goto out_free;
}
if (!peeked)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (sin) {
sin->sin_family = AF_INET;
sin->sin_port = udp_hdr(skb)->source;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
*addr_len = sizeof(*sin);
}
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
}
unlock_sock_fast(sk, slow);
if (noblock)
return -EAGAIN;
/* starting over for a new packet */
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
int udp_disconnect(struct sock *sk, int flags)
{
struct inet_sock *inet = inet_sk(sk);
/*
* 1003.1g - break association.
*/
sk->sk_state = TCP_CLOSE;
inet->inet_daddr = 0;
inet->inet_dport = 0;
sock_rps_reset_rxhash(sk);
sk->sk_bound_dev_if = 0;
if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
inet_reset_saddr(sk);
if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
sk->sk_prot->unhash(sk);
inet->inet_sport = 0;
}
sk_dst_reset(sk);
return 0;
}
EXPORT_SYMBOL(udp_disconnect);
void udp_lib_unhash(struct sock *sk)
{
if (sk_hashed(sk)) {
struct udp_table *udptable = sk->sk_prot->h.udp_table;
struct udp_hslot *hslot, *hslot2;
hslot = udp_hashslot(udptable, sock_net(sk),
udp_sk(sk)->udp_port_hash);
hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
spin_lock_bh(&hslot->lock);
if (sk_nulls_del_node_init_rcu(sk)) {
hslot->count--;
inet_sk(sk)->inet_num = 0;
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
spin_lock(&hslot2->lock);
hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
hslot2->count--;
spin_unlock(&hslot2->lock);
}
spin_unlock_bh(&hslot->lock);
}
}
EXPORT_SYMBOL(udp_lib_unhash);
/*
* inet_rcv_saddr was changed, we must rehash secondary hash
*/
void udp_lib_rehash(struct sock *sk, u16 newhash)
{
if (sk_hashed(sk)) {
struct udp_table *udptable = sk->sk_prot->h.udp_table;
struct udp_hslot *hslot, *hslot2, *nhslot2;
hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
nhslot2 = udp_hashslot2(udptable, newhash);
udp_sk(sk)->udp_portaddr_hash = newhash;
if (hslot2 != nhslot2) {
hslot = udp_hashslot(udptable, sock_net(sk),
udp_sk(sk)->udp_port_hash);
/* we must lock primary chain too */
spin_lock_bh(&hslot->lock);
spin_lock(&hslot2->lock);
hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
hslot2->count--;
spin_unlock(&hslot2->lock);
spin_lock(&nhslot2->lock);
hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
&nhslot2->head);
nhslot2->count++;
spin_unlock(&nhslot2->lock);
spin_unlock_bh(&hslot->lock);
}
}
}
EXPORT_SYMBOL(udp_lib_rehash);
static void udp_v4_rehash(struct sock *sk)
{
u16 new_hash = udp4_portaddr_hash(sock_net(sk),
inet_sk(sk)->inet_rcv_saddr,
inet_sk(sk)->inet_num);
udp_lib_rehash(sk, new_hash);
}
static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
int rc;
if (inet_sk(sk)->inet_daddr) {
sock_rps_save_rxhash(sk, skb);
sk_mark_napi_id(sk, skb);
}
rc = sock_queue_rcv_skb(sk, skb);
if (rc < 0) {
int is_udplite = IS_UDPLITE(sk);
/* Note that an ENOMEM error is charged twice */
if (rc == -ENOMEM)
UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS,
is_udplite);
UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
kfree_skb(skb);
trace_udp_fail_queue_rcv_skb(rc, sk);
return -1;
}
return 0;
}
static struct static_key udp_encap_needed __read_mostly;
void udp_encap_enable(void)
{
if (!static_key_enabled(&udp_encap_needed))
static_key_slow_inc(&udp_encap_needed);
}
EXPORT_SYMBOL(udp_encap_enable);
/* returns:
* -1: error
* 0: success
* >0: "udp encap" protocol resubmission
*
* Note that in the success and error cases, the skb is assumed to
* have either been requeued or freed.
*/
int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
struct udp_sock *up = udp_sk(sk);
int rc;
int is_udplite = IS_UDPLITE(sk);
/*
* Charge it to the socket, dropping if the queue is full.
*/
if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
goto drop;
nf_reset(skb);
if (static_key_false(&udp_encap_needed) && up->encap_type) {
int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
/*
* This is an encapsulation socket so pass the skb to
* the socket's udp_encap_rcv() hook. Otherwise, just
* fall through and pass this up the UDP socket.
* up->encap_rcv() returns the following value:
* =0 if skb was successfully passed to the encap
* handler or was discarded by it.
* >0 if skb should be passed on to UDP.
* <0 if skb should be resubmitted as proto -N
*/
/* if we're overly short, let UDP handle it */
encap_rcv = ACCESS_ONCE(up->encap_rcv);
if (skb->len > sizeof(struct udphdr) && encap_rcv != NULL) {
int ret;
ret = encap_rcv(sk, skb);
if (ret <= 0) {
UDP_INC_STATS_BH(sock_net(sk),
UDP_MIB_INDATAGRAMS,
is_udplite);
return -ret;
}
}
/* FALLTHROUGH -- it's a UDP Packet */
}
/*
* UDP-Lite specific tests, ignored on UDP sockets
*/
if ((is_udplite & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) {
/*
* MIB statistics other than incrementing the error count are
* disabled for the following two types of errors: these depend
* on the application settings, not on the functioning of the
* protocol stack as such.
*
* RFC 3828 here recommends (sec 3.3): "There should also be a
* way ... to ... at least let the receiving application block
* delivery of packets with coverage values less than a value
* provided by the application."
*/
if (up->pcrlen == 0) { /* full coverage was set */
LIMIT_NETDEBUG(KERN_WARNING "UDPLite: partial coverage %d while full coverage %d requested\n",
UDP_SKB_CB(skb)->cscov, skb->len);
goto drop;
}
/* The next case involves violating the min. coverage requested
* by the receiver. This is subtle: if receiver wants x and x is
* greater than the buffersize/MTU then receiver will complain
* that it wants x while sender emits packets of smaller size y.
* Therefore the above ...()->partial_cov statement is essential.
*/
if (UDP_SKB_CB(skb)->cscov < up->pcrlen) {
LIMIT_NETDEBUG(KERN_WARNING "UDPLite: coverage %d too small, need min %d\n",
UDP_SKB_CB(skb)->cscov, up->pcrlen);
goto drop;
}
}
if (rcu_access_pointer(sk->sk_filter) &&
udp_lib_checksum_complete(skb))
goto csum_error;
if (sk_rcvqueues_full(sk, skb, sk->sk_rcvbuf))
goto drop;
rc = 0;
ipv4_pktinfo_prepare(sk, skb);
bh_lock_sock(sk);
if (!sock_owned_by_user(sk))
rc = __udp_queue_rcv_skb(sk, skb);
else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) {
bh_unlock_sock(sk);
goto drop;
}
bh_unlock_sock(sk);
return rc;
csum_error:
UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
drop:
UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
atomic_inc(&sk->sk_drops);
kfree_skb(skb);
return -1;
}
static void flush_stack(struct sock **stack, unsigned int count,
struct sk_buff *skb, unsigned int final)
{
unsigned int i;
struct sk_buff *skb1 = NULL;
struct sock *sk;
for (i = 0; i < count; i++) {
sk = stack[i];
if (likely(skb1 == NULL))
skb1 = (i == final) ? skb : skb_clone(skb, GFP_ATOMIC);
if (!skb1) {
atomic_inc(&sk->sk_drops);
UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS,
IS_UDPLITE(sk));
UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS,
IS_UDPLITE(sk));
}
if (skb1 && udp_queue_rcv_skb(sk, skb1) <= 0)
skb1 = NULL;
}
if (unlikely(skb1))
kfree_skb(skb1);
}
static void udp_sk_rx_dst_set(struct sock *sk, const struct sk_buff *skb)
{
struct dst_entry *dst = skb_dst(skb);
dst_hold(dst);
sk->sk_rx_dst = dst;
}
/*
* Multicasts and broadcasts go to each listener.
*
* Note: called only from the BH handler context.
*/
static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
struct udphdr *uh,
__be32 saddr, __be32 daddr,
struct udp_table *udptable)
{
struct sock *sk, *stack[256 / sizeof(struct sock *)];
struct udp_hslot *hslot = udp_hashslot(udptable, net, ntohs(uh->dest));
int dif;
unsigned int i, count = 0;
spin_lock(&hslot->lock);
sk = sk_nulls_head(&hslot->head);
dif = skb->dev->ifindex;
sk = udp_v4_mcast_next(net, sk, uh->dest, daddr, uh->source, saddr, dif);
while (sk) {
stack[count++] = sk;
sk = udp_v4_mcast_next(net, sk_nulls_next(sk), uh->dest,
daddr, uh->source, saddr, dif);
if (unlikely(count == ARRAY_SIZE(stack))) {
if (!sk)
break;
flush_stack(stack, count, skb, ~0);
count = 0;
}
}
/*
* before releasing chain lock, we must take a reference on sockets
*/
for (i = 0; i < count; i++)
sock_hold(stack[i]);
spin_unlock(&hslot->lock);
/*
* do the slow work with no lock held
*/
if (count) {
flush_stack(stack, count, skb, count - 1);
for (i = 0; i < count; i++)
sock_put(stack[i]);
} else {
kfree_skb(skb);
}
return 0;
}
/* Initialize UDP checksum. If exited with zero value (success),
* CHECKSUM_UNNECESSARY means, that no more checks are required.
* Otherwise, csum completion requires chacksumming packet body,
* including udp header and folding it to skb->csum.
*/
static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh,
int proto)
{
const struct iphdr *iph;
int err;
UDP_SKB_CB(skb)->partial_cov = 0;
UDP_SKB_CB(skb)->cscov = skb->len;
if (proto == IPPROTO_UDPLITE) {
err = udplite_checksum_init(skb, uh);
if (err)
return err;
}
iph = ip_hdr(skb);
if (uh->check == 0) {
skb->ip_summed = CHECKSUM_UNNECESSARY;
} else if (skb->ip_summed == CHECKSUM_COMPLETE) {
if (!csum_tcpudp_magic(iph->saddr, iph->daddr, skb->len,
proto, skb->csum))
skb->ip_summed = CHECKSUM_UNNECESSARY;
}
if (!skb_csum_unnecessary(skb))
skb->csum = csum_tcpudp_nofold(iph->saddr, iph->daddr,
skb->len, proto, 0);
/* Probably, we should checksum udp header (it should be in cache
* in any case) and data in tiny packets (< rx copybreak).
*/
return 0;
}
/*
* All we need to do is get the socket, and then do a checksum.
*/
int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
int proto)
{
struct sock *sk;
struct udphdr *uh;
unsigned short ulen;
struct rtable *rt = skb_rtable(skb);
__be32 saddr, daddr;
struct net *net = dev_net(skb->dev);
/*
* Validate the packet.
*/
if (!pskb_may_pull(skb, sizeof(struct udphdr)))
goto drop; /* No space for header. */
uh = udp_hdr(skb);
ulen = ntohs(uh->len);
saddr = ip_hdr(skb)->saddr;
daddr = ip_hdr(skb)->daddr;
if (ulen > skb->len)
goto short_packet;
if (proto == IPPROTO_UDP) {
/* UDP validates ulen. */
if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
goto short_packet;
uh = udp_hdr(skb);
}
if (udp4_csum_init(skb, uh, proto))
goto csum_error;
if (skb->sk) {
int ret;
sk = skb->sk;
if (unlikely(sk->sk_rx_dst == NULL))
udp_sk_rx_dst_set(sk, skb);
ret = udp_queue_rcv_skb(sk, skb);
/* a return value > 0 means to resubmit the input, but
* it wants the return to be -protocol, or 0
*/
if (ret > 0)
return -ret;
return 0;
} else {
if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
return __udp4_lib_mcast_deliver(net, skb, uh,
saddr, daddr, udptable);
sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
}
if (sk != NULL) {
int ret;
ret = udp_queue_rcv_skb(sk, skb);
sock_put(sk);
/* a return value > 0 means to resubmit the input, but
* it wants the return to be -protocol, or 0
*/
if (ret > 0)
return -ret;
return 0;
}
if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
goto drop;
nf_reset(skb);
/* No socket. Drop packet silently, if checksum is wrong */
if (udp_lib_checksum_complete(skb))
goto csum_error;
UDP_INC_STATS_BH(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
/*
* Hmm. We got an UDP packet to a port to which we
* don't wanna listen. Ignore it.
*/
kfree_skb(skb);
return 0;
short_packet:
LIMIT_NETDEBUG(KERN_DEBUG "UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
proto == IPPROTO_UDPLITE ? "Lite" : "",
&saddr, ntohs(uh->source),
ulen, skb->len,
&daddr, ntohs(uh->dest));
goto drop;
csum_error:
/*
* RFC1122: OK. Discards the bad packet silently (as far as
* the network is concerned, anyway) as per 4.1.3.4 (MUST).
*/
LIMIT_NETDEBUG(KERN_DEBUG "UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
proto == IPPROTO_UDPLITE ? "Lite" : "",
&saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
ulen);
UDP_INC_STATS_BH(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
drop:
UDP_INC_STATS_BH(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
kfree_skb(skb);
return 0;
}
/* We can only early demux multicast if there is a single matching socket.
* If more than one socket found returns NULL
*/
static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net,
__be16 loc_port, __be32 loc_addr,
__be16 rmt_port, __be32 rmt_addr,
int dif)
{
struct sock *sk, *result;
struct hlist_nulls_node *node;
unsigned short hnum = ntohs(loc_port);
unsigned int count, slot = udp_hashfn(net, hnum, udp_table.mask);
struct udp_hslot *hslot = &udp_table.hash[slot];
rcu_read_lock();
begin:
count = 0;
result = NULL;
sk_nulls_for_each_rcu(sk, node, &hslot->head) {
if (__udp_is_mcast_sock(net, sk,
loc_port, loc_addr,
rmt_port, rmt_addr,
dif, hnum)) {
result = sk;
++count;
}
}
/*
* if the nulls value we got at the end of this lookup is
* not the expected one, we must restart lookup.
* We probably met an item that was moved to another chain.
*/
if (get_nulls_value(node) != slot)
goto begin;
if (result) {
if (count != 1 ||
unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2)))
result = NULL;
else if (unlikely(!__udp_is_mcast_sock(net, result,
loc_port, loc_addr,
rmt_port, rmt_addr,
dif, hnum))) {
sock_put(result);
result = NULL;
}
}
rcu_read_unlock();
return result;
}
/* For unicast we should only early demux connected sockets or we can
* break forwarding setups. The chains here can be long so only check
* if the first socket is an exact match and if not move on.
*/
static struct sock *__udp4_lib_demux_lookup(struct net *net,
__be16 loc_port, __be32 loc_addr,
__be16 rmt_port, __be32 rmt_addr,
int dif)
{
struct sock *sk, *result;
struct hlist_nulls_node *node;
unsigned short hnum = ntohs(loc_port);
unsigned int hash2 = udp4_portaddr_hash(net, loc_addr, hnum);
unsigned int slot2 = hash2 & udp_table.mask;
struct udp_hslot *hslot2 = &udp_table.hash2[slot2];
INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr)
const __portpair ports = INET_COMBINED_PORTS(rmt_port, hnum);
rcu_read_lock();
result = NULL;
udp_portaddr_for_each_entry_rcu(sk, node, &hslot2->head) {
if (INET_MATCH(sk, net, acookie,
rmt_addr, loc_addr, ports, dif))
result = sk;
/* Only check first socket in chain */
break;
}
if (result) {
if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2)))
result = NULL;
else if (unlikely(!INET_MATCH(sk, net, acookie,
rmt_addr, loc_addr,
ports, dif))) {
sock_put(result);
result = NULL;
}
}
rcu_read_unlock();
return result;
}
void udp_v4_early_demux(struct sk_buff *skb)
{
const struct iphdr *iph = ip_hdr(skb);
const struct udphdr *uh = udp_hdr(skb);
struct sock *sk;
struct dst_entry *dst;
struct net *net = dev_net(skb->dev);
int dif = skb->dev->ifindex;
/* validate the packet */
if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr)))
return;
if (skb->pkt_type == PACKET_BROADCAST ||
skb->pkt_type == PACKET_MULTICAST)
sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr,
uh->source, iph->saddr, dif);
else if (skb->pkt_type == PACKET_HOST)
sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr,
uh->source, iph->saddr, dif);
else
return;
if (!sk)
return;
skb->sk = sk;
skb->destructor = sock_edemux;
dst = sk->sk_rx_dst;
if (dst)
dst = dst_check(dst, 0);
if (dst)
skb_dst_set_noref(skb, dst);
}
int udp_rcv(struct sk_buff *skb)
{
return __udp4_lib_rcv(skb, &udp_table, IPPROTO_UDP);
}
void udp_destroy_sock(struct sock *sk)
{
struct udp_sock *up = udp_sk(sk);
bool slow = lock_sock_fast(sk);
udp_flush_pending_frames(sk);
unlock_sock_fast(sk, slow);
if (static_key_false(&udp_encap_needed) && up->encap_type) {
void (*encap_destroy)(struct sock *sk);
encap_destroy = ACCESS_ONCE(up->encap_destroy);
if (encap_destroy)
encap_destroy(sk);
}
}
/*
* Socket option code for UDP
*/
int udp_lib_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen,
int (*push_pending_frames)(struct sock *))
{
struct udp_sock *up = udp_sk(sk);
int val;
int err = 0;
int is_udplite = IS_UDPLITE(sk);
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
switch (optname) {
case UDP_CORK:
if (val != 0) {
up->corkflag = 1;
} else {
up->corkflag = 0;
lock_sock(sk);
(*push_pending_frames)(sk);
release_sock(sk);
}
break;
case UDP_ENCAP:
switch (val) {
case 0:
case UDP_ENCAP_ESPINUDP:
case UDP_ENCAP_ESPINUDP_NON_IKE:
up->encap_rcv = xfrm4_udp_encap_rcv;
/* FALLTHROUGH */
case UDP_ENCAP_L2TPINUDP:
up->encap_type = val;
udp_encap_enable();
break;
default:
err = -ENOPROTOOPT;
break;
}
break;
/*
* UDP-Lite's partial checksum coverage (RFC 3828).
*/
/* The sender sets actual checksum coverage length via this option.
* The case coverage > packet length is handled by send module. */
case UDPLITE_SEND_CSCOV:
if (!is_udplite) /* Disable the option on UDP sockets */
return -ENOPROTOOPT;
if (val != 0 && val < 8) /* Illegal coverage: use default (8) */
val = 8;
else if (val > USHRT_MAX)
val = USHRT_MAX;
up->pcslen = val;
up->pcflag |= UDPLITE_SEND_CC;
break;
/* The receiver specifies a minimum checksum coverage value. To make
* sense, this should be set to at least 8 (as done below). If zero is
* used, this again means full checksum coverage. */
case UDPLITE_RECV_CSCOV:
if (!is_udplite) /* Disable the option on UDP sockets */
return -ENOPROTOOPT;
if (val != 0 && val < 8) /* Avoid silly minimal values. */
val = 8;
else if (val > USHRT_MAX)
val = USHRT_MAX;
up->pcrlen = val;
up->pcflag |= UDPLITE_RECV_CC;
break;
default:
err = -ENOPROTOOPT;
break;
}
return err;
}
EXPORT_SYMBOL(udp_lib_setsockopt);
int udp_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
if (level == SOL_UDP || level == SOL_UDPLITE)
return udp_lib_setsockopt(sk, level, optname, optval, optlen,
udp_push_pending_frames);
return ip_setsockopt(sk, level, optname, optval, optlen);
}
#ifdef CONFIG_COMPAT
int compat_udp_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
if (level == SOL_UDP || level == SOL_UDPLITE)
return udp_lib_setsockopt(sk, level, optname, optval, optlen,
udp_push_pending_frames);
return compat_ip_setsockopt(sk, level, optname, optval, optlen);
}
#endif
int udp_lib_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
struct udp_sock *up = udp_sk(sk);
int val, len;
if (get_user(len, optlen))
return -EFAULT;
len = min_t(unsigned int, len, sizeof(int));
if (len < 0)
return -EINVAL;
switch (optname) {
case UDP_CORK:
val = up->corkflag;
break;
case UDP_ENCAP:
val = up->encap_type;
break;
/* The following two cannot be changed on UDP sockets, the return is
* always 0 (which corresponds to the full checksum coverage of UDP). */
case UDPLITE_SEND_CSCOV:
val = up->pcslen;
break;
case UDPLITE_RECV_CSCOV:
val = up->pcrlen;
break;
default:
return -ENOPROTOOPT;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
EXPORT_SYMBOL(udp_lib_getsockopt);
int udp_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
if (level == SOL_UDP || level == SOL_UDPLITE)
return udp_lib_getsockopt(sk, level, optname, optval, optlen);
return ip_getsockopt(sk, level, optname, optval, optlen);
}
#ifdef CONFIG_COMPAT
int compat_udp_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
if (level == SOL_UDP || level == SOL_UDPLITE)
return udp_lib_getsockopt(sk, level, optname, optval, optlen);
return compat_ip_getsockopt(sk, level, optname, optval, optlen);
}
#endif
/**
* udp_poll - wait for a UDP event.
* @file - file struct
* @sock - socket
* @wait - poll table
*
* This is same as datagram poll, except for the special case of
* blocking sockets. If application is using a blocking fd
* and a packet with checksum error is in the queue;
* then it could get return from select indicating data available
* but then block when reading it. Add special case code
* to work around these arguably broken applications.
*/
unsigned int udp_poll(struct file *file, struct socket *sock, poll_table *wait)
{
unsigned int mask = datagram_poll(file, sock, wait);
struct sock *sk = sock->sk;
sock_rps_record_flow(sk);
/* Check for false positives due to checksum errors */
if ((mask & POLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
!(sk->sk_shutdown & RCV_SHUTDOWN) && !first_packet_length(sk))
mask &= ~(POLLIN | POLLRDNORM);
return mask;
}
EXPORT_SYMBOL(udp_poll);
struct proto udp_prot = {
.name = "UDP",
.owner = THIS_MODULE,
.close = udp_lib_close,
.connect = ip4_datagram_connect,
.disconnect = udp_disconnect,
.ioctl = udp_ioctl,
.destroy = udp_destroy_sock,
.setsockopt = udp_setsockopt,
.getsockopt = udp_getsockopt,
.sendmsg = udp_sendmsg,
.recvmsg = udp_recvmsg,
.sendpage = udp_sendpage,
.backlog_rcv = __udp_queue_rcv_skb,
.release_cb = ip4_datagram_release_cb,
.hash = udp_lib_hash,
.unhash = udp_lib_unhash,
.rehash = udp_v4_rehash,
.get_port = udp_v4_get_port,
.memory_allocated = &udp_memory_allocated,
.sysctl_mem = sysctl_udp_mem,
.sysctl_wmem = &sysctl_udp_wmem_min,
.sysctl_rmem = &sysctl_udp_rmem_min,
.obj_size = sizeof(struct udp_sock),
.slab_flags = SLAB_DESTROY_BY_RCU,
.h.udp_table = &udp_table,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_udp_setsockopt,
.compat_getsockopt = compat_udp_getsockopt,
#endif
.clear_sk = sk_prot_clear_portaddr_nulls,
};
EXPORT_SYMBOL(udp_prot);
/* ------------------------------------------------------------------------ */
#ifdef CONFIG_PROC_FS
static struct sock *udp_get_first(struct seq_file *seq, int start)
{
struct sock *sk;
struct udp_iter_state *state = seq->private;
struct net *net = seq_file_net(seq);
for (state->bucket = start; state->bucket <= state->udp_table->mask;
++state->bucket) {
struct hlist_nulls_node *node;
struct udp_hslot *hslot = &state->udp_table->hash[state->bucket];
if (hlist_nulls_empty(&hslot->head))
continue;
spin_lock_bh(&hslot->lock);
sk_nulls_for_each(sk, node, &hslot->head) {
if (!net_eq(sock_net(sk), net))
continue;
if (sk->sk_family == state->family)
goto found;
}
spin_unlock_bh(&hslot->lock);
}
sk = NULL;
found:
return sk;
}
static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
{
struct udp_iter_state *state = seq->private;
struct net *net = seq_file_net(seq);
do {
sk = sk_nulls_next(sk);
} while (sk && (!net_eq(sock_net(sk), net) || sk->sk_family != state->family));
if (!sk) {
if (state->bucket <= state->udp_table->mask)
spin_unlock_bh(&state->udp_table->hash[state->bucket].lock);
return udp_get_first(seq, state->bucket + 1);
}
return sk;
}
static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
{
struct sock *sk = udp_get_first(seq, 0);
if (sk)
while (pos && (sk = udp_get_next(seq, sk)) != NULL)
--pos;
return pos ? NULL : sk;
}
static void *udp_seq_start(struct seq_file *seq, loff_t *pos)
{
struct udp_iter_state *state = seq->private;
state->bucket = MAX_UDP_PORTS;
return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
}
static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct sock *sk;
if (v == SEQ_START_TOKEN)
sk = udp_get_idx(seq, 0);
else
sk = udp_get_next(seq, v);
++*pos;
return sk;
}
static void udp_seq_stop(struct seq_file *seq, void *v)
{
struct udp_iter_state *state = seq->private;
if (state->bucket <= state->udp_table->mask)
spin_unlock_bh(&state->udp_table->hash[state->bucket].lock);
}
int udp_seq_open(struct inode *inode, struct file *file)
{
struct udp_seq_afinfo *afinfo = PDE_DATA(inode);
struct udp_iter_state *s;
int err;
err = seq_open_net(inode, file, &afinfo->seq_ops,
sizeof(struct udp_iter_state));
if (err < 0)
return err;
s = ((struct seq_file *)file->private_data)->private;
s->family = afinfo->family;
s->udp_table = afinfo->udp_table;
return err;
}
EXPORT_SYMBOL(udp_seq_open);
/* ------------------------------------------------------------------------ */
int udp_proc_register(struct net *net, struct udp_seq_afinfo *afinfo)
{
struct proc_dir_entry *p;
int rc = 0;
afinfo->seq_ops.start = udp_seq_start;
afinfo->seq_ops.next = udp_seq_next;
afinfo->seq_ops.stop = udp_seq_stop;
p = proc_create_data(afinfo->name, S_IRUGO, net->proc_net,
afinfo->seq_fops, afinfo);
if (!p)
rc = -ENOMEM;
return rc;
}
EXPORT_SYMBOL(udp_proc_register);
void udp_proc_unregister(struct net *net, struct udp_seq_afinfo *afinfo)
{
remove_proc_entry(afinfo->name, net->proc_net);
}
EXPORT_SYMBOL(udp_proc_unregister);
/* ------------------------------------------------------------------------ */
static void udp4_format_sock(struct sock *sp, struct seq_file *f,
int bucket, int *len)
{
struct inet_sock *inet = inet_sk(sp);
__be32 dest = inet->inet_daddr;
__be32 src = inet->inet_rcv_saddr;
__u16 destp = ntohs(inet->inet_dport);
__u16 srcp = ntohs(inet->inet_sport);
seq_printf(f, "%5d: %08X:%04X %08X:%04X"
" %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %d%n",
bucket, src, srcp, dest, destp, sp->sk_state,
sk_wmem_alloc_get(sp),
sk_rmem_alloc_get(sp),
0, 0L, 0,
from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
0, sock_i_ino(sp),
atomic_read(&sp->sk_refcnt), sp,
atomic_read(&sp->sk_drops), len);
}
int udp4_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_printf(seq, "%-127s\n",
" sl local_address rem_address st tx_queue "
"rx_queue tr tm->when retrnsmt uid timeout "
"inode ref pointer drops");
else {
struct udp_iter_state *state = seq->private;
int len;
udp4_format_sock(v, seq, state->bucket, &len);
seq_printf(seq, "%*s\n", 127 - len, "");
}
return 0;
}
static const struct file_operations udp_afinfo_seq_fops = {
.owner = THIS_MODULE,
.open = udp_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net
};
/* ------------------------------------------------------------------------ */
static struct udp_seq_afinfo udp4_seq_afinfo = {
.name = "udp",
.family = AF_INET,
.udp_table = &udp_table,
.seq_fops = &udp_afinfo_seq_fops,
.seq_ops = {
.show = udp4_seq_show,
},
};
static int __net_init udp4_proc_init_net(struct net *net)
{
return udp_proc_register(net, &udp4_seq_afinfo);
}
static void __net_exit udp4_proc_exit_net(struct net *net)
{
udp_proc_unregister(net, &udp4_seq_afinfo);
}
static struct pernet_operations udp4_net_ops = {
.init = udp4_proc_init_net,
.exit = udp4_proc_exit_net,
};
int __init udp4_proc_init(void)
{
return register_pernet_subsys(&udp4_net_ops);
}
void udp4_proc_exit(void)
{
unregister_pernet_subsys(&udp4_net_ops);
}
#endif /* CONFIG_PROC_FS */
static __initdata unsigned long uhash_entries;
static int __init set_uhash_entries(char *str)
{
ssize_t ret;
if (!str)
return 0;
ret = kstrtoul(str, 0, &uhash_entries);
if (ret)
return 0;
if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
uhash_entries = UDP_HTABLE_SIZE_MIN;
return 1;
}
__setup("uhash_entries=", set_uhash_entries);
void __init udp_table_init(struct udp_table *table, const char *name)
{
unsigned int i;
table->hash = alloc_large_system_hash(name,
2 * sizeof(struct udp_hslot),
uhash_entries,
21, /* one slot per 2 MB */
0,
&table->log,
&table->mask,
UDP_HTABLE_SIZE_MIN,
64 * 1024);
table->hash2 = table->hash + (table->mask + 1);
for (i = 0; i <= table->mask; i++) {
INIT_HLIST_NULLS_HEAD(&table->hash[i].head, i);
table->hash[i].count = 0;
spin_lock_init(&table->hash[i].lock);
}
for (i = 0; i <= table->mask; i++) {
INIT_HLIST_NULLS_HEAD(&table->hash2[i].head, i);
table->hash2[i].count = 0;
spin_lock_init(&table->hash2[i].lock);
}
}
void __init udp_init(void)
{
unsigned long limit;
udp_table_init(&udp_table, "UDP");
limit = nr_free_buffer_pages() / 8;
limit = max(limit, 128UL);
sysctl_udp_mem[0] = limit / 4 * 3;
sysctl_udp_mem[1] = limit;
sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
sysctl_udp_rmem_min = SK_MEM_QUANTUM;
sysctl_udp_wmem_min = SK_MEM_QUANTUM;
}
struct sk_buff *skb_udp_tunnel_segment(struct sk_buff *skb,
netdev_features_t features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
int mac_len = skb->mac_len;
int tnl_hlen = skb_inner_mac_header(skb) - skb_transport_header(skb);
__be16 protocol = skb->protocol;
netdev_features_t enc_features;
int outer_hlen;
if (unlikely(!pskb_may_pull(skb, tnl_hlen)))
goto out;
skb->encapsulation = 0;
__skb_pull(skb, tnl_hlen);
skb_reset_mac_header(skb);
skb_set_network_header(skb, skb_inner_network_offset(skb));
skb->mac_len = skb_inner_network_offset(skb);
skb->protocol = htons(ETH_P_TEB);
/* segment inner packet. */
enc_features = skb->dev->hw_enc_features & netif_skb_features(skb);
segs = skb_mac_gso_segment(skb, enc_features);
if (!segs || IS_ERR(segs))
goto out;
outer_hlen = skb_tnl_header_len(skb);
skb = segs;
do {
struct udphdr *uh;
int udp_offset = outer_hlen - tnl_hlen;
skb_reset_inner_headers(skb);
skb->encapsulation = 1;
skb->mac_len = mac_len;
skb_push(skb, outer_hlen);
skb_reset_mac_header(skb);
skb_set_network_header(skb, mac_len);
skb_set_transport_header(skb, udp_offset);
uh = udp_hdr(skb);
uh->len = htons(skb->len - udp_offset);
/* csum segment if tunnel sets skb with csum. */
if (protocol == htons(ETH_P_IP) && unlikely(uh->check)) {
struct iphdr *iph = ip_hdr(skb);
uh->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr,
skb->len - udp_offset,
IPPROTO_UDP, 0);
uh->check = csum_fold(skb_checksum(skb, udp_offset,
skb->len - udp_offset, 0));
if (uh->check == 0)
uh->check = CSUM_MANGLED_0;
} else if (protocol == htons(ETH_P_IPV6)) {
struct ipv6hdr *ipv6h = ipv6_hdr(skb);
u32 len = skb->len - udp_offset;
uh->check = ~csum_ipv6_magic(&ipv6h->saddr, &ipv6h->daddr,
len, IPPROTO_UDP, 0);
uh->check = csum_fold(skb_checksum(skb, udp_offset, len, 0));
if (uh->check == 0)
uh->check = CSUM_MANGLED_0;
skb->ip_summed = CHECKSUM_NONE;
}
skb->protocol = protocol;
} while ((skb = skb->next));
out:
return segs;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5844_3 |
crossvul-cpp_data_bad_5117_0 | /* State machine for IKEv1
* Copyright (C) 1997 Angelos D. Keromytis.
* Copyright (C) 1998-2010,2013-2015 D. Hugh Redelmeier <hugh@mimosa.com>
* Copyright (C) 2003-2008 Michael Richardson <mcr@xelerance.com>
* Copyright (C) 2008-2009 David McCullough <david_mccullough@securecomputing.com>
* Copyright (C) 2008-2010 Paul Wouters <paul@xelerance.com>
* Copyright (C) 2011 Avesh Agarwal <avagarwa@redhat.com>
* Copyright (C) 2008 Hiren Joshi <joshihirenn@gmail.com>
* Copyright (C) 2009 Anthony Tong <atong@TrustedCS.com>
* Copyright (C) 2012-2013 Paul Wouters <pwouters@redhat.com>
* Copyright (C) 2013 Wolfgang Nothdurft <wolfgang@linogate.de>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
*/
/* Ordering Constraints on Payloads
*
* rfc2409: The Internet Key Exchange (IKE)
*
* 5 Exchanges:
* "The SA payload MUST precede all other payloads in a phase 1 exchange."
*
* "Except where otherwise noted, there are no requirements for ISAKMP
* payloads in any message to be in any particular order."
*
* 5.3 Phase 1 Authenticated With a Revised Mode of Public Key Encryption:
*
* "If the HASH payload is sent it MUST be the first payload of the
* second message exchange and MUST be followed by the encrypted
* nonce. If the HASH payload is not sent, the first payload of the
* second message exchange MUST be the encrypted nonce."
*
* "Save the requirements on the location of the optional HASH payload
* and the mandatory nonce payload there are no further payload
* requirements. All payloads-- in whatever order-- following the
* encrypted nonce MUST be encrypted with Ke_i or Ke_r depending on the
* direction."
*
* 5.5 Phase 2 - Quick Mode
*
* "In Quick Mode, a HASH payload MUST immediately follow the ISAKMP
* header and a SA payload MUST immediately follow the HASH."
* [NOTE: there may be more than one SA payload, so this is not
* totally reasonable. Probably all SAs should be so constrained.]
*
* "If ISAKMP is acting as a client negotiator on behalf of another
* party, the identities of the parties MUST be passed as IDci and
* then IDcr."
*
* "With the exception of the HASH, SA, and the optional ID payloads,
* there are no payload ordering restrictions on Quick Mode."
*/
/* Unfolding of Identity -- a central mystery
*
* This concerns Phase 1 identities, those of the IKE hosts.
* These are the only ones that are authenticated. Phase 2
* identities are for IPsec SAs.
*
* There are three case of interest:
*
* (1) We initiate, based on a whack command specifying a Connection.
* We know the identity of the peer from the Connection.
*
* (2) (to be implemented) we initiate based on a flow from our client
* to some IP address.
* We immediately know one of the peer's client IP addresses from
* the flow. We must use this to figure out the peer's IP address
* and Id. To be solved.
*
* (3) We respond to an IKE negotiation.
* We immediately know the peer's IP address.
* We get an ID Payload in Main I2.
*
* Unfortunately, this is too late for a number of things:
* - the ISAKMP SA proposals have already been made (Main I1)
* AND one accepted (Main R1)
* - the SA includes a specification of the type of ID
* authentication so this is negotiated without being told the ID.
* - with Preshared Key authentication, Main I2 is encrypted
* using the key, so it cannot be decoded to reveal the ID
* without knowing (or guessing) which key to use.
*
* There are three reasonable choices here for the responder:
* + assume that the initiator is making wise offers since it
* knows the IDs involved. We can balk later (but not gracefully)
* when we find the actual initiator ID
* + attempt to infer identity by IP address. Again, we can balk
* when the true identity is revealed. Actually, it is enough
* to infer properties of the identity (eg. SA properties and
* PSK, if needed).
* + make all properties universal so discrimination based on
* identity isn't required. For example, always accept the same
* kinds of encryption. Accept Public Key Id authentication
* since the Initiator presumably has our public key and thinks
* we must have / can find his. This approach is weakest
* for preshared key since the actual key must be known to
* decrypt the Initiator's ID Payload.
* These choices can be blended. For example, a class of Identities
* can be inferred, sufficient to select a preshared key but not
* sufficient to infer a unique identity.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <libreswan.h>
#include "sysdep.h"
#include "constants.h"
#include "lswlog.h"
#include "defs.h"
#include "cookie.h"
#include "id.h"
#include "x509.h"
#include "pluto_x509.h"
#include "certs.h"
#include "connections.h" /* needs id.h */
#include "state.h"
#include "ikev1_msgid.h"
#include "packet.h"
#include "md5.h"
#include "sha1.h"
#include "crypto.h" /* requires sha1.h and md5.h */
#include "ike_alg.h"
#include "log.h"
#include "demux.h" /* needs packet.h */
#include "ikev1.h"
#include "ipsec_doi.h" /* needs demux.h and state.h */
#include "ikev1_quick.h"
#include "timer.h"
#include "whack.h" /* requires connections.h */
#include "server.h"
#include "ikev1_xauth.h"
#include "nat_traversal.h"
#include "vendor.h"
#include "ikev1_dpd.h"
#include "hostpair.h"
#include "pluto_crypt.h" /* just for log_crypto_workers() */
#ifdef HAVE_NM
#include "kernel.h"
#endif
/* state_microcode is a tuple of information parameterizing certain
* centralized processing of a packet. For example, it roughly
* specifies what payloads are expected in this message.
* The microcode is selected primarily based on the state.
* In Phase 1, the payload structure often depends on the
* authentication technique, so that too plays a part in selecting
* the state_microcode to use.
*/
struct state_microcode {
enum state_kind state, next_state;
lset_t flags;
lset_t req_payloads; /* required payloads (allows just one) */
lset_t opt_payloads; /* optional payloads (any mumber) */
/* if not ISAKMP_NEXT_NONE, process_packet will emit HDR with this as np */
u_int8_t first_out_payload;
enum event_type timeout_event;
state_transition_fn *processor;
};
/* State Microcode Flags, in several groups */
/* Oakley Auth values: to which auth values does this entry apply?
* Most entries will use SMF_ALL_AUTH because they apply to all.
* Note: SMF_ALL_AUTH matches 0 for those circumstances when no auth
* has been set.
*/
#define SMF_ALL_AUTH LRANGE(0, OAKLEY_AUTH_ROOF - 1)
#define SMF_PSK_AUTH LELEM(OAKLEY_PRESHARED_KEY)
#define SMF_DS_AUTH (LELEM(OAKLEY_DSS_SIG) | LELEM(OAKLEY_RSA_SIG))
#define SMF_PKE_AUTH LELEM(OAKLEY_RSA_ENC)
#define SMF_RPKE_AUTH LELEM(OAKLEY_RSA_REVISED_MODE)
/* misc flags */
#define SMF_INITIATOR LELEM(OAKLEY_AUTH_ROOF + 0)
#define SMF_FIRST_ENCRYPTED_INPUT LELEM(OAKLEY_AUTH_ROOF + 1)
#define SMF_INPUT_ENCRYPTED LELEM(OAKLEY_AUTH_ROOF + 2)
#define SMF_OUTPUT_ENCRYPTED LELEM(OAKLEY_AUTH_ROOF + 3)
#define SMF_RETRANSMIT_ON_DUPLICATE LELEM(OAKLEY_AUTH_ROOF + 4)
#define SMF_ENCRYPTED (SMF_INPUT_ENCRYPTED | SMF_OUTPUT_ENCRYPTED)
/* this state generates a reply message */
#define SMF_REPLY LELEM(OAKLEY_AUTH_ROOF + 5)
/* this state completes P1, so any pending P2 negotiations should start */
#define SMF_RELEASE_PENDING_P2 LELEM(OAKLEY_AUTH_ROOF + 6)
/* if we have canoncalized the authentication from XAUTH mode */
#define SMF_XAUTH_AUTH LELEM(OAKLEY_AUTH_ROOF + 7)
/* end of flags */
static state_transition_fn /* forward declaration */
unexpected,
informational;
/* v1_state_microcode_table is a table of all state_microcode tuples.
* It must be in order of state (the first element).
* After initialization, ike_microcode_index[s] points to the
* first entry in v1_state_microcode_table for state s.
* Remember that each state name in Main or Quick Mode describes
* what has happened in the past, not what this message is.
*/
static const struct state_microcode
*ike_microcode_index[STATE_IKE_ROOF - STATE_IKE_FLOOR];
static const struct state_microcode v1_state_microcode_table[] = {
#define PT(n) ISAKMP_NEXT_ ## n
#define P(n) LELEM(PT(n))
/***** Phase 1 Main Mode *****/
/* No state for main_outI1: --> HDR, SA */
/* STATE_MAIN_R0: I1 --> R1
* HDR, SA --> HDR, SA
*/
{ STATE_MAIN_R0, STATE_MAIN_R1,
SMF_ALL_AUTH | SMF_REPLY,
P(SA), P(VID) | P(CR), PT(NONE),
EVENT_v1_RETRANSMIT, main_inI1_outR1 },
/* STATE_MAIN_I1: R1 --> I2
* HDR, SA --> auth dependent
* SMF_PSK_AUTH, SMF_DS_AUTH: --> HDR, KE, Ni
* SMF_PKE_AUTH:
* --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
* SMF_RPKE_AUTH:
* --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
* Note: since we don't know auth at start, we cannot differentiate
* microcode entries based on it.
*/
{ STATE_MAIN_I1, STATE_MAIN_I2,
SMF_ALL_AUTH | SMF_INITIATOR | SMF_REPLY,
P(SA), P(VID) | P(CR), PT(NONE), /* don't know yet */
EVENT_v1_RETRANSMIT, main_inR1_outI2 },
/* STATE_MAIN_R1: I2 --> R2
* SMF_PSK_AUTH, SMF_DS_AUTH: HDR, KE, Ni --> HDR, KE, Nr
* SMF_PKE_AUTH: HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
* --> HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
* SMF_RPKE_AUTH:
* HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
* --> HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
*/
{ STATE_MAIN_R1, STATE_MAIN_R2,
SMF_PSK_AUTH | SMF_DS_AUTH | SMF_REPLY
, P(KE) | P(NONCE), P(VID) | P(CR) | P(NATD_RFC), PT(NONE)
, EVENT_v1_RETRANSMIT, main_inI2_outR2 },
{ STATE_MAIN_R1, STATE_UNDEFINED,
SMF_PKE_AUTH | SMF_REPLY,
P(KE) | P(ID) | P(NONCE), P(VID) | P(CR) | P(HASH), PT(KE),
EVENT_v1_RETRANSMIT, unexpected /* ??? not yet implemented */ },
{ STATE_MAIN_R1, STATE_UNDEFINED,
SMF_RPKE_AUTH | SMF_REPLY,
P(NONCE) | P(KE) | P(ID), P(VID) | P(CR) | P(HASH) | P(CERT), PT(
NONCE),
EVENT_v1_RETRANSMIT, unexpected /* ??? not yet implemented */ },
/* for states from here on, output message must be encrypted */
/* STATE_MAIN_I2: R2 --> I3
* SMF_PSK_AUTH: HDR, KE, Nr --> HDR*, IDi1, HASH_I
* SMF_DS_AUTH: HDR, KE, Nr --> HDR*, IDi1, [ CERT, ] SIG_I
* SMF_PKE_AUTH: HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
* --> HDR*, HASH_I
* SMF_RPKE_AUTH: HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
* --> HDR*, HASH_I
*/
{ STATE_MAIN_I2, STATE_MAIN_I3,
SMF_PSK_AUTH | SMF_DS_AUTH | SMF_INITIATOR | SMF_OUTPUT_ENCRYPTED |
SMF_REPLY
, P(KE) | P(NONCE), P(VID) | P(CR) | P(NATD_RFC), PT(ID)
, EVENT_v1_RETRANSMIT, main_inR2_outI3 },
{ STATE_MAIN_I2, STATE_UNDEFINED,
SMF_PKE_AUTH | SMF_INITIATOR | SMF_OUTPUT_ENCRYPTED | SMF_REPLY,
P(KE) | P(ID) | P(NONCE), P(VID) | P(CR), PT(HASH),
EVENT_v1_RETRANSMIT, unexpected /* ??? not yet implemented */ },
{ STATE_MAIN_I2, STATE_UNDEFINED,
SMF_ALL_AUTH | SMF_INITIATOR | SMF_OUTPUT_ENCRYPTED | SMF_REPLY,
P(NONCE) | P(KE) | P(ID), P(VID) | P(CR), PT(HASH),
EVENT_v1_RETRANSMIT, unexpected /* ??? not yet implemented */ },
/* for states from here on, input message must be encrypted */
/* STATE_MAIN_R2: I3 --> R3
* SMF_PSK_AUTH: HDR*, IDi1, HASH_I --> HDR*, IDr1, HASH_R
* SMF_DS_AUTH: HDR*, IDi1, [ CERT, ] SIG_I --> HDR*, IDr1, [ CERT, ] SIG_R
* SMF_PKE_AUTH, SMF_RPKE_AUTH: HDR*, HASH_I --> HDR*, HASH_R
*/
{ STATE_MAIN_R2, STATE_MAIN_R3,
SMF_PSK_AUTH | SMF_FIRST_ENCRYPTED_INPUT | SMF_ENCRYPTED |
SMF_REPLY | SMF_RELEASE_PENDING_P2,
P(ID) | P(HASH), P(VID) | P(CR), PT(NONE),
EVENT_SA_REPLACE, main_inI3_outR3 },
{ STATE_MAIN_R2, STATE_MAIN_R3,
SMF_DS_AUTH | SMF_FIRST_ENCRYPTED_INPUT | SMF_ENCRYPTED |
SMF_REPLY | SMF_RELEASE_PENDING_P2,
P(ID) | P(SIG), P(VID) | P(CR) | P(CERT), PT(NONE),
EVENT_SA_REPLACE, main_inI3_outR3 },
{ STATE_MAIN_R2, STATE_UNDEFINED,
SMF_PKE_AUTH | SMF_RPKE_AUTH | SMF_FIRST_ENCRYPTED_INPUT |
SMF_ENCRYPTED |
SMF_REPLY | SMF_RELEASE_PENDING_P2,
P(HASH), P(VID) | P(CR), PT(NONE),
EVENT_SA_REPLACE, unexpected /* ??? not yet implemented */ },
/* STATE_MAIN_I3: R3 --> done
* SMF_PSK_AUTH: HDR*, IDr1, HASH_R --> done
* SMF_DS_AUTH: HDR*, IDr1, [ CERT, ] SIG_R --> done
* SMF_PKE_AUTH, SMF_RPKE_AUTH: HDR*, HASH_R --> done
* May initiate quick mode by calling quick_outI1
*/
{ STATE_MAIN_I3, STATE_MAIN_I4,
SMF_PSK_AUTH | SMF_INITIATOR |
SMF_FIRST_ENCRYPTED_INPUT | SMF_ENCRYPTED | SMF_RELEASE_PENDING_P2,
P(ID) | P(HASH), P(VID) | P(CR), PT(NONE),
EVENT_SA_REPLACE, main_inR3 },
{ STATE_MAIN_I3, STATE_MAIN_I4,
SMF_DS_AUTH | SMF_INITIATOR |
SMF_FIRST_ENCRYPTED_INPUT | SMF_ENCRYPTED | SMF_RELEASE_PENDING_P2,
P(ID) | P(SIG), P(VID) | P(CR) | P(CERT), PT(NONE),
EVENT_SA_REPLACE, main_inR3 },
{ STATE_MAIN_I3, STATE_UNDEFINED,
SMF_PKE_AUTH | SMF_RPKE_AUTH | SMF_INITIATOR |
SMF_FIRST_ENCRYPTED_INPUT | SMF_ENCRYPTED | SMF_RELEASE_PENDING_P2,
P(HASH), P(VID) | P(CR), PT(NONE),
EVENT_SA_REPLACE, unexpected /* ??? not yet implemented */ },
/* STATE_MAIN_R3: can only get here due to packet loss */
{ STATE_MAIN_R3, STATE_UNDEFINED,
SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_RETRANSMIT_ON_DUPLICATE,
LEMPTY, LEMPTY,
PT(NONE), EVENT_NULL, unexpected },
/* STATE_MAIN_I4: can only get here due to packet loss */
{ STATE_MAIN_I4, STATE_UNDEFINED,
SMF_ALL_AUTH | SMF_INITIATOR | SMF_ENCRYPTED,
LEMPTY, LEMPTY,
PT(NONE), EVENT_NULL, unexpected },
/***** Phase 1 Aggressive Mode *****/
/* No initial state for aggr_outI1:
* SMF_DS_AUTH (RFC 2409 5.1) and SMF_PSK_AUTH (RFC 2409 5.4):
* -->HDR, SA, KE, Ni, IDii
*
* Not implemented:
* RFC 2409 5.2: --> HDR, SA, [ HASH(1),] KE, <IDii_b>Pubkey_r, <Ni_b>Pubkey_r
* RFC 2409 5.3: --> HDR, SA, [ HASH(1),] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDii_b>Ke_i [, <Cert-I_b>Ke_i ]
*/
/* STATE_AGGR_R0:
* SMF_PSK_AUTH: HDR, SA, KE, Ni, IDii
* --> HDR, SA, KE, Nr, IDir, HASH_R
* SMF_DS_AUTH: HDR, SA, KE, Nr, IDii
* --> HDR, SA, KE, Nr, IDir, [CERT,] SIG_R
*/
{ STATE_AGGR_R0, STATE_AGGR_R1,
SMF_PSK_AUTH | SMF_DS_AUTH | SMF_REPLY,
P(SA) | P(KE) | P(NONCE) | P(ID), P(VID) | P(NATD_RFC), PT(NONE),
EVENT_v1_RETRANSMIT, aggr_inI1_outR1 },
/* STATE_AGGR_I1:
* SMF_PSK_AUTH: HDR, SA, KE, Nr, IDir, HASH_R
* --> HDR*, HASH_I
* SMF_DS_AUTH: HDR, SA, KE, Nr, IDir, [CERT,] SIG_R
* --> HDR*, [CERT,] SIG_I
*/
{ STATE_AGGR_I1, STATE_AGGR_I2,
SMF_PSK_AUTH | SMF_INITIATOR | SMF_OUTPUT_ENCRYPTED | SMF_REPLY |
SMF_RELEASE_PENDING_P2,
P(SA) | P(KE) | P(NONCE) | P(ID) | P(HASH), P(VID) | P(NATD_RFC),
PT(NONE),
EVENT_SA_REPLACE, aggr_inR1_outI2 },
{ STATE_AGGR_I1, STATE_AGGR_I2,
SMF_DS_AUTH | SMF_INITIATOR | SMF_OUTPUT_ENCRYPTED | SMF_REPLY |
SMF_RELEASE_PENDING_P2,
P(SA) | P(KE) | P(NONCE) | P(ID) | P(SIG), P(VID) | P(NATD_RFC),
PT(NONE),
EVENT_SA_REPLACE, aggr_inR1_outI2 },
/* STATE_AGGR_R1:
* SMF_PSK_AUTH: HDR*, HASH_I --> done
* SMF_DS_AUTH: HDR*, SIG_I --> done
*/
{ STATE_AGGR_R1, STATE_AGGR_R2,
SMF_PSK_AUTH | SMF_FIRST_ENCRYPTED_INPUT |
SMF_ENCRYPTED | SMF_RELEASE_PENDING_P2,
P(HASH), P(VID) | P(NATD_RFC), PT(NONE),
EVENT_SA_REPLACE, aggr_inI2 },
{ STATE_AGGR_R1, STATE_AGGR_R2,
SMF_DS_AUTH | SMF_FIRST_ENCRYPTED_INPUT |
SMF_ENCRYPTED | SMF_RELEASE_PENDING_P2,
P(SIG), P(VID) | P(NATD_RFC), PT(NONE),
EVENT_SA_REPLACE, aggr_inI2 },
/* STATE_AGGR_I2: can only get here due to packet loss */
{ STATE_AGGR_I2, STATE_UNDEFINED,
SMF_ALL_AUTH | SMF_INITIATOR | SMF_RETRANSMIT_ON_DUPLICATE,
LEMPTY, LEMPTY, PT(NONE), EVENT_NULL, unexpected },
/* STATE_AGGR_R2: can only get here due to packet loss */
{ STATE_AGGR_R2, STATE_UNDEFINED,
SMF_ALL_AUTH,
LEMPTY, LEMPTY, PT(NONE), EVENT_NULL, unexpected },
/***** Phase 2 Quick Mode *****/
/* No state for quick_outI1:
* --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
*/
/* STATE_QUICK_R0:
* HDR*, HASH(1), SA, Ni [, KE ] [, IDci, IDcr ] -->
* HDR*, HASH(2), SA, Nr [, KE ] [, IDci, IDcr ]
* Installs inbound IPsec SAs.
* Because it may suspend for asynchronous DNS, first_out_payload
* is set to NONE to suppress early emission of HDR*.
* ??? it is legal to have multiple SAs, but we don't support it yet.
*/
{ STATE_QUICK_R0, STATE_QUICK_R1,
SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY
, P(HASH) | P(SA) | P(NONCE), /* P(SA) | */ P(KE) | P(ID) | P(
NATOA_RFC), PT(NONE)
, EVENT_v1_RETRANSMIT, quick_inI1_outR1 },
/* STATE_QUICK_I1:
* HDR*, HASH(2), SA, Nr [, KE ] [, IDci, IDcr ] -->
* HDR*, HASH(3)
* Installs inbound and outbound IPsec SAs, routing, etc.
* ??? it is legal to have multiple SAs, but we don't support it yet.
*/
{ STATE_QUICK_I1, STATE_QUICK_I2,
SMF_ALL_AUTH | SMF_INITIATOR | SMF_ENCRYPTED | SMF_REPLY
, P(HASH) | P(SA) | P(NONCE), /* P(SA) | */ P(KE) | P(ID) | P(
NATOA_RFC), PT(HASH)
, EVENT_SA_REPLACE, quick_inR1_outI2 },
/* STATE_QUICK_R1: HDR*, HASH(3) --> done
* Installs outbound IPsec SAs, routing, etc.
*/
{ STATE_QUICK_R1, STATE_QUICK_R2,
SMF_ALL_AUTH | SMF_ENCRYPTED,
P(HASH), LEMPTY, PT(NONE),
EVENT_SA_REPLACE, quick_inI2 },
/* STATE_QUICK_I2: can only happen due to lost packet */
{ STATE_QUICK_I2, STATE_UNDEFINED,
SMF_ALL_AUTH | SMF_INITIATOR | SMF_ENCRYPTED |
SMF_RETRANSMIT_ON_DUPLICATE,
LEMPTY, LEMPTY, PT(NONE),
EVENT_NULL, unexpected },
/* STATE_QUICK_R2: can only happen due to lost packet */
{ STATE_QUICK_R2, STATE_UNDEFINED,
SMF_ALL_AUTH | SMF_ENCRYPTED,
LEMPTY, LEMPTY, PT(NONE),
EVENT_NULL, unexpected },
/***** informational messages *****/
/* Informational Exchange (RFC 2408 4.8):
* HDR N/D
* Unencrypted: must not occur after ISAKMP Phase 1 exchange of keying material.
*/
/* STATE_INFO: */
{ STATE_INFO, STATE_UNDEFINED,
SMF_ALL_AUTH,
LEMPTY, LEMPTY, PT(NONE),
EVENT_NULL, informational },
/* Informational Exchange (RFC 2408 4.8):
* HDR* N/D
*/
/* STATE_INFO_PROTECTED: */
{ STATE_INFO_PROTECTED, STATE_UNDEFINED,
SMF_ALL_AUTH | SMF_ENCRYPTED,
P(HASH), LEMPTY, PT(NONE),
EVENT_NULL, informational },
{ STATE_XAUTH_R0, STATE_XAUTH_R1,
SMF_ALL_AUTH | SMF_ENCRYPTED,
P(MCFG_ATTR) | P(HASH), P(VID), PT(NONE),
EVENT_NULL, xauth_inR0 }, /*Re-transmit may be done by previous state*/
{ STATE_XAUTH_R1, STATE_MAIN_R3,
SMF_ALL_AUTH | SMF_ENCRYPTED,
P(MCFG_ATTR) | P(HASH), P(VID), PT(NONE),
EVENT_SA_REPLACE, xauth_inR1 },
#if 0
/* for situation where there is XAUTH + ModeCFG */
{ STATE_XAUTH_R2, STATE_XAUTH_R3,
SMF_ALL_AUTH | SMF_ENCRYPTED,
P(MCFG_ATTR) | P(HASH), P(VID), PT(NONE),
EVENT_SA_REPLACE, xauth_inR2 },
{ STATE_XAUTH_R3, STATE_MAIN_R3,
SMF_ALL_AUTH | SMF_ENCRYPTED,
P(MCFG_ATTR) | P(HASH), P(VID), PT(NONE),
EVENT_SA_REPLACE, xauth_inR3 },
#endif
/* MODE_CFG_x:
* Case R0: Responder -> Initiator
* <- Req(addr=0)
* Reply(ad=x) ->
*
* Case R1: Set(addr=x) ->
* <- Ack(ok)
*/
{ STATE_MODE_CFG_R0, STATE_MODE_CFG_R1,
SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY,
P(MCFG_ATTR) | P(HASH), P(VID), PT(HASH),
EVENT_SA_REPLACE, modecfg_inR0 },
{ STATE_MODE_CFG_R1, STATE_MODE_CFG_R2,
SMF_ALL_AUTH | SMF_ENCRYPTED,
P(MCFG_ATTR) | P(HASH), P(VID), PT(HASH),
EVENT_SA_REPLACE, modecfg_inR1 },
{ STATE_MODE_CFG_R2, STATE_UNDEFINED,
SMF_ALL_AUTH | SMF_ENCRYPTED,
LEMPTY, LEMPTY, PT(NONE),
EVENT_NULL, unexpected },
{ STATE_MODE_CFG_I1, STATE_MAIN_I4,
SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_RELEASE_PENDING_P2,
P(MCFG_ATTR) | P(HASH), P(VID), PT(HASH),
EVENT_SA_REPLACE, modecfg_inR1 },
{ STATE_XAUTH_I0, STATE_XAUTH_I1,
SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY | SMF_RELEASE_PENDING_P2,
P(MCFG_ATTR) | P(HASH), P(VID), PT(HASH),
EVENT_SA_REPLACE, xauth_inI0 },
{ STATE_XAUTH_I1, STATE_MAIN_I4,
SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY | SMF_RELEASE_PENDING_P2,
P(MCFG_ATTR) | P(HASH), P(VID), PT(HASH),
EVENT_SA_REPLACE, xauth_inI1 },
#undef P
#undef PT
};
void init_ikev1(void)
{
/* fill ike_microcode_index:
* make ike_microcode_index[s] point to first entry in
* v1_state_microcode_table for state s (backward scan makes this easier).
* Check that table is in order -- catch coding errors.
* For what it's worth, this routine is idempotent.
*/
const struct state_microcode *t;
for (t = &v1_state_microcode_table[elemsof(v1_state_microcode_table) - 1];;)
{
passert(STATE_IKE_FLOOR <= t->state &&
t->state < STATE_IKE_ROOF);
ike_microcode_index[t->state - STATE_IKE_FLOOR] = t;
if (t == v1_state_microcode_table)
break;
t--;
passert(t[0].state <= t[1].state);
}
}
static stf_status unexpected(struct msg_digest *md)
{
loglog(RC_LOG_SERIOUS, "unexpected message received in state %s",
enum_name(&state_names, md->st->st_state));
return STF_IGNORE;
}
/*
* RFC 2408 Section 4.6
*
* # Initiator Direction Responder NOTE
* (1) HDR*; N/D => Error Notification or Deletion
*/
static stf_status informational(struct msg_digest *md)
{
struct payload_digest *const n_pld = md->chain[ISAKMP_NEXT_N];
/* If the Notification Payload is not null... */
if (n_pld != NULL) {
pb_stream *const n_pbs = &n_pld->pbs;
struct isakmp_notification *const n =
&n_pld->payload.notification;
struct state *st = md->st; /* may be NULL */
/* Switch on Notification Type (enum) */
/* note that we _can_ get notification payloads unencrypted
* once we are at least in R3/I4.
* and that the handler is expected to treat them suspiciously.
*/
DBG(DBG_CONTROL, DBG_log("processing informational %s (%d)",
enum_name(&ikev1_notify_names,
n->isan_type),
n->isan_type));
switch (n->isan_type) {
case R_U_THERE:
if (st == NULL) {
loglog(RC_LOG_SERIOUS,
"received bogus R_U_THERE informational message");
return STF_IGNORE;
}
return dpd_inI_outR(st, n, n_pbs);
case R_U_THERE_ACK:
if (st == NULL) {
loglog(RC_LOG_SERIOUS,
"received bogus R_U_THERE_ACK informational message");
return STF_IGNORE;
}
return dpd_inR(st, n, n_pbs);
case PAYLOAD_MALFORMED:
if (st != NULL) {
st->hidden_variables.st_malformed_received++;
libreswan_log(
"received %u malformed payload notifies",
st->hidden_variables.st_malformed_received);
if (st->hidden_variables.st_malformed_sent >
MAXIMUM_MALFORMED_NOTIFY / 2 &&
((st->hidden_variables.st_malformed_sent +
st->hidden_variables.
st_malformed_received) >
MAXIMUM_MALFORMED_NOTIFY)) {
libreswan_log(
"too many malformed payloads (we sent %u and received %u",
st->hidden_variables.st_malformed_sent,
st->hidden_variables.st_malformed_received);
delete_state(st);
md->st = st = NULL;
}
}
return STF_IGNORE;
case ISAKMP_N_CISCO_LOAD_BALANCE:
if (st != NULL && IS_ISAKMP_SA_ESTABLISHED(st->st_state)) {
/* Saving connection name and whack sock id */
const char *tmp_name = st->st_connection->name;
int tmp_whack_sock = dup_any(st->st_whack_sock);
/* deleting ISAKMP SA with the current remote peer */
delete_state(st);
md->st = st = NULL;
/* to find and store the connection associated with tmp_name */
/* ??? how do we know that tmp_name hasn't been freed? */
struct connection *tmp_c = con_by_name(tmp_name, FALSE);
DBG_cond_dump(DBG_PARSING,
"redirected remote end info:", n_pbs->cur + pbs_left(
n_pbs) - 4, 4);
/* Current remote peer info */
{
ipstr_buf b;
const struct spd_route *tmp_spd =
&tmp_c->spd;
int count_spd = 0;
do {
DBG(DBG_CONTROLMORE,
DBG_log("spd route number: %d",
++count_spd));
/**that info**/
DBG(DBG_CONTROLMORE,
DBG_log("that id kind: %d",
tmp_spd->that.id.kind));
DBG(DBG_CONTROLMORE,
DBG_log("that id ipaddr: %s",
ipstr(&tmp_spd->that.id.ip_addr, &b)));
if (tmp_spd->that.id.name.ptr
!= NULL)
DBG(DBG_CONTROLMORE,
DBG_dump_chunk(
"that id name",
tmp_spd->
that.id.
name));
DBG(DBG_CONTROLMORE,
DBG_log("that host_addr: %s",
ipstr(&tmp_spd->that.host_addr, &b)));
DBG(DBG_CONTROLMORE,
DBG_log("that nexthop: %s",
ipstr(&tmp_spd->that.host_nexthop, &b)));
DBG(DBG_CONTROLMORE,
DBG_log("that srcip: %s",
ipstr(&tmp_spd->that.host_srcip, &b)));
DBG(DBG_CONTROLMORE,
DBG_log("that client_addr: %s, maskbits:%d",
ipstr(&tmp_spd->that.client.addr, &b),
tmp_spd->that.
client.maskbits));
DBG(DBG_CONTROLMORE,
DBG_log("that has_client: %d",
tmp_spd->that.
has_client));
DBG(DBG_CONTROLMORE,
DBG_log("that has_client_wildcard: %d",
tmp_spd->that.
has_client_wildcard));
DBG(DBG_CONTROLMORE,
DBG_log("that has_port_wildcard: %d",
tmp_spd->that.
has_port_wildcard));
DBG(DBG_CONTROLMORE,
DBG_log("that has_id_wildcards: %d",
tmp_spd->that.
has_id_wildcards));
tmp_spd = tmp_spd->spd_next;
} while (tmp_spd != NULL);
if (tmp_c->interface != NULL) {
DBG(DBG_CONTROLMORE,
DBG_log("Current interface_addr: %s",
ipstr(&tmp_c->interface->ip_addr, &b)));
}
if (tmp_c->gw_info != NULL) {
DBG(DBG_CONTROLMORE, {
DBG_log("Current gw_client_addr: %s",
ipstr(&tmp_c->gw_info->client_id.ip_addr, &b));
DBG_log("Current gw_gw_addr: %s",
ipstr(&tmp_c->gw_info->gw_id.ip_addr, &b));
});
}
}
/* storing old address for comparison purposes */
ip_address old_addr = tmp_c->spd.that.host_addr;
/* Decoding remote peer address info where connection has to be redirected to */
memcpy(&tmp_c->spd.that.host_addr.u.v4.sin_addr.s_addr,
(u_int32_t *)(n_pbs->cur +
pbs_left(n_pbs) - 4),
sizeof(tmp_c->spd.that.host_addr.u.v4.
sin_addr.
s_addr));
/* Modifying connection info to store the redirected remote peer info */
DBG(DBG_CONTROLMORE,
DBG_log("Old host_addr_name : %s",
tmp_c->spd.that.host_addr_name));
tmp_c->spd.that.host_addr_name = NULL;
tmp_c->spd.that.id.ip_addr =
tmp_c->spd.that.host_addr;
DBG(DBG_CONTROLMORE, {
ipstr_buf b;
if (sameaddr(&tmp_c->spd.this.
host_nexthop,
&old_addr)) {
DBG_log("Old remote addr %s",
ipstr(&old_addr, &b));
DBG_log("Old this host next hop %s",
ipstr(&tmp_c->spd.this.host_nexthop, &b));
tmp_c->spd.this.host_nexthop = tmp_c->spd.that.host_addr;
DBG_log("New this host next hop %s",
ipstr(&tmp_c->spd.this.host_nexthop, &b));
}
if (sameaddr(&tmp_c->spd.that.
host_srcip,
&old_addr)) {
DBG_log("Old that host srcip %s",
ipstr(&tmp_c->spd.that.host_srcip, &b));
tmp_c->spd.that.host_srcip = tmp_c->spd.that.host_addr;
DBG_log("New that host srcip %s",
ipstr(&tmp_c->spd.that.host_srcip, &b));
}
if (sameaddr(&tmp_c->spd.that.
client.addr,
&old_addr)) {
DBG_log("Old that client ip %s",
ipstr(&tmp_c->spd.that.client.addr, &b));
tmp_c->spd.that.client.addr = tmp_c->spd.that.host_addr;
DBG_log("New that client ip %s",
ipstr(&tmp_c->spd.that.client.addr, &b));
}
});
tmp_c->host_pair->him.addr =
tmp_c->spd.that.host_addr;
/* Initiating connection to the redirected peer */
initiate_connection(tmp_name, tmp_whack_sock,
LEMPTY, pcim_demand_crypto);
return STF_IGNORE;
}
loglog(RC_LOG_SERIOUS,
"received and ignored informational message with ISAKMP_N_CISCO_LOAD_BALANCE for unestablished state.");
return STF_IGNORE;
default:
if (st != NULL &&
(st->st_connection->extra_debugging &
IMPAIR_DIE_ONINFO)) {
loglog(RC_LOG_SERIOUS,
"received unhandled informational notification payload %d: '%s'",
n->isan_type,
enum_name(&ikev1_notify_names,
n->isan_type));
return STF_FATAL;
}
loglog(RC_LOG_SERIOUS,
"received and ignored informational message");
return STF_IGNORE;
}
} else {
loglog(RC_LOG_SERIOUS,
"received and ignored empty informational notification payload");
return STF_IGNORE;
}
}
/* create output HDR as replica of input HDR - IKEv1 only */
void ikev1_echo_hdr(struct msg_digest *md, bool enc, u_int8_t np)
{
struct isakmp_hdr hdr = md->hdr; /* mostly same as incoming header */
/* make sure we start with a clean buffer */
init_out_pbs(&reply_stream, reply_buffer, sizeof(reply_buffer),
"reply packet");
hdr.isa_flags = 0; /* zero all flags */
if (enc)
hdr.isa_flags |= ISAKMP_FLAGS_v1_ENCRYPTION;
if (DBGP(IMPAIR_SEND_BOGUS_ISAKMP_FLAG)) {
hdr.isa_flags |= ISAKMP_FLAGS_RESERVED_BIT6;
}
/* there is only one IKEv1 version, and no new one will ever come - no need to set version */
hdr.isa_np = np;
if (!out_struct(&hdr, &isakmp_hdr_desc, &reply_stream, &md->rbody))
impossible(); /* surely must have room and be well-formed */
}
/* process an input packet, possibly generating a reply.
*
* If all goes well, this routine eventually calls a state-specific
* transition function.
*
* This routine will not release_any_md(mdp). It is expected that its
* caller will do this. In fact, it will zap *mdp to NULL if it thinks
* **mdp should not be freed. So the caller should be prepared for
* *mdp being set to NULL.
*/
void process_v1_packet(struct msg_digest **mdp)
{
struct msg_digest *md = *mdp;
const struct state_microcode *smc;
bool new_iv_set = FALSE;
struct state *st = NULL;
enum state_kind from_state = STATE_UNDEFINED; /* state we started in */
#define SEND_NOTIFICATION(t) { \
if (st != NULL) \
send_notification_from_state(st, from_state, t); \
else \
send_notification_from_md(md, t); }
switch (md->hdr.isa_xchg) {
#ifdef NOTYET
case ISAKMP_XCHG_NONE:
case ISAKMP_XCHG_BASE:
case ISAKMP_XCHG_AO:
#endif
case ISAKMP_XCHG_AGGR:
case ISAKMP_XCHG_IDPROT: /* part of a Main Mode exchange */
if (md->hdr.isa_msgid != v1_MAINMODE_MSGID) {
libreswan_log(
"Message ID was 0x%08lx but should be zero in phase 1",
(unsigned long) md->hdr.isa_msgid);
SEND_NOTIFICATION(INVALID_MESSAGE_ID);
return;
}
if (is_zero_cookie(md->hdr.isa_icookie)) {
libreswan_log(
"Initiator Cookie must not be zero in phase 1 message");
SEND_NOTIFICATION(INVALID_COOKIE);
return;
}
if (is_zero_cookie(md->hdr.isa_rcookie)) {
/* initial message from initiator
* ??? what if this is a duplicate of another message?
*/
if (md->hdr.isa_flags & ISAKMP_FLAGS_v1_ENCRYPTION) {
libreswan_log("initial phase 1 message is invalid:"
" its Encrypted Flag is on");
SEND_NOTIFICATION(INVALID_FLAGS);
return;
}
/* don't build a state until the message looks tasty */
from_state = (md->hdr.isa_xchg == ISAKMP_XCHG_IDPROT ?
STATE_MAIN_R0 : STATE_AGGR_R0);
} else {
/* not an initial message */
st = find_state_ikev1(md->hdr.isa_icookie,
md->hdr.isa_rcookie,
md->hdr.isa_msgid);
if (st == NULL) {
/* perhaps this is a first message from the responder
* and contains a responder cookie that we've not yet seen.
*/
st = find_state_ikev1(md->hdr.isa_icookie,
zero_cookie,
md->hdr.isa_msgid);
if (st == NULL) {
libreswan_log(
"phase 1 message is part of an unknown exchange");
/* XXX Could send notification back */
return;
}
}
set_cur_state(st);
from_state = st->st_state;
}
break;
case ISAKMP_XCHG_INFO: /* an informational exchange */
st = ikev1_find_info_state(md->hdr.isa_icookie, md->hdr.isa_rcookie,
&md->sender, v1_MAINMODE_MSGID);
if (st == NULL) {
/*
* might be an informational response to our first
* message, in which case, we don't know the rcookie yet.
*/
st = find_state_ikev1(md->hdr.isa_icookie, zero_cookie,
v1_MAINMODE_MSGID);
}
if (st != NULL)
set_cur_state(st);
if (md->hdr.isa_flags & ISAKMP_FLAGS_v1_ENCRYPTION) {
bool quiet = (st == NULL ||
(st->st_connection->policy & POLICY_OPPORTUNISTIC));
if (st == NULL) {
DBG(DBG_CONTROL, DBG_log(
"Informational Exchange is for an unknown (expired?) SA with MSGID:0x%08lx",
(unsigned long)md->hdr.isa_msgid));
/* Let's try to log some info about these to track them down */
DBG(DBG_CONTROL, {
DBG_dump("- unknown SA's md->hdr.isa_icookie:",
md->hdr.isa_icookie,
COOKIE_SIZE);
DBG_dump("- unknown SA's md->hdr.isa_rcookie:",
md->hdr.isa_rcookie,
COOKIE_SIZE);
});
/* XXX Could send notification back */
return;
}
if (!IS_ISAKMP_ENCRYPTED(st->st_state)) {
if (!quiet) {
loglog(RC_LOG_SERIOUS, "encrypted Informational Exchange message is invalid because no key is known");
}
/* XXX Could send notification back */
return;
}
if (md->hdr.isa_msgid == v1_MAINMODE_MSGID) {
if (!quiet) {
loglog(RC_LOG_SERIOUS, "Informational Exchange message is invalid because it has a Message ID of 0");
}
/* XXX Could send notification back */
return;
}
if (!unique_msgid(st, md->hdr.isa_msgid)) {
if (!quiet) {
loglog(RC_LOG_SERIOUS, "Informational Exchange message is invalid because it has a previously used Message ID (0x%08lx)",
(unsigned long)md->hdr.isa_msgid);
}
/* XXX Could send notification back */
return;
}
st->st_msgid_reserved = FALSE;
init_phase2_iv(st, &md->hdr.isa_msgid);
new_iv_set = TRUE;
from_state = STATE_INFO_PROTECTED;
} else {
if (st != NULL &&
IS_ISAKMP_AUTHENTICATED(st->st_state)) {
if ((st->st_connection->policy & POLICY_OPPORTUNISTIC) == LEMPTY) {
loglog(RC_LOG_SERIOUS, "Informational Exchange message must be encrypted");
}
/* XXX Could send notification back */
return;
}
from_state = STATE_INFO;
}
break;
case ISAKMP_XCHG_QUICK: /* part of a Quick Mode exchange */
if (is_zero_cookie(md->hdr.isa_icookie)) {
DBG(DBG_CONTROL, DBG_log(
"Quick Mode message is invalid because it has an Initiator Cookie of 0"));
SEND_NOTIFICATION(INVALID_COOKIE);
return;
}
if (is_zero_cookie(md->hdr.isa_rcookie)) {
DBG(DBG_CONTROL, DBG_log(
"Quick Mode message is invalid because it has a Responder Cookie of 0"));
SEND_NOTIFICATION(INVALID_COOKIE);
return;
}
if (md->hdr.isa_msgid == v1_MAINMODE_MSGID) {
DBG(DBG_CONTROL, DBG_log(
"Quick Mode message is invalid because it has a Message ID of 0"));
SEND_NOTIFICATION(INVALID_MESSAGE_ID);
return;
}
st = find_state_ikev1(md->hdr.isa_icookie, md->hdr.isa_rcookie,
md->hdr.isa_msgid);
if (st == NULL) {
/* No appropriate Quick Mode state.
* See if we have a Main Mode state.
* ??? what if this is a duplicate of another message?
*/
st = find_state_ikev1(md->hdr.isa_icookie,
md->hdr.isa_rcookie,
v1_MAINMODE_MSGID);
if (st == NULL) {
DBG(DBG_CONTROL, DBG_log(
"Quick Mode message is for a non-existent (expired?) ISAKMP SA"));
/* XXX Could send notification back */
return;
}
if (st->st_oakley.doing_xauth) {
DBG(DBG_CONTROL, DBG_log(
"Cannot do Quick Mode until XAUTH done."));
return;
}
/* Have we just given an IP address to peer? */
if (st->st_state == STATE_MODE_CFG_R2) {
/* ISAKMP is up... */
change_state(st, STATE_MAIN_R3);
}
#ifdef SOFTREMOTE_CLIENT_WORKAROUND
/* See: http://popoludnica.pl/?id=10100110 */
if (st->st_state == STATE_MODE_CFG_R1) {
libreswan_log(
"SoftRemote workaround: Cannot do Quick Mode until MODECFG done.");
return;
}
#endif
set_cur_state(st);
if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state)) {
if (DBGP(DBG_OPPO) || (st->st_connection->policy & POLICY_OPPORTUNISTIC) == LEMPTY) {
loglog(RC_LOG_SERIOUS, "Quick Mode message is unacceptable because it is for an incomplete ISAKMP SA");
}
SEND_NOTIFICATION(PAYLOAD_MALFORMED /* XXX ? */);
return;
}
if (!unique_msgid(st, md->hdr.isa_msgid)) {
if (DBGP(DBG_OPPO) || (st->st_connection->policy & POLICY_OPPORTUNISTIC) == LEMPTY) {
loglog(RC_LOG_SERIOUS, "Quick Mode I1 message is unacceptable because it uses a previously used Message ID 0x%08lx (perhaps this is a duplicated packet)",
(unsigned long) md->hdr.isa_msgid);
}
SEND_NOTIFICATION(INVALID_MESSAGE_ID);
return;
}
st->st_msgid_reserved = FALSE;
/* Quick Mode Initial IV */
init_phase2_iv(st, &md->hdr.isa_msgid);
new_iv_set = TRUE;
from_state = STATE_QUICK_R0;
} else {
if (st->st_oakley.doing_xauth) {
if (DBGP(DBG_OPPO) ||
(st->st_connection->policy & POLICY_OPPORTUNISTIC) == LEMPTY) {
libreswan_log("Cannot do Quick Mode until XAUTH done.");
}
return;
}
set_cur_state(st);
from_state = st->st_state;
}
break;
case ISAKMP_XCHG_MODE_CFG:
if (is_zero_cookie(md->hdr.isa_icookie)) {
DBG(DBG_CONTROL, DBG_log("Mode Config message is invalid because it has an Initiator Cookie of 0"));
/* XXX Could send notification back */
return;
}
if (is_zero_cookie(md->hdr.isa_rcookie)) {
DBG(DBG_CONTROL, DBG_log("Mode Config message is invalid because it has a Responder Cookie of 0"));
/* XXX Could send notification back */
return;
}
if (md->hdr.isa_msgid == 0) {
DBG(DBG_CONTROL, DBG_log("Mode Config message is invalid because it has a Message ID of 0"));
/* XXX Could send notification back */
return;
}
st = ikev1_find_info_state(md->hdr.isa_icookie, md->hdr.isa_rcookie,
&md->sender, md->hdr.isa_msgid);
if (st == NULL) {
DBG(DBG_CONTROL, DBG_log(
"No appropriate Mode Config state yet.See if we have a Main Mode state"));
/* No appropriate Mode Config state.
* See if we have a Main Mode state.
* ??? what if this is a duplicate of another message?
*/
st = ikev1_find_info_state(md->hdr.isa_icookie,
md->hdr.isa_rcookie,
&md->sender, 0);
if (st == NULL) {
DBG(DBG_CONTROL, DBG_log(
"Mode Config message is for a non-existent (expired?) ISAKMP SA"));
/* XXX Could send notification back */
return;
}
set_cur_state(st);
DBG(DBG_CONTROLMORE, DBG_log(" processing received "
"isakmp_xchg_type %s.",
enum_show(&ikev1_exchange_names,
md->hdr.isa_xchg)));
DBG(DBG_CONTROLMORE, DBG_log(" this is a%s%s%s%s",
st->st_connection->spd.
this.xauth_server ?
" xauthserver" : "",
st->st_connection->spd.
this.xauth_client ?
" xauthclient" : "",
st->st_connection->spd.
this.modecfg_server ?
" modecfgserver" : "",
st->st_connection->spd.
this.modecfg_client ?
" modecfgclient" : ""
));
if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state)) {
DBG(DBG_CONTROLMORE, DBG_log(
"Mode Config message is unacceptable because it is for an incomplete ISAKMP SA (state=%s)",
enum_name(&state_names, st->st_state)));
/* XXX Could send notification back */
return;
}
DBG(DBG_CONTROLMORE, DBG_log(" call init_phase2_iv"));
init_phase2_iv(st, &md->hdr.isa_msgid);
new_iv_set = TRUE;
/*
* okay, now we have to figure out if we are receiving a bogus
* new message in an oustanding XAUTH server conversation
* (i.e. a reply to our challenge)
* (this occurs with some broken other implementations).
*
* or if receiving for the first time, an XAUTH challenge.
*
* or if we are getting a MODECFG request.
*
* we distinguish these states because we cannot both be an
* XAUTH server and client, and our policy tells us which
* one we are.
*
* to complicate further, it is normal to start a new msgid
* when going from one state to another, or when restarting
* the challenge.
*
*/
if (st->st_connection->spd.this.xauth_server &&
st->st_state == STATE_XAUTH_R1 &&
st->quirks.xauth_ack_msgid) {
from_state = STATE_XAUTH_R1;
DBG(DBG_CONTROLMORE, DBG_log(
" set from_state to %s state is STATE_XAUTH_R1 and quirks.xauth_ack_msgid is TRUE",
enum_name(&state_names,
st->st_state
)));
} else if (st->st_connection->spd.this.xauth_client
&&
IS_PHASE1(st->st_state)) {
from_state = STATE_XAUTH_I0;
DBG(DBG_CONTROLMORE, DBG_log(
" set from_state to %s this is xauthclient and IS_PHASE1() is TRUE",
enum_name(&state_names,
st->st_state
)));
} else if (st->st_connection->spd.this.xauth_client
&&
st->st_state == STATE_XAUTH_I1) {
/*
* in this case, we got a new MODECFG message after I0, maybe
* because it wants to start over again.
*/
from_state = STATE_XAUTH_I0;
DBG(DBG_CONTROLMORE, DBG_log(
" set from_state to %s this is xauthclient and state == STATE_XAUTH_I1",
enum_name(&state_names,
st->st_state
)));
} else if (st->st_connection->spd.this.modecfg_server
&&
IS_PHASE1(st->st_state)) {
from_state = STATE_MODE_CFG_R0;
DBG(DBG_CONTROLMORE, DBG_log(
" set from_state to %s this is modecfgserver and IS_PHASE1() is TRUE",
enum_name(&state_names,
st->st_state
)));
} else if (st->st_connection->spd.this.modecfg_client
&&
IS_PHASE1(st->st_state)) {
from_state = STATE_MODE_CFG_R1;
DBG(DBG_CONTROLMORE, DBG_log(
" set from_state to %s this is modecfgclient and IS_PHASE1() is TRUE",
enum_name(&state_names,
st->st_state
)));
} else {
DBG(DBG_CONTROLMORE, DBG_log(
"received isakmp_xchg_type %s",
enum_show(&ikev1_exchange_names,
md->hdr.isa_xchg)));
DBG(DBG_CONTROLMORE, DBG_log(
"this is a%s%s%s%s in state %s. Reply with UNSUPPORTED_EXCHANGE_TYPE",
st->st_connection
->spd.this.xauth_server ?
" xauthserver" : "",
st->st_connection
->spd.this.xauth_client ?
" xauthclient" : "",
st->st_connection
->spd.this.modecfg_server ?
" modecfgserver" :
"",
st->st_connection
->spd.this.modecfg_client ?
" modecfgclient" :
"",
enum_name(&
state_names,
st->st_state)
));
return;
}
} else {
if (st->st_connection->spd.this.xauth_server &&
IS_PHASE1(st->st_state)) {
/* Switch from Phase1 to Mode Config */
DBG(DBG_CONTROL, DBG_log(
"We were in phase 1, with no state, so we went to XAUTH_R0"));
change_state(st, STATE_XAUTH_R0);
}
/* otherweise, this is fine, we continue in the state we are in */
set_cur_state(st);
from_state = st->st_state;
}
break;
case ISAKMP_XCHG_NGRP:
default:
DBG(DBG_CONTROL, DBG_log("unsupported exchange type %s in message",
enum_show(&ikev1_exchange_names, md->hdr.isa_xchg)));
SEND_NOTIFICATION(UNSUPPORTED_EXCHANGE_TYPE);
return;
}
/* We have found a from_state, and perhaps a state object.
* If we need to build a new state object,
* we wait until the packet has been sanity checked.
*/
/* We don't support the Commit Flag. It is such a bad feature.
* It isn't protected -- neither encrypted nor authenticated.
* A man in the middle turns it on, leading to DoS.
* We just ignore it, with a warning.
*/
if (md->hdr.isa_flags & ISAKMP_FLAGS_v1_COMMIT)
DBG(DBG_CONTROL, DBG_log(
"IKE message has the Commit Flag set but Pluto doesn't implement this feature due to security concerns; ignoring flag"));
/* Handle IKE fragmentation payloads */
if (md->hdr.isa_np == ISAKMP_NEXT_IKE_FRAGMENTATION) {
struct isakmp_ikefrag fraghdr;
struct ike_frag *ike_frag, **i;
int last_frag_index = 0; /* index of the last fragment */
pb_stream frag_pbs;
if (st == NULL) {
DBG(DBG_CONTROL, DBG_log(
"received IKE fragment, but have no state. Ignoring packet."));
return;
}
if ((st->st_connection->policy & POLICY_IKE_FRAG_ALLOW) == 0) {
DBG(DBG_CONTROL, DBG_log(
"discarding IKE fragment packet - fragmentation not allowed by local policy (ike_frag=no)"));
return;
}
if (!in_struct(&fraghdr, &isakmp_ikefrag_desc,
&md->message_pbs, &frag_pbs) ||
pbs_room(&frag_pbs) != fraghdr.isafrag_length ||
fraghdr.isafrag_np != 0 ||
fraghdr.isafrag_number == 0 || fraghdr.isafrag_number >
16) {
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
return;
}
DBG(DBG_CONTROL,
DBG_log("received IKE fragment id '%d', number '%u'%s",
fraghdr.isafrag_id,
fraghdr.isafrag_number,
(fraghdr.isafrag_flags == 1) ? "(last)" : ""));
ike_frag = alloc_thing(struct ike_frag, "ike_frag");
ike_frag->md = md;
ike_frag->index = fraghdr.isafrag_number;
ike_frag->last = (fraghdr.isafrag_flags & 1);
ike_frag->size = pbs_left(&frag_pbs);
ike_frag->data = frag_pbs.cur;
#if 0
/* is this ever hit? It was wrongly checking one byte instead of 4 bytes of marker */
/* Strip non-ESP marker from first fragment */
if (md->iface->ike_float && ike_frag->index == 1 &&
(ike_frag->size >= NON_ESP_MARKER_SIZE &&
memeq(non_ESP_marker, ike_frag->data,
NON_ESP_MARKER_SIZE))) {
ike_frag->data += NON_ESP_MARKER_SIZE;
ike_frag->size -= NON_ESP_MARKER_SIZE;
}
#endif
/* Add the fragment to the state */
i = &st->ike_frags;
for (;;) {
if (ike_frag != NULL) {
/* Still looking for a place to insert ike_frag */
if (*i == NULL ||
(*i)->index > ike_frag->index) {
ike_frag->next = *i;
*i = ike_frag;
ike_frag = NULL;
} else if ((*i)->index == ike_frag->index) {
/* Replace fragment with same index */
struct ike_frag *old = *i;
ike_frag->next = old->next;
*i = ike_frag;
release_md(old->md);
pfree(old);
ike_frag = NULL;
}
}
if (*i == NULL)
break;
if ((*i)->last)
last_frag_index = (*i)->index;
i = &(*i)->next;
}
/* We have the last fragment, reassemble if complete */
if (last_frag_index != 0) {
size_t size = 0;
int prev_index = 0;
struct ike_frag *frag;
for (frag = st->ike_frags; frag; frag = frag->next) {
size += frag->size;
if (frag->index != ++prev_index) {
break; /* fragment list incomplete */
} else if (frag->index == last_frag_index) {
struct msg_digest *whole_md = alloc_md();
u_int8_t *buffer = alloc_bytes(size,
"IKE fragments buffer");
size_t offset = 0;
whole_md->iface = frag->md->iface;
whole_md->sender = frag->md->sender;
whole_md->sender_port =
frag->md->sender_port;
/* Reassemble fragments in buffer */
frag = st->ike_frags;
while (frag != NULL &&
frag->index <= last_frag_index)
{
passert(offset + frag->size <=
size);
memcpy(buffer + offset,
frag->data, frag->size);
offset += frag->size;
frag = frag->next;
}
init_pbs(&whole_md->packet_pbs, buffer, size,
"packet");
process_packet(&whole_md);
release_any_md(&whole_md);
release_fragments(st);
/* optimize: if receiving fragments, immediately respond with fragments too */
st->st_seen_fragments = TRUE;
DBG(DBG_CONTROL, DBG_log(
" updated IKE fragment state to respond using fragments without waiting for re-transmits"));
break;
}
}
}
/* Don't release the md, taken care of by the ike_frag code */
/* ??? I'm not sure -- DHR */
*mdp = NULL;
return;
}
/* Set smc to describe this state's properties.
* Look up the appropriate microcode based on state and
* possibly Oakley Auth type.
*/
passert(STATE_IKE_FLOOR <= from_state && from_state <= STATE_IKE_ROOF);
smc = ike_microcode_index[from_state - STATE_IKE_FLOOR];
if (st != NULL) {
oakley_auth_t baseauth =
xauth_calcbaseauth(st->st_oakley.auth);
while (!LHAS(smc->flags, baseauth)) {
smc++;
passert(smc->state == from_state);
}
}
if (state_busy(st))
return;
/* Detect and handle duplicated packets.
* This won't work for the initial packet of an exchange
* because we won't have a state object to remember it.
* If we are in a non-receiving state (terminal), and the preceding
* state did transmit, then the duplicate may indicate that that
* transmission wasn't received -- retransmit it.
* Otherwise, just discard it.
* ??? Notification packets are like exchanges -- I hope that
* they are idempotent!
*/
if (st != NULL &&
st->st_rpacket.ptr != NULL &&
st->st_rpacket.len == pbs_room(&md->packet_pbs) &&
memeq(st->st_rpacket.ptr, md->packet_pbs.start,
st->st_rpacket.len)) {
if (smc->flags & SMF_RETRANSMIT_ON_DUPLICATE) {
if (st->st_retransmit < MAXIMUM_v1_ACCEPTED_DUPLICATES) {
st->st_retransmit++;
loglog(RC_RETRANSMISSION,
"retransmitting in response to duplicate packet; already %s",
enum_name(&state_names, st->st_state));
resend_ike_v1_msg(st,
"retransmit in response to duplicate");
} else {
loglog(RC_LOG_SERIOUS,
"discarding duplicate packet -- exhausted retransmission; already %s",
enum_name(&state_names, st->st_state));
}
} else {
loglog(RC_LOG_SERIOUS,
"discarding duplicate packet; already %s",
enum_name(&state_names, st->st_state));
}
return;
}
/* save values for use in resumption of processing below.
* (may be suspended due to crypto operation not yet complete)
*/
md->st = st;
md->from_state = from_state;
md->smc = smc;
md->new_iv_set = new_iv_set;
/*
* look for encrypt packets. We cannot handle them if we have not
* yet calculated the skeyids. We will just store the packet in
* the suspended state, since the calculation is likely underway.
*
* note that this differs from above, because skeyid is calculated
* in between states. (or will be, once DH is async)
*
*/
if ((md->hdr.isa_flags & ISAKMP_FLAGS_v1_ENCRYPTION) &&
st != NULL && !st->hidden_variables.st_skeyid_calculated ) {
DBG(DBG_CRYPT | DBG_CONTROL, {
ipstr_buf b;
DBG_log("received encrypted packet from %s:%u but exponentiation still in progress",
ipstr(&md->sender, &b),
(unsigned)md->sender_port);
});
/* if there was a previous packet, let it go, and go with most
* recent one.
*/
if (st->st_suspended_md != NULL) {
DBG(DBG_CONTROL,
DBG_log("releasing suspended operation before completion: %p",
st->st_suspended_md));
release_any_md(&st->st_suspended_md);
}
set_suspended(st, md);
*mdp = NULL;
return;
}
process_packet_tail(mdp);
/* our caller will release_any_md(mdp); */
}
/*
* This routine will not release_any_md(mdp). It is expected that its
* caller will do this. In fact, it will zap *mdp to NULL if it thinks
* **mdp should not be freed. So the caller should be prepared for
* *mdp being set to NULL.
*/
void process_packet_tail(struct msg_digest **mdp)
{
struct msg_digest *md = *mdp;
struct state *st = md->st;
enum state_kind from_state = md->from_state;
const struct state_microcode *smc = md->smc;
bool new_iv_set = md->new_iv_set;
bool self_delete = FALSE;
if (md->hdr.isa_flags & ISAKMP_FLAGS_v1_ENCRYPTION) {
DBG(DBG_CRYPT, {
ipstr_buf b;
DBG_log("received encrypted packet from %s:%u",
ipstr(&md->sender, &b),
(unsigned)md->sender_port);
});
if (st == NULL) {
libreswan_log(
"discarding encrypted message for an unknown ISAKMP SA");
SEND_NOTIFICATION(PAYLOAD_MALFORMED /* XXX ? */);
return;
}
if (st->st_skey_ei_nss == NULL) {
loglog(RC_LOG_SERIOUS,
"discarding encrypted message because we haven't yet negotiated keying material");
SEND_NOTIFICATION(INVALID_FLAGS);
return;
}
/* Mark as encrypted */
md->encrypted = TRUE;
DBG(DBG_CRYPT,
DBG_log("decrypting %u bytes using algorithm %s",
(unsigned) pbs_left(&md->message_pbs),
enum_show(&oakley_enc_names,
st->st_oakley.encrypt)));
/* do the specified decryption
*
* IV is from st->st_iv or (if new_iv_set) st->st_new_iv.
* The new IV is placed in st->st_new_iv
*
* See RFC 2409 "IKE" Appendix B
*
* XXX The IV should only be updated really if the packet
* is successfully processed.
* We should keep this value, check for a success return
* value from the parsing routines and then replace.
*
* Each post phase 1 exchange generates IVs from
* the last phase 1 block, not the last block sent.
*/
{
const struct encrypt_desc *e = st->st_oakley.encrypter;
if (pbs_left(&md->message_pbs) % e->enc_blocksize != 0)
{
loglog(RC_LOG_SERIOUS,
"malformed message: not a multiple of encryption blocksize");
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
return;
}
/* XXX Detect weak keys */
/* grab a copy of raw packet (for duplicate packet detection) */
clonetochunk(md->raw_packet, md->packet_pbs.start,
pbs_room(&md->packet_pbs), "raw packet");
/* Decrypt everything after header */
if (!new_iv_set) {
if (st->st_iv_len == 0) {
init_phase2_iv(st, &md->hdr.isa_msgid);
} else {
/* use old IV */
restore_new_iv(st, st->st_iv, st->st_iv_len);
}
}
crypto_cbc_encrypt(e, FALSE, md->message_pbs.cur,
pbs_left(&md->message_pbs), st);
}
DBG_cond_dump(DBG_CRYPT, "decrypted:\n", md->message_pbs.cur,
md->message_pbs.roof - md->message_pbs.cur);
DBG_cond_dump(DBG_CRYPT, "next IV:",
st->st_new_iv, st->st_new_iv_len);
} else {
/* packet was not encryped -- should it have been? */
if (smc->flags & SMF_INPUT_ENCRYPTED) {
loglog(RC_LOG_SERIOUS,
"packet rejected: should have been encrypted");
SEND_NOTIFICATION(INVALID_FLAGS);
return;
}
}
/* Digest the message.
* Padding must be removed to make hashing work.
* Padding comes from encryption (so this code must be after decryption).
* Padding rules are described before the definition of
* struct isakmp_hdr in packet.h.
*/
{
struct payload_digest *pd = md->digest;
enum next_payload_types_ikev1 np = md->hdr.isa_np;
lset_t needed = smc->req_payloads;
const char *excuse =
LIN(SMF_PSK_AUTH | SMF_FIRST_ENCRYPTED_INPUT,
smc->flags) ?
"probable authentication failure (mismatch of preshared secrets?): "
:
"";
while (np != ISAKMP_NEXT_NONE) {
struct_desc *sd = v1_payload_desc(np);
if (pd == &md->digest[PAYLIMIT]) {
loglog(RC_LOG_SERIOUS,
"more than %d payloads in message; ignored",
PAYLIMIT);
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
return;
}
/*
* only do this in main mode. In aggressive mode, there
* is no negotiation of NAT-T method. Get it right.
*/
if (st != NULL && st->st_connection != NULL &&
(st->st_connection->policy & POLICY_AGGRESSIVE) == LEMPTY)
{
switch (np) {
case ISAKMP_NEXT_NATD_RFC:
case ISAKMP_NEXT_NATOA_RFC:
if ((st->hidden_variables.st_nat_traversal & NAT_T_WITH_RFC_VALUES) == LEMPTY) {
/*
* don't accept NAT-D/NAT-OA reloc directly in message,
* unless we're using NAT-T RFC
*/
DBG(DBG_NATT,
DBG_log("st_nat_traversal was: %s",
bitnamesof(natt_bit_names,
st->hidden_variables.st_nat_traversal)));
sd = NULL;
}
break;
default:
break;
}
}
if (sd == NULL) {
/* payload type is out of range or requires special handling */
switch (np) {
case ISAKMP_NEXT_ID:
/* ??? two kinds of ID payloads */
sd = (IS_PHASE1(from_state) ||
IS_PHASE15(from_state)) ?
&isakmp_identification_desc :
&isakmp_ipsec_identification_desc;
break;
case ISAKMP_NEXT_NATD_DRAFTS:
/* NAT-D was a private use type before RFC-3947 -- same format */
np = ISAKMP_NEXT_NATD_RFC;
sd = v1_payload_desc(np);
break;
case ISAKMP_NEXT_NATOA_DRAFTS:
/* NAT-OA was a private use type before RFC-3947 -- same format */
np = ISAKMP_NEXT_NATOA_RFC;
sd = v1_payload_desc(np);
break;
case ISAKMP_NEXT_SAK: /* or ISAKMP_NEXT_NATD_BADDRAFTS */
/*
* Official standards say that this is ISAKMP_NEXT_SAK,
* a part of Group DOI, something we don't implement.
* Old non-updated Cisco gear abused this number in ancient NAT drafts.
* We ignore (rather than reject) this in support of people
* with crufty Cisco machines.
*/
loglog(RC_LOG_SERIOUS,
"%smessage with unsupported payload ISAKMP_NEXT_SAK (or ISAKMP_NEXT_NATD_BADDRAFTS) ignored",
excuse);
/*
* Hack to discard payload, whatever it was.
* Since we are skipping the rest of the loop
* body we must do some things ourself:
* - demarshall the payload
* - grab the next payload number (np)
* - don't keep payload (don't increment pd)
* - skip rest of loop body
*/
if (!in_struct(&pd->payload, &isakmp_ignore_desc, &md->message_pbs,
&pd->pbs)) {
loglog(RC_LOG_SERIOUS,
"%smalformed payload in packet",
excuse);
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
return;
}
np = pd->payload.generic.isag_np;
/* NOTE: we do not increment pd! */
continue; /* skip rest of the loop */
default:
loglog(RC_LOG_SERIOUS,
"%smessage ignored because it contains an unknown or unexpected payload type (%s) at the outermost level",
excuse,
enum_show(&ikev1_payload_names, np));
SEND_NOTIFICATION(INVALID_PAYLOAD_TYPE);
return;
}
passert(sd != NULL);
}
passert(np < LELEM_ROOF);
{
lset_t s = LELEM(np);
if (LDISJOINT(s,
needed | smc->opt_payloads |
LELEM(ISAKMP_NEXT_VID) |
LELEM(ISAKMP_NEXT_N) |
LELEM(ISAKMP_NEXT_D) |
LELEM(ISAKMP_NEXT_CR) |
LELEM(ISAKMP_NEXT_CERT))) {
loglog(RC_LOG_SERIOUS, "%smessage ignored because it "
"contains an unexpected payload type (%s)",
excuse,
enum_show(&ikev1_payload_names, np));
SEND_NOTIFICATION(INVALID_PAYLOAD_TYPE);
return;
}
DBG(DBG_PARSING,
DBG_log("got payload 0x%" PRIxLSET" (%s) needed: 0x%" PRIxLSET "opt: 0x%" PRIxLSET,
s, enum_show(&ikev1_payload_names, np),
needed, smc->opt_payloads));
needed &= ~s;
}
if (!in_struct(&pd->payload, sd, &md->message_pbs,
&pd->pbs)) {
loglog(RC_LOG_SERIOUS,
"%smalformed payload in packet",
excuse);
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
return;
}
/* do payload-type specific debugging */
switch (np) {
case ISAKMP_NEXT_ID:
case ISAKMP_NEXT_NATOA_RFC:
/* dump ID section */
DBG(DBG_PARSING,
DBG_dump(" obj: ", pd->pbs.cur,
pbs_left(&pd->pbs)));
break;
default:
break;
}
/* place this payload at the end of the chain for this type */
{
struct payload_digest **p;
for (p = &md->chain[np]; *p != NULL;
p = &(*p)->next)
;
*p = pd;
pd->next = NULL;
}
np = pd->payload.generic.isag_np;
pd++;
/* since we've digested one payload happily, it is probably
* the case that any decryption worked. So we will not suggest
* encryption failure as an excuse for subsequent payload
* problems.
*/
excuse = "";
}
md->digest_roof = pd;
DBG(DBG_PARSING, {
if (pbs_left(&md->message_pbs) != 0)
DBG_log("removing %d bytes of padding",
(int) pbs_left(&md->message_pbs));
});
md->message_pbs.roof = md->message_pbs.cur;
/* check that all mandatory payloads appeared */
if (needed != 0) {
loglog(RC_LOG_SERIOUS,
"message for %s is missing payloads %s",
enum_show(&state_names, from_state),
bitnamesof(payload_name_ikev1, needed));
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
return;
}
}
/* more sanity checking: enforce most ordering constraints */
if (IS_PHASE1(from_state) || IS_PHASE15(from_state)) {
/* rfc2409: The Internet Key Exchange (IKE), 5 Exchanges:
* "The SA payload MUST precede all other payloads in a phase 1 exchange."
*/
if (md->chain[ISAKMP_NEXT_SA] != NULL &&
md->hdr.isa_np != ISAKMP_NEXT_SA) {
loglog(RC_LOG_SERIOUS,
"malformed Phase 1 message: does not start with an SA payload");
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
return;
}
} else if (IS_QUICK(from_state)) {
/* rfc2409: The Internet Key Exchange (IKE), 5.5 Phase 2 - Quick Mode
*
* "In Quick Mode, a HASH payload MUST immediately follow the ISAKMP
* header and a SA payload MUST immediately follow the HASH."
* [NOTE: there may be more than one SA payload, so this is not
* totally reasonable. Probably all SAs should be so constrained.]
*
* "If ISAKMP is acting as a client negotiator on behalf of another
* party, the identities of the parties MUST be passed as IDci and
* then IDcr."
*
* "With the exception of the HASH, SA, and the optional ID payloads,
* there are no payload ordering restrictions on Quick Mode."
*/
if (md->hdr.isa_np != ISAKMP_NEXT_HASH) {
loglog(RC_LOG_SERIOUS,
"malformed Quick Mode message: does not start with a HASH payload");
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
return;
}
{
struct payload_digest *p;
int i;
p = md->chain[ISAKMP_NEXT_SA];
i = 1;
while (p != NULL) {
if (p != &md->digest[i]) {
loglog(RC_LOG_SERIOUS,
"malformed Quick Mode message: SA payload is in wrong position");
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
return;
}
p = p->next;
i++;
}
}
/* rfc2409: The Internet Key Exchange (IKE), 5.5 Phase 2 - Quick Mode:
* "If ISAKMP is acting as a client negotiator on behalf of another
* party, the identities of the parties MUST be passed as IDci and
* then IDcr."
*/
{
struct payload_digest *id = md->chain[ISAKMP_NEXT_ID];
if (id != NULL) {
if (id->next == NULL ||
id->next->next != NULL) {
loglog(RC_LOG_SERIOUS, "malformed Quick Mode message:"
" if any ID payload is present,"
" there must be exactly two");
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
return;
}
if (id + 1 != id->next) {
loglog(RC_LOG_SERIOUS, "malformed Quick Mode message:"
" the ID payloads are not adjacent");
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
return;
}
}
}
}
/*
* Ignore payloads that we don't handle:
*/
/* XXX Handle Notifications */
{
struct payload_digest *p = md->chain[ISAKMP_NEXT_N];
while (p != NULL) {
switch (p->payload.notification.isan_type) {
case R_U_THERE:
case R_U_THERE_ACK:
case ISAKMP_N_CISCO_LOAD_BALANCE:
case PAYLOAD_MALFORMED:
case INVALID_MESSAGE_ID:
case IPSEC_RESPONDER_LIFETIME:
if (md->hdr.isa_xchg == ISAKMP_XCHG_INFO) {
/* these are handled later on in informational() */
break;
}
/* FALL THROUGH */
default:
if (st == NULL || (st != NULL &&
(st->st_connection->policy & POLICY_OPPORTUNISTIC))) {
DBG(DBG_CONTROL, DBG_log(
"ignoring informational payload %s, no corresponding state",
enum_show(& ikev1_notify_names,
p->payload.
notification.isan_type)));
} else {
loglog(RC_LOG_SERIOUS,
"ignoring informational payload %s, msgid=%08" PRIx32 ", length=%d",
enum_show(&ikev1_notify_names,
p->payload.
notification.isan_type),
st->st_msgid,
p->payload.notification.isan_length);
DBG_dump_pbs(&p->pbs);
}
if (st != NULL &&
st->st_connection->extra_debugging &
IMPAIR_DIE_ONINFO) {
loglog(RC_LOG_SERIOUS,
"received and failed on unknown informational message");
complete_v1_state_transition(mdp,
STF_FATAL);
/* our caller will release_any_md(mdp); */
return;
}
}
DBG_cond_dump(DBG_PARSING, "info:", p->pbs.cur, pbs_left(
&p->pbs));
p = p->next;
}
p = md->chain[ISAKMP_NEXT_D];
while (p != NULL) {
self_delete |= accept_delete(md, p);
DBG_cond_dump(DBG_PARSING, "del:", p->pbs.cur, pbs_left(
&p->pbs));
p = p->next;
}
p = md->chain[ISAKMP_NEXT_VID];
while (p != NULL) {
handle_vendorid(md, (char *)p->pbs.cur,
pbs_left(&p->pbs), FALSE);
p = p->next;
}
}
if (self_delete) {
accept_self_delete(md);
st = md->st; /* st not subsequently used */
/* note: st ought to be NULL from here on */
}
#if 0
/* this does not seem to be right */
/* VERIFY that we only accept NAT-D/NAT-OE when they sent us the VID */
if ((md->chain[ISAKMP_NEXT_NATD_RFC] != NULL ||
md->chain[ISAKMP_NEXT_NATOA_RFC] != NULL) &&
(st->hidden_variables.st_nat_traversal & NAT_T_WITH_RFC_VALUES) == LEMPTY) {
/*
* don't accept NAT-D/NAT-OA reloc directly in message,
* unless we're using NAT-T RFC
*/
loglog(RC_LOG_SERIOUS,
"message ignored because it contains a NAT payload, when we did not receive the appropriate VendorID");
return;
}
#endif
/* possibly fill in hdr */
if (smc->first_out_payload != ISAKMP_NEXT_NONE)
ikev1_echo_hdr(md, (smc->flags & SMF_OUTPUT_ENCRYPTED) != 0,
smc->first_out_payload);
complete_v1_state_transition(mdp, smc->processor(md));
/* our caller will release_any_md(mdp); */
}
/*
* replace previous receive packet with latest, to update
* our notion of a retransmitted packet. This is important
* to do, even for failing transitions, and suspended transitions
* because the sender may well retransmit their request.
* We had better be idempotent since we can be called
* multiple times in handling a packet due to crypto helper logic.
*/
static void remember_received_packet(struct state *st, struct msg_digest *md)
{
if (md->encrypted) {
/* if encrypted, duplication already done */
if (md->raw_packet.ptr != NULL) {
pfreeany(st->st_rpacket.ptr);
st->st_rpacket = md->raw_packet;
md->raw_packet.ptr = NULL;
}
} else {
/* this may be a repeat, but it will work */
pfreeany(st->st_rpacket.ptr);
clonetochunk(st->st_rpacket,
md->packet_pbs.start,
pbs_room(&md->packet_pbs), "raw packet");
}
}
/* complete job started by the state-specific state transition function
*
* This routine will not release_any_md(mdp). It is expected that its
* caller will do this. In fact, it will zap *mdp to NULL if it thinks
* **mdp should not be freed. So the caller should be prepared for
* *mdp being set to NULL.
*
* md is used to:
* - find st
* - find from_state (st might be gone)
* - find note for STF_FAIL (might not be part of result (STF_FAIL+note))
* - find note for STF_INTERNAL_ERROR
* - record md->event_already_set
* - remember_received_packet(st, md);
* - nat_traversal_change_port_lookup(md, st);
* - smc for smc->next_state
* - smc for smc->flags & SMF_REPLY to trigger a reply
* - smc for smc->timeout_event
* - smc for !(smc->flags & SMF_INITIATOR) for Contivity mode
* - smc for smc->flags & SMF_RELEASE_PENDING_P2 to trigger unpend call
* - smc for smc->flags & SMF_INITIATOR to adjust retransmission
* - fragvid, dpd, nortel
*/
void complete_v1_state_transition(struct msg_digest **mdp, stf_status result)
{
struct msg_digest *md = *mdp;
enum state_kind from_state;
struct state *st;
passert(md != NULL);
/* handle oddball/meta results now */
switch (result) {
case STF_SUSPEND:
cur_state = md->st; /* might have changed */
/* FALL THROUGH */
case STF_INLINE: /* all done, including release_any_md */
*mdp = NULL; /* take md away from parent */
/* FALL THROUGH */
case STF_IGNORE:
DBG(DBG_CONTROL,
DBG_log("complete v1 state transition with %s",
enum_show(&stfstatus_name, result)));
return;
default:
break;
}
DBG(DBG_CONTROL,
DBG_log("complete v1 state transition with %s",
result > STF_FAIL ?
enum_name(&ikev1_notify_names, result - STF_FAIL) :
enum_name(&stfstatus_name, result)));
/* safe to refer to *md */
from_state = md->from_state;
cur_state = st = md->st; /* might have changed */
passert(st != NULL);
passert(!st->st_calculating);
switch (result) {
case STF_OK:
{
/* advance the state */
const struct state_microcode *smc = md->smc;
libreswan_log("transition from state %s to state %s",
enum_name(&state_names, from_state),
enum_name(&state_names, smc->next_state));
/* accept info from VID because we accept this message */
/* If state has FRAGMENTATION support, import it */
if (md->fragvid) {
DBG(DBG_CONTROLMORE, DBG_log("peer supports fragmentation"));
st->st_seen_fragvid = TRUE;
}
/* If state has DPD support, import it */
if (md->dpd &&
st->hidden_variables.st_peer_supports_dpd != md->dpd) {
DBG(DBG_DPD, DBG_log("peer supports dpd"));
st->hidden_variables.st_peer_supports_dpd = md->dpd;
if (dpd_active_locally(st)) {
DBG(DBG_DPD, DBG_log("dpd is active locally"));
}
}
/* If state has VID_NORTEL, import it to activate workaround */
if (md->nortel) {
DBG(DBG_CONTROLMORE, DBG_log("peer requires Nortel Contivity workaround"));
st->st_seen_nortel_vid = TRUE;
}
if (!st->st_msgid_reserved &&
IS_CHILD_SA(st) &&
st->st_msgid != v1_MAINMODE_MSGID) {
struct state *p1st = state_with_serialno(
st->st_clonedfrom);
if (p1st != NULL) {
/* do message ID reservation */
reserve_msgid(p1st, st->st_msgid);
}
st->st_msgid_reserved = TRUE;
}
change_state(st, smc->next_state);
/* XAUTH negotiation withOUT modecfg ends in STATE_XAUTH_I1
* which is wrong and creates issues further in several places
* As per libreswan design, it seems every phase 1 negotiation
* including xauth/modecfg must end with STATE_MAIN_I4 to mark
* actual end of phase 1. With modecfg, negotiation ends with
* STATE_MAIN_I4 already.
*/
#if 0 /* ??? what's this code for? */
if (st->st_connection->spd.this.xauth_client
&& st->hidden_variables.st_xauth_client_done
&& !st->st_connection->spd.this.modecfg_client
&& st->st_state == STATE_XAUTH_I1) {
DBG(DBG_CONTROL,
DBG_log("As XAUTH is done and modecfg is not configured, so Phase 1 neogtiation finishes successfully"));
change_state(st, STATE_MAIN_I4);
}
#endif
/* Schedule for whatever timeout is specified */
if (!md->event_already_set) {
/* Delete previous retransmission event.
* New event will be scheduled below.
*/
delete_event(st);
}
/* Delete IKE fragments */
release_fragments(st);
/* update the previous packet history */
remember_received_packet(st, md);
/* free previous transmit packet */
freeanychunk(st->st_tpacket);
/* in aggressive mode, there will be no reply packet in transition
* from STATE_AGGR_R1 to STATE_AGGR_R2
*/
if (nat_traversal_enabled) {
/* adjust our destination port if necessary */
nat_traversal_change_port_lookup(md, st);
}
/* if requested, send the new reply packet */
if (smc->flags & SMF_REPLY) {
DBG(DBG_CONTROL, {
ipstr_buf b;
DBG_log("sending reply packet to %s:%u (from port %u)",
ipstr(&st->st_remoteaddr, &b),
st->st_remoteport,
st->st_interface->port);
});
close_output_pbs(&reply_stream); /* good form, but actually a no-op */
record_and_send_ike_msg(st, &reply_stream,
enum_name(&state_names, from_state));
}
/* Schedule for whatever timeout is specified */
if (!md->event_already_set) {
unsigned long delay_ms; /* delay is in milliseconds here */
enum event_type kind = smc->timeout_event;
bool agreed_time = FALSE;
struct connection *c = st->st_connection;
switch (kind) {
case EVENT_v1_RETRANSMIT: /* Retransmit packet */
delay_ms = c->r_interval;
break;
case EVENT_SA_REPLACE: /* SA replacement event */
if (IS_PHASE1(st->st_state) ||
IS_PHASE15(st->st_state )) {
/* Note: we will defer to the "negotiated" (dictated)
* lifetime if we are POLICY_DONT_REKEY.
* This allows the other side to dictate
* a time we would not otherwise accept
* but it prevents us from having to initiate
* rekeying. The negative consequences seem
* minor.
*/
delay_ms = deltamillisecs(c->sa_ike_life_seconds);
if ((c->policy & POLICY_DONT_REKEY) ||
delay_ms >= deltamillisecs(st->st_oakley.life_seconds))
{
agreed_time = TRUE;
delay_ms = deltamillisecs(st->st_oakley.life_seconds);
}
} else {
/* Delay is min of up to four things:
* each can limit the lifetime.
*/
time_t delay = deltasecs(c->sa_ipsec_life_seconds);
#define clamp_delay(trans) { \
if (st->trans.present && \
delay >= deltasecs(st->trans.attrs.life_seconds)) { \
agreed_time = TRUE; \
delay = deltasecs(st->trans.attrs.life_seconds); \
} \
}
clamp_delay(st_ah);
clamp_delay(st_esp);
clamp_delay(st_ipcomp);
delay_ms = delay * 1000;
#undef clamp_delay
}
/* By default, we plan to rekey.
*
* If there isn't enough time to rekey, plan to
* expire.
*
* If we are --dontrekey, a lot more rules apply.
* If we are the Initiator, use REPLACE_IF_USED.
* If we are the Responder, and the dictated time
* was unacceptable (too large), plan to REPLACE
* (the only way to ratchet down the time).
* If we are the Responder, and the dictated time
* is acceptable, plan to EXPIRE.
*
* Important policy lies buried here.
* For example, we favour the initiator over the
* responder by making the initiator start rekeying
* sooner. Also, fuzz is only added to the
* initiator's margin.
*
* Note: for ISAKMP SA, we let the negotiated
* time stand (implemented by earlier logic).
*/
if (agreed_time &&
(c->policy & POLICY_DONT_REKEY)) {
kind = (smc->flags & SMF_INITIATOR) ?
EVENT_SA_REPLACE_IF_USED :
EVENT_SA_EXPIRE;
}
if (kind != EVENT_SA_EXPIRE) {
time_t marg =
deltasecs(c->sa_rekey_margin);
if (smc->flags & SMF_INITIATOR) {
marg += marg *
c->sa_rekey_fuzz /
100.E0 *
(rand() /
(RAND_MAX + 1.E0));
} else {
marg /= 2;
}
if (delay_ms > (unsigned long)marg * 1000) {
delay_ms -= (unsigned long)marg * 1000;
st->st_margin = deltatime(marg);
} else {
kind = EVENT_SA_EXPIRE;
}
}
break;
default:
bad_case(kind);
}
event_schedule_ms(kind, delay_ms, st);
}
/* tell whack and log of progress */
{
const char *story = enum_name(&state_stories,
st->st_state);
enum rc_type w = RC_NEW_STATE + st->st_state;
char sadetails[512];
passert(st->st_state < STATE_IKE_ROOF);
sadetails[0] = '\0';
/* document IPsec SA details for admin's pleasure */
if (IS_IPSEC_SA_ESTABLISHED(st->st_state)) {
fmt_ipsec_sa_established(st, sadetails,
sizeof(sadetails));
} else if (IS_ISAKMP_SA_ESTABLISHED(st->st_state) &&
!st->hidden_variables.st_logged_p1algos) {
fmt_isakmp_sa_established(st, sadetails,
sizeof(sadetails));
}
if (IS_ISAKMP_SA_ESTABLISHED(st->st_state) ||
IS_IPSEC_SA_ESTABLISHED(st->st_state)) {
/* log our success */
w = RC_SUCCESS;
}
/* tell whack and logs our progress */
loglog(w,
"%s: %s%s",
enum_name(&state_names, st->st_state),
story,
sadetails);
}
/*
* make sure that a DPD event gets created for a new phase 1
* SA.
*/
if (IS_ISAKMP_SA_ESTABLISHED(st->st_state)) {
if (deltasecs(st->st_connection->dpd_delay) > 0 &&
deltasecs(st->st_connection->dpd_timeout) > 0) {
/* don't ignore failure */
/* ??? in fact, we do ignore this:
* result is NEVER used
* (clang 3.4 noticed this)
*/
stf_status s = dpd_init(st);
pexpect(s != STF_FAIL);
if (s == STF_FAIL)
result = STF_FAIL; /* ??? fall through !?! */
}
}
/* Special case for XAUTH server */
if (st->st_connection->spd.this.xauth_server) {
if (st->st_oakley.doing_xauth &&
IS_ISAKMP_SA_ESTABLISHED(st->st_state)) {
DBG(DBG_CONTROL,
DBG_log("XAUTH: "
"Sending XAUTH Login/Password Request"));
event_schedule_ms(EVENT_v1_SEND_XAUTH,
EVENT_v1_SEND_XAUTH_DELAY, st);
break;
}
}
/*
* for XAUTH client, we are also done, because we need to
* stay in this state, and let the server query us
*/
if (!IS_QUICK(st->st_state) &&
st->st_connection->spd.this.xauth_client &&
!st->hidden_variables.st_xauth_client_done) {
DBG(DBG_CONTROL,
DBG_log("XAUTH client is not yet authenticated"));
break;
}
/*
* when talking to some vendors, we need to initiate a mode
* cfg request to get challenged, but there is also an
* override in the form of a policy bit.
*/
DBG(DBG_CONTROL,
DBG_log("modecfg pull: %s policy:%s %s",
(st->quirks.modecfg_pull_mode ?
"quirk-poll" : "noquirk"),
(st->st_connection->policy & POLICY_MODECFG_PULL) ?
"pull" : "push",
(st->st_connection->spd.this.modecfg_client ?
"modecfg-client" : "not-client")));
if (st->st_connection->spd.this.modecfg_client &&
IS_ISAKMP_SA_ESTABLISHED(st->st_state) &&
(st->quirks.modecfg_pull_mode ||
st->st_connection->policy & POLICY_MODECFG_PULL) &&
!st->hidden_variables.st_modecfg_started) {
DBG(DBG_CONTROL,
DBG_log("modecfg client is starting due to %s",
st->quirks.modecfg_pull_mode ? "quirk" :
"policy"));
modecfg_send_request(st);
break;
}
/* Should we set the peer's IP address regardless? */
if (st->st_connection->spd.this.modecfg_server &&
IS_ISAKMP_SA_ESTABLISHED(st->st_state) &&
!st->hidden_variables.st_modecfg_vars_set &&
!(st->st_connection->policy & POLICY_MODECFG_PULL)) {
change_state(st, STATE_MODE_CFG_R1);
set_cur_state(st);
libreswan_log("Sending MODE CONFIG set");
modecfg_start_set(st);
break;
}
/*
* If we are the responder and the client is in "Contivity mode",
* we need to initiate Quick mode
*/
if (!(smc->flags & SMF_INITIATOR) &&
IS_MODE_CFG_ESTABLISHED(st->st_state) &&
(st->st_seen_nortel_vid)) {
libreswan_log("Nortel 'Contivity Mode' detected, starting Quick Mode");
change_state(st, STATE_MAIN_R3); /* ISAKMP is up... */
set_cur_state(st);
quick_outI1(st->st_whack_sock, st, st->st_connection,
st->st_connection->policy, 1, SOS_NOBODY
#ifdef HAVE_LABELED_IPSEC
, NULL /* Setting NULL as this is responder and will not have sec ctx from a flow*/
#endif
);
break;
}
/* wait for modecfg_set */
if (st->st_connection->spd.this.modecfg_client &&
IS_ISAKMP_SA_ESTABLISHED(st->st_state) &&
!st->hidden_variables.st_modecfg_vars_set) {
DBG(DBG_CONTROL,
DBG_log("waiting for modecfg set from server"));
break;
}
if (st->st_rekeytov2) {
DBG(DBG_CONTROL,
DBG_log("waiting for IKEv1 -> IKEv2 rekey"));
break;
}
DBG(DBG_CONTROL,
DBG_log("phase 1 is done, looking for phase 2 to unpend"));
if (smc->flags & SMF_RELEASE_PENDING_P2) {
/* Initiate any Quick Mode negotiations that
* were waiting to piggyback on this Keying Channel.
*
* ??? there is a potential race condition
* if we are the responder: the initial Phase 2
* message might outrun the final Phase 1 message.
*
* so, instead of actually sending the traffic now,
* we schedule an event to do so.
*
* but, in fact, quick_mode will enqueue a cryptographic operation
* anyway, which will get done "later" anyway, so maybe it is just fine
* as it is.
*
*/
unpend(st);
}
if (IS_ISAKMP_SA_ESTABLISHED(st->st_state) ||
IS_IPSEC_SA_ESTABLISHED(st->st_state))
release_whack(st);
if (IS_QUICK(st->st_state))
break;
break;
}
case STF_INTERNAL_ERROR:
/* update the previous packet history */
remember_received_packet(st, md);
whack_log(RC_INTERNALERR + md->note,
"%s: internal error",
enum_name(&state_names, st->st_state));
DBG(DBG_CONTROL,
DBG_log("state transition function for %s had internal error",
enum_name(&state_names, from_state)));
break;
case STF_TOOMUCHCRYPTO:
/* ??? Why is this comment useful:
* well, this should never happen during a whack, since
* a whack will always force crypto.
*/
/* ??? why no call of remember_received_packet? */
unset_suspended(st);
libreswan_log(
"message in state %s ignored due to cryptographic overload",
enum_name(&state_names, from_state));
log_crypto_workers();
/* ??? the ikev2.c version used to FALL THROUGH to STF_FATAL */
break;
case STF_FATAL:
/* update the previous packet history */
remember_received_packet(st, md);
whack_log(RC_FATAL,
"encountered fatal error in state %s",
enum_name(&state_names, st->st_state));
#ifdef HAVE_NM
if (st->st_connection->remotepeertype == CISCO &&
st->st_connection->nmconfigured) {
if (!do_command(st->st_connection,
&st->st_connection->spd,
"disconnectNM", st))
DBG(DBG_CONTROL,
DBG_log("sending disconnect to NM failed, you may need to do it manually"));
}
#endif
release_pending_whacks(st, "fatal error");
delete_state(st);
md->st = st = NULL;
break;
default: /* a shortcut to STF_FAIL, setting md->note */
passert(result > STF_FAIL);
md->note = result - STF_FAIL;
/* FALL THROUGH */
case STF_FAIL:
/* As it is, we act as if this message never happened:
* whatever retrying was in place, remains in place.
*/
/*
* ??? why no call of remember_received_packet?
* Perhaps because the message hasn't been authenticated?
* But then then any duplicate would lose too, I would think.
*/
whack_log(RC_NOTIFICATION + md->note,
"%s: %s", enum_name(&state_names, st->st_state),
enum_name(&ikev1_notify_names, md->note));
if (md->note != NOTHING_WRONG)
SEND_NOTIFICATION(md->note);
DBG(DBG_CONTROL,
DBG_log("state transition function for %s failed: %s",
enum_name(&state_names, from_state),
enum_name(&ikev1_notify_names, md->note)));
#ifdef HAVE_NM
if (st->st_connection->remotepeertype == CISCO &&
st->st_connection->nmconfigured) {
if (!do_command(st->st_connection,
&st->st_connection->spd,
"disconnectNM", st))
DBG(DBG_CONTROL,
DBG_log("sending disconnect to NM failed, you may need to do it manually"));
}
#endif
if (IS_PHASE1_INIT(st->st_state)) {
delete_event(st);
release_whack(st);
}
if (IS_QUICK(st->st_state)) {
delete_state(st);
/* wipe out dangling pointer to st */
md->st = NULL;
}
break;
}
}
/* note: may change which connection is referenced by md->st->st_connection */
bool ikev1_decode_peer_id(struct msg_digest *md, bool initiator, bool aggrmode)
{
struct state *const st = md->st;
struct payload_digest *const id_pld = md->chain[ISAKMP_NEXT_ID];
const pb_stream *const id_pbs = &id_pld->pbs;
struct isakmp_id *const id = &id_pld->payload.id;
struct id peer;
/* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
* It talks about the protocol ID and Port fields of the ID
* Payload, but they don't exist as such in Phase 1.
* We use more appropriate names.
* isaid_doi_specific_a is in place of Protocol ID.
* isaid_doi_specific_b is in place of Port.
* Besides, there is no good reason for allowing these to be
* other than 0 in Phase 1.
*/
if (st->hidden_variables.st_nat_traversal != LEMPTY &&
id->isaid_doi_specific_a == IPPROTO_UDP &&
(id->isaid_doi_specific_b == 0 ||
id->isaid_doi_specific_b == pluto_nat_port)) {
DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
"accepted with port_floating NAT-T",
id->isaid_doi_specific_a, id->isaid_doi_specific_b);
} else if (!(id->isaid_doi_specific_a == 0 &&
id->isaid_doi_specific_b == 0) &&
!(id->isaid_doi_specific_a == IPPROTO_UDP &&
id->isaid_doi_specific_b == pluto_port))
{
loglog(RC_LOG_SERIOUS, "protocol/port in Phase 1 ID Payload MUST be 0/0 or %d/%d"
" but are %d/%d (attempting to continue)",
IPPROTO_UDP, pluto_port,
id->isaid_doi_specific_a,
id->isaid_doi_specific_b);
/* we have turned this into a warning because of bugs in other vendors
* products. Specifically CISCO VPN3000.
*/
/* return FALSE; */
}
zero(&peer); /* ??? pointer fields might not be NULLed */
peer.kind = id->isaid_idtype;
if (!extract_peer_id(&peer, id_pbs))
return FALSE;
/*
* For interop with SoftRemote/aggressive mode we need to remember some
* things for checking the hash
*/
st->st_peeridentity_protocol = id->isaid_doi_specific_a;
st->st_peeridentity_port = ntohs(id->isaid_doi_specific_b);
{
char buf[IDTOA_BUF];
idtoa(&peer, buf, sizeof(buf));
libreswan_log("%s mode peer ID is %s: '%s'",
aggrmode ? "Aggressive" : "Main",
enum_show(&ike_idtype_names, id->isaid_idtype), buf);
}
/* check for certificates */
if (!ikev1_decode_cert(md))
return FALSE;
/* Now that we've decoded the ID payload, let's see if we
* need to switch connections.
* We must not switch horses if we initiated:
* - if the initiation was explicit, we'd be ignoring user's intent
* - if opportunistic, we'll lose our HOLD info
*/
if (initiator) {
if (!same_id(&st->st_connection->spd.that.id, &peer) &&
id_kind(&st->st_connection->spd.that.id) != ID_FROMCERT) {
char expect[IDTOA_BUF],
found[IDTOA_BUF];
idtoa(&st->st_connection->spd.that.id, expect,
sizeof(expect));
idtoa(&peer, found, sizeof(found));
loglog(RC_LOG_SERIOUS,
"we require IKEv1 peer to have ID '%s', but peer declares '%s'",
expect, found);
return FALSE;
} else if (id_kind(&st->st_connection->spd.that.id) == ID_FROMCERT) {
if (id_kind(&peer) != ID_DER_ASN1_DN) {
loglog(RC_LOG_SERIOUS,
"peer ID is not a certificate type");
return FALSE;
}
duplicate_id(&st->st_connection->spd.that.id, &peer);
}
} else {
struct connection *c = st->st_connection;
struct connection *r = NULL;
bool fromcert;
uint16_t auth = xauth_calcbaseauth(st->st_oakley.auth);
lset_t auth_policy = LEMPTY;
switch (auth) {
case OAKLEY_PRESHARED_KEY:
auth_policy = POLICY_PSK;
break;
case OAKLEY_RSA_SIG:
auth_policy = POLICY_RSASIG;
break;
/* Not implemented */
case OAKLEY_DSS_SIG:
case OAKLEY_RSA_ENC:
case OAKLEY_RSA_REVISED_MODE:
case OAKLEY_ECDSA_P256:
case OAKLEY_ECDSA_P384:
case OAKLEY_ECDSA_P521:
default:
DBG(DBG_CONTROL, DBG_log("ikev1 ikev1_decode_peer_id bad_case due to not supported policy"));
// bad_case(auth);
}
if (aggrmode)
auth_policy |= POLICY_AGGRESSIVE;
/* check for certificate requests */
ikev1_decode_cr(md);
if ((auth_policy & ~POLICY_AGGRESSIVE) != LEMPTY) {
r = refine_host_connection(st, &peer, initiator, auth_policy, &fromcert);
pexpect(r != NULL);
}
if (r == NULL) {
char buf[IDTOA_BUF];
idtoa(&peer, buf, sizeof(buf));
loglog(RC_LOG_SERIOUS,
"no suitable connection for peer '%s'",
buf);
return FALSE;
}
DBG(DBG_CONTROL, {
char buf[IDTOA_BUF];
dntoa_or_null(buf, IDTOA_BUF, r->spd.this.ca,
"%none");
DBG_log("offered CA: '%s'", buf);
});
if (r != c) {
char b1[CONN_INST_BUF];
char b2[CONN_INST_BUF];
/* apparently, r is an improvement on c -- replace */
libreswan_log("switched from \"%s\"%s to \"%s\"%s",
c->name,
fmt_conn_instance(c, b1),
r->name,
fmt_conn_instance(r, b2));
if (r->kind == CK_TEMPLATE || r->kind == CK_GROUP) {
/* instantiate it, filling in peer's ID */
r = rw_instantiate(r, &c->spd.that.host_addr,
NULL,
&peer);
}
update_state_connection(st, r);
} else if (c->spd.that.has_id_wildcards) {
free_id_content(&c->spd.that.id);
c->spd.that.id = peer;
c->spd.that.has_id_wildcards = FALSE;
unshare_id_content(&c->spd.that.id);
} else if (fromcert) {
DBG(DBG_CONTROL, DBG_log("copying ID for fromcert"));
duplicate_id(&r->spd.that.id, &peer);
}
}
return TRUE;
}
bool ikev1_ship_chain(chunk_t *chain, int n, pb_stream *outs,
u_int8_t type,
u_int8_t setnp)
{
int i;
u_int8_t np;
for (i = 0; i < n; i++) {
/* set np for last cert, or another */
np = i == n - 1 ? setnp : ISAKMP_NEXT_CERT;
if (!ikev1_ship_CERT(type, chain[i], outs, np))
return FALSE;
}
return TRUE;
}
void doi_log_cert_thinking(u_int16_t auth,
enum ike_cert_type certtype,
enum certpolicy policy,
bool gotcertrequest,
bool send_cert,
bool send_chain)
{
DBG(DBG_CONTROL,
DBG_log("thinking about whether to send my certificate:"));
DBG(DBG_CONTROL, {
struct esb_buf esb;
DBG_log(" I have RSA key: %s cert.type: %s ",
enum_showb(&oakley_auth_names, auth, &esb),
enum_show(&ike_cert_type_names, certtype));
});
DBG(DBG_CONTROL,
DBG_log(" sendcert: %s and I did%s get a certificate request ",
enum_show(&certpolicy_type_names, policy),
gotcertrequest ? "" : " not"));
DBG(DBG_CONTROL,
DBG_log(" so %ssend cert.", send_cert ? "" : "do not "));
if (!send_cert) {
if (auth == OAKLEY_PRESHARED_KEY) {
DBG(DBG_CONTROL,
DBG_log("I did not send a certificate "
"because digital signatures are not "
"being used. (PSK)"));
} else if (certtype == CERT_NONE) {
DBG(DBG_CONTROL,
DBG_log("I did not send a certificate because "
"I do not have one."));
} else if (policy == cert_sendifasked) {
DBG(DBG_CONTROL,
DBG_log("I did not send my certificate "
"because I was not asked to."));
}
/* ??? should there be an additional else catch-all? */
}
if (send_chain)
DBG(DBG_CONTROL, DBG_log("Sending one or more authcerts"));
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5117_0 |
crossvul-cpp_data_good_4286_0 | /* CBOR-to-JSON translation utility */
#include "rtjsonsrc/osrtjson.h"
#include "rtcborsrc/osrtcbor.h"
#include "rtxsrc/rtxCharStr.h"
#include "rtxsrc/rtxContext.h"
#include "rtxsrc/rtxFile.h"
#include "rtxsrc/rtxHexDump.h"
#include <stdio.h>
#ifndef _NO_INT64_SUPPORT
#define OSUINTTYPE OSUINT64
#define OSINTTYPE OSINT64
#define rtCborDecUInt rtCborDecUInt64
#define rtCborDecInt rtCborDecInt64
#else
#define OSUINTTYPE OSUINT32
#define OSINTTYPE OSINT32
#define rtCborDecUInt rtCborDecUInt32
#define rtCborDecInt rtCborDecInt32
#endif
static int cborTagNotSupp (OSCTXT* pctxt, OSOCTET tag)
{
char numbuf[10];
char errtext[80];
rtxUIntToCharStr (tag, numbuf, sizeof(numbuf), 0);
rtxStrJoin (errtext, sizeof(errtext), "CBOR tag ", numbuf, 0, 0, 0);
rtxErrAddStrParm (pctxt, errtext);
return RTERR_NOTSUPP;
}
static int cborElemNameToJson (OSCTXT* pCborCtxt, OSCTXT* pJsonCtxt)
{
char* pElemName = 0;
OSOCTET ub;
int ret;
/* Read byte from stream */
ret = rtxReadBytes (pCborCtxt, &ub, 1);
if (0 != ret) return LOG_RTERR (pCborCtxt, ret);
/* Decode element name (note: only string type is currently supported) */
ret = rtCborDecDynUTF8Str (pCborCtxt, ub, &pElemName);
if (0 != ret) return LOG_RTERR (pCborCtxt, ret);
/* Encode map element name as string */
ret = rtJsonEncStringValue (pJsonCtxt, (const OSUTF8CHAR*)pElemName);
rtxMemFreePtr (pCborCtxt, pElemName);
if (0 != ret) return LOG_RTERR (pJsonCtxt, ret);
OSRTSAFEPUTCHAR (pJsonCtxt, ':');
return 0;
}
static int cbor2json (OSCTXT* pCborCtxt, OSCTXT* pJsonCtxt)
{
int ret = 0;
OSOCTET tag, ub;
/* Read byte from stream */
ret = rtxReadBytes (pCborCtxt, &ub, 1);
if (0 != ret) return LOG_RTERR (pCborCtxt, ret);
tag = ub >> 5;
/* Switch on tag value */
switch (tag) {
case OSRTCBOR_UINT: {
OSUINTTYPE value;
ret = rtCborDecUInt (pCborCtxt, ub, &value);
if (0 != ret) return LOG_RTERR (pCborCtxt, ret);
/* Encode JSON */
#ifndef _NO_INT64_SUPPORT
ret = rtJsonEncUInt64Value (pJsonCtxt, value);
#else
ret = rtJsonEncUIntValue (pJsonCtxt, value);
#endif
if (0 != ret) return LOG_RTERR (pJsonCtxt, ret);
break;
}
case OSRTCBOR_NEGINT: {
OSINTTYPE value;
ret = rtCborDecInt (pCborCtxt, ub, &value);
if (0 != ret) return LOG_RTERR (pCborCtxt, ret);
/* Encode JSON */
#ifndef _NO_INT64_SUPPORT
ret = rtJsonEncInt64Value (pJsonCtxt, value);
#else
ret = rtJsonEncIntValue (pJsonCtxt, value);
#endif
if (0 != ret) return LOG_RTERR (pJsonCtxt, ret);
break;
}
case OSRTCBOR_BYTESTR: {
OSDynOctStr64 byteStr;
ret = rtCborDecDynByteStr (pCborCtxt, ub, &byteStr);
if (0 != ret) return LOG_RTERR (pCborCtxt, ret);
/* Encode JSON */
ret = rtJsonEncHexStr (pJsonCtxt, byteStr.numocts, byteStr.data);
rtxMemFreePtr (pCborCtxt, byteStr.data);
if (0 != ret) return LOG_RTERR (pJsonCtxt, ret);
break;
}
case OSRTCBOR_UTF8STR: {
OSUTF8CHAR* utf8str;
ret = rtCborDecDynUTF8Str (pCborCtxt, ub, (char**)&utf8str);
if (0 != ret) return LOG_RTERR (pCborCtxt, ret);
ret = rtJsonEncStringValue (pJsonCtxt, utf8str);
rtxMemFreePtr (pCborCtxt, utf8str);
if (0 != ret) return LOG_RTERR (pJsonCtxt, ret);
break;
}
case OSRTCBOR_ARRAY:
case OSRTCBOR_MAP: {
OSOCTET len = ub & 0x1F;
char startChar = (tag == OSRTCBOR_ARRAY) ? '[' : '{';
char endChar = (tag == OSRTCBOR_ARRAY) ? ']' : '}';
OSRTSAFEPUTCHAR (pJsonCtxt, startChar);
if (len == OSRTCBOR_INDEF) {
OSBOOL first = TRUE;
for (;;) {
if (OSRTCBOR_MATCHEOC (pCborCtxt)) {
pCborCtxt->buffer.byteIndex++;
break;
}
if (!first)
OSRTSAFEPUTCHAR (pJsonCtxt, ',');
else
first = FALSE;
/* If map, decode object name */
if (tag == OSRTCBOR_MAP) {
ret = cborElemNameToJson (pCborCtxt, pJsonCtxt);
}
/* Make recursive call */
if (0 == ret)
ret = cbor2json (pCborCtxt, pJsonCtxt);
if (0 != ret) {
OSCTXT* pctxt =
(rtxErrGetErrorCnt(pJsonCtxt) > 0) ? pJsonCtxt : pCborCtxt;
return LOG_RTERR (pctxt, ret);
}
}
}
else { /* definite length */
OSSIZE nitems;
/* Decode tag and number of items */
ret = rtCborDecSize (pCborCtxt, len, &nitems);
if (0 == ret) {
OSSIZE i;
/* Loop to decode array items */
for (i = 0; i < nitems; i++) {
if (0 != i) OSRTSAFEPUTCHAR (pJsonCtxt, ',');
/* If map, decode object name */
if (tag == OSRTCBOR_MAP) {
ret = cborElemNameToJson (pCborCtxt, pJsonCtxt);
}
/* Make recursive call */
if (0 == ret)
ret = cbor2json (pCborCtxt, pJsonCtxt);
if (0 != ret) {
OSCTXT* pctxt =
(rtxErrGetErrorCnt(pJsonCtxt) > 0) ? pJsonCtxt : pCborCtxt;
return LOG_RTERR (pctxt, ret);
}
}
}
}
OSRTSAFEPUTCHAR (pJsonCtxt, endChar);
break;
}
case OSRTCBOR_FLOAT:
if (tag == OSRTCBOR_FALSEENC || tag == OSRTCBOR_TRUEENC) {
OSBOOL boolval = (ub == OSRTCBOR_TRUEENC) ? TRUE : FALSE;
ret = rtJsonEncBoolValue (pJsonCtxt, boolval);
if (0 != ret) return LOG_RTERR (pJsonCtxt, ret);
}
else if (tag == OSRTCBOR_FLT16ENC ||
tag == OSRTCBOR_FLT32ENC ||
tag == OSRTCBOR_FLT64ENC) {
OSDOUBLE fltval;
ret = rtCborDecFloat (pCborCtxt, ub, &fltval);
if (0 != ret) return LOG_RTERR (pCborCtxt, ret);
/* Encode JSON */
ret = rtJsonEncDoubleValue (pJsonCtxt, fltval, 0);
if (0 != ret) return LOG_RTERR (pJsonCtxt, ret);
}
else {
ret = cborTagNotSupp (pCborCtxt, tag);
}
break;
default:
ret = cborTagNotSupp (pCborCtxt, tag);
}
return ret;
}
int main (int argc, char** argv)
{
OSCTXT jsonCtxt, cborCtxt;
OSOCTET* pMsgBuf = 0;
size_t msglen;
OSBOOL verbose = FALSE;
const char* filename = "message.cbor";
const char* outfname = "message.json";
int ret;
/* Process command line arguments */
if (argc > 1) {
int i;
for (i = 1; i < argc; i++) {
if (!strcmp (argv[i], "-v")) verbose = TRUE;
else if (!strcmp (argv[i], "-i")) filename = argv[++i];
else if (!strcmp (argv[i], "-o")) outfname = argv[++i];
else {
printf ("usage: cbor2json [-v] [-i <filename>] [-o filename]\n");
printf (" -v verbose mode: print trace info\n");
printf (" -i <filename> read CBOR msg from <filename>\n");
printf (" -o <filename> write JSON data to <filename>\n");
return 1;
}
}
}
/* Initialize context structures */
ret = rtxInitContext (&jsonCtxt);
if (ret != 0) {
rtxErrPrint (&jsonCtxt);
return ret;
}
rtxErrInit();
/* rtxSetDiag (&jsonCtxt, verbose); */
ret = rtxInitContext (&cborCtxt);
if (ret != 0) {
rtxErrPrint (&cborCtxt);
return ret;
}
/* rtxSetDiag (&cborCtxt, verbose); */
/* Create file input stream */
#if 0
/* Streaming not supported in open source version
ret = rtxStreamFileCreateReader (&jsonCtxt, filename);
*/
#else
/* Read input file into memory buffer */
ret = rtxFileReadBinary (&cborCtxt, filename, &pMsgBuf, &msglen);
if (0 == ret) {
ret = rtxInitContextBuffer (&cborCtxt, pMsgBuf, msglen);
}
#endif
if (0 != ret) {
rtxErrPrint (&jsonCtxt);
rtxFreeContext (&jsonCtxt);
rtxFreeContext (&cborCtxt);
return ret;
}
/* Init JSON output buffer */
ret = rtxInitContextBuffer (&jsonCtxt, 0, 0);
if (0 != ret) {
rtxErrPrint (&jsonCtxt);
rtxFreeContext (&jsonCtxt);
rtxFreeContext (&cborCtxt);
return ret;
}
/* Invoke the translation function */
ret = cbor2json (&cborCtxt, &jsonCtxt);
if (0 == ret && cborCtxt.level != 0)
ret = LOG_RTERR (&cborCtxt, RTERR_UNBAL);
if (0 == ret && 0 != outfname) {
/* Write encoded JSON data to output file */
OSRTSAFEPUTCHAR (&jsonCtxt, '\0'); /* null terminate buffer */
int fileret = rtxFileWriteText
(outfname, (const char*)jsonCtxt.buffer.data);
if (0 != fileret) {
printf ("unable to write message data to '%s', status = %d\n",
outfname, fileret);
}
}
if (0 != ret) {
rtxErrPrint (&jsonCtxt);
rtxErrPrint (&cborCtxt);
}
rtxFreeContext (&jsonCtxt);
rtxFreeContext (&cborCtxt);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_4286_0 |
crossvul-cpp_data_good_1563_0 | #include <gio/gio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include "libabrt.h"
#include "abrt-polkit.h"
#include "abrt_glib.h"
#include <libreport/dump_dir.h>
#include "problem_api.h"
static GMainLoop *loop;
static guint g_timeout_source;
/* default, settable with -t: */
static unsigned g_timeout_value = 120;
/* ---------------------------------------------------------------------------------------------------- */
static GDBusNodeInfo *introspection_data = NULL;
/* Introspection data for the service we are exporting */
static const gchar introspection_xml[] =
"<node>"
" <interface name='"ABRT_DBUS_IFACE"'>"
" <method name='NewProblem'>"
" <arg type='a{ss}' name='problem_data' direction='in'/>"
" <arg type='s' name='problem_id' direction='out'/>"
" </method>"
" <method name='GetProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetAllProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetForeignProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetInfo'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='as' name='element_names' direction='in'/>"
" <arg type='a{ss}' name='response' direction='out'/>"
" </method>"
" <method name='SetElement'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" <arg type='s' name='value' direction='in'/>"
" </method>"
" <method name='DeleteElement'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" </method>"
" <method name='ChownProblemDir'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" </method>"
" <method name='DeleteProblem'>"
" <arg type='as' name='problem_dir' direction='in'/>"
" </method>"
" <method name='FindProblemByElementInTimeRange'>"
" <arg type='s' name='element' direction='in'/>"
" <arg type='s' name='value' direction='in'/>"
" <arg type='x' name='timestamp_from' direction='in'/>"
" <arg type='x' name='timestamp_to' direction='in'/>"
" <arg type='b' name='all_users' direction='in'/>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='Quit' />"
" </interface>"
"</node>";
/* ---------------------------------------------------------------------------------------------------- */
/* forward */
static gboolean on_timeout_cb(gpointer user_data);
static void reset_timeout(void)
{
if (g_timeout_source > 0)
{
log_info("Removing timeout");
g_source_remove(g_timeout_source);
}
log_info("Setting a new timeout");
g_timeout_source = g_timeout_add_seconds(g_timeout_value, on_timeout_cb, NULL);
}
static uid_t get_caller_uid(GDBusConnection *connection, GDBusMethodInvocation *invocation, const char *caller)
{
GError *error = NULL;
guint caller_uid;
GDBusProxy * proxy = g_dbus_proxy_new_sync(connection,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
NULL,
&error);
GVariant *result = g_dbus_proxy_call_sync(proxy,
"GetConnectionUnixUser",
g_variant_new ("(s)", caller),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
if (result == NULL)
{
/* we failed to get the uid, so return (uid_t) -1 to indicate the error
*/
if (error)
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidUser",
error->message);
g_error_free(error);
}
else
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidUser",
_("Unknown error"));
}
return (uid_t) -1;
}
g_variant_get(result, "(u)", &caller_uid);
g_variant_unref(result);
log_info("Caller uid: %i", caller_uid);
return caller_uid;
}
bool allowed_problem_dir(const char *dir_name)
{
if (!dir_is_in_dump_location(dir_name))
{
error_msg("Bad problem directory name '%s', should start with: '%s'", dir_name, g_settings_dump_location);
return false;
}
/* We cannot test correct permissions yet because we still need to chown
* dump directories before reporting and Chowing changes the file owner to
* the reporter, which causes this test to fail and prevents users from
* getting problem data after reporting it.
*
* Fortunately, libreport has been hardened against hard link and symbolic
* link attacks and refuses to work with such files, so this test isn't
* really necessary, however, we will use it once we get rid of the
* chowning files.
*
* abrt-server refuses to run post-create on directories that have
* incorrect owner (not "root:(abrt|root)"), incorrect permissions (other
* bits are not 0) and are complete (post-create finished). So, there is no
* way to run security sensitive event scripts (post-create) on crafted
* problem directories.
*/
#if 0
if (!dir_has_correct_permissions(dir_name))
{
error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dir_name);
return false;
}
#endif
return true;
}
static char *handle_new_problem(GVariant *problem_info, uid_t caller_uid, char **error)
{
problem_data_t *pd = problem_data_new();
GVariantIter *iter;
g_variant_get(problem_info, "a{ss}", &iter);
gchar *key, *value;
while (g_variant_iter_loop(iter, "{ss}", &key, &value))
{
problem_data_add_text_editable(pd, key, value);
}
if (caller_uid != 0 || problem_data_get_content_or_NULL(pd, FILENAME_UID) == NULL)
{ /* set uid field to caller's uid if caller is not root or root doesn't pass own uid */
log_info("Adding UID %d to problem data", caller_uid);
char buf[sizeof(uid_t) * 3 + 2];
snprintf(buf, sizeof(buf), "%d", caller_uid);
problem_data_add_text_noteditable(pd, FILENAME_UID, buf);
}
/* At least it should generate local problem identifier UUID */
problem_data_add_basics(pd);
char *problem_id = problem_data_save(pd);
if (problem_id)
notify_new_path(problem_id);
else if (error)
*error = xasprintf("Cannot create a new problem");
problem_data_free(pd);
return problem_id;
}
static void return_InvalidProblemDir_error(GDBusMethodInvocation *invocation, const char *dir_name)
{
char *msg = xasprintf(_("'%s' is not a valid problem directory"), dir_name);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidProblemDir",
msg);
free(msg);
}
/*
* Checks element's rights and does not open directory if element is protected.
* Checks problem's rights and does not open directory if user hasn't got
* access to a problem.
*
* Returns a dump directory opend for writing or NULL.
*
* If any operation from the above listed fails, immediately returns D-Bus
* error to a D-Bus caller.
*/
static struct dump_dir *open_directory_for_modification_of_element(
GDBusMethodInvocation *invocation,
uid_t caller_uid,
const char *problem_id,
const char *element)
{
static const char *const protected_elements[] = {
FILENAME_TIME,
FILENAME_UID,
NULL,
};
for (const char *const *protected = protected_elements; *protected; ++protected)
{
if (strcmp(*protected, element) == 0)
{
log_notice("'%s' element of '%s' can't be modified", element, problem_id);
char *error = xasprintf(_("'%s' element can't be modified"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ProtectedElement",
error);
free(error);
return NULL;
}
}
int dir_fd = dd_openfd(problem_id);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", problem_id);
return_InvalidProblemDir_error(invocation, problem_id);
return NULL;
}
if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("'%s' is not a valid problem directory", problem_id);
return_InvalidProblemDir_error(invocation, problem_id);
}
else
{
log_notice("UID(%d) is not Authorized to access '%s'", caller_uid, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
}
close(dir_fd);
return NULL;
}
struct dump_dir *dd = dd_fdopendir(dir_fd, problem_id, /* flags : */ 0);
if (!dd)
{ /* This should not happen because of the access check above */
log_notice("Can't access the problem '%s' for modification", problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("Can't access the problem for modification"));
return NULL;
}
return dd;
}
/*
* Lists problems which have given element and were seen in given time interval
*/
struct field_and_time_range {
GList *list;
const char *element;
const char *value;
unsigned long timestamp_from;
unsigned long timestamp_to;
};
static int add_dirname_to_GList_if_matches(struct dump_dir *dd, void *arg)
{
struct field_and_time_range *me = arg;
char *field_data = dd_load_text(dd, me->element);
int brk = (strcmp(field_data, me->value) != 0);
free(field_data);
if (brk)
return 0;
field_data = dd_load_text(dd, FILENAME_LAST_OCCURRENCE);
long val = atol(field_data);
free(field_data);
if (val < me->timestamp_from || val > me->timestamp_to)
return 0;
me->list = g_list_prepend(me->list, xstrdup(dd->dd_dirname));
return 0;
}
static GList *get_problem_dirs_for_element_in_time(uid_t uid,
const char *element,
const char *value,
unsigned long timestamp_from,
unsigned long timestamp_to)
{
if (timestamp_to == 0) /* not sure this is possible, but... */
timestamp_to = time(NULL);
struct field_and_time_range me = {
.list = NULL,
.element = element,
.value = value,
.timestamp_from = timestamp_from,
.timestamp_to = timestamp_to,
};
for_each_problem_in_dir(g_settings_dump_location, uid, add_dirname_to_GList_if_matches, &me);
return g_list_reverse(me.list);
}
static void handle_method_call(GDBusConnection *connection,
const gchar *caller,
const gchar *object_path,
const gchar *interface_name,
const gchar *method_name,
GVariant *parameters,
GDBusMethodInvocation *invocation,
gpointer user_data)
{
reset_timeout();
uid_t caller_uid;
GVariant *response;
caller_uid = get_caller_uid(connection, invocation, caller);
log_notice("caller_uid:%ld method:'%s'", (long)caller_uid, method_name);
if (caller_uid == (uid_t) -1)
return;
if (g_strcmp0(method_name, "NewProblem") == 0)
{
char *error = NULL;
char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error);
if (!problem_id)
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
free(error);
return;
}
/* else */
response = g_variant_new("(s)", problem_id);
g_dbus_method_invocation_return_value(invocation, response);
free(problem_id);
return;
}
if (g_strcmp0(method_name, "GetProblems") == 0)
{
GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
//I was told that g_dbus_method frees the response
//g_variant_unref(response);
return;
}
if (g_strcmp0(method_name, "GetAllProblems") == 0)
{
/*
- so, we have UID,
- if it's 0, then we don't have to check anything and just return all directories
- if uid != 0 then we want to ask for authorization
*/
if (caller_uid != 0)
{
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes)
caller_uid = 0;
}
GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "GetForeignProblems") == 0)
{
GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "ChownProblemDir") == 0)
{
const gchar *problem_dir;
g_variant_get(parameters, "(&s)", &problem_dir);
log_notice("problem_dir:'%s'", problem_dir);
if (!allowed_problem_dir(problem_dir))
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int dir_fd = dd_openfd(problem_dir);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid);
if (ddstat < 0)
{
if (errno == ENOTDIR)
{
log_notice("requested directory does not exist '%s'", problem_dir);
}
else
{
perror_msg("can't get stat of '%s'", problem_dir);
}
return_InvalidProblemDir_error(invocation, problem_dir);
close(dir_fd);
return;
}
if (ddstat & DD_STAT_OWNED_BY_UID)
{ //caller seems to be in group with access to this dir, so no action needed
log_notice("caller has access to the requested directory %s", problem_dir);
g_dbus_method_invocation_return_value(invocation, NULL);
close(dir_fd);
return;
}
if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 &&
polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{
log_notice("not authorized");
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
close(dir_fd);
return;
}
struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);
if (!dd)
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int chown_res = dd_chown(dd, caller_uid);
if (chown_res != 0)
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ChownError",
_("Chowning directory failed. Check system logs for more details."));
else
g_dbus_method_invocation_return_value(invocation, NULL);
dd_close(dd);
return;
}
if (g_strcmp0(method_name, "GetInfo") == 0)
{
/* Parameter tuple is (sas) */
/* Get 1st param - problem dir name */
const gchar *problem_dir;
g_variant_get_child(parameters, 0, "&s", &problem_dir);
log_notice("problem_dir:'%s'", problem_dir);
if (!allowed_problem_dir(problem_dir))
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int dir_fd = dd_openfd(problem_dir);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("Requested directory does not exist '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
close(dir_fd);
return;
}
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{
log_notice("not authorized");
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
close(dir_fd);
return;
}
}
struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);
if (!dd)
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
/* Get 2nd param - vector of element names */
GVariant *array = g_variant_get_child_value(parameters, 1);
GList *elements = string_list_from_variant(array);
g_variant_unref(array);
GVariantBuilder *builder = NULL;
for (GList *l = elements; l; l = l->next)
{
const char *element_name = (const char*)l->data;
char *value = dd_load_text_ext(dd, element_name, 0
| DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE
| DD_FAIL_QUIETLY_ENOENT
| DD_FAIL_QUIETLY_EACCES);
log_notice("element '%s' %s", element_name, value ? "fetched" : "not found");
if (value)
{
if (!builder)
builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
/* g_variant_builder_add makes a copy. No need to xstrdup here */
g_variant_builder_add(builder, "{ss}", element_name, value);
free(value);
}
}
list_free_with_free(elements);
dd_close(dd);
/* It is OK to call g_variant_new("(a{ss})", NULL) because */
/* G_VARIANT_TYPE_TUPLE allows NULL value */
GVariant *response = g_variant_new("(a{ss})", builder);
if (builder)
g_variant_builder_unref(builder);
log_info("GetInfo: returning value for '%s'", problem_dir);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "SetElement") == 0)
{
const char *problem_id;
const char *element;
const char *value;
g_variant_get(parameters, "(&s&s&s)", &problem_id, &element, &value);
if (element == NULL || element[0] == '\0' || strlen(element) > 64)
{
log_notice("'%s' is not a valid element name of '%s'", element, problem_id);
char *error = xasprintf(_("'%s' is not a valid element name"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidElement",
error);
free(error);
return;
}
struct dump_dir *dd = open_directory_for_modification_of_element(
invocation, caller_uid, problem_id, element);
if (!dd)
/* Already logged from open_directory_for_modification_of_element() */
return;
/* Is it good idea to make it static? Is it possible to change the max size while a single run? */
const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024);
const long item_size = dd_get_item_size(dd, element);
if (item_size < 0)
{
log_notice("Can't get size of '%s/%s'", problem_id, element);
char *error = xasprintf(_("Can't get size of '%s'"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
return;
}
const double requested_size = (double)strlen(value) - item_size;
/* Don't want to check the size limit in case of reducing of size */
if (requested_size > 0
&& requested_size > (max_dir_size - get_dirsize(g_settings_dump_location)))
{
log_notice("No problem space left in '%s' (requested Bytes %f)", problem_id, requested_size);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("No problem space left"));
}
else
{
dd_save_text(dd, element, value);
g_dbus_method_invocation_return_value(invocation, NULL);
}
dd_close(dd);
return;
}
if (g_strcmp0(method_name, "DeleteElement") == 0)
{
const char *problem_id;
const char *element;
g_variant_get(parameters, "(&s&s)", &problem_id, &element);
struct dump_dir *dd = open_directory_for_modification_of_element(
invocation, caller_uid, problem_id, element);
if (!dd)
/* Already logged from open_directory_for_modification_of_element() */
return;
const int res = dd_delete_item(dd, element);
dd_close(dd);
if (res != 0)
{
log_notice("Can't delete the element '%s' from the problem directory '%s'", element, problem_id);
char *error = xasprintf(_("Can't delete the element '%s' from the problem directory '%s'"), element, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
free(error);
return;
}
g_dbus_method_invocation_return_value(invocation, NULL);
return;
}
if (g_strcmp0(method_name, "DeleteProblem") == 0)
{
/* Dbus parameters are always tuples.
* In this case, it's (as) - a tuple of one element (array of strings).
* Need to fetch the array:
*/
GVariant *array = g_variant_get_child_value(parameters, 0);
GList *problem_dirs = string_list_from_variant(array);
g_variant_unref(array);
for (GList *l = problem_dirs; l; l = l->next)
{
const char *dir_name = (const char*)l->data;
log_notice("dir_name:'%s'", dir_name);
if (!allowed_problem_dir(dir_name))
{
return_InvalidProblemDir_error(invocation, dir_name);
goto ret;
}
}
for (GList *l = problem_dirs; l; l = l->next)
{
const char *dir_name = (const char*)l->data;
int dir_fd = dd_openfd(dir_name);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", dir_name);
return_InvalidProblemDir_error(invocation, dir_name);
return;
}
if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("Requested directory does not exist '%s'", dir_name);
close(dir_fd);
continue;
}
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{ // if user didn't provide correct credentials, just move to the next dir
close(dir_fd);
continue;
}
}
struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0);
if (dd)
{
if (dd_delete(dd) != 0)
{
error_msg("Failed to delete problem directory '%s'", dir_name);
dd_close(dd);
}
}
}
g_dbus_method_invocation_return_value(invocation, NULL);
ret:
list_free_with_free(problem_dirs);
return;
}
if (g_strcmp0(method_name, "FindProblemByElementInTimeRange") == 0)
{
const gchar *element;
const gchar *value;
glong timestamp_from;
glong timestamp_to;
gboolean all;
g_variant_get_child(parameters, 0, "&s", &element);
g_variant_get_child(parameters, 1, "&s", &value);
g_variant_get_child(parameters, 2, "x", ×tamp_from);
g_variant_get_child(parameters, 3, "x", ×tamp_to);
g_variant_get_child(parameters, 4, "b", &all);
if (all && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes)
caller_uid = 0;
GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from,
timestamp_to);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "Quit") == 0)
{
g_dbus_method_invocation_return_value(invocation, NULL);
g_main_loop_quit(loop);
return;
}
}
static gboolean on_timeout_cb(gpointer user_data)
{
g_main_loop_quit(loop);
return TRUE;
}
static const GDBusInterfaceVTable interface_vtable =
{
.method_call = handle_method_call,
.get_property = NULL,
.set_property = NULL,
};
static void on_bus_acquired(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
guint registration_id;
registration_id = g_dbus_connection_register_object(connection,
ABRT_DBUS_OBJECT,
introspection_data->interfaces[0],
&interface_vtable,
NULL, /* user_data */
NULL, /* user_data_free_func */
NULL); /* GError** */
g_assert(registration_id > 0);
reset_timeout();
}
/* not used
static void on_name_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
}
*/
static void on_name_lost(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
g_print(_("The name '%s' has been lost, please check if other "
"service owning the name is not running.\n"), name);
exit(1);
}
int main(int argc, char *argv[])
{
/* I18n */
setlocale(LC_ALL, "");
#if ENABLE_NLS
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
#endif
guint owner_id;
abrt_init(argv);
const char *program_usage_string = _(
"& [options]"
);
enum {
OPT_v = 1 << 0,
OPT_t = 1 << 1,
};
/* Keep enum above and order of options below in sync! */
struct options program_options[] = {
OPT__VERBOSE(&g_verbose),
OPT_INTEGER('t', NULL, &g_timeout_value, _("Exit after NUM seconds of inactivity")),
OPT_END()
};
/*unsigned opts =*/ parse_opts(argc, argv, program_options, program_usage_string);
export_abrt_envvars(0);
/* When dbus daemon starts us, it doesn't set PATH
* (I saw it set only DBUS_STARTER_ADDRESS and DBUS_STARTER_BUS_TYPE).
* In this case, set something sane:
*/
const char *env_path = getenv("PATH");
if (!env_path || !env_path[0])
putenv((char*)"PATH=/usr/sbin:/usr/bin:/sbin:/bin");
msg_prefix = "abrt-dbus"; /* for log(), error_msg() and such */
if (getuid() != 0)
error_msg_and_die(_("This program must be run as root."));
glib_init();
/* We are lazy here - we don't want to manually provide
* the introspection data structures - so we just build
* them from XML.
*/
introspection_data = g_dbus_node_info_new_for_xml(introspection_xml, NULL);
g_assert(introspection_data != NULL);
owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
ABRT_DBUS_NAME,
G_BUS_NAME_OWNER_FLAGS_NONE,
on_bus_acquired,
NULL,
on_name_lost,
NULL,
NULL);
/* initialize the g_settings_dump_location */
load_abrt_conf();
loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(loop);
log_notice("Cleaning up");
g_bus_unown_name(owner_id);
g_dbus_node_info_unref(introspection_data);
free_abrt_conf_data();
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_1563_0 |
crossvul-cpp_data_bad_1821_2 | /*
* PowerPC version
* Copyright (C) 1995-1996 Gary Thomas (gdt@linuxppc.org)
*
* Derived from "arch/i386/kernel/signal.c"
* Copyright (C) 1991, 1992 Linus Torvalds
* 1997-11-28 Modified for POSIX.1b signals by Richard Henderson
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/wait.h>
#include <linux/unistd.h>
#include <linux/stddef.h>
#include <linux/elf.h>
#include <linux/ptrace.h>
#include <linux/ratelimit.h>
#include <asm/sigcontext.h>
#include <asm/ucontext.h>
#include <asm/uaccess.h>
#include <asm/pgtable.h>
#include <asm/unistd.h>
#include <asm/cacheflush.h>
#include <asm/syscalls.h>
#include <asm/vdso.h>
#include <asm/switch_to.h>
#include <asm/tm.h>
#include "signal.h"
#define GP_REGS_SIZE min(sizeof(elf_gregset_t), sizeof(struct pt_regs))
#define FP_REGS_SIZE sizeof(elf_fpregset_t)
#define TRAMP_TRACEBACK 3
#define TRAMP_SIZE 6
/*
* When we have signals to deliver, we set up on the user stack,
* going down from the original stack pointer:
* 1) a rt_sigframe struct which contains the ucontext
* 2) a gap of __SIGNAL_FRAMESIZE bytes which acts as a dummy caller
* frame for the signal handler.
*/
struct rt_sigframe {
/* sys_rt_sigreturn requires the ucontext be the first field */
struct ucontext uc;
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
struct ucontext uc_transact;
#endif
unsigned long _unused[2];
unsigned int tramp[TRAMP_SIZE];
struct siginfo __user *pinfo;
void __user *puc;
struct siginfo info;
/* New 64 bit little-endian ABI allows redzone of 512 bytes below sp */
char abigap[USER_REDZONE_SIZE];
} __attribute__ ((aligned (16)));
static const char fmt32[] = KERN_INFO \
"%s[%d]: bad frame in %s: %08lx nip %08lx lr %08lx\n";
static const char fmt64[] = KERN_INFO \
"%s[%d]: bad frame in %s: %016lx nip %016lx lr %016lx\n";
/*
* This computes a quad word aligned pointer inside the vmx_reserve array
* element. For historical reasons sigcontext might not be quad word aligned,
* but the location we write the VMX regs to must be. See the comment in
* sigcontext for more detail.
*/
#ifdef CONFIG_ALTIVEC
static elf_vrreg_t __user *sigcontext_vmx_regs(struct sigcontext __user *sc)
{
return (elf_vrreg_t __user *) (((unsigned long)sc->vmx_reserve + 15) & ~0xful);
}
#endif
/*
* Set up the sigcontext for the signal frame.
*/
static long setup_sigcontext(struct sigcontext __user *sc, struct pt_regs *regs,
int signr, sigset_t *set, unsigned long handler,
int ctx_has_vsx_region)
{
/* When CONFIG_ALTIVEC is set, we _always_ setup v_regs even if the
* process never used altivec yet (MSR_VEC is zero in pt_regs of
* the context). This is very important because we must ensure we
* don't lose the VRSAVE content that may have been set prior to
* the process doing its first vector operation
* Userland shall check AT_HWCAP to know whether it can rely on the
* v_regs pointer or not
*/
#ifdef CONFIG_ALTIVEC
elf_vrreg_t __user *v_regs = sigcontext_vmx_regs(sc);
#endif
unsigned long msr = regs->msr;
long err = 0;
#ifdef CONFIG_ALTIVEC
err |= __put_user(v_regs, &sc->v_regs);
/* save altivec registers */
if (current->thread.used_vr) {
flush_altivec_to_thread(current);
/* Copy 33 vec registers (vr0..31 and vscr) to the stack */
err |= __copy_to_user(v_regs, ¤t->thread.vr_state,
33 * sizeof(vector128));
/* set MSR_VEC in the MSR value in the frame to indicate that sc->v_reg)
* contains valid data.
*/
msr |= MSR_VEC;
}
/* We always copy to/from vrsave, it's 0 if we don't have or don't
* use altivec.
*/
if (cpu_has_feature(CPU_FTR_ALTIVEC))
current->thread.vrsave = mfspr(SPRN_VRSAVE);
err |= __put_user(current->thread.vrsave, (u32 __user *)&v_regs[33]);
#else /* CONFIG_ALTIVEC */
err |= __put_user(0, &sc->v_regs);
#endif /* CONFIG_ALTIVEC */
flush_fp_to_thread(current);
/* copy fpr regs and fpscr */
err |= copy_fpr_to_user(&sc->fp_regs, current);
/*
* Clear the MSR VSX bit to indicate there is no valid state attached
* to this context, except in the specific case below where we set it.
*/
msr &= ~MSR_VSX;
#ifdef CONFIG_VSX
/*
* Copy VSX low doubleword to local buffer for formatting,
* then out to userspace. Update v_regs to point after the
* VMX data.
*/
if (current->thread.used_vsr && ctx_has_vsx_region) {
__giveup_vsx(current);
v_regs += ELF_NVRREG;
err |= copy_vsx_to_user(v_regs, current);
/* set MSR_VSX in the MSR value in the frame to
* indicate that sc->vs_reg) contains valid data.
*/
msr |= MSR_VSX;
}
#endif /* CONFIG_VSX */
err |= __put_user(&sc->gp_regs, &sc->regs);
WARN_ON(!FULL_REGS(regs));
err |= __copy_to_user(&sc->gp_regs, regs, GP_REGS_SIZE);
err |= __put_user(msr, &sc->gp_regs[PT_MSR]);
err |= __put_user(signr, &sc->signal);
err |= __put_user(handler, &sc->handler);
if (set != NULL)
err |= __put_user(set->sig[0], &sc->oldmask);
return err;
}
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
/*
* As above, but Transactional Memory is in use, so deliver sigcontexts
* containing checkpointed and transactional register states.
*
* To do this, we treclaim (done before entering here) to gather both sets of
* registers and set up the 'normal' sigcontext registers with rolled-back
* register values such that a simple signal handler sees a correct
* checkpointed register state. If interested, a TM-aware sighandler can
* examine the transactional registers in the 2nd sigcontext to determine the
* real origin of the signal.
*/
static long setup_tm_sigcontexts(struct sigcontext __user *sc,
struct sigcontext __user *tm_sc,
struct pt_regs *regs,
int signr, sigset_t *set, unsigned long handler)
{
/* When CONFIG_ALTIVEC is set, we _always_ setup v_regs even if the
* process never used altivec yet (MSR_VEC is zero in pt_regs of
* the context). This is very important because we must ensure we
* don't lose the VRSAVE content that may have been set prior to
* the process doing its first vector operation
* Userland shall check AT_HWCAP to know wether it can rely on the
* v_regs pointer or not.
*/
#ifdef CONFIG_ALTIVEC
elf_vrreg_t __user *v_regs = sigcontext_vmx_regs(sc);
elf_vrreg_t __user *tm_v_regs = sigcontext_vmx_regs(tm_sc);
#endif
unsigned long msr = regs->msr;
long err = 0;
BUG_ON(!MSR_TM_ACTIVE(regs->msr));
/* Remove TM bits from thread's MSR. The MSR in the sigcontext
* just indicates to userland that we were doing a transaction, but we
* don't want to return in transactional state. This also ensures
* that flush_fp_to_thread won't set TIF_RESTORE_TM again.
*/
regs->msr &= ~MSR_TS_MASK;
flush_fp_to_thread(current);
#ifdef CONFIG_ALTIVEC
err |= __put_user(v_regs, &sc->v_regs);
err |= __put_user(tm_v_regs, &tm_sc->v_regs);
/* save altivec registers */
if (current->thread.used_vr) {
flush_altivec_to_thread(current);
/* Copy 33 vec registers (vr0..31 and vscr) to the stack */
err |= __copy_to_user(v_regs, ¤t->thread.vr_state,
33 * sizeof(vector128));
/* If VEC was enabled there are transactional VRs valid too,
* else they're a copy of the checkpointed VRs.
*/
if (msr & MSR_VEC)
err |= __copy_to_user(tm_v_regs,
¤t->thread.transact_vr,
33 * sizeof(vector128));
else
err |= __copy_to_user(tm_v_regs,
¤t->thread.vr_state,
33 * sizeof(vector128));
/* set MSR_VEC in the MSR value in the frame to indicate
* that sc->v_reg contains valid data.
*/
msr |= MSR_VEC;
}
/* We always copy to/from vrsave, it's 0 if we don't have or don't
* use altivec.
*/
if (cpu_has_feature(CPU_FTR_ALTIVEC))
current->thread.vrsave = mfspr(SPRN_VRSAVE);
err |= __put_user(current->thread.vrsave, (u32 __user *)&v_regs[33]);
if (msr & MSR_VEC)
err |= __put_user(current->thread.transact_vrsave,
(u32 __user *)&tm_v_regs[33]);
else
err |= __put_user(current->thread.vrsave,
(u32 __user *)&tm_v_regs[33]);
#else /* CONFIG_ALTIVEC */
err |= __put_user(0, &sc->v_regs);
err |= __put_user(0, &tm_sc->v_regs);
#endif /* CONFIG_ALTIVEC */
/* copy fpr regs and fpscr */
err |= copy_fpr_to_user(&sc->fp_regs, current);
if (msr & MSR_FP)
err |= copy_transact_fpr_to_user(&tm_sc->fp_regs, current);
else
err |= copy_fpr_to_user(&tm_sc->fp_regs, current);
#ifdef CONFIG_VSX
/*
* Copy VSX low doubleword to local buffer for formatting,
* then out to userspace. Update v_regs to point after the
* VMX data.
*/
if (current->thread.used_vsr) {
__giveup_vsx(current);
v_regs += ELF_NVRREG;
tm_v_regs += ELF_NVRREG;
err |= copy_vsx_to_user(v_regs, current);
if (msr & MSR_VSX)
err |= copy_transact_vsx_to_user(tm_v_regs, current);
else
err |= copy_vsx_to_user(tm_v_regs, current);
/* set MSR_VSX in the MSR value in the frame to
* indicate that sc->vs_reg) contains valid data.
*/
msr |= MSR_VSX;
}
#endif /* CONFIG_VSX */
err |= __put_user(&sc->gp_regs, &sc->regs);
err |= __put_user(&tm_sc->gp_regs, &tm_sc->regs);
WARN_ON(!FULL_REGS(regs));
err |= __copy_to_user(&tm_sc->gp_regs, regs, GP_REGS_SIZE);
err |= __copy_to_user(&sc->gp_regs,
¤t->thread.ckpt_regs, GP_REGS_SIZE);
err |= __put_user(msr, &tm_sc->gp_regs[PT_MSR]);
err |= __put_user(msr, &sc->gp_regs[PT_MSR]);
err |= __put_user(signr, &sc->signal);
err |= __put_user(handler, &sc->handler);
if (set != NULL)
err |= __put_user(set->sig[0], &sc->oldmask);
return err;
}
#endif
/*
* Restore the sigcontext from the signal frame.
*/
static long restore_sigcontext(struct pt_regs *regs, sigset_t *set, int sig,
struct sigcontext __user *sc)
{
#ifdef CONFIG_ALTIVEC
elf_vrreg_t __user *v_regs;
#endif
unsigned long err = 0;
unsigned long save_r13 = 0;
unsigned long msr;
#ifdef CONFIG_VSX
int i;
#endif
/* If this is not a signal return, we preserve the TLS in r13 */
if (!sig)
save_r13 = regs->gpr[13];
/* copy the GPRs */
err |= __copy_from_user(regs->gpr, sc->gp_regs, sizeof(regs->gpr));
err |= __get_user(regs->nip, &sc->gp_regs[PT_NIP]);
/* get MSR separately, transfer the LE bit if doing signal return */
err |= __get_user(msr, &sc->gp_regs[PT_MSR]);
if (sig)
regs->msr = (regs->msr & ~MSR_LE) | (msr & MSR_LE);
err |= __get_user(regs->orig_gpr3, &sc->gp_regs[PT_ORIG_R3]);
err |= __get_user(regs->ctr, &sc->gp_regs[PT_CTR]);
err |= __get_user(regs->link, &sc->gp_regs[PT_LNK]);
err |= __get_user(regs->xer, &sc->gp_regs[PT_XER]);
err |= __get_user(regs->ccr, &sc->gp_regs[PT_CCR]);
/* skip SOFTE */
regs->trap = 0;
err |= __get_user(regs->dar, &sc->gp_regs[PT_DAR]);
err |= __get_user(regs->dsisr, &sc->gp_regs[PT_DSISR]);
err |= __get_user(regs->result, &sc->gp_regs[PT_RESULT]);
if (!sig)
regs->gpr[13] = save_r13;
if (set != NULL)
err |= __get_user(set->sig[0], &sc->oldmask);
/*
* Do this before updating the thread state in
* current->thread.fpr/vr. That way, if we get preempted
* and another task grabs the FPU/Altivec, it won't be
* tempted to save the current CPU state into the thread_struct
* and corrupt what we are writing there.
*/
discard_lazy_cpu_state();
/*
* Force reload of FP/VEC.
* This has to be done before copying stuff into current->thread.fpr/vr
* for the reasons explained in the previous comment.
*/
regs->msr &= ~(MSR_FP | MSR_FE0 | MSR_FE1 | MSR_VEC | MSR_VSX);
#ifdef CONFIG_ALTIVEC
err |= __get_user(v_regs, &sc->v_regs);
if (err)
return err;
if (v_regs && !access_ok(VERIFY_READ, v_regs, 34 * sizeof(vector128)))
return -EFAULT;
/* Copy 33 vec registers (vr0..31 and vscr) from the stack */
if (v_regs != NULL && (msr & MSR_VEC) != 0)
err |= __copy_from_user(¤t->thread.vr_state, v_regs,
33 * sizeof(vector128));
else if (current->thread.used_vr)
memset(¤t->thread.vr_state, 0, 33 * sizeof(vector128));
/* Always get VRSAVE back */
if (v_regs != NULL)
err |= __get_user(current->thread.vrsave, (u32 __user *)&v_regs[33]);
else
current->thread.vrsave = 0;
if (cpu_has_feature(CPU_FTR_ALTIVEC))
mtspr(SPRN_VRSAVE, current->thread.vrsave);
#endif /* CONFIG_ALTIVEC */
/* restore floating point */
err |= copy_fpr_from_user(current, &sc->fp_regs);
#ifdef CONFIG_VSX
/*
* Get additional VSX data. Update v_regs to point after the
* VMX data. Copy VSX low doubleword from userspace to local
* buffer for formatting, then into the taskstruct.
*/
v_regs += ELF_NVRREG;
if ((msr & MSR_VSX) != 0)
err |= copy_vsx_from_user(current, v_regs);
else
for (i = 0; i < 32 ; i++)
current->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0;
#endif
return err;
}
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
/*
* Restore the two sigcontexts from the frame of a transactional processes.
*/
static long restore_tm_sigcontexts(struct pt_regs *regs,
struct sigcontext __user *sc,
struct sigcontext __user *tm_sc)
{
#ifdef CONFIG_ALTIVEC
elf_vrreg_t __user *v_regs, *tm_v_regs;
#endif
unsigned long err = 0;
unsigned long msr;
#ifdef CONFIG_VSX
int i;
#endif
/* copy the GPRs */
err |= __copy_from_user(regs->gpr, tm_sc->gp_regs, sizeof(regs->gpr));
err |= __copy_from_user(¤t->thread.ckpt_regs, sc->gp_regs,
sizeof(regs->gpr));
/*
* TFHAR is restored from the checkpointed 'wound-back' ucontext's NIP.
* TEXASR was set by the signal delivery reclaim, as was TFIAR.
* Users doing anything abhorrent like thread-switching w/ signals for
* TM-Suspended code will have to back TEXASR/TFIAR up themselves.
* For the case of getting a signal and simply returning from it,
* we don't need to re-copy them here.
*/
err |= __get_user(regs->nip, &tm_sc->gp_regs[PT_NIP]);
err |= __get_user(current->thread.tm_tfhar, &sc->gp_regs[PT_NIP]);
/* get MSR separately, transfer the LE bit if doing signal return */
err |= __get_user(msr, &sc->gp_regs[PT_MSR]);
/* pull in MSR TM from user context */
regs->msr = (regs->msr & ~MSR_TS_MASK) | (msr & MSR_TS_MASK);
/* pull in MSR LE from user context */
regs->msr = (regs->msr & ~MSR_LE) | (msr & MSR_LE);
/* The following non-GPR non-FPR non-VR state is also checkpointed: */
err |= __get_user(regs->ctr, &tm_sc->gp_regs[PT_CTR]);
err |= __get_user(regs->link, &tm_sc->gp_regs[PT_LNK]);
err |= __get_user(regs->xer, &tm_sc->gp_regs[PT_XER]);
err |= __get_user(regs->ccr, &tm_sc->gp_regs[PT_CCR]);
err |= __get_user(current->thread.ckpt_regs.ctr,
&sc->gp_regs[PT_CTR]);
err |= __get_user(current->thread.ckpt_regs.link,
&sc->gp_regs[PT_LNK]);
err |= __get_user(current->thread.ckpt_regs.xer,
&sc->gp_regs[PT_XER]);
err |= __get_user(current->thread.ckpt_regs.ccr,
&sc->gp_regs[PT_CCR]);
/* These regs are not checkpointed; they can go in 'regs'. */
err |= __get_user(regs->trap, &sc->gp_regs[PT_TRAP]);
err |= __get_user(regs->dar, &sc->gp_regs[PT_DAR]);
err |= __get_user(regs->dsisr, &sc->gp_regs[PT_DSISR]);
err |= __get_user(regs->result, &sc->gp_regs[PT_RESULT]);
/*
* Do this before updating the thread state in
* current->thread.fpr/vr. That way, if we get preempted
* and another task grabs the FPU/Altivec, it won't be
* tempted to save the current CPU state into the thread_struct
* and corrupt what we are writing there.
*/
discard_lazy_cpu_state();
/*
* Force reload of FP/VEC.
* This has to be done before copying stuff into current->thread.fpr/vr
* for the reasons explained in the previous comment.
*/
regs->msr &= ~(MSR_FP | MSR_FE0 | MSR_FE1 | MSR_VEC | MSR_VSX);
#ifdef CONFIG_ALTIVEC
err |= __get_user(v_regs, &sc->v_regs);
err |= __get_user(tm_v_regs, &tm_sc->v_regs);
if (err)
return err;
if (v_regs && !access_ok(VERIFY_READ, v_regs, 34 * sizeof(vector128)))
return -EFAULT;
if (tm_v_regs && !access_ok(VERIFY_READ,
tm_v_regs, 34 * sizeof(vector128)))
return -EFAULT;
/* Copy 33 vec registers (vr0..31 and vscr) from the stack */
if (v_regs != NULL && tm_v_regs != NULL && (msr & MSR_VEC) != 0) {
err |= __copy_from_user(¤t->thread.vr_state, v_regs,
33 * sizeof(vector128));
err |= __copy_from_user(¤t->thread.transact_vr, tm_v_regs,
33 * sizeof(vector128));
}
else if (current->thread.used_vr) {
memset(¤t->thread.vr_state, 0, 33 * sizeof(vector128));
memset(¤t->thread.transact_vr, 0, 33 * sizeof(vector128));
}
/* Always get VRSAVE back */
if (v_regs != NULL && tm_v_regs != NULL) {
err |= __get_user(current->thread.vrsave,
(u32 __user *)&v_regs[33]);
err |= __get_user(current->thread.transact_vrsave,
(u32 __user *)&tm_v_regs[33]);
}
else {
current->thread.vrsave = 0;
current->thread.transact_vrsave = 0;
}
if (cpu_has_feature(CPU_FTR_ALTIVEC))
mtspr(SPRN_VRSAVE, current->thread.vrsave);
#endif /* CONFIG_ALTIVEC */
/* restore floating point */
err |= copy_fpr_from_user(current, &sc->fp_regs);
err |= copy_transact_fpr_from_user(current, &tm_sc->fp_regs);
#ifdef CONFIG_VSX
/*
* Get additional VSX data. Update v_regs to point after the
* VMX data. Copy VSX low doubleword from userspace to local
* buffer for formatting, then into the taskstruct.
*/
if (v_regs && ((msr & MSR_VSX) != 0)) {
v_regs += ELF_NVRREG;
tm_v_regs += ELF_NVRREG;
err |= copy_vsx_from_user(current, v_regs);
err |= copy_transact_vsx_from_user(current, tm_v_regs);
} else {
for (i = 0; i < 32 ; i++) {
current->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0;
current->thread.transact_fp.fpr[i][TS_VSRLOWOFFSET] = 0;
}
}
#endif
tm_enable();
/* Make sure the transaction is marked as failed */
current->thread.tm_texasr |= TEXASR_FS;
/* This loads the checkpointed FP/VEC state, if used */
tm_recheckpoint(¤t->thread, msr);
/* This loads the speculative FP/VEC state, if used */
if (msr & MSR_FP) {
do_load_up_transact_fpu(¤t->thread);
regs->msr |= (MSR_FP | current->thread.fpexc_mode);
}
#ifdef CONFIG_ALTIVEC
if (msr & MSR_VEC) {
do_load_up_transact_altivec(¤t->thread);
regs->msr |= MSR_VEC;
}
#endif
return err;
}
#endif
/*
* Setup the trampoline code on the stack
*/
static long setup_trampoline(unsigned int syscall, unsigned int __user *tramp)
{
int i;
long err = 0;
/* addi r1, r1, __SIGNAL_FRAMESIZE # Pop the dummy stackframe */
err |= __put_user(0x38210000UL | (__SIGNAL_FRAMESIZE & 0xffff), &tramp[0]);
/* li r0, __NR_[rt_]sigreturn| */
err |= __put_user(0x38000000UL | (syscall & 0xffff), &tramp[1]);
/* sc */
err |= __put_user(0x44000002UL, &tramp[2]);
/* Minimal traceback info */
for (i=TRAMP_TRACEBACK; i < TRAMP_SIZE ;i++)
err |= __put_user(0, &tramp[i]);
if (!err)
flush_icache_range((unsigned long) &tramp[0],
(unsigned long) &tramp[TRAMP_SIZE]);
return err;
}
/*
* Userspace code may pass a ucontext which doesn't include VSX added
* at the end. We need to check for this case.
*/
#define UCONTEXTSIZEWITHOUTVSX \
(sizeof(struct ucontext) - 32*sizeof(long))
/*
* Handle {get,set,swap}_context operations
*/
int sys_swapcontext(struct ucontext __user *old_ctx,
struct ucontext __user *new_ctx,
long ctx_size, long r6, long r7, long r8, struct pt_regs *regs)
{
unsigned char tmp;
sigset_t set;
unsigned long new_msr = 0;
int ctx_has_vsx_region = 0;
if (new_ctx &&
get_user(new_msr, &new_ctx->uc_mcontext.gp_regs[PT_MSR]))
return -EFAULT;
/*
* Check that the context is not smaller than the original
* size (with VMX but without VSX)
*/
if (ctx_size < UCONTEXTSIZEWITHOUTVSX)
return -EINVAL;
/*
* If the new context state sets the MSR VSX bits but
* it doesn't provide VSX state.
*/
if ((ctx_size < sizeof(struct ucontext)) &&
(new_msr & MSR_VSX))
return -EINVAL;
/* Does the context have enough room to store VSX data? */
if (ctx_size >= sizeof(struct ucontext))
ctx_has_vsx_region = 1;
if (old_ctx != NULL) {
if (!access_ok(VERIFY_WRITE, old_ctx, ctx_size)
|| setup_sigcontext(&old_ctx->uc_mcontext, regs, 0, NULL, 0,
ctx_has_vsx_region)
|| __copy_to_user(&old_ctx->uc_sigmask,
¤t->blocked, sizeof(sigset_t)))
return -EFAULT;
}
if (new_ctx == NULL)
return 0;
if (!access_ok(VERIFY_READ, new_ctx, ctx_size)
|| __get_user(tmp, (u8 __user *) new_ctx)
|| __get_user(tmp, (u8 __user *) new_ctx + ctx_size - 1))
return -EFAULT;
/*
* If we get a fault copying the context into the kernel's
* image of the user's registers, we can't just return -EFAULT
* because the user's registers will be corrupted. For instance
* the NIP value may have been updated but not some of the
* other registers. Given that we have done the access_ok
* and successfully read the first and last bytes of the region
* above, this should only happen in an out-of-memory situation
* or if another thread unmaps the region containing the context.
* We kill the task with a SIGSEGV in this situation.
*/
if (__copy_from_user(&set, &new_ctx->uc_sigmask, sizeof(set)))
do_exit(SIGSEGV);
set_current_blocked(&set);
if (restore_sigcontext(regs, NULL, 0, &new_ctx->uc_mcontext))
do_exit(SIGSEGV);
/* This returns like rt_sigreturn */
set_thread_flag(TIF_RESTOREALL);
return 0;
}
/*
* Do a signal return; undo the signal stack.
*/
int sys_rt_sigreturn(unsigned long r3, unsigned long r4, unsigned long r5,
unsigned long r6, unsigned long r7, unsigned long r8,
struct pt_regs *regs)
{
struct ucontext __user *uc = (struct ucontext __user *)regs->gpr[1];
sigset_t set;
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
unsigned long msr;
#endif
/* Always make any pending restarted system calls return -EINTR */
current->restart_block.fn = do_no_restart_syscall;
if (!access_ok(VERIFY_READ, uc, sizeof(*uc)))
goto badframe;
if (__copy_from_user(&set, &uc->uc_sigmask, sizeof(set)))
goto badframe;
set_current_blocked(&set);
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
if (__get_user(msr, &uc->uc_mcontext.gp_regs[PT_MSR]))
goto badframe;
if (MSR_TM_ACTIVE(msr)) {
/* We recheckpoint on return. */
struct ucontext __user *uc_transact;
if (__get_user(uc_transact, &uc->uc_link))
goto badframe;
if (restore_tm_sigcontexts(regs, &uc->uc_mcontext,
&uc_transact->uc_mcontext))
goto badframe;
}
else
/* Fall through, for non-TM restore */
#endif
if (restore_sigcontext(regs, NULL, 1, &uc->uc_mcontext))
goto badframe;
if (restore_altstack(&uc->uc_stack))
goto badframe;
set_thread_flag(TIF_RESTOREALL);
return 0;
badframe:
if (show_unhandled_signals)
printk_ratelimited(regs->msr & MSR_64BIT ? fmt64 : fmt32,
current->comm, current->pid, "rt_sigreturn",
(long)uc, regs->nip, regs->link);
force_sig(SIGSEGV, current);
return 0;
}
int handle_rt_signal64(struct ksignal *ksig, sigset_t *set, struct pt_regs *regs)
{
struct rt_sigframe __user *frame;
unsigned long newsp = 0;
long err = 0;
frame = get_sigframe(ksig, get_tm_stackpointer(regs), sizeof(*frame), 0);
if (unlikely(frame == NULL))
goto badframe;
err |= __put_user(&frame->info, &frame->pinfo);
err |= __put_user(&frame->uc, &frame->puc);
err |= copy_siginfo_to_user(&frame->info, &ksig->info);
if (err)
goto badframe;
/* Create the ucontext. */
err |= __put_user(0, &frame->uc.uc_flags);
err |= __save_altstack(&frame->uc.uc_stack, regs->gpr[1]);
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
if (MSR_TM_ACTIVE(regs->msr)) {
/* The ucontext_t passed to userland points to the second
* ucontext_t (for transactional state) with its uc_link ptr.
*/
err |= __put_user(&frame->uc_transact, &frame->uc.uc_link);
err |= setup_tm_sigcontexts(&frame->uc.uc_mcontext,
&frame->uc_transact.uc_mcontext,
regs, ksig->sig,
NULL,
(unsigned long)ksig->ka.sa.sa_handler);
} else
#endif
{
err |= __put_user(0, &frame->uc.uc_link);
err |= setup_sigcontext(&frame->uc.uc_mcontext, regs, ksig->sig,
NULL, (unsigned long)ksig->ka.sa.sa_handler,
1);
}
err |= __copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set));
if (err)
goto badframe;
/* Make sure signal handler doesn't get spurious FP exceptions */
current->thread.fp_state.fpscr = 0;
/* Set up to return from userspace. */
if (vdso64_rt_sigtramp && current->mm->context.vdso_base) {
regs->link = current->mm->context.vdso_base + vdso64_rt_sigtramp;
} else {
err |= setup_trampoline(__NR_rt_sigreturn, &frame->tramp[0]);
if (err)
goto badframe;
regs->link = (unsigned long) &frame->tramp[0];
}
/* Allocate a dummy caller frame for the signal handler. */
newsp = ((unsigned long)frame) - __SIGNAL_FRAMESIZE;
err |= put_user(regs->gpr[1], (unsigned long __user *)newsp);
/* Set up "regs" so we "return" to the signal handler. */
if (is_elf2_task()) {
regs->nip = (unsigned long) ksig->ka.sa.sa_handler;
regs->gpr[12] = regs->nip;
} else {
/* Handler is *really* a pointer to the function descriptor for
* the signal routine. The first entry in the function
* descriptor is the entry address of signal and the second
* entry is the TOC value we need to use.
*/
func_descr_t __user *funct_desc_ptr =
(func_descr_t __user *) ksig->ka.sa.sa_handler;
err |= get_user(regs->nip, &funct_desc_ptr->entry);
err |= get_user(regs->gpr[2], &funct_desc_ptr->toc);
}
/* enter the signal handler in native-endian mode */
regs->msr &= ~MSR_LE;
regs->msr |= (MSR_KERNEL & MSR_LE);
regs->gpr[1] = newsp;
regs->gpr[3] = ksig->sig;
regs->result = 0;
if (ksig->ka.sa.sa_flags & SA_SIGINFO) {
err |= get_user(regs->gpr[4], (unsigned long __user *)&frame->pinfo);
err |= get_user(regs->gpr[5], (unsigned long __user *)&frame->puc);
regs->gpr[6] = (unsigned long) frame;
} else {
regs->gpr[4] = (unsigned long)&frame->uc.uc_mcontext;
}
if (err)
goto badframe;
return 0;
badframe:
if (show_unhandled_signals)
printk_ratelimited(regs->msr & MSR_64BIT ? fmt64 : fmt32,
current->comm, current->pid, "setup_rt_frame",
(long)frame, regs->nip, regs->link);
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1821_2 |
crossvul-cpp_data_bad_2628_0 | /* dlist.c - list protocol for dump and sync
*
* Copyright (c) 1994-2008 Carnegie Mellon University. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The name "Carnegie Mellon University" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For permission or any legal
* details, please contact
* Carnegie Mellon University
* Center for Technology Transfer and Enterprise Creation
* 4615 Forbes Avenue
* Suite 302
* Pittsburgh, PA 15213
* (412) 268-7393, fax: (412) 268-7395
* innovation@andrew.cmu.edu
*
* 4. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Computing Services
* at Carnegie Mellon University (http://www.cmu.edu/computing/)."
*
* CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <config.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <syslog.h>
#include <string.h>
#include <sys/wait.h>
#include <dirent.h>
#include "global.h"
#include "assert.h"
#include "mboxlist.h"
#include "mailbox.h"
#include "quota.h"
#include "xmalloc.h"
#include "seen.h"
#include "mboxname.h"
#include "map.h"
#include "imapd.h"
#include "message.h"
#include "util.h"
#include "prot.h"
/* generated headers are not necessarily in current directory */
#include "imap/imap_err.h"
#include "dlist.h"
/* Parse routines */
static const char *lastkey = NULL;
static void printfile(struct protstream *out, const struct dlist *dl)
{
struct stat sbuf;
FILE *f;
unsigned long size;
struct message_guid guid2;
const char *msg_base = NULL;
size_t msg_len = 0;
assert(dlist_isfile(dl));
f = fopen(dl->sval, "r");
if (!f) {
syslog(LOG_ERR, "IOERROR: Failed to read file %s", dl->sval);
prot_printf(out, "NIL");
return;
}
if (fstat(fileno(f), &sbuf) == -1) {
syslog(LOG_ERR, "IOERROR: Failed to stat file %s", dl->sval);
prot_printf(out, "NIL");
fclose(f);
return;
}
size = sbuf.st_size;
if (size != dl->nval) {
syslog(LOG_ERR, "IOERROR: Size mismatch %s (%lu != " MODSEQ_FMT ")",
dl->sval, size, dl->nval);
prot_printf(out, "NIL");
fclose(f);
return;
}
map_refresh(fileno(f), 1, &msg_base, &msg_len, sbuf.st_size,
"new message", 0);
message_guid_generate(&guid2, msg_base, msg_len);
if (!message_guid_equal(&guid2, dl->gval)) {
syslog(LOG_ERR, "IOERROR: GUID mismatch %s",
dl->sval);
prot_printf(out, "NIL");
fclose(f);
map_free(&msg_base, &msg_len);
return;
}
prot_printf(out, "%%{");
prot_printastring(out, dl->part);
prot_printf(out, " ");
prot_printastring(out, message_guid_encode(dl->gval));
prot_printf(out, " %lu}\r\n", size);
prot_write(out, msg_base, msg_len);
fclose(f);
map_free(&msg_base, &msg_len);
}
/* XXX - these two functions should be out in append.c or reserve.c
* or something more general */
EXPORTED const char *dlist_reserve_path(const char *part, int isarchive,
const struct message_guid *guid)
{
static char buf[MAX_MAILBOX_PATH];
const char *base;
/* part can be either a configured partition name, or a path */
if (strchr(part, '/')) {
base = part;
}
else {
base = isarchive ? config_archivepartitiondir(part)
: config_partitiondir(part);
}
/* we expect to have a base at this point, so let's assert that */
assert(base != NULL);
snprintf(buf, MAX_MAILBOX_PATH, "%s/sync./%lu/%s",
base, (unsigned long)getpid(),
message_guid_encode(guid));
/* gotta make sure we can create files */
if (cyrus_mkdir(buf, 0755)) {
/* it's going to fail later, but at least this will help */
syslog(LOG_ERR, "IOERROR: failed to create %s/sync./%lu/ for reserve: %m",
base, (unsigned long)getpid());
}
return buf;
}
static int reservefile(struct protstream *in, const char *part,
struct message_guid *guid, unsigned long size,
const char **fname)
{
FILE *file;
char buf[8192+1];
int r = 0;
/* XXX - write to a temporary file then move in to place! */
*fname = dlist_reserve_path(part, /*isarchive*/0, guid);
/* remove any duplicates if they're still here */
unlink(*fname);
file = fopen(*fname, "w+");
if (!file) {
syslog(LOG_ERR,
"IOERROR: failed to upload file %s", message_guid_encode(guid));
r = IMAP_IOERROR;
/* Note: we still read the file's data from the wire,
* to avoid losing protocol sync */
}
/* XXX - calculate sha1 on the fly? */
while (size) {
size_t n = prot_read(in, buf, size > 8192 ? 8192 : size);
if (!n) {
syslog(LOG_ERR,
"IOERROR: reading message: unexpected end of file");
r = IMAP_IOERROR;
break;
}
size -= n;
if (fwrite(buf, 1, n, file) != n) {
syslog(LOG_ERR, "IOERROR: writing to file '%s': %m", *fname);
r = IMAP_IOERROR;
break;
}
}
if (r)
goto error;
/* Make sure that message flushed to disk just incase mmap has problems */
fflush(file);
if (ferror(file)) {
r = IMAP_IOERROR;
goto error;
}
if (fsync(fileno(file)) < 0) {
syslog(LOG_ERR, "IOERROR: fsyncing file '%s': %m", *fname);
r = IMAP_IOERROR;
goto error;
}
fclose(file);
return 0;
error:
if (file) {
fclose(file);
unlink(*fname);
*fname = NULL;
}
return r;
}
/* DLIST STUFF */
EXPORTED void dlist_stitch(struct dlist *parent, struct dlist *child)
{
assert(!child->next);
if (parent->tail) {
parent->tail->next = child;
parent->tail = child;
}
else {
parent->head = parent->tail = child;
}
}
EXPORTED void dlist_unstitch(struct dlist *parent, struct dlist *child)
{
struct dlist *prev = NULL;
struct dlist *replace = NULL;
/* find old record */
for (replace = parent->head; replace; replace = replace->next) {
if (replace == child) break;
prev = replace;
}
assert(replace);
if (prev) prev->next = child->next;
else parent->head = child->next;
if (parent->tail == child) parent->tail = prev;
child->next = NULL;
}
static struct dlist *dlist_child(struct dlist *dl, const char *name)
{
struct dlist *i = xzmalloc(sizeof(struct dlist));
if (name) i->name = xstrdup(name);
i->type = DL_NIL;
if (dl)
dlist_stitch(dl, i);
return i;
}
static void _dlist_free_children(struct dlist *dl)
{
struct dlist *next;
struct dlist *i;
if (!dl) return;
i = dl->head;
while (i) {
next = i->next;
dlist_free(&i);
i = next;
}
dl->head = dl->tail = NULL;
}
static void _dlist_clean(struct dlist *dl)
{
if (!dl) return;
/* remove any children */
_dlist_free_children(dl);
/* clean out values */
free(dl->part);
dl->part = NULL;
free(dl->sval);
dl->sval = NULL;
free(dl->gval);
dl->gval = NULL;
dl->nval = 0;
}
void dlist_makeatom(struct dlist *dl, const char *val)
{
if (!dl) return;
_dlist_clean(dl);
if (val) {
dl->type = DL_ATOM;
dl->sval = xstrdup(val);
dl->nval = strlen(val);
}
else
dl->type = DL_NIL;
}
void dlist_makeflag(struct dlist *dl, const char *val)
{
if (!dl) return;
_dlist_clean(dl);
if (val) {
dl->type = DL_FLAG;
dl->sval = xstrdup(val);
dl->nval = strlen(val);
}
else
dl->type = DL_NIL;
}
void dlist_makenum32(struct dlist *dl, uint32_t val)
{
if (!dl) return;
_dlist_clean(dl);
dl->type = DL_NUM;
dl->nval = val;
}
void dlist_makenum64(struct dlist *dl, bit64 val)
{
if (!dl) return;
_dlist_clean(dl);
dl->type = DL_NUM;
dl->nval = val;
}
void dlist_makedate(struct dlist *dl, time_t val)
{
if (!dl) return;
_dlist_clean(dl);
dl->type = DL_DATE;
dl->nval = val;
}
void dlist_makehex64(struct dlist *dl, bit64 val)
{
if (!dl) return;
_dlist_clean(dl);
dl->type = DL_HEX;
dl->nval = val;
}
void dlist_makeguid(struct dlist *dl, const struct message_guid *guid)
{
if (!dl) return;
_dlist_clean(dl);
if (guid) {
dl->type = DL_GUID,
dl->gval = xzmalloc(sizeof(struct message_guid));
message_guid_copy(dl->gval, guid);
}
else
dl->type = DL_NIL;
}
void dlist_makefile(struct dlist *dl,
const char *part, const struct message_guid *guid,
unsigned long size, const char *fname)
{
if (!dl) return;
_dlist_clean(dl);
if (part && guid && fname) {
dl->type = DL_FILE;
dl->gval = xzmalloc(sizeof(struct message_guid));
message_guid_copy(dl->gval, guid);
dl->sval = xstrdup(fname);
dl->nval = size;
dl->part = xstrdup(part);
}
else
dl->type = DL_NIL;
}
EXPORTED void dlist_makemap(struct dlist *dl, const char *val, size_t len)
{
if (!dl) return;
_dlist_clean(dl);
if (val) {
dl->type = DL_BUF;
/* WARNING - DO NOT replace this with xstrndup - the
* data may be binary, and xstrndup does not copy
* binary data correctly - but we still want to NULL
* terminate for non-binary data */
dl->sval = xmalloc(len+1);
memcpy(dl->sval, val, len);
dl->sval[len] = '\0'; /* make it string safe too */
dl->nval = len;
}
else
dl->type = DL_NIL;
}
EXPORTED struct dlist *dlist_newkvlist(struct dlist *parent, const char *name)
{
struct dlist *dl = dlist_child(parent, name);
dl->type = DL_KVLIST;
return dl;
}
EXPORTED struct dlist *dlist_newlist(struct dlist *parent, const char *name)
{
struct dlist *dl = dlist_child(parent, name);
dl->type = DL_ATOMLIST;
return dl;
}
EXPORTED struct dlist *dlist_newpklist(struct dlist *parent, const char *name)
{
struct dlist *dl = dlist_child(parent, name);
dl->type = DL_ATOMLIST;
dl->nval = 1;
return dl;
}
EXPORTED struct dlist *dlist_setatom(struct dlist *parent, const char *name, const char *val)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makeatom(dl, val);
return dl;
}
EXPORTED struct dlist *dlist_setflag(struct dlist *parent, const char *name, const char *val)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makeflag(dl, val);
return dl;
}
EXPORTED struct dlist *dlist_setnum64(struct dlist *parent, const char *name, bit64 val)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makenum64(dl, val);
return dl;
}
EXPORTED struct dlist *dlist_setnum32(struct dlist *parent, const char *name, uint32_t val)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makenum32(dl, val);
return dl;
}
EXPORTED struct dlist *dlist_setdate(struct dlist *parent, const char *name, time_t val)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makedate(dl, val);
return dl;
}
EXPORTED struct dlist *dlist_sethex64(struct dlist *parent, const char *name, bit64 val)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makehex64(dl, val);
return dl;
}
EXPORTED struct dlist *dlist_setmap(struct dlist *parent, const char *name,
const char *val, size_t len)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makemap(dl, val, len);
return dl;
}
EXPORTED struct dlist *dlist_setguid(struct dlist *parent, const char *name,
const struct message_guid *guid)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makeguid(dl, guid);
return dl;
}
EXPORTED struct dlist *dlist_setfile(struct dlist *parent, const char *name,
const char *part, const struct message_guid *guid,
size_t size, const char *fname)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makefile(dl, part, guid, size, fname);
return dl;
}
static struct dlist *dlist_updatechild(struct dlist *parent, const char *name)
{
struct dlist *dl = dlist_getchild(parent, name);
if (!dl) dl = dlist_child(parent, name);
return dl;
}
struct dlist *dlist_updateatom(struct dlist *parent, const char *name, const char *val)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makeatom(dl, val);
return dl;
}
struct dlist *dlist_updateflag(struct dlist *parent, const char *name, const char *val)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makeflag(dl, val);
return dl;
}
struct dlist *dlist_updatenum64(struct dlist *parent, const char *name, bit64 val)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makenum64(dl, val);
return dl;
}
struct dlist *dlist_updatenum32(struct dlist *parent, const char *name, uint32_t val)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makenum32(dl, val);
return dl;
}
struct dlist *dlist_updatedate(struct dlist *parent, const char *name, time_t val)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makedate(dl, val);
return dl;
}
struct dlist *dlist_updatehex64(struct dlist *parent, const char *name, bit64 val)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makehex64(dl, val);
return dl;
}
struct dlist *dlist_updatemap(struct dlist *parent, const char *name,
const char *val, size_t len)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makemap(dl, val, len);
return dl;
}
struct dlist *dlist_updateguid(struct dlist *parent, const char *name,
const struct message_guid *guid)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makeguid(dl, guid);
return dl;
}
struct dlist *dlist_updatefile(struct dlist *parent, const char *name,
const char *part, const struct message_guid *guid,
size_t size, const char *fname)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makefile(dl, part, guid, size, fname);
return dl;
}
EXPORTED void dlist_print(const struct dlist *dl, int printkeys,
struct protstream *out)
{
struct dlist *di;
if (printkeys) {
prot_printastring(out, dl->name);
prot_putc(' ', out);
}
switch (dl->type) {
case DL_NIL:
prot_printf(out, "NIL");
break;
case DL_ATOM:
prot_printastring(out, dl->sval);
break;
case DL_FLAG:
prot_printf(out, "%s", dl->sval);
break;
case DL_NUM:
case DL_DATE: /* for now, we will format it later */
prot_printf(out, "%llu", dl->nval);
break;
case DL_FILE:
printfile(out, dl);
break;
case DL_BUF:
if (strlen(dl->sval) == dl->nval)
prot_printastring(out, dl->sval);
else
prot_printliteral(out, dl->sval, dl->nval);
break;
case DL_GUID:
prot_printf(out, "%s", message_guid_encode(dl->gval));
break;
case DL_HEX:
{
char buf[17];
snprintf(buf, 17, "%016llx", dl->nval);
prot_printf(out, "%s", buf);
}
break;
case DL_KVLIST:
prot_printf(out, "%%(");
for (di = dl->head; di; di = di->next) {
dlist_print(di, 1, out);
if (di->next) {
prot_printf(out, " ");
}
}
prot_printf(out, ")");
break;
case DL_ATOMLIST:
prot_printf(out, "(");
for (di = dl->head; di; di = di->next) {
dlist_print(di, dl->nval, out);
if (di->next)
prot_printf(out, " ");
}
prot_printf(out, ")");
break;
}
}
EXPORTED void dlist_printbuf(const struct dlist *dl, int printkeys, struct buf *outbuf)
{
struct protstream *outstream;
outstream = prot_writebuf(outbuf);
dlist_print(dl, printkeys, outstream);
prot_flush(outstream);
prot_free(outstream);
}
EXPORTED void dlist_unlink_files(struct dlist *dl)
{
struct dlist *i;
if (!dl) return;
for (i = dl->head; i; i = i->next) {
dlist_unlink_files(i);
}
if (dl->type != DL_FILE) return;
if (!dl->sval) return;
syslog(LOG_DEBUG, "%s: unlinking %s", __func__, dl->sval);
unlink(dl->sval);
}
EXPORTED void dlist_free(struct dlist **dlp)
{
if (!*dlp) return;
_dlist_clean(*dlp);
free((*dlp)->name);
free(*dlp);
*dlp = NULL;
}
struct dlist_stack_node {
const struct dlist *dl;
int printkeys;
struct dlist_stack_node *next;
};
struct dlist_print_iter {
int printkeys;
struct dlist_stack_node *parent;
const struct dlist *next;
};
EXPORTED struct dlist_print_iter *dlist_print_iter_new(const struct dlist *dl, int printkeys)
{
struct dlist_print_iter *iter = xzmalloc(sizeof *iter);
iter->printkeys = printkeys;
iter->next = dl;
return iter;
}
EXPORTED const char *dlist_print_iter_step(struct dlist_print_iter *iter, struct buf *outbuf)
{
/* already finished */
if (!iter->next) return NULL;
buf_reset(outbuf);
/* Bundle short steps together to minimise call overhead.
* Note that outbuf can grow significantly longer than this limit, if a
* single item in the dlist is very long (e.g. a message), but then it
* won't bundle up more than that.
*/
while (iter->next != NULL && buf_len(outbuf) < 1024) {
const struct dlist *curr = iter->next;
struct dlist_stack_node *parent = NULL;
int descend = 0;
/* output */
switch (curr->type) {
case DL_KVLIST:
case DL_ATOMLIST:
// XXX should use equiv to "prot_printastring" for curr->name
if (iter->printkeys)
buf_printf(outbuf, "%s ", curr->name);
buf_appendcstr(outbuf, curr->type == DL_KVLIST ? "%(" : "(");
if (curr->head) {
descend = 1;
}
else {
buf_putc(outbuf, ')');
if (curr->next)
buf_putc(outbuf, ' ');
}
break;
default:
dlist_printbuf(curr, iter->printkeys, outbuf);
if (curr->next)
buf_putc(outbuf, ' ');
break;
}
/* increment */
if (descend) {
parent = xmalloc(sizeof *parent);
parent->printkeys = iter->printkeys;
parent->dl = curr;
parent->next = iter->parent;
iter->parent = parent;
iter->next = curr->head;
// XXX can this always be 1? we know an atom list here is non-empty
iter->printkeys = curr->type == DL_KVLIST ? 1 : curr->nval;
}
else if (curr->next) {
iter->next = curr->next;
}
else if (iter->parent) {
/* multiple parents might be ending at the same point
* don't mistake one parent ending for end of entire tree
*/
do {
buf_putc(outbuf, ')');
parent = iter->parent;
iter->parent = iter->parent->next;
iter->next = parent->dl->next;
iter->printkeys = parent->printkeys;
free(parent);
if (iter->next) {
/* found an unfinished dlist, stop closing parents */
buf_putc(outbuf, ' ');
break;
}
} while (iter->parent);
}
else {
iter->next = NULL;
}
}
/* and return */
return buf_cstringnull(outbuf);
}
EXPORTED void dlist_print_iter_free(struct dlist_print_iter **iterp)
{
struct dlist_print_iter *iter = *iterp;
struct dlist_stack_node *tmp = NULL;
*iterp = NULL;
while (iter->parent) {
tmp = iter->parent;
iter->parent = iter->parent->next;
free(tmp);
}
free(iter);
}
struct dlistsax_state {
const char *base;
const char *p;
const char *end;
dlistsax_cb_t *proc;
int depth;
struct dlistsax_data d;
struct buf gbuf;
};
static int _parseqstring(struct dlistsax_state *s, struct buf *buf)
{
buf->len = 0;
/* get over the first quote */
if (*s->p++ != '"') return IMAP_INVALID_IDENTIFIER;
while (s->p < s->end) {
/* found the end quote */
if (*s->p == '"') {
s->p++;
return 0;
}
/* backslash just quotes the next char, no matter what it is */
if (*s->p == '\\') {
s->p++;
if (s->p == s->end) break;
/* fall through */
}
buf_putc(buf, *s->p++);
}
return IMAP_INVALID_IDENTIFIER;
}
static int _parseliteral(struct dlistsax_state *s, struct buf *buf)
{
size_t len = 0;
if (*s->p++ != '{') return IMAP_INVALID_IDENTIFIER;
while (s->p < s->end) {
if (cyrus_isdigit(*s->p)) {
len = (len * 10) + (*s->p++ - '0');
}
else if (*s->p == '}') {
if (s->p + 3 + len >= s->end) break;
if (s->p[1] != '\r') break;
if (s->p[2] != '\n') break;
buf_setmap(buf, s->p+3, len);
s->p += len = 3;
return 0;
}
}
return IMAP_INVALID_IDENTIFIER;
}
static int _parseitem(struct dlistsax_state *s, struct buf *buf)
{
const char *sp;
if (*s->p == '"')
return _parseqstring(s, buf);
else if (*s->p == '{')
return _parseliteral(s, buf);
sp = memchr(s->p, ' ', s->end - s->p);
if (!sp) sp = s->end;
while (sp[-1] == ')' && sp > s->p) sp--;
/* this is much faster because it doesn't do a reset and check the MMAP flag */
buf->len = 0;
buf_appendmap(buf, s->p, sp - s->p);
s->p = sp;
return 0; /* this could be the last thing, so end is OK */
}
static int _parsesax(struct dlistsax_state *s, int parsekey)
{
int r = 0;
s->depth++;
/* handle the key if wanted */
if (parsekey) {
r = _parseitem(s, &s->d.kbuf);
if (r) return r;
if (s->p >= s->end) return IMAP_INVALID_IDENTIFIER;
if (*s->p == ' ') s->p++;
else return IMAP_INVALID_IDENTIFIER;
}
else {
s->d.kbuf.len = 0;
}
if (s->p >= s->end) return IMAP_INVALID_IDENTIFIER;
/* check what sort of value we have */
if (*s->p == '(') {
r = s->proc(DLISTSAX_LISTSTART, &s->d);
if (r) return r;
s->p++;
if (s->p >= s->end) return IMAP_INVALID_IDENTIFIER;
while (*s->p != ')') {
r = _parsesax(s, 0);
if (r) return r;
if (*s->p == ')') break;
if (*s->p == ' ') s->p++;
else return IMAP_INVALID_IDENTIFIER;
if (s->p >= s->end) return IMAP_INVALID_IDENTIFIER;
}
r = s->proc(DLISTSAX_LISTEND, &s->d);
if (r) return r;
s->p++;
}
else if (*s->p == '%') {
s->p++;
if (s->p >= s->end) return IMAP_INVALID_IDENTIFIER;
/* no whitespace allowed here */
if (*s->p == '(') {
r = s->proc(DLISTSAX_KVLISTSTART, &s->d);
if (r) return r;
s->p++;
if (s->p >= s->end) return IMAP_INVALID_IDENTIFIER;
while (*s->p != ')') {
r = _parsesax(s, 1);
if (r) return r;
if (*s->p == ')') break;
if (*s->p == ' ') s->p++;
else return IMAP_INVALID_IDENTIFIER;
if (s->p >= s->end) return IMAP_INVALID_IDENTIFIER;
}
r = s->proc(DLISTSAX_KVLISTEND, &s->d);
if (r) return r;
s->p++;
}
else {
/* unknown percent type */
return IMAP_INVALID_IDENTIFIER;
}
}
else {
r = _parseitem(s, &s->d.buf);
if (r) return r;
r = s->proc(DLISTSAX_STRING, &s->d);
if (r) return r;
}
s->depth--;
/* success */
return 0;
}
EXPORTED int dlist_parsesax(const char *base, size_t len, int parsekey,
dlistsax_cb_t *proc, void *rock)
{
static struct dlistsax_state state;
int r;
state.base = base;
state.p = base;
state.end = base + len;
state.proc = proc;
state.d.rock = rock;
r = _parsesax(&state, parsekey);
if (r) return r;
if (state.p < state.end)
return IMAP_IOERROR;
return 0;
}
static char next_nonspace(struct protstream *in, char c)
{
while (Uisspace(c)) c = prot_getc(in);
return c;
}
EXPORTED int dlist_parse(struct dlist **dlp, int parsekey,
struct protstream *in, const char *alt_reserve_base)
{
struct dlist *dl = NULL;
static struct buf kbuf;
static struct buf vbuf;
int c;
/* handle the key if wanted */
if (parsekey) {
c = getastring(in, NULL, &kbuf);
c = next_nonspace(in, c);
}
else {
buf_setcstr(&kbuf, "");
c = prot_getc(in);
}
/* connection dropped? */
if (c == EOF) goto fail;
/* check what sort of value we have */
if (c == '(') {
dl = dlist_newlist(NULL, kbuf.s);
c = next_nonspace(in, ' ');
while (c != ')') {
struct dlist *di = NULL;
prot_ungetc(c, in);
c = dlist_parse(&di, 0, in, alt_reserve_base);
if (di) dlist_stitch(dl, di);
c = next_nonspace(in, c);
if (c == EOF) goto fail;
}
c = prot_getc(in);
}
else if (c == '%') {
/* no whitespace allowed here */
c = prot_getc(in);
if (c == '(') {
dl = dlist_newkvlist(NULL, kbuf.s);
c = next_nonspace(in, ' ');
while (c != ')') {
struct dlist *di = NULL;
prot_ungetc(c, in);
c = dlist_parse(&di, 1, in, alt_reserve_base);
if (di) dlist_stitch(dl, di);
c = next_nonspace(in, c);
if (c == EOF) goto fail;
}
}
else if (c == '{') {
struct message_guid tmp_guid;
static struct buf pbuf, gbuf;
unsigned size = 0;
const char *fname;
const char *part;
c = getastring(in, NULL, &pbuf);
if (c != ' ') goto fail;
c = getastring(in, NULL, &gbuf);
if (c != ' ') goto fail;
c = getuint32(in, &size);
if (c != '}') goto fail;
c = prot_getc(in);
if (c == '\r') c = prot_getc(in);
if (c != '\n') goto fail;
if (!message_guid_decode(&tmp_guid, gbuf.s)) goto fail;
part = alt_reserve_base ? alt_reserve_base : pbuf.s;
if (reservefile(in, part, &tmp_guid, size, &fname)) goto fail;
dl = dlist_setfile(NULL, kbuf.s, pbuf.s, &tmp_guid, size, fname);
/* file literal */
}
else {
/* unknown percent type */
goto fail;
}
c = prot_getc(in);
}
else if (c == '{') {
prot_ungetc(c, in);
/* could be binary in a literal */
c = getbastring(in, NULL, &vbuf);
dl = dlist_setmap(NULL, kbuf.s, vbuf.s, vbuf.len);
}
else if (c == '\\') { /* special case for flags */
prot_ungetc(c, in);
c = getastring(in, NULL, &vbuf);
dl = dlist_setflag(NULL, kbuf.s, vbuf.s);
}
else {
prot_ungetc(c, in);
c = getnastring(in, NULL, &vbuf);
dl = dlist_setatom(NULL, kbuf.s, vbuf.s);
}
/* success */
*dlp = dl;
return c;
fail:
dlist_free(&dl);
return EOF;
}
EXPORTED int dlist_parse_asatomlist(struct dlist **dlp, int parsekey,
struct protstream *in)
{
int c = dlist_parse(dlp, parsekey, in, NULL);
/* make a list with one item */
if (*dlp && !dlist_isatomlist(*dlp)) {
struct dlist *tmp = dlist_newlist(NULL, "");
dlist_stitch(tmp, *dlp);
*dlp = tmp;
}
return c;
}
EXPORTED int dlist_parsemap(struct dlist **dlp, int parsekey,
const char *base, unsigned len)
{
struct protstream *stream;
int c;
struct dlist *dl = NULL;
stream = prot_readmap(base, len);
prot_setisclient(stream, 1); /* don't sync literals */
c = dlist_parse(&dl, parsekey, stream, NULL);
prot_free(stream);
if (c != EOF) {
dlist_free(&dl);
return IMAP_IOERROR; /* failed to slurp entire buffer */
}
*dlp = dl;
return 0;
}
EXPORTED struct dlist *dlist_getchild(struct dlist *dl, const char *name)
{
struct dlist *i;
if (!dl) return NULL;
for (i = dl->head; i; i = i->next) {
if (i->name && !strcmp(name, i->name))
return i;
}
lastkey = name;
return NULL;
}
EXPORTED struct dlist *dlist_getchildn(struct dlist *dl, int num)
{
struct dlist *i;
if (!dl) return NULL;
for (i = dl->head; i && num; i = i->next)
num--;
return i;
}
/* duplicate the parent list as a new list, and then move @num
* of the children from the parent onto the new list */
EXPORTED struct dlist *dlist_splice(struct dlist *dl, int num)
{
struct dlist *ret = dlist_newlist(NULL, dl->name);
/* clone exact type */
ret->type = dl->type;
ret->nval = dl->nval;
if (num > 0) {
struct dlist *end = dlist_getchildn(dl, num - 1);
/* take the start of the list */
ret->head = dl->head;
/* leave the end (if any) */
if (end) {
ret->tail = end;
dl->head = end->next;
end->next = NULL;
}
else {
ret->tail = dl->tail;
dl->head = NULL;
dl->tail = NULL;
}
}
return ret;
}
EXPORTED void dlist_splat(struct dlist *parent, struct dlist *child)
{
struct dlist *prev = NULL;
struct dlist *replace;
/* find old record */
for (replace = parent->head; replace; replace = replace->next) {
if (replace == child) break;
prev = replace;
}
assert(replace);
if (child->head) {
/* stitch in children */
if (prev) prev->next = child->head;
else parent->head = child->head;
if (child->next) child->tail->next = child->next;
else parent->tail = child->tail;
}
else {
/* just remove the record */
if (prev) prev->next = child->next;
else parent->head = child->next;
if (!child->next) parent->tail = prev;
}
/* remove the node itself, carefully blanking out
* the now unlinked children */
child->head = NULL;
child->tail = NULL;
dlist_free(&child);
}
struct dlist *dlist_getkvchild_bykey(struct dlist *dl,
const char *key, const char *val)
{
struct dlist *i;
struct dlist *tmp;
if (!dl) return NULL;
for (i = dl->head; i; i = i->next) {
tmp = dlist_getchild(i, key);
if (tmp && !strcmp(tmp->sval, val))
return i;
}
return NULL;
}
int dlist_toatom(struct dlist *dl, const char **valp)
{
const char *str;
size_t len;
if (!dl) return 0;
/* atom can be NULL */
if (dl->type == DL_NIL) {
*valp = NULL;
return 1;
}
/* tomap always adds a trailing \0 */
if (!dlist_tomap(dl, &str, &len))
return 0;
/* got NULLs? */
if (dl->type == DL_BUF && strlen(str) != len)
return 0;
if (valp) *valp = str;
return 1;
}
HIDDEN int dlist_tomap(struct dlist *dl, const char **valp, size_t *lenp)
{
char tmp[30];
if (!dl) return 0;
switch (dl->type) {
case DL_NUM:
case DL_DATE:
snprintf(tmp, 30, "%llu", dl->nval);
dlist_makeatom(dl, tmp);
break;
case DL_HEX:
snprintf(tmp, 30, "%016llx", dl->nval);
dlist_makeatom(dl, tmp);
break;
case DL_GUID:
dlist_makeatom(dl, message_guid_encode(dl->gval));
break;
case DL_ATOM:
case DL_FLAG:
case DL_BUF:
break;
default:
return 0;
}
if (valp) *valp = dl->sval;
if (lenp) *lenp = dl->nval;
return 1;
}
/* ensure value is exactly one number */
static int dlist_tonum64(struct dlist *dl, bit64 *valp)
{
const char *end;
bit64 newval;
if (!dl) return 0;
switch (dl->type) {
case DL_ATOM:
case DL_BUF:
if (parsenum(dl->sval, &end, dl->nval, &newval))
return 0;
if (end - dl->sval != (int)dl->nval)
return 0;
/* successfully parsed - switch to a numeric value */
dlist_makenum64(dl, newval);
break;
case DL_NUM:
case DL_HEX:
case DL_DATE:
break;
default:
return 0;
}
if (valp) *valp = dl->nval;
return 1;
}
EXPORTED int dlist_tonum32(struct dlist *dl, uint32_t *valp)
{
bit64 v;
if (dlist_tonum64(dl, &v)) {
if (valp) *valp = (uint32_t)v;
return 1;
}
return 0;
}
int dlist_todate(struct dlist *dl, time_t *valp)
{
bit64 v;
if (dlist_tonum64(dl, &v)) {
if (valp) *valp = (time_t)v;
dl->type = DL_DATE;
return 1;
}
return 0;
}
static int dlist_tohex64(struct dlist *dl, bit64 *valp)
{
const char *end = NULL;
bit64 newval;
if (!dl) return 0;
switch (dl->type) {
case DL_ATOM:
case DL_BUF:
if (parsehex(dl->sval, &end, dl->nval, &newval))
return 0;
if (end - dl->sval != (int)dl->nval)
return 0;
/* successfully parsed - switch to a numeric value */
dlist_makehex64(dl, newval);
break;
case DL_NUM:
case DL_HEX:
case DL_DATE:
dl->type = DL_HEX;
break;
default:
return 0;
}
if (valp) *valp = dl->nval;
return 1;
}
EXPORTED int dlist_toguid(struct dlist *dl, struct message_guid **valp)
{
struct message_guid tmpguid;
if (!dl) return 0;
switch (dl->type) {
case DL_ATOM:
case DL_BUF:
if (dl->nval != 40)
return 0;
if (!message_guid_decode(&tmpguid, dl->sval))
return 0;
/* successfully parsed - switch to guid value */
dlist_makeguid(dl, &tmpguid);
break;
case DL_GUID:
break;
default:
return 0;
}
if (valp) *valp = dl->gval;
return 1;
}
EXPORTED int dlist_tofile(struct dlist *dl,
const char **partp, struct message_guid **guidp,
unsigned long *sizep, const char **fnamep)
{
if (!dlist_isfile(dl)) return 0;
if (guidp) *guidp = dl->gval;
if (sizep) *sizep = dl->nval;
if (fnamep) *fnamep = dl->sval;
if (partp) *partp = dl->part;
return 1;
}
EXPORTED int dlist_isatomlist(const struct dlist *dl)
{
if (!dl) return 0;
return (dl->type == DL_ATOMLIST);
}
int dlist_iskvlist(const struct dlist *dl)
{
if (!dl) return 0;
return (dl->type == DL_KVLIST);
}
int dlist_isfile(const struct dlist *dl)
{
if (!dl) return 0;
return (dl->type == DL_FILE);
}
/* XXX - these ones aren't const, because they can change
* things... */
int dlist_isnum(struct dlist *dl)
{
bit64 tmp;
if (!dl) return 0;
/* see if it can be parsed as a number */
return dlist_tonum64(dl, &tmp);
}
/* XXX - these ones aren't const, because they can change
* things... */
EXPORTED int dlist_ishex64(struct dlist *dl)
{
bit64 tmp;
if (!dl) return 0;
/* see if it can be parsed as a number */
return dlist_tohex64(dl, &tmp);
}
/* XXX - these ones aren't const, because they can change
* things... */
int dlist_isguid(struct dlist *dl)
{
struct message_guid *tmp = NULL;
if (!dl) return 0;
return dlist_toguid(dl, &tmp);
}
/* XXX - this stuff is all shitty, rationalise later */
EXPORTED bit64 dlist_num(struct dlist *dl)
{
bit64 v;
if (!dl) return 0;
if (dlist_tonum64(dl, &v))
return v;
return 0;
}
/* XXX - this stuff is all shitty, rationalise later */
EXPORTED const char *dlist_cstring(struct dlist *dl)
{
static char zerochar = '\0';
if (dl) {
const char *res = NULL;
dlist_toatom(dl, &res);
if (res) return res;
}
return &zerochar;
}
EXPORTED int dlist_getatom(struct dlist *parent, const char *name, const char **valp)
{
struct dlist *child = dlist_getchild(parent, name);
return dlist_toatom(child, valp);
}
EXPORTED int dlist_getnum32(struct dlist *parent, const char *name, uint32_t *valp)
{
struct dlist *child = dlist_getchild(parent, name);
return dlist_tonum32(child, valp);
}
EXPORTED int dlist_getnum64(struct dlist *parent, const char *name, bit64 *valp)
{
struct dlist *child = dlist_getchild(parent, name);
return dlist_tonum64(child, valp);
}
EXPORTED int dlist_getdate(struct dlist *parent, const char *name, time_t *valp)
{
struct dlist *child = dlist_getchild(parent, name);
return dlist_todate(child, valp);
}
EXPORTED int dlist_gethex64(struct dlist *parent, const char *name, bit64 *valp)
{
struct dlist *child = dlist_getchild(parent, name);
return dlist_tohex64(child, valp);
}
EXPORTED int dlist_getguid(struct dlist *parent, const char *name,
struct message_guid **valp)
{
struct dlist *child = dlist_getchild(parent, name);
return dlist_toguid(child, valp);
}
EXPORTED int dlist_getmap(struct dlist *parent, const char *name,
const char **valp, size_t *lenp)
{
struct dlist *child = dlist_getchild(parent, name);
return dlist_tomap(child, valp, lenp);
}
EXPORTED int dlist_getbuf(struct dlist *parent, const char *name,
struct buf *value)
{
const char *v = NULL;
size_t l = 0;
if (dlist_getmap(parent, name, &v, &l)) {
buf_init_ro(value, v, l);
return 1;
}
return 0;
}
int dlist_getfile(struct dlist *parent, const char *name,
const char **partp,
struct message_guid **guidp,
unsigned long *sizep,
const char **fnamep)
{
struct dlist *child = dlist_getchild(parent, name);
return dlist_tofile(child, partp, guidp, sizep, fnamep);
}
EXPORTED int dlist_getlist(struct dlist *dl, const char *name, struct dlist **valp)
{
struct dlist *i = dlist_getchild(dl, name);
if (!i) return 0;
*valp = i;
return 1;
}
EXPORTED const char *dlist_lastkey(void)
{
return lastkey;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2628_0 |
crossvul-cpp_data_bad_1752_1 | #include <ruby.h>
#include <fiddle.h>
VALUE rb_cHandle;
struct dl_handle {
void *ptr;
int open;
int enable_close;
};
#ifdef _WIN32
# ifndef _WIN32_WCE
static void *
w32_coredll(void)
{
MEMORY_BASIC_INFORMATION m;
memset(&m, 0, sizeof(m));
if( !VirtualQuery(_errno, &m, sizeof(m)) ) return NULL;
return m.AllocationBase;
}
# endif
static int
w32_dlclose(void *ptr)
{
# ifndef _WIN32_WCE
if( ptr == w32_coredll() ) return 0;
# endif
if( FreeLibrary((HMODULE)ptr) ) return 0;
return errno = rb_w32_map_errno(GetLastError());
}
#define dlclose(ptr) w32_dlclose(ptr)
#endif
static void
fiddle_handle_free(void *ptr)
{
struct dl_handle *fiddle_handle = ptr;
if( fiddle_handle->ptr && fiddle_handle->open && fiddle_handle->enable_close ){
dlclose(fiddle_handle->ptr);
}
xfree(ptr);
}
static size_t
fiddle_handle_memsize(const void *ptr)
{
return ptr ? sizeof(struct dl_handle) : 0;
}
static const rb_data_type_t fiddle_handle_data_type = {
"fiddle/handle",
{0, fiddle_handle_free, fiddle_handle_memsize,},
};
/*
* call-seq: close
*
* Close this handle.
*
* Calling close more than once will raise a Fiddle::DLError exception.
*/
static VALUE
rb_fiddle_handle_close(VALUE self)
{
struct dl_handle *fiddle_handle;
TypedData_Get_Struct(self, struct dl_handle, &fiddle_handle_data_type, fiddle_handle);
if(fiddle_handle->open) {
int ret = dlclose(fiddle_handle->ptr);
fiddle_handle->open = 0;
/* Check dlclose for successful return value */
if(ret) {
#if defined(HAVE_DLERROR)
rb_raise(rb_eFiddleError, "%s", dlerror());
#else
rb_raise(rb_eFiddleError, "could not close handle");
#endif
}
return INT2NUM(ret);
}
rb_raise(rb_eFiddleError, "dlclose() called too many times");
UNREACHABLE;
}
static VALUE
rb_fiddle_handle_s_allocate(VALUE klass)
{
VALUE obj;
struct dl_handle *fiddle_handle;
obj = TypedData_Make_Struct(rb_cHandle, struct dl_handle, &fiddle_handle_data_type, fiddle_handle);
fiddle_handle->ptr = 0;
fiddle_handle->open = 0;
fiddle_handle->enable_close = 0;
return obj;
}
static VALUE
predefined_fiddle_handle(void *handle)
{
VALUE obj = rb_fiddle_handle_s_allocate(rb_cHandle);
struct dl_handle *fiddle_handle = DATA_PTR(obj);
fiddle_handle->ptr = handle;
fiddle_handle->open = 1;
OBJ_FREEZE(obj);
return obj;
}
/*
* call-seq:
* new(library = nil, flags = Fiddle::RTLD_LAZY | Fiddle::RTLD_GLOBAL)
*
* Create a new handler that opens +library+ with +flags+.
*
* If no +library+ is specified or +nil+ is given, DEFAULT is used, which is
* the equivalent to RTLD_DEFAULT. See <code>man 3 dlopen</code> for more.
*
* lib = Fiddle::Handle.new
*
* The default is dependent on OS, and provide a handle for all libraries
* already loaded. For example, in most cases you can use this to access +libc+
* functions, or ruby functions like +rb_str_new+.
*/
static VALUE
rb_fiddle_handle_initialize(int argc, VALUE argv[], VALUE self)
{
void *ptr;
struct dl_handle *fiddle_handle;
VALUE lib, flag;
char *clib;
int cflag;
const char *err;
switch( rb_scan_args(argc, argv, "02", &lib, &flag) ){
case 0:
clib = NULL;
cflag = RTLD_LAZY | RTLD_GLOBAL;
break;
case 1:
clib = NIL_P(lib) ? NULL : StringValuePtr(lib);
cflag = RTLD_LAZY | RTLD_GLOBAL;
break;
case 2:
clib = NIL_P(lib) ? NULL : StringValuePtr(lib);
cflag = NUM2INT(flag);
break;
default:
rb_bug("rb_fiddle_handle_new");
}
rb_secure(2);
#if defined(_WIN32)
if( !clib ){
HANDLE rb_libruby_handle(void);
ptr = rb_libruby_handle();
}
else if( STRCASECMP(clib, "libc") == 0
# ifdef RUBY_COREDLL
|| STRCASECMP(clib, RUBY_COREDLL) == 0
|| STRCASECMP(clib, RUBY_COREDLL".dll") == 0
# endif
){
# ifdef _WIN32_WCE
ptr = dlopen("coredll.dll", cflag);
# else
ptr = w32_coredll();
# endif
}
else
#endif
ptr = dlopen(clib, cflag);
#if defined(HAVE_DLERROR)
if( !ptr && (err = dlerror()) ){
rb_raise(rb_eFiddleError, "%s", err);
}
#else
if( !ptr ){
err = dlerror();
rb_raise(rb_eFiddleError, "%s", err);
}
#endif
TypedData_Get_Struct(self, struct dl_handle, &fiddle_handle_data_type, fiddle_handle);
if( fiddle_handle->ptr && fiddle_handle->open && fiddle_handle->enable_close ){
dlclose(fiddle_handle->ptr);
}
fiddle_handle->ptr = ptr;
fiddle_handle->open = 1;
fiddle_handle->enable_close = 0;
if( rb_block_given_p() ){
rb_ensure(rb_yield, self, rb_fiddle_handle_close, self);
}
return Qnil;
}
/*
* call-seq: enable_close
*
* Enable a call to dlclose() when this handle is garbage collected.
*/
static VALUE
rb_fiddle_handle_enable_close(VALUE self)
{
struct dl_handle *fiddle_handle;
TypedData_Get_Struct(self, struct dl_handle, &fiddle_handle_data_type, fiddle_handle);
fiddle_handle->enable_close = 1;
return Qnil;
}
/*
* call-seq: disable_close
*
* Disable a call to dlclose() when this handle is garbage collected.
*/
static VALUE
rb_fiddle_handle_disable_close(VALUE self)
{
struct dl_handle *fiddle_handle;
TypedData_Get_Struct(self, struct dl_handle, &fiddle_handle_data_type, fiddle_handle);
fiddle_handle->enable_close = 0;
return Qnil;
}
/*
* call-seq: close_enabled?
*
* Returns +true+ if dlclose() will be called when this handle is garbage collected.
*
* See man(3) dlclose() for more info.
*/
static VALUE
rb_fiddle_handle_close_enabled_p(VALUE self)
{
struct dl_handle *fiddle_handle;
TypedData_Get_Struct(self, struct dl_handle, &fiddle_handle_data_type, fiddle_handle);
if(fiddle_handle->enable_close) return Qtrue;
return Qfalse;
}
/*
* call-seq: to_i
*
* Returns the memory address for this handle.
*/
static VALUE
rb_fiddle_handle_to_i(VALUE self)
{
struct dl_handle *fiddle_handle;
TypedData_Get_Struct(self, struct dl_handle, &fiddle_handle_data_type, fiddle_handle);
return PTR2NUM(fiddle_handle);
}
static VALUE fiddle_handle_sym(void *handle, const char *symbol);
/*
* Document-method: sym
*
* call-seq: sym(name)
*
* Get the address as an Integer for the function named +name+.
*/
static VALUE
rb_fiddle_handle_sym(VALUE self, VALUE sym)
{
struct dl_handle *fiddle_handle;
TypedData_Get_Struct(self, struct dl_handle, &fiddle_handle_data_type, fiddle_handle);
if( ! fiddle_handle->open ){
rb_raise(rb_eFiddleError, "closed handle");
}
return fiddle_handle_sym(fiddle_handle->ptr, StringValueCStr(sym));
}
#ifndef RTLD_NEXT
#define RTLD_NEXT NULL
#endif
#ifndef RTLD_DEFAULT
#define RTLD_DEFAULT NULL
#endif
/*
* Document-method: sym
*
* call-seq: sym(name)
*
* Get the address as an Integer for the function named +name+. The function
* is searched via dlsym on RTLD_NEXT.
*
* See man(3) dlsym() for more info.
*/
static VALUE
rb_fiddle_handle_s_sym(VALUE self, VALUE sym)
{
return fiddle_handle_sym(RTLD_NEXT, StringValueCStr(sym));
}
static VALUE
fiddle_handle_sym(void *handle, const char *name)
{
#if defined(HAVE_DLERROR)
const char *err;
# define CHECK_DLERROR if( err = dlerror() ){ func = 0; }
#else
# define CHECK_DLERROR
#endif
void (*func)();
rb_secure(2);
#ifdef HAVE_DLERROR
dlerror();
#endif
func = (void (*)())(VALUE)dlsym(handle, name);
CHECK_DLERROR;
#if defined(FUNC_STDCALL)
if( !func ){
int i;
int len = (int)strlen(name);
char *name_n;
#if defined(__CYGWIN__) || defined(_WIN32) || defined(__MINGW32__)
{
char *name_a = (char*)xmalloc(len+2);
strcpy(name_a, name);
name_n = name_a;
name_a[len] = 'A';
name_a[len+1] = '\0';
func = dlsym(handle, name_a);
CHECK_DLERROR;
if( func ) goto found;
name_n = xrealloc(name_a, len+6);
}
#else
name_n = (char*)xmalloc(len+6);
#endif
memcpy(name_n, name, len);
name_n[len++] = '@';
for( i = 0; i < 256; i += 4 ){
sprintf(name_n + len, "%d", i);
func = dlsym(handle, name_n);
CHECK_DLERROR;
if( func ) break;
}
if( func ) goto found;
name_n[len-1] = 'A';
name_n[len++] = '@';
for( i = 0; i < 256; i += 4 ){
sprintf(name_n + len, "%d", i);
func = dlsym(handle, name_n);
CHECK_DLERROR;
if( func ) break;
}
found:
xfree(name_n);
}
#endif
if( !func ){
rb_raise(rb_eFiddleError, "unknown symbol \"%s\"", name);
}
return PTR2NUM(func);
}
void
Init_fiddle_handle(void)
{
/*
* Document-class: Fiddle::Handle
*
* The Fiddle::Handle is the manner to access the dynamic library
*
* == Example
*
* === Setup
*
* libc_so = "/lib64/libc.so.6"
* => "/lib64/libc.so.6"
* @handle = Fiddle::Handle.new(libc_so)
* => #<Fiddle::Handle:0x00000000d69ef8>
*
* === Setup, with flags
*
* libc_so = "/lib64/libc.so.6"
* => "/lib64/libc.so.6"
* @handle = Fiddle::Handle.new(libc_so, Fiddle::RTLD_LAZY | Fiddle::RTLD_GLOBAL)
* => #<Fiddle::Handle:0x00000000d69ef8>
*
* See RTLD_LAZY and RTLD_GLOBAL
*
* === Addresses to symbols
*
* strcpy_addr = @handle['strcpy']
* => 140062278451968
*
* or
*
* strcpy_addr = @handle.sym('strcpy')
* => 140062278451968
*
*/
rb_cHandle = rb_define_class_under(mFiddle, "Handle", rb_cObject);
rb_define_alloc_func(rb_cHandle, rb_fiddle_handle_s_allocate);
rb_define_singleton_method(rb_cHandle, "sym", rb_fiddle_handle_s_sym, 1);
rb_define_singleton_method(rb_cHandle, "[]", rb_fiddle_handle_s_sym, 1);
/* Document-const: NEXT
*
* A predefined pseudo-handle of RTLD_NEXT
*
* Which will find the next occurrence of a function in the search order
* after the current library.
*/
rb_define_const(rb_cHandle, "NEXT", predefined_fiddle_handle(RTLD_NEXT));
/* Document-const: DEFAULT
*
* A predefined pseudo-handle of RTLD_DEFAULT
*
* Which will find the first occurrence of the desired symbol using the
* default library search order
*/
rb_define_const(rb_cHandle, "DEFAULT", predefined_fiddle_handle(RTLD_DEFAULT));
/* Document-const: RTLD_GLOBAL
*
* rtld Fiddle::Handle flag.
*
* The symbols defined by this library will be made available for symbol
* resolution of subsequently loaded libraries.
*/
rb_define_const(rb_cHandle, "RTLD_GLOBAL", INT2NUM(RTLD_GLOBAL));
/* Document-const: RTLD_LAZY
*
* rtld Fiddle::Handle flag.
*
* Perform lazy binding. Only resolve symbols as the code that references
* them is executed. If the symbol is never referenced, then it is never
* resolved. (Lazy binding is only performed for function references;
* references to variables are always immediately bound when the library
* is loaded.)
*/
rb_define_const(rb_cHandle, "RTLD_LAZY", INT2NUM(RTLD_LAZY));
/* Document-const: RTLD_NOW
*
* rtld Fiddle::Handle flag.
*
* If this value is specified or the environment variable LD_BIND_NOW is
* set to a nonempty string, all undefined symbols in the library are
* resolved before Fiddle.dlopen returns. If this cannot be done an error
* is returned.
*/
rb_define_const(rb_cHandle, "RTLD_NOW", INT2NUM(RTLD_NOW));
rb_define_method(rb_cHandle, "initialize", rb_fiddle_handle_initialize, -1);
rb_define_method(rb_cHandle, "to_i", rb_fiddle_handle_to_i, 0);
rb_define_method(rb_cHandle, "close", rb_fiddle_handle_close, 0);
rb_define_method(rb_cHandle, "sym", rb_fiddle_handle_sym, 1);
rb_define_method(rb_cHandle, "[]", rb_fiddle_handle_sym, 1);
rb_define_method(rb_cHandle, "disable_close", rb_fiddle_handle_disable_close, 0);
rb_define_method(rb_cHandle, "enable_close", rb_fiddle_handle_enable_close, 0);
rb_define_method(rb_cHandle, "close_enabled?", rb_fiddle_handle_close_enabled_p, 0);
}
/* vim: set noet sws=4 sw=4: */
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1752_1 |
crossvul-cpp_data_good_245_0 | /**
* @file
* Send/receive commands to/from an IMAP server
*
* @authors
* Copyright (C) 1996-1998,2010,2012 Michael R. Elkins <me@mutt.org>
* Copyright (C) 1996-1999 Brandon Long <blong@fiction.net>
* Copyright (C) 1999-2009,2011 Brendan Cully <brendan@kublai.com>
*
* @copyright
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @page imap_command Send/receive commands to/from an IMAP server
*
* Send/receive commands to/from an IMAP server
*/
#include "config.h"
#include <ctype.h>
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "imap_private.h"
#include "mutt/mutt.h"
#include "conn/conn.h"
#include "buffy.h"
#include "context.h"
#include "globals.h"
#include "header.h"
#include "imap/imap.h"
#include "mailbox.h"
#include "message.h"
#include "mutt_account.h"
#include "mutt_menu.h"
#include "mutt_socket.h"
#include "mx.h"
#include "options.h"
#include "protos.h"
#include "url.h"
#define IMAP_CMD_BUFSIZE 512
/**
* Capabilities - Server capabilities strings that we understand
*
* @note This must be kept in the same order as ImapCaps.
*
* @note Gmail documents one string but use another, so we support both.
*/
static const char *const Capabilities[] = {
"IMAP4", "IMAP4rev1", "STATUS", "ACL",
"NAMESPACE", "AUTH=CRAM-MD5", "AUTH=GSSAPI", "AUTH=ANONYMOUS",
"STARTTLS", "LOGINDISABLED", "IDLE", "SASL-IR",
"ENABLE", "X-GM-EXT-1", "X-GM-EXT1", NULL,
};
/**
* cmd_queue_full - Is the IMAP command queue full?
* @param idata Server data
* @retval true Queue is full
*/
static bool cmd_queue_full(struct ImapData *idata)
{
if ((idata->nextcmd + 1) % idata->cmdslots == idata->lastcmd)
return true;
return false;
}
/**
* cmd_new - Create and queue a new command control block
* @param idata IMAP data
* @retval NULL if the pipeline is full
* @retval ptr New command
*/
static struct ImapCommand *cmd_new(struct ImapData *idata)
{
struct ImapCommand *cmd = NULL;
if (cmd_queue_full(idata))
{
mutt_debug(3, "IMAP command queue full\n");
return NULL;
}
cmd = idata->cmds + idata->nextcmd;
idata->nextcmd = (idata->nextcmd + 1) % idata->cmdslots;
snprintf(cmd->seq, sizeof(cmd->seq), "a%04u", idata->seqno++);
if (idata->seqno > 9999)
idata->seqno = 0;
cmd->state = IMAP_CMD_NEW;
return cmd;
}
/**
* cmd_queue - Add a IMAP command to the queue
* @param idata Server data
* @param cmdstr Command string
* @param flags Server flags, e.g. #IMAP_CMD_POLL
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*
* If the queue is full, attempts to drain it.
*/
static int cmd_queue(struct ImapData *idata, const char *cmdstr, int flags)
{
if (cmd_queue_full(idata))
{
mutt_debug(3, "Draining IMAP command pipeline\n");
const int rc = imap_exec(idata, NULL, IMAP_CMD_FAIL_OK | (flags & IMAP_CMD_POLL));
if (rc < 0 && rc != -2)
return rc;
}
struct ImapCommand *cmd = cmd_new(idata);
if (!cmd)
return IMAP_CMD_BAD;
if (mutt_buffer_printf(idata->cmdbuf, "%s %s\r\n", cmd->seq, cmdstr) < 0)
return IMAP_CMD_BAD;
return 0;
}
/**
* cmd_handle_fatal - When ImapData is in fatal state, do what we can
* @param idata Server data
*/
static void cmd_handle_fatal(struct ImapData *idata)
{
idata->status = IMAP_FATAL;
if ((idata->state >= IMAP_SELECTED) && (idata->reopen & IMAP_REOPEN_ALLOW))
{
mx_fastclose_mailbox(idata->ctx);
mutt_socket_close(idata->conn);
mutt_error(_("Mailbox %s@%s closed"), idata->conn->account.login,
idata->conn->account.host);
idata->state = IMAP_DISCONNECTED;
}
imap_close_connection(idata);
if (!idata->recovering)
{
idata->recovering = true;
if (imap_conn_find(&idata->conn->account, 0))
mutt_clear_error();
idata->recovering = false;
}
}
/**
* cmd_start - Start a new IMAP command
* @param idata Server data
* @param cmdstr Command string
* @param flags Command flags, e.g. #IMAP_CMD_QUEUE
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*/
static int cmd_start(struct ImapData *idata, const char *cmdstr, int flags)
{
int rc;
if (idata->status == IMAP_FATAL)
{
cmd_handle_fatal(idata);
return -1;
}
if (cmdstr && ((rc = cmd_queue(idata, cmdstr, flags)) < 0))
return rc;
if (flags & IMAP_CMD_QUEUE)
return 0;
if (idata->cmdbuf->dptr == idata->cmdbuf->data)
return IMAP_CMD_BAD;
rc = mutt_socket_send_d(idata->conn, idata->cmdbuf->data,
(flags & IMAP_CMD_PASS) ? IMAP_LOG_PASS : IMAP_LOG_CMD);
idata->cmdbuf->dptr = idata->cmdbuf->data;
/* unidle when command queue is flushed */
if (idata->state == IMAP_IDLE)
idata->state = IMAP_SELECTED;
return (rc < 0) ? IMAP_CMD_BAD : 0;
}
/**
* cmd_status - parse response line for tagged OK/NO/BAD
* @param s Status string from server
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*/
static int cmd_status(const char *s)
{
s = imap_next_word((char *) s);
if (mutt_str_strncasecmp("OK", s, 2) == 0)
return IMAP_CMD_OK;
if (mutt_str_strncasecmp("NO", s, 2) == 0)
return IMAP_CMD_NO;
return IMAP_CMD_BAD;
}
/**
* cmd_parse_expunge - Parse expunge command
* @param idata Server data
* @param s String containing MSN of message to expunge
*
* cmd_parse_expunge: mark headers with new sequence ID and mark idata to be
* reopened at our earliest convenience
*/
static void cmd_parse_expunge(struct ImapData *idata, const char *s)
{
unsigned int exp_msn;
struct Header *h = NULL;
mutt_debug(2, "Handling EXPUNGE\n");
if (mutt_str_atoui(s, &exp_msn) < 0 || exp_msn < 1 || exp_msn > idata->max_msn)
return;
h = idata->msn_index[exp_msn - 1];
if (h)
{
/* imap_expunge_mailbox() will rewrite h->index.
* It needs to resort using SORT_ORDER anyway, so setting to INT_MAX
* makes the code simpler and possibly more efficient. */
h->index = INT_MAX;
HEADER_DATA(h)->msn = 0;
}
/* decrement seqno of those above. */
for (unsigned int cur = exp_msn; cur < idata->max_msn; cur++)
{
h = idata->msn_index[cur];
if (h)
HEADER_DATA(h)->msn--;
idata->msn_index[cur - 1] = h;
}
idata->msn_index[idata->max_msn - 1] = NULL;
idata->max_msn--;
idata->reopen |= IMAP_EXPUNGE_PENDING;
}
/**
* cmd_parse_fetch - Load fetch response into ImapData
* @param idata Server data
* @param s String containing MSN of message to fetch
*
* Currently only handles unanticipated FETCH responses, and only FLAGS data.
* We get these if another client has changed flags for a mailbox we've
* selected. Of course, a lot of code here duplicates code in message.c.
*/
static void cmd_parse_fetch(struct ImapData *idata, char *s)
{
unsigned int msn, uid;
struct Header *h = NULL;
int server_changes = 0;
mutt_debug(3, "Handling FETCH\n");
if (mutt_str_atoui(s, &msn) < 0 || msn < 1 || msn > idata->max_msn)
{
mutt_debug(3, "#1 FETCH response ignored for this message\n");
return;
}
h = idata->msn_index[msn - 1];
if (!h || !h->active)
{
mutt_debug(3, "#2 FETCH response ignored for this message\n");
return;
}
mutt_debug(2, "Message UID %u updated\n", HEADER_DATA(h)->uid);
/* skip FETCH */
s = imap_next_word(s);
s = imap_next_word(s);
if (*s != '(')
{
mutt_debug(1, "Malformed FETCH response\n");
return;
}
s++;
while (*s)
{
SKIPWS(s);
if (mutt_str_strncasecmp("FLAGS", s, 5) == 0)
{
imap_set_flags(idata, h, s, &server_changes);
if (server_changes)
{
/* If server flags could conflict with neomutt's flags, reopen the mailbox. */
if (h->changed)
idata->reopen |= IMAP_EXPUNGE_PENDING;
else
idata->check_status = IMAP_FLAGS_PENDING;
}
return;
}
else if (mutt_str_strncasecmp("UID", s, 3) == 0)
{
s += 3;
SKIPWS(s);
if (mutt_str_atoui(s, &uid) < 0)
{
mutt_debug(2, "Illegal UID. Skipping update.\n");
return;
}
if (uid != HEADER_DATA(h)->uid)
{
mutt_debug(2, "FETCH UID vs MSN mismatch. Skipping update.\n");
return;
}
s = imap_next_word(s);
}
else if (*s == ')')
s++; /* end of request */
else if (*s)
{
mutt_debug(2, "Only handle FLAGS updates\n");
return;
}
}
}
/**
* cmd_parse_capability - set capability bits according to CAPABILITY response
* @param idata Server data
* @param s Command string with capabilities
*/
static void cmd_parse_capability(struct ImapData *idata, char *s)
{
mutt_debug(3, "Handling CAPABILITY\n");
s = imap_next_word(s);
char *bracket = strchr(s, ']');
if (bracket)
*bracket = '\0';
FREE(&idata->capstr);
idata->capstr = mutt_str_strdup(s);
memset(idata->capabilities, 0, sizeof(idata->capabilities));
while (*s)
{
for (int i = 0; i < CAPMAX; i++)
{
if (mutt_str_word_casecmp(Capabilities[i], s) == 0)
{
mutt_bit_set(idata->capabilities, i);
mutt_debug(4, " Found capability \"%s\": %d\n", Capabilities[i], i);
break;
}
}
s = imap_next_word(s);
}
}
/**
* cmd_parse_list - Parse a server LIST command (list mailboxes)
* @param idata Server data
* @param s Command string with folder list
*/
static void cmd_parse_list(struct ImapData *idata, char *s)
{
struct ImapList *list = NULL;
struct ImapList lb;
char delimbuf[5]; /* worst case: "\\"\0 */
unsigned int litlen;
if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST)
list = (struct ImapList *) idata->cmddata;
else
list = &lb;
memset(list, 0, sizeof(struct ImapList));
/* flags */
s = imap_next_word(s);
if (*s != '(')
{
mutt_debug(1, "Bad LIST response\n");
return;
}
s++;
while (*s)
{
if (mutt_str_strncasecmp(s, "\\NoSelect", 9) == 0)
list->noselect = true;
else if (mutt_str_strncasecmp(s, "\\NoInferiors", 12) == 0)
list->noinferiors = true;
/* See draft-gahrns-imap-child-mailbox-?? */
else if (mutt_str_strncasecmp(s, "\\HasNoChildren", 14) == 0)
list->noinferiors = true;
s = imap_next_word(s);
if (*(s - 2) == ')')
break;
}
/* Delimiter */
if (mutt_str_strncasecmp(s, "NIL", 3) != 0)
{
delimbuf[0] = '\0';
mutt_str_strcat(delimbuf, 5, s);
imap_unquote_string(delimbuf);
list->delim = delimbuf[0];
}
/* Name */
s = imap_next_word(s);
/* Notes often responds with literals here. We need a real tokenizer. */
if (imap_get_literal_count(s, &litlen) == 0)
{
if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE)
{
idata->status = IMAP_FATAL;
return;
}
list->name = idata->buf;
}
else
{
imap_unmunge_mbox_name(idata, s);
list->name = s;
}
if (list->name[0] == '\0')
{
idata->delim = list->delim;
mutt_debug(3, "Root delimiter: %c\n", idata->delim);
}
}
/**
* cmd_parse_lsub - Parse a server LSUB (list subscribed mailboxes)
* @param idata Server data
* @param s Command string with folder list
*/
static void cmd_parse_lsub(struct ImapData *idata, char *s)
{
char buf[STRING];
char errstr[STRING];
struct Buffer err, token;
struct Url url;
struct ImapList list;
if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST)
{
/* caller will handle response itself */
cmd_parse_list(idata, s);
return;
}
if (!ImapCheckSubscribed)
return;
idata->cmdtype = IMAP_CT_LIST;
idata->cmddata = &list;
cmd_parse_list(idata, s);
idata->cmddata = NULL;
/* noselect is for a gmail quirk (#3445) */
if (!list.name || list.noselect)
return;
mutt_debug(3, "Subscribing to %s\n", list.name);
mutt_str_strfcpy(buf, "mailboxes \"", sizeof(buf));
mutt_account_tourl(&idata->conn->account, &url);
/* escape \ and " */
imap_quote_string(errstr, sizeof(errstr), list.name, true);
url.path = errstr + 1;
url.path[strlen(url.path) - 1] = '\0';
if (mutt_str_strcmp(url.user, ImapUser) == 0)
url.user = NULL;
url_tostring(&url, buf + 11, sizeof(buf) - 11, 0);
mutt_str_strcat(buf, sizeof(buf), "\"");
mutt_buffer_init(&token);
mutt_buffer_init(&err);
err.data = errstr;
err.dsize = sizeof(errstr);
if (mutt_parse_rc_line(buf, &token, &err))
mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr);
FREE(&token.data);
}
/**
* cmd_parse_myrights - Set rights bits according to MYRIGHTS response
* @param idata Server data
* @param s Command string with rights info
*/
static void cmd_parse_myrights(struct ImapData *idata, const char *s)
{
mutt_debug(2, "Handling MYRIGHTS\n");
s = imap_next_word((char *) s);
s = imap_next_word((char *) s);
/* zero out current rights set */
memset(idata->ctx->rights, 0, sizeof(idata->ctx->rights));
while (*s && !isspace((unsigned char) *s))
{
switch (*s)
{
case 'a':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_ADMIN);
break;
case 'e':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_EXPUNGE);
break;
case 'i':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_INSERT);
break;
case 'k':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_CREATE);
break;
case 'l':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_LOOKUP);
break;
case 'p':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_POST);
break;
case 'r':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_READ);
break;
case 's':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_SEEN);
break;
case 't':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELETE);
break;
case 'w':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_WRITE);
break;
case 'x':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELMX);
break;
/* obsolete rights */
case 'c':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_CREATE);
mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELMX);
break;
case 'd':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELETE);
mutt_bit_set(idata->ctx->rights, MUTT_ACL_EXPUNGE);
break;
default:
mutt_debug(1, "Unknown right: %c\n", *s);
}
s++;
}
}
/**
* cmd_parse_search - store SEARCH response for later use
* @param idata Server data
* @param s Command string with search results
*/
static void cmd_parse_search(struct ImapData *idata, const char *s)
{
unsigned int uid;
struct Header *h = NULL;
mutt_debug(2, "Handling SEARCH\n");
while ((s = imap_next_word((char *) s)) && *s != '\0')
{
if (mutt_str_atoui(s, &uid) < 0)
continue;
h = (struct Header *) mutt_hash_int_find(idata->uid_hash, uid);
if (h)
h->matched = true;
}
}
/**
* cmd_parse_status - Parse status from server
* @param idata Server data
* @param s Command string with status info
*
* first cut: just do buffy update. Later we may wish to cache all mailbox
* information, even that not desired by buffy
*/
static void cmd_parse_status(struct ImapData *idata, char *s)
{
char *value = NULL;
struct Buffy *inc = NULL;
struct ImapMbox mx;
struct ImapStatus *status = NULL;
unsigned int olduv, oldun;
unsigned int litlen;
short new = 0;
short new_msg_count = 0;
char *mailbox = imap_next_word(s);
/* We need a real tokenizer. */
if (imap_get_literal_count(mailbox, &litlen) == 0)
{
if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE)
{
idata->status = IMAP_FATAL;
return;
}
if (strlen(idata->buf) < litlen)
{
mutt_debug(1, "Error parsing STATUS mailbox\n");
return;
}
mailbox = idata->buf;
s = mailbox + litlen;
*s = '\0';
s++;
SKIPWS(s);
}
else
{
s = imap_next_word(mailbox);
*(s - 1) = '\0';
imap_unmunge_mbox_name(idata, mailbox);
}
status = imap_mboxcache_get(idata, mailbox, 1);
olduv = status->uidvalidity;
oldun = status->uidnext;
if (*s++ != '(')
{
mutt_debug(1, "Error parsing STATUS\n");
return;
}
while (*s && *s != ')')
{
value = imap_next_word(s);
errno = 0;
const unsigned long ulcount = strtoul(value, &value, 10);
if (((errno == ERANGE) && (ulcount == ULONG_MAX)) || ((unsigned int) ulcount != ulcount))
{
mutt_debug(1, "Error parsing STATUS number\n");
return;
}
const unsigned int count = (unsigned int) ulcount;
if (mutt_str_strncmp("MESSAGES", s, 8) == 0)
{
status->messages = count;
new_msg_count = 1;
}
else if (mutt_str_strncmp("RECENT", s, 6) == 0)
status->recent = count;
else if (mutt_str_strncmp("UIDNEXT", s, 7) == 0)
status->uidnext = count;
else if (mutt_str_strncmp("UIDVALIDITY", s, 11) == 0)
status->uidvalidity = count;
else if (mutt_str_strncmp("UNSEEN", s, 6) == 0)
status->unseen = count;
s = value;
if (*s && *s != ')')
s = imap_next_word(s);
}
mutt_debug(3, "%s (UIDVALIDITY: %u, UIDNEXT: %u) %d messages, %d recent, %d unseen\n",
status->name, status->uidvalidity, status->uidnext,
status->messages, status->recent, status->unseen);
/* caller is prepared to handle the result herself */
if (idata->cmddata && idata->cmdtype == IMAP_CT_STATUS)
{
memcpy(idata->cmddata, status, sizeof(struct ImapStatus));
return;
}
mutt_debug(3, "Running default STATUS handler\n");
/* should perhaps move this code back to imap_buffy_check */
for (inc = Incoming; inc; inc = inc->next)
{
if (inc->magic != MUTT_IMAP)
continue;
if (imap_parse_path(inc->path, &mx) < 0)
{
mutt_debug(1, "Error parsing mailbox %s, skipping\n", inc->path);
continue;
}
if (imap_account_match(&idata->conn->account, &mx.account))
{
if (mx.mbox)
{
value = mutt_str_strdup(mx.mbox);
imap_fix_path(idata, mx.mbox, value, mutt_str_strlen(value) + 1);
FREE(&mx.mbox);
}
else
value = mutt_str_strdup("INBOX");
if (value && (imap_mxcmp(mailbox, value) == 0))
{
mutt_debug(3, "Found %s in buffy list (OV: %u ON: %u U: %d)\n", mailbox,
olduv, oldun, status->unseen);
if (MailCheckRecent)
{
if (olduv && olduv == status->uidvalidity)
{
if (oldun < status->uidnext)
new = (status->unseen > 0);
}
else if (!olduv && !oldun)
{
/* first check per session, use recent. might need a flag for this. */
new = (status->recent > 0);
}
else
new = (status->unseen > 0);
}
else
new = (status->unseen > 0);
#ifdef USE_SIDEBAR
if ((inc->new != new) || (inc->msg_count != status->messages) ||
(inc->msg_unread != status->unseen))
{
mutt_menu_set_current_redraw(REDRAW_SIDEBAR);
}
#endif
inc->new = new;
if (new_msg_count)
inc->msg_count = status->messages;
inc->msg_unread = status->unseen;
if (inc->new)
{
/* force back to keep detecting new mail until the mailbox is
opened */
status->uidnext = oldun;
}
FREE(&value);
return;
}
FREE(&value);
}
FREE(&mx.mbox);
}
}
/**
* cmd_parse_enabled - Record what the server has enabled
* @param idata Server data
* @param s Command string containing acceptable encodings
*/
static void cmd_parse_enabled(struct ImapData *idata, const char *s)
{
mutt_debug(2, "Handling ENABLED\n");
while ((s = imap_next_word((char *) s)) && *s != '\0')
{
if ((mutt_str_strncasecmp(s, "UTF8=ACCEPT", 11) == 0) ||
(mutt_str_strncasecmp(s, "UTF8=ONLY", 9) == 0))
{
idata->unicode = 1;
}
}
}
/**
* cmd_handle_untagged - fallback parser for otherwise unhandled messages
* @param idata Server data
* @retval 0 Success
* @retval -1 Failure
*/
static int cmd_handle_untagged(struct ImapData *idata)
{
unsigned int count = 0;
char *s = imap_next_word(idata->buf);
char *pn = imap_next_word(s);
if ((idata->state >= IMAP_SELECTED) && isdigit((unsigned char) *s))
{
pn = s;
s = imap_next_word(s);
/* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the
* connection, so update that one.
*/
if (mutt_str_strncasecmp("EXISTS", s, 6) == 0)
{
mutt_debug(2, "Handling EXISTS\n");
/* new mail arrived */
if (mutt_str_atoui(pn, &count) < 0)
{
mutt_debug(1, "Malformed EXISTS: '%s'\n", pn);
}
if (!(idata->reopen & IMAP_EXPUNGE_PENDING) && count < idata->max_msn)
{
/* Notes 6.0.3 has a tendency to report fewer messages exist than
* it should. */
mutt_debug(1, "Message count is out of sync\n");
return 0;
}
/* at least the InterChange server sends EXISTS messages freely,
* even when there is no new mail */
else if (count == idata->max_msn)
mutt_debug(3, "superfluous EXISTS message.\n");
else
{
if (!(idata->reopen & IMAP_EXPUNGE_PENDING))
{
mutt_debug(2, "New mail in %s - %d messages total.\n", idata->mailbox, count);
idata->reopen |= IMAP_NEWMAIL_PENDING;
}
idata->new_mail_count = count;
}
}
/* pn vs. s: need initial seqno */
else if (mutt_str_strncasecmp("EXPUNGE", s, 7) == 0)
cmd_parse_expunge(idata, pn);
else if (mutt_str_strncasecmp("FETCH", s, 5) == 0)
cmd_parse_fetch(idata, pn);
}
else if (mutt_str_strncasecmp("CAPABILITY", s, 10) == 0)
cmd_parse_capability(idata, s);
else if (mutt_str_strncasecmp("OK [CAPABILITY", s, 14) == 0)
cmd_parse_capability(idata, pn);
else if (mutt_str_strncasecmp("OK [CAPABILITY", pn, 14) == 0)
cmd_parse_capability(idata, imap_next_word(pn));
else if (mutt_str_strncasecmp("LIST", s, 4) == 0)
cmd_parse_list(idata, s);
else if (mutt_str_strncasecmp("LSUB", s, 4) == 0)
cmd_parse_lsub(idata, s);
else if (mutt_str_strncasecmp("MYRIGHTS", s, 8) == 0)
cmd_parse_myrights(idata, s);
else if (mutt_str_strncasecmp("SEARCH", s, 6) == 0)
cmd_parse_search(idata, s);
else if (mutt_str_strncasecmp("STATUS", s, 6) == 0)
cmd_parse_status(idata, s);
else if (mutt_str_strncasecmp("ENABLED", s, 7) == 0)
cmd_parse_enabled(idata, s);
else if (mutt_str_strncasecmp("BYE", s, 3) == 0)
{
mutt_debug(2, "Handling BYE\n");
/* check if we're logging out */
if (idata->status == IMAP_BYE)
return 0;
/* server shut down our connection */
s += 3;
SKIPWS(s);
mutt_error("%s", s);
cmd_handle_fatal(idata);
return -1;
}
else if (ImapServernoise && (mutt_str_strncasecmp("NO", s, 2) == 0))
{
mutt_debug(2, "Handling untagged NO\n");
/* Display the warning message from the server */
mutt_error("%s", s + 2);
}
return 0;
}
/**
* imap_cmd_start - Given an IMAP command, send it to the server
* @param idata Server data
* @param cmdstr Command string to send
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*
* If cmdstr is NULL, sends queued commands.
*/
int imap_cmd_start(struct ImapData *idata, const char *cmdstr)
{
return cmd_start(idata, cmdstr, 0);
}
/**
* imap_cmd_step - Reads server responses from an IMAP command
* @param idata Server data
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*
* detects tagged completion response, handles untagged messages, can read
* arbitrarily large strings (using malloc, so don't make it _too_ large!).
*/
int imap_cmd_step(struct ImapData *idata)
{
size_t len = 0;
int c;
int rc;
int stillrunning = 0;
struct ImapCommand *cmd = NULL;
if (idata->status == IMAP_FATAL)
{
cmd_handle_fatal(idata);
return IMAP_CMD_BAD;
}
/* read into buffer, expanding buffer as necessary until we have a full
* line */
do
{
if (len == idata->blen)
{
mutt_mem_realloc(&idata->buf, idata->blen + IMAP_CMD_BUFSIZE);
idata->blen = idata->blen + IMAP_CMD_BUFSIZE;
mutt_debug(3, "grew buffer to %u bytes\n", idata->blen);
}
/* back up over '\0' */
if (len)
len--;
c = mutt_socket_readln(idata->buf + len, idata->blen - len, idata->conn);
if (c <= 0)
{
mutt_debug(1, "Error reading server response.\n");
cmd_handle_fatal(idata);
return IMAP_CMD_BAD;
}
len += c;
}
/* if we've read all the way to the end of the buffer, we haven't read a
* full line (mutt_socket_readln strips the \r, so we always have at least
* one character free when we've read a full line) */
while (len == idata->blen);
/* don't let one large string make cmd->buf hog memory forever */
if ((idata->blen > IMAP_CMD_BUFSIZE) && (len <= IMAP_CMD_BUFSIZE))
{
mutt_mem_realloc(&idata->buf, IMAP_CMD_BUFSIZE);
idata->blen = IMAP_CMD_BUFSIZE;
mutt_debug(3, "shrank buffer to %u bytes\n", idata->blen);
}
idata->lastread = time(NULL);
/* handle untagged messages. The caller still gets its shot afterwards. */
if (((mutt_str_strncmp(idata->buf, "* ", 2) == 0) ||
(mutt_str_strncmp(imap_next_word(idata->buf), "OK [", 4) == 0)) &&
cmd_handle_untagged(idata))
{
return IMAP_CMD_BAD;
}
/* server demands a continuation response from us */
if (idata->buf[0] == '+')
return IMAP_CMD_RESPOND;
/* Look for tagged command completions.
*
* Some response handlers can end up recursively calling
* imap_cmd_step() and end up handling all tagged command
* completions.
* (e.g. FETCH->set_flag->set_header_color->~h pattern match.)
*
* Other callers don't even create an idata->cmds entry.
*
* For both these cases, we default to returning OK */
rc = IMAP_CMD_OK;
c = idata->lastcmd;
do
{
cmd = &idata->cmds[c];
if (cmd->state == IMAP_CMD_NEW)
{
if (mutt_str_strncmp(idata->buf, cmd->seq, SEQLEN) == 0)
{
if (!stillrunning)
{
/* first command in queue has finished - move queue pointer up */
idata->lastcmd = (idata->lastcmd + 1) % idata->cmdslots;
}
cmd->state = cmd_status(idata->buf);
/* bogus - we don't know which command result to return here. Caller
* should provide a tag. */
rc = cmd->state;
}
else
stillrunning++;
}
c = (c + 1) % idata->cmdslots;
} while (c != idata->nextcmd);
if (stillrunning)
rc = IMAP_CMD_CONTINUE;
else
{
mutt_debug(3, "IMAP queue drained\n");
imap_cmd_finish(idata);
}
return rc;
}
/**
* imap_code - Was the command successful
* @param s IMAP command status
* @retval 1 Command result was OK
* @retval 0 If NO or BAD
*/
bool imap_code(const char *s)
{
return (cmd_status(s) == IMAP_CMD_OK);
}
/**
* imap_cmd_trailer - Extra information after tagged command response if any
* @param idata Server data
* @retval ptr Extra command information (pointer into idata->buf)
* @retval "" Error (static string)
*/
const char *imap_cmd_trailer(struct ImapData *idata)
{
static const char *notrailer = "";
const char *s = idata->buf;
if (!s)
{
mutt_debug(2, "not a tagged response\n");
return notrailer;
}
s = imap_next_word((char *) s);
if (!s || ((mutt_str_strncasecmp(s, "OK", 2) != 0) &&
(mutt_str_strncasecmp(s, "NO", 2) != 0) &&
(mutt_str_strncasecmp(s, "BAD", 3) != 0)))
{
mutt_debug(2, "not a command completion: %s\n", idata->buf);
return notrailer;
}
s = imap_next_word((char *) s);
if (!s)
return notrailer;
return s;
}
/**
* imap_exec - Execute a command and wait for the response from the server
* @param idata IMAP data
* @param cmdstr Command to execute
* @param flags Flags (see below)
* @retval 0 Success
* @retval -1 Failure
* @retval -2 OK Failure
*
* Also, handle untagged responses.
*
* Flags:
* * IMAP_CMD_FAIL_OK: the calling procedure can handle failure.
* This is used for checking for a mailbox on append and login
* * IMAP_CMD_PASS: command contains a password. Suppress logging.
* * IMAP_CMD_QUEUE: only queue command, do not execute.
* * IMAP_CMD_POLL: poll the socket for a response before running imap_cmd_step.
*/
int imap_exec(struct ImapData *idata, const char *cmdstr, int flags)
{
int rc;
rc = cmd_start(idata, cmdstr, flags);
if (rc < 0)
{
cmd_handle_fatal(idata);
return -1;
}
if (flags & IMAP_CMD_QUEUE)
return 0;
if ((flags & IMAP_CMD_POLL) && (ImapPollTimeout > 0) &&
(mutt_socket_poll(idata->conn, ImapPollTimeout)) == 0)
{
mutt_error(_("Connection to %s timed out"), idata->conn->account.host);
cmd_handle_fatal(idata);
return -1;
}
/* Allow interruptions, particularly useful if there are network problems. */
mutt_sig_allow_interrupt(1);
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
mutt_sig_allow_interrupt(0);
if (rc == IMAP_CMD_NO && (flags & IMAP_CMD_FAIL_OK))
return -2;
if (rc != IMAP_CMD_OK)
{
if ((flags & IMAP_CMD_FAIL_OK) && idata->status != IMAP_FATAL)
return -2;
mutt_debug(1, "command failed: %s\n", idata->buf);
return -1;
}
return 0;
}
/**
* imap_cmd_finish - Attempt to perform cleanup
* @param idata Server data
*
* Attempts to perform cleanup (eg fetch new mail if detected, do expunge).
* Called automatically by imap_cmd_step(), but may be called at any time.
* Called by imap_check_mailbox() just before the index is refreshed, for
* instance.
*/
void imap_cmd_finish(struct ImapData *idata)
{
if (idata->status == IMAP_FATAL)
{
cmd_handle_fatal(idata);
return;
}
if (!(idata->state >= IMAP_SELECTED) || idata->ctx->closing)
return;
if (idata->reopen & IMAP_REOPEN_ALLOW)
{
unsigned int count = idata->new_mail_count;
if (!(idata->reopen & IMAP_EXPUNGE_PENDING) &&
(idata->reopen & IMAP_NEWMAIL_PENDING) && count > idata->max_msn)
{
/* read new mail messages */
mutt_debug(2, "Fetching new mail\n");
/* check_status: curs_main uses imap_check_mailbox to detect
* whether the index needs updating */
idata->check_status = IMAP_NEWMAIL_PENDING;
imap_read_headers(idata, idata->max_msn + 1, count);
}
else if (idata->reopen & IMAP_EXPUNGE_PENDING)
{
mutt_debug(2, "Expunging mailbox\n");
imap_expunge_mailbox(idata);
/* Detect whether we've gotten unexpected EXPUNGE messages */
if ((idata->reopen & IMAP_EXPUNGE_PENDING) && !(idata->reopen & IMAP_EXPUNGE_EXPECTED))
idata->check_status = IMAP_EXPUNGE_PENDING;
idata->reopen &=
~(IMAP_EXPUNGE_PENDING | IMAP_NEWMAIL_PENDING | IMAP_EXPUNGE_EXPECTED);
}
}
idata->status = false;
}
/**
* imap_cmd_idle - Enter the IDLE state
* @param idata Server data
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*/
int imap_cmd_idle(struct ImapData *idata)
{
int rc;
if (cmd_start(idata, "IDLE", IMAP_CMD_POLL) < 0)
{
cmd_handle_fatal(idata);
return -1;
}
if ((ImapPollTimeout > 0) && (mutt_socket_poll(idata->conn, ImapPollTimeout)) == 0)
{
mutt_error(_("Connection to %s timed out"), idata->conn->account.host);
cmd_handle_fatal(idata);
return -1;
}
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
if (rc == IMAP_CMD_RESPOND)
{
/* successfully entered IDLE state */
idata->state = IMAP_IDLE;
/* queue automatic exit when next command is issued */
mutt_buffer_printf(idata->cmdbuf, "DONE\r\n");
rc = IMAP_CMD_OK;
}
if (rc != IMAP_CMD_OK)
{
mutt_debug(1, "error starting IDLE\n");
return -1;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_245_0 |
crossvul-cpp_data_good_4900_0 | /* vi:set ts=8 sts=4 sw=4 noet:
*
* VIM - Vi IMproved by Bram Moolenaar
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
/*
* Code to handle user-settable options. This is all pretty much table-
* driven. Checklist for adding a new option:
* - Put it in the options array below (copy an existing entry).
* - For a global option: Add a variable for it in option.h.
* - For a buffer or window local option:
* - Add a PV_XX entry to the enum below.
* - Add a variable to the window or buffer struct in structs.h.
* - For a window option, add some code to copy_winopt().
* - For a buffer option, add some code to buf_copy_options().
* - For a buffer string option, add code to check_buf_options().
* - If it's a numeric option, add any necessary bounds checks to do_set().
* - If it's a list of flags, add some code in do_set(), search for WW_ALL.
* - When adding an option with expansion (P_EXPAND), but with a different
* default for Vi and Vim (no P_VI_DEF), add some code at VIMEXP.
* - Add documentation! One line in doc/quickref.txt, full description in
* options.txt, and any other related places.
* - Add an entry in runtime/optwin.vim.
* When making changes:
* - Adjust the help for the option in doc/option.txt.
* - When an entry has the P_VIM flag, or is lacking the P_VI_DEF flag, add a
* comment at the help for the 'compatible' option.
*/
#define IN_OPTION_C
#include "vim.h"
/*
* The options that are local to a window or buffer have "indir" set to one of
* these values. Special values:
* PV_NONE: global option.
* PV_WIN is added: window-local option
* PV_BUF is added: buffer-local option
* PV_BOTH is added: global option which also has a local value.
*/
#define PV_BOTH 0x1000
#define PV_WIN 0x2000
#define PV_BUF 0x4000
#define PV_MASK 0x0fff
#define OPT_WIN(x) (idopt_T)(PV_WIN + (int)(x))
#define OPT_BUF(x) (idopt_T)(PV_BUF + (int)(x))
#define OPT_BOTH(x) (idopt_T)(PV_BOTH + (int)(x))
/*
* Definition of the PV_ values for buffer-local options.
* The BV_ values are defined in option.h.
*/
#define PV_AI OPT_BUF(BV_AI)
#define PV_AR OPT_BOTH(OPT_BUF(BV_AR))
#define PV_BKC OPT_BOTH(OPT_BUF(BV_BKC))
#ifdef FEAT_QUICKFIX
# define PV_BH OPT_BUF(BV_BH)
# define PV_BT OPT_BUF(BV_BT)
# define PV_EFM OPT_BOTH(OPT_BUF(BV_EFM))
# define PV_GP OPT_BOTH(OPT_BUF(BV_GP))
# define PV_MP OPT_BOTH(OPT_BUF(BV_MP))
#endif
#define PV_BIN OPT_BUF(BV_BIN)
#define PV_BL OPT_BUF(BV_BL)
#ifdef FEAT_MBYTE
# define PV_BOMB OPT_BUF(BV_BOMB)
#endif
#define PV_CI OPT_BUF(BV_CI)
#ifdef FEAT_CINDENT
# define PV_CIN OPT_BUF(BV_CIN)
# define PV_CINK OPT_BUF(BV_CINK)
# define PV_CINO OPT_BUF(BV_CINO)
#endif
#if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT)
# define PV_CINW OPT_BUF(BV_CINW)
#endif
#define PV_CM OPT_BOTH(OPT_BUF(BV_CM))
#ifdef FEAT_FOLDING
# define PV_CMS OPT_BUF(BV_CMS)
#endif
#ifdef FEAT_COMMENTS
# define PV_COM OPT_BUF(BV_COM)
#endif
#ifdef FEAT_INS_EXPAND
# define PV_CPT OPT_BUF(BV_CPT)
# define PV_DICT OPT_BOTH(OPT_BUF(BV_DICT))
# define PV_TSR OPT_BOTH(OPT_BUF(BV_TSR))
#endif
#ifdef FEAT_COMPL_FUNC
# define PV_CFU OPT_BUF(BV_CFU)
#endif
#ifdef FEAT_FIND_ID
# define PV_DEF OPT_BOTH(OPT_BUF(BV_DEF))
# define PV_INC OPT_BOTH(OPT_BUF(BV_INC))
#endif
#define PV_EOL OPT_BUF(BV_EOL)
#define PV_FIXEOL OPT_BUF(BV_FIXEOL)
#define PV_EP OPT_BOTH(OPT_BUF(BV_EP))
#define PV_ET OPT_BUF(BV_ET)
#ifdef FEAT_MBYTE
# define PV_FENC OPT_BUF(BV_FENC)
#endif
#if defined(FEAT_BEVAL) && defined(FEAT_EVAL)
# define PV_BEXPR OPT_BOTH(OPT_BUF(BV_BEXPR))
#endif
#ifdef FEAT_EVAL
# define PV_FEX OPT_BUF(BV_FEX)
#endif
#define PV_FF OPT_BUF(BV_FF)
#define PV_FLP OPT_BUF(BV_FLP)
#define PV_FO OPT_BUF(BV_FO)
#ifdef FEAT_AUTOCMD
# define PV_FT OPT_BUF(BV_FT)
#endif
#define PV_IMI OPT_BUF(BV_IMI)
#define PV_IMS OPT_BUF(BV_IMS)
#if defined(FEAT_CINDENT) && defined(FEAT_EVAL)
# define PV_INDE OPT_BUF(BV_INDE)
# define PV_INDK OPT_BUF(BV_INDK)
#endif
#if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
# define PV_INEX OPT_BUF(BV_INEX)
#endif
#define PV_INF OPT_BUF(BV_INF)
#define PV_ISK OPT_BUF(BV_ISK)
#ifdef FEAT_CRYPT
# define PV_KEY OPT_BUF(BV_KEY)
#endif
#ifdef FEAT_KEYMAP
# define PV_KMAP OPT_BUF(BV_KMAP)
#endif
#define PV_KP OPT_BOTH(OPT_BUF(BV_KP))
#ifdef FEAT_LISP
# define PV_LISP OPT_BUF(BV_LISP)
# define PV_LW OPT_BOTH(OPT_BUF(BV_LW))
#endif
#define PV_MA OPT_BUF(BV_MA)
#define PV_ML OPT_BUF(BV_ML)
#define PV_MOD OPT_BUF(BV_MOD)
#define PV_MPS OPT_BUF(BV_MPS)
#define PV_NF OPT_BUF(BV_NF)
#ifdef FEAT_COMPL_FUNC
# define PV_OFU OPT_BUF(BV_OFU)
#endif
#define PV_PATH OPT_BOTH(OPT_BUF(BV_PATH))
#define PV_PI OPT_BUF(BV_PI)
#ifdef FEAT_TEXTOBJ
# define PV_QE OPT_BUF(BV_QE)
#endif
#define PV_RO OPT_BUF(BV_RO)
#ifdef FEAT_SMARTINDENT
# define PV_SI OPT_BUF(BV_SI)
#endif
#define PV_SN OPT_BUF(BV_SN)
#ifdef FEAT_SYN_HL
# define PV_SMC OPT_BUF(BV_SMC)
# define PV_SYN OPT_BUF(BV_SYN)
#endif
#ifdef FEAT_SPELL
# define PV_SPC OPT_BUF(BV_SPC)
# define PV_SPF OPT_BUF(BV_SPF)
# define PV_SPL OPT_BUF(BV_SPL)
#endif
#define PV_STS OPT_BUF(BV_STS)
#ifdef FEAT_SEARCHPATH
# define PV_SUA OPT_BUF(BV_SUA)
#endif
#define PV_SW OPT_BUF(BV_SW)
#define PV_SWF OPT_BUF(BV_SWF)
#define PV_TAGS OPT_BOTH(OPT_BUF(BV_TAGS))
#define PV_TC OPT_BOTH(OPT_BUF(BV_TC))
#define PV_TS OPT_BUF(BV_TS)
#define PV_TW OPT_BUF(BV_TW)
#define PV_TX OPT_BUF(BV_TX)
#ifdef FEAT_PERSISTENT_UNDO
# define PV_UDF OPT_BUF(BV_UDF)
#endif
#define PV_WM OPT_BUF(BV_WM)
/*
* Definition of the PV_ values for window-local options.
* The WV_ values are defined in option.h.
*/
#define PV_LIST OPT_WIN(WV_LIST)
#ifdef FEAT_ARABIC
# define PV_ARAB OPT_WIN(WV_ARAB)
#endif
#ifdef FEAT_LINEBREAK
# define PV_BRI OPT_WIN(WV_BRI)
# define PV_BRIOPT OPT_WIN(WV_BRIOPT)
#endif
#ifdef FEAT_DIFF
# define PV_DIFF OPT_WIN(WV_DIFF)
#endif
#ifdef FEAT_FOLDING
# define PV_FDC OPT_WIN(WV_FDC)
# define PV_FEN OPT_WIN(WV_FEN)
# define PV_FDI OPT_WIN(WV_FDI)
# define PV_FDL OPT_WIN(WV_FDL)
# define PV_FDM OPT_WIN(WV_FDM)
# define PV_FML OPT_WIN(WV_FML)
# define PV_FDN OPT_WIN(WV_FDN)
# ifdef FEAT_EVAL
# define PV_FDE OPT_WIN(WV_FDE)
# define PV_FDT OPT_WIN(WV_FDT)
# endif
# define PV_FMR OPT_WIN(WV_FMR)
#endif
#ifdef FEAT_LINEBREAK
# define PV_LBR OPT_WIN(WV_LBR)
#endif
#define PV_NU OPT_WIN(WV_NU)
#define PV_RNU OPT_WIN(WV_RNU)
#ifdef FEAT_LINEBREAK
# define PV_NUW OPT_WIN(WV_NUW)
#endif
#if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
# define PV_PVW OPT_WIN(WV_PVW)
#endif
#ifdef FEAT_RIGHTLEFT
# define PV_RL OPT_WIN(WV_RL)
# define PV_RLC OPT_WIN(WV_RLC)
#endif
#ifdef FEAT_SCROLLBIND
# define PV_SCBIND OPT_WIN(WV_SCBIND)
#endif
#define PV_SCROLL OPT_WIN(WV_SCROLL)
#ifdef FEAT_SPELL
# define PV_SPELL OPT_WIN(WV_SPELL)
#endif
#ifdef FEAT_SYN_HL
# define PV_CUC OPT_WIN(WV_CUC)
# define PV_CUL OPT_WIN(WV_CUL)
# define PV_CC OPT_WIN(WV_CC)
#endif
#ifdef FEAT_STL_OPT
# define PV_STL OPT_BOTH(OPT_WIN(WV_STL))
#endif
#define PV_UL OPT_BOTH(OPT_BUF(BV_UL))
#ifdef FEAT_WINDOWS
# define PV_WFH OPT_WIN(WV_WFH)
# define PV_WFW OPT_WIN(WV_WFW)
#endif
#define PV_WRAP OPT_WIN(WV_WRAP)
#ifdef FEAT_CURSORBIND
# define PV_CRBIND OPT_WIN(WV_CRBIND)
#endif
#ifdef FEAT_CONCEAL
# define PV_COCU OPT_WIN(WV_COCU)
# define PV_COLE OPT_WIN(WV_COLE)
#endif
#ifdef FEAT_SIGNS
# define PV_SCL OPT_WIN(WV_SCL)
#endif
/* WV_ and BV_ values get typecasted to this for the "indir" field */
typedef enum
{
PV_NONE = 0,
PV_MAXVAL = 0xffff /* to avoid warnings for value out of range */
} idopt_T;
/*
* Options local to a window have a value local to a buffer and global to all
* buffers. Indicate this by setting "var" to VAR_WIN.
*/
#define VAR_WIN ((char_u *)-1)
/*
* These are the global values for options which are also local to a buffer.
* Only to be used in option.c!
*/
static int p_ai;
static int p_bin;
#ifdef FEAT_MBYTE
static int p_bomb;
#endif
#if defined(FEAT_QUICKFIX)
static char_u *p_bh;
static char_u *p_bt;
#endif
static int p_bl;
static int p_ci;
#ifdef FEAT_CINDENT
static int p_cin;
static char_u *p_cink;
static char_u *p_cino;
#endif
#if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT)
static char_u *p_cinw;
#endif
#ifdef FEAT_COMMENTS
static char_u *p_com;
#endif
#ifdef FEAT_FOLDING
static char_u *p_cms;
#endif
#ifdef FEAT_INS_EXPAND
static char_u *p_cpt;
#endif
#ifdef FEAT_COMPL_FUNC
static char_u *p_cfu;
static char_u *p_ofu;
#endif
static int p_eol;
static int p_fixeol;
static int p_et;
#ifdef FEAT_MBYTE
static char_u *p_fenc;
#endif
static char_u *p_ff;
static char_u *p_fo;
static char_u *p_flp;
#ifdef FEAT_AUTOCMD
static char_u *p_ft;
#endif
static long p_iminsert;
static long p_imsearch;
#if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
static char_u *p_inex;
#endif
#if defined(FEAT_CINDENT) && defined(FEAT_EVAL)
static char_u *p_inde;
static char_u *p_indk;
#endif
#if defined(FEAT_EVAL)
static char_u *p_fex;
#endif
static int p_inf;
static char_u *p_isk;
#ifdef FEAT_CRYPT
static char_u *p_key;
#endif
#ifdef FEAT_LISP
static int p_lisp;
#endif
static int p_ml;
static int p_ma;
static int p_mod;
static char_u *p_mps;
static char_u *p_nf;
static int p_pi;
#ifdef FEAT_TEXTOBJ
static char_u *p_qe;
#endif
static int p_ro;
#ifdef FEAT_SMARTINDENT
static int p_si;
#endif
static int p_sn;
static long p_sts;
#if defined(FEAT_SEARCHPATH)
static char_u *p_sua;
#endif
static long p_sw;
static int p_swf;
#ifdef FEAT_SYN_HL
static long p_smc;
static char_u *p_syn;
#endif
#ifdef FEAT_SPELL
static char_u *p_spc;
static char_u *p_spf;
static char_u *p_spl;
#endif
static long p_ts;
static long p_tw;
static int p_tx;
#ifdef FEAT_PERSISTENT_UNDO
static int p_udf;
#endif
static long p_wm;
#ifdef FEAT_KEYMAP
static char_u *p_keymap;
#endif
/* Saved values for when 'bin' is set. */
static int p_et_nobin;
static int p_ml_nobin;
static long p_tw_nobin;
static long p_wm_nobin;
/* Saved values for when 'paste' is set */
static int p_ai_nopaste;
static int p_et_nopaste;
static long p_sts_nopaste;
static long p_tw_nopaste;
static long p_wm_nopaste;
struct vimoption
{
char *fullname; /* full option name */
char *shortname; /* permissible abbreviation */
long_u flags; /* see below */
char_u *var; /* global option: pointer to variable;
* window-local option: VAR_WIN;
* buffer-local option: global value */
idopt_T indir; /* global option: PV_NONE;
* local option: indirect option index */
char_u *def_val[2]; /* default values for variable (vi and vim) */
#ifdef FEAT_EVAL
scid_T scriptID; /* script in which the option was last set */
# define SCRIPTID_INIT , 0
#else
# define SCRIPTID_INIT
#endif
};
#define VI_DEFAULT 0 /* def_val[VI_DEFAULT] is Vi default value */
#define VIM_DEFAULT 1 /* def_val[VIM_DEFAULT] is Vim default value */
/*
* Flags
*/
#define P_BOOL 0x01 /* the option is boolean */
#define P_NUM 0x02 /* the option is numeric */
#define P_STRING 0x04 /* the option is a string */
#define P_ALLOCED 0x08 /* the string option is in allocated memory,
must use free_string_option() when
assigning new value. Not set if default is
the same. */
#define P_EXPAND 0x10 /* environment expansion. NOTE: P_EXPAND can
never be used for local or hidden options! */
#define P_NODEFAULT 0x40 /* don't set to default value */
#define P_DEF_ALLOCED 0x80 /* default value is in allocated memory, must
use vim_free() when assigning new value */
#define P_WAS_SET 0x100 /* option has been set/reset */
#define P_NO_MKRC 0x200 /* don't include in :mkvimrc output */
#define P_VI_DEF 0x400 /* Use Vi default for Vim */
#define P_VIM 0x800 /* Vim option, reset when 'cp' set */
/* when option changed, what to display: */
#define P_RSTAT 0x1000 /* redraw status lines */
#define P_RWIN 0x2000 /* redraw current window */
#define P_RBUF 0x4000 /* redraw current buffer */
#define P_RALL 0x6000 /* redraw all windows */
#define P_RCLR 0x7000 /* clear and redraw all */
#define P_COMMA 0x8000 /* comma separated list */
#define P_ONECOMMA 0x18000L /* P_COMMA and cannot have two consecutive
* commas */
#define P_NODUP 0x20000L /* don't allow duplicate strings */
#define P_FLAGLIST 0x40000L /* list of single-char flags */
#define P_SECURE 0x80000L /* cannot change in modeline or secure mode */
#define P_GETTEXT 0x100000L /* expand default value with _() */
#define P_NOGLOB 0x200000L /* do not use local value for global vimrc */
#define P_NFNAME 0x400000L /* only normal file name chars allowed */
#define P_INSECURE 0x800000L /* option was set from a modeline */
#define P_PRI_MKRC 0x1000000L /* priority for :mkvimrc (setting option has
side effects) */
#define P_NO_ML 0x2000000L /* not allowed in modeline */
#define P_CURSWANT 0x4000000L /* update curswant required; not needed when
* there is a redraw flag */
#define ISK_LATIN1 (char_u *)"@,48-57,_,192-255"
/* 'isprint' for latin1 is also used for MS-Windows cp1252, where 0x80 is used
* for the currency sign. */
#if defined(MSWIN)
# define ISP_LATIN1 (char_u *)"@,~-255"
#else
# define ISP_LATIN1 (char_u *)"@,161-255"
#endif
/* Make the string as short as possible when compiling with few features. */
#if defined(FEAT_DIFF) || defined(FEAT_FOLDING) || defined(FEAT_SPELL) \
|| defined(FEAT_WINDOWS) || defined(FEAT_CLIPBOARD) \
|| defined(FEAT_INS_EXPAND) || defined(FEAT_SYN_HL) || defined(FEAT_CONCEAL)
# define HIGHLIGHT_INIT "8:SpecialKey,~:EndOfBuffer,@:NonText,d:Directory,e:ErrorMsg,i:IncSearch,l:Search,m:MoreMsg,M:ModeMsg,n:LineNr,N:CursorLineNr,r:Question,s:StatusLine,S:StatusLineNC,c:VertSplit,t:Title,v:Visual,V:VisualNOS,w:WarningMsg,W:WildMenu,f:Folded,F:FoldColumn,A:DiffAdd,C:DiffChange,D:DiffDelete,T:DiffText,>:SignColumn,-:Conceal,B:SpellBad,P:SpellCap,R:SpellRare,L:SpellLocal,+:Pmenu,=:PmenuSel,x:PmenuSbar,X:PmenuThumb,*:TabLine,#:TabLineSel,_:TabLineFill,!:CursorColumn,.:CursorLine,o:ColorColumn"
#else
# define HIGHLIGHT_INIT "8:SpecialKey,@:NonText,d:Directory,e:ErrorMsg,i:IncSearch,l:Search,m:MoreMsg,M:ModeMsg,n:LineNr,N:CursorLineNr,r:Question,s:StatusLine,S:StatusLineNC,t:Title,v:Visual,w:WarningMsg,W:WildMenu,>:SignColumn,*:TabLine,#:TabLineSel,_:TabLineFill"
#endif
/*
* options[] is initialized here.
* The order of the options MUST be alphabetic for ":set all" and findoption().
* All option names MUST start with a lowercase letter (for findoption()).
* Exception: "t_" options are at the end.
* The options with a NULL variable are 'hidden': a set command for them is
* ignored and they are not printed.
*/
static struct vimoption options[] =
{
{"aleph", "al", P_NUM|P_VI_DEF|P_CURSWANT,
#ifdef FEAT_RIGHTLEFT
(char_u *)&p_aleph, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{
#if (defined(WIN3264)) && !defined(FEAT_GUI_W32)
(char_u *)128L,
#else
(char_u *)224L,
#endif
(char_u *)0L} SCRIPTID_INIT},
{"antialias", "anti", P_BOOL|P_VI_DEF|P_VIM|P_RCLR,
#if defined(FEAT_GUI) && defined(MACOS_X)
(char_u *)&p_antialias, PV_NONE,
{(char_u *)FALSE, (char_u *)FALSE}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)FALSE, (char_u *)FALSE}
#endif
SCRIPTID_INIT},
{"arabic", "arab", P_BOOL|P_VI_DEF|P_VIM|P_CURSWANT,
#ifdef FEAT_ARABIC
(char_u *)VAR_WIN, PV_ARAB,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"arabicshape", "arshape", P_BOOL|P_VI_DEF|P_VIM|P_RCLR,
#ifdef FEAT_ARABIC
(char_u *)&p_arshape, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"allowrevins", "ari", P_BOOL|P_VI_DEF|P_VIM,
#ifdef FEAT_RIGHTLEFT
(char_u *)&p_ari, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"altkeymap", "akm", P_BOOL|P_VI_DEF,
#ifdef FEAT_FKMAP
(char_u *)&p_altkeymap, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"ambiwidth", "ambw", P_STRING|P_VI_DEF|P_RCLR,
#if defined(FEAT_MBYTE)
(char_u *)&p_ambw, PV_NONE,
{(char_u *)"single", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
#ifdef FEAT_AUTOCHDIR
{"autochdir", "acd", P_BOOL|P_VI_DEF,
(char_u *)&p_acd, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
#endif
{"autoindent", "ai", P_BOOL|P_VI_DEF,
(char_u *)&p_ai, PV_AI,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"autoprint", "ap", P_BOOL|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"autoread", "ar", P_BOOL|P_VI_DEF,
(char_u *)&p_ar, PV_AR,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"autowrite", "aw", P_BOOL|P_VI_DEF,
(char_u *)&p_aw, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"autowriteall","awa", P_BOOL|P_VI_DEF,
(char_u *)&p_awa, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"background", "bg", P_STRING|P_VI_DEF|P_RCLR,
(char_u *)&p_bg, PV_NONE,
{
#if (defined(WIN3264)) && !defined(FEAT_GUI)
(char_u *)"dark",
#else
(char_u *)"light",
#endif
(char_u *)0L} SCRIPTID_INIT},
{"backspace", "bs", P_STRING|P_VI_DEF|P_VIM|P_ONECOMMA|P_NODUP,
(char_u *)&p_bs, PV_NONE,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"backup", "bk", P_BOOL|P_VI_DEF|P_VIM,
(char_u *)&p_bk, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"backupcopy", "bkc", P_STRING|P_VIM|P_ONECOMMA|P_NODUP,
(char_u *)&p_bkc, PV_BKC,
#ifdef UNIX
{(char_u *)"yes", (char_u *)"auto"}
#else
{(char_u *)"auto", (char_u *)"auto"}
#endif
SCRIPTID_INIT},
{"backupdir", "bdir", P_STRING|P_EXPAND|P_VI_DEF|P_ONECOMMA
|P_NODUP|P_SECURE,
(char_u *)&p_bdir, PV_NONE,
{(char_u *)DFLT_BDIR, (char_u *)0L} SCRIPTID_INIT},
{"backupext", "bex", P_STRING|P_VI_DEF|P_NFNAME,
(char_u *)&p_bex, PV_NONE,
{
#ifdef VMS
(char_u *)"_",
#else
(char_u *)"~",
#endif
(char_u *)0L} SCRIPTID_INIT},
{"backupskip", "bsk", P_STRING|P_VI_DEF|P_ONECOMMA,
#ifdef FEAT_WILDIGN
(char_u *)&p_bsk, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
#ifdef FEAT_BEVAL
{"balloondelay","bdlay",P_NUM|P_VI_DEF,
(char_u *)&p_bdlay, PV_NONE,
{(char_u *)600L, (char_u *)0L} SCRIPTID_INIT},
{"ballooneval", "beval",P_BOOL|P_VI_DEF|P_NO_MKRC,
(char_u *)&p_beval, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
# ifdef FEAT_EVAL
{"balloonexpr", "bexpr", P_STRING|P_ALLOCED|P_VI_DEF|P_VIM,
(char_u *)&p_bexpr, PV_BEXPR,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
# endif
#endif
{"beautify", "bf", P_BOOL|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"belloff", "bo", P_STRING|P_VI_DEF|P_COMMA|P_NODUP,
(char_u *)&p_bo, PV_NONE,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"binary", "bin", P_BOOL|P_VI_DEF|P_RSTAT,
(char_u *)&p_bin, PV_BIN,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"bioskey", "biosk",P_BOOL|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"bomb", NULL, P_BOOL|P_NO_MKRC|P_VI_DEF|P_RSTAT,
#ifdef FEAT_MBYTE
(char_u *)&p_bomb, PV_BOMB,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"breakat", "brk", P_STRING|P_VI_DEF|P_RALL|P_FLAGLIST,
#ifdef FEAT_LINEBREAK
(char_u *)&p_breakat, PV_NONE,
{(char_u *)" \t!@*-+;:,./?", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"breakindent", "bri", P_BOOL|P_VI_DEF|P_VIM|P_RWIN,
#ifdef FEAT_LINEBREAK
(char_u *)VAR_WIN, PV_BRI,
{(char_u *)FALSE, (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"breakindentopt", "briopt", P_STRING|P_ALLOCED|P_VI_DEF|P_RBUF
|P_ONECOMMA|P_NODUP,
#ifdef FEAT_LINEBREAK
(char_u *)VAR_WIN, PV_BRIOPT,
{(char_u *)"", (char_u *)NULL}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)"", (char_u *)NULL}
#endif
SCRIPTID_INIT},
{"browsedir", "bsdir",P_STRING|P_VI_DEF,
#ifdef FEAT_BROWSE
(char_u *)&p_bsdir, PV_NONE,
{(char_u *)"last", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"bufhidden", "bh", P_STRING|P_ALLOCED|P_VI_DEF|P_NOGLOB,
#if defined(FEAT_QUICKFIX)
(char_u *)&p_bh, PV_BH,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"buflisted", "bl", P_BOOL|P_VI_DEF|P_NOGLOB,
(char_u *)&p_bl, PV_BL,
{(char_u *)1L, (char_u *)0L}
SCRIPTID_INIT},
{"buftype", "bt", P_STRING|P_ALLOCED|P_VI_DEF|P_NOGLOB,
#if defined(FEAT_QUICKFIX)
(char_u *)&p_bt, PV_BT,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"casemap", "cmp", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_MBYTE
(char_u *)&p_cmp, PV_NONE,
{(char_u *)"internal,keepascii", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"cdpath", "cd", P_STRING|P_EXPAND|P_VI_DEF|P_COMMA|P_NODUP,
#ifdef FEAT_SEARCHPATH
(char_u *)&p_cdpath, PV_NONE,
{(char_u *)",,", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"cedit", NULL, P_STRING,
#ifdef FEAT_CMDWIN
(char_u *)&p_cedit, PV_NONE,
{(char_u *)"", (char_u *)CTRL_F_STR}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"charconvert", "ccv", P_STRING|P_VI_DEF|P_SECURE,
#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
(char_u *)&p_ccv, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"cindent", "cin", P_BOOL|P_VI_DEF|P_VIM,
#ifdef FEAT_CINDENT
(char_u *)&p_cin, PV_CIN,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"cinkeys", "cink", P_STRING|P_ALLOCED|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_CINDENT
(char_u *)&p_cink, PV_CINK,
{(char_u *)"0{,0},0),:,0#,!^F,o,O,e", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"cinoptions", "cino", P_STRING|P_ALLOCED|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_CINDENT
(char_u *)&p_cino, PV_CINO,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"cinwords", "cinw", P_STRING|P_ALLOCED|P_VI_DEF|P_ONECOMMA|P_NODUP,
#if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT)
(char_u *)&p_cinw, PV_CINW,
{(char_u *)"if,else,while,do,for,switch",
(char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"clipboard", "cb", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_CLIPBOARD
(char_u *)&p_cb, PV_NONE,
# ifdef FEAT_XCLIPBOARD
{(char_u *)"autoselect,exclude:cons\\|linux",
(char_u *)0L}
# else
{(char_u *)"", (char_u *)0L}
# endif
#else
(char_u *)NULL, PV_NONE,
{(char_u *)"", (char_u *)0L}
#endif
SCRIPTID_INIT},
{"cmdheight", "ch", P_NUM|P_VI_DEF|P_RALL,
(char_u *)&p_ch, PV_NONE,
{(char_u *)1L, (char_u *)0L} SCRIPTID_INIT},
{"cmdwinheight", "cwh", P_NUM|P_VI_DEF,
#ifdef FEAT_CMDWIN
(char_u *)&p_cwh, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)7L, (char_u *)0L} SCRIPTID_INIT},
{"colorcolumn", "cc", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP|P_RWIN,
#ifdef FEAT_SYN_HL
(char_u *)VAR_WIN, PV_CC,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"columns", "co", P_NUM|P_NODEFAULT|P_NO_MKRC|P_VI_DEF|P_RCLR,
(char_u *)&Columns, PV_NONE,
{(char_u *)80L, (char_u *)0L} SCRIPTID_INIT},
{"comments", "com", P_STRING|P_ALLOCED|P_VI_DEF|P_ONECOMMA
|P_NODUP|P_CURSWANT,
#ifdef FEAT_COMMENTS
(char_u *)&p_com, PV_COM,
{(char_u *)"s1:/*,mb:*,ex:*/,://,b:#,:%,:XCOMM,n:>,fb:-",
(char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"commentstring", "cms", P_STRING|P_ALLOCED|P_VI_DEF|P_CURSWANT,
#ifdef FEAT_FOLDING
(char_u *)&p_cms, PV_CMS,
{(char_u *)"/*%s*/", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
/* P_PRI_MKRC isn't needed here, optval_default()
* always returns TRUE for 'compatible' */
{"compatible", "cp", P_BOOL|P_RALL,
(char_u *)&p_cp, PV_NONE,
{(char_u *)TRUE, (char_u *)FALSE} SCRIPTID_INIT},
{"complete", "cpt", P_STRING|P_ALLOCED|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_INS_EXPAND
(char_u *)&p_cpt, PV_CPT,
{(char_u *)".,w,b,u,t,i", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"concealcursor","cocu", P_STRING|P_ALLOCED|P_RWIN|P_VI_DEF,
#ifdef FEAT_CONCEAL
(char_u *)VAR_WIN, PV_COCU,
{(char_u *)"", (char_u *)NULL}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"conceallevel","cole", P_NUM|P_RWIN|P_VI_DEF,
#ifdef FEAT_CONCEAL
(char_u *)VAR_WIN, PV_COLE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)0L, (char_u *)0L}
SCRIPTID_INIT},
{"completefunc", "cfu", P_STRING|P_ALLOCED|P_VI_DEF|P_SECURE,
#ifdef FEAT_COMPL_FUNC
(char_u *)&p_cfu, PV_CFU,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"completeopt", "cot", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_INS_EXPAND
(char_u *)&p_cot, PV_NONE,
{(char_u *)"menu,preview", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"confirm", "cf", P_BOOL|P_VI_DEF,
#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
(char_u *)&p_confirm, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"conskey", "consk",P_BOOL|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"copyindent", "ci", P_BOOL|P_VI_DEF|P_VIM,
(char_u *)&p_ci, PV_CI,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"cpoptions", "cpo", P_STRING|P_VIM|P_RALL|P_FLAGLIST,
(char_u *)&p_cpo, PV_NONE,
{(char_u *)CPO_VI, (char_u *)CPO_VIM}
SCRIPTID_INIT},
{"cryptmethod", "cm", P_STRING|P_ALLOCED|P_VI_DEF,
#ifdef FEAT_CRYPT
(char_u *)&p_cm, PV_CM,
{(char_u *)"zip", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"cscopepathcomp", "cspc", P_NUM|P_VI_DEF|P_VIM,
#ifdef FEAT_CSCOPE
(char_u *)&p_cspc, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"cscopeprg", "csprg", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
#ifdef FEAT_CSCOPE
(char_u *)&p_csprg, PV_NONE,
{(char_u *)"cscope", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"cscopequickfix", "csqf", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
#if defined(FEAT_CSCOPE) && defined(FEAT_QUICKFIX)
(char_u *)&p_csqf, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"cscoperelative", "csre", P_BOOL|P_VI_DEF|P_VIM,
#ifdef FEAT_CSCOPE
(char_u *)&p_csre, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"cscopetag", "cst", P_BOOL|P_VI_DEF|P_VIM,
#ifdef FEAT_CSCOPE
(char_u *)&p_cst, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"cscopetagorder", "csto", P_NUM|P_VI_DEF|P_VIM,
#ifdef FEAT_CSCOPE
(char_u *)&p_csto, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"cscopeverbose", "csverb", P_BOOL|P_VI_DEF|P_VIM,
#ifdef FEAT_CSCOPE
(char_u *)&p_csverbose, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"cursorbind", "crb", P_BOOL|P_VI_DEF,
#ifdef FEAT_CURSORBIND
(char_u *)VAR_WIN, PV_CRBIND,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"cursorcolumn", "cuc", P_BOOL|P_VI_DEF|P_RWIN,
#ifdef FEAT_SYN_HL
(char_u *)VAR_WIN, PV_CUC,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"cursorline", "cul", P_BOOL|P_VI_DEF|P_RWIN,
#ifdef FEAT_SYN_HL
(char_u *)VAR_WIN, PV_CUL,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"debug", NULL, P_STRING|P_VI_DEF,
(char_u *)&p_debug, PV_NONE,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"define", "def", P_STRING|P_ALLOCED|P_VI_DEF|P_CURSWANT,
#ifdef FEAT_FIND_ID
(char_u *)&p_def, PV_DEF,
{(char_u *)"^\\s*#\\s*define", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"delcombine", "deco", P_BOOL|P_VI_DEF|P_VIM,
#ifdef FEAT_MBYTE
(char_u *)&p_deco, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"dictionary", "dict", P_STRING|P_EXPAND|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_INS_EXPAND
(char_u *)&p_dict, PV_DICT,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"diff", NULL, P_BOOL|P_VI_DEF|P_RWIN|P_NOGLOB,
#ifdef FEAT_DIFF
(char_u *)VAR_WIN, PV_DIFF,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"diffexpr", "dex", P_STRING|P_VI_DEF|P_SECURE|P_CURSWANT,
#if defined(FEAT_DIFF) && defined(FEAT_EVAL)
(char_u *)&p_dex, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"diffopt", "dip", P_STRING|P_ALLOCED|P_VI_DEF|P_RWIN|P_ONECOMMA
|P_NODUP,
#ifdef FEAT_DIFF
(char_u *)&p_dip, PV_NONE,
{(char_u *)"filler", (char_u *)NULL}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)"", (char_u *)NULL}
#endif
SCRIPTID_INIT},
{"digraph", "dg", P_BOOL|P_VI_DEF|P_VIM,
#ifdef FEAT_DIGRAPHS
(char_u *)&p_dg, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"directory", "dir", P_STRING|P_EXPAND|P_VI_DEF|P_ONECOMMA
|P_NODUP|P_SECURE,
(char_u *)&p_dir, PV_NONE,
{(char_u *)DFLT_DIR, (char_u *)0L} SCRIPTID_INIT},
{"display", "dy", P_STRING|P_VI_DEF|P_ONECOMMA|P_RALL|P_NODUP,
(char_u *)&p_dy, PV_NONE,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"eadirection", "ead", P_STRING|P_VI_DEF,
#ifdef FEAT_WINDOWS
(char_u *)&p_ead, PV_NONE,
{(char_u *)"both", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"edcompatible","ed", P_BOOL|P_VI_DEF,
(char_u *)&p_ed, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"emoji", "emo", P_BOOL|P_VI_DEF|P_RCLR,
#if defined(FEAT_MBYTE)
(char_u *)&p_emoji, PV_NONE,
{(char_u *)TRUE, (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"encoding", "enc", P_STRING|P_VI_DEF|P_RCLR|P_NO_ML,
#ifdef FEAT_MBYTE
(char_u *)&p_enc, PV_NONE,
{(char_u *)ENC_DFLT, (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"endofline", "eol", P_BOOL|P_NO_MKRC|P_VI_DEF|P_RSTAT,
(char_u *)&p_eol, PV_EOL,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"equalalways", "ea", P_BOOL|P_VI_DEF|P_RALL,
(char_u *)&p_ea, PV_NONE,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"equalprg", "ep", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
(char_u *)&p_ep, PV_EP,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"errorbells", "eb", P_BOOL|P_VI_DEF,
(char_u *)&p_eb, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"errorfile", "ef", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
#ifdef FEAT_QUICKFIX
(char_u *)&p_ef, PV_NONE,
{(char_u *)DFLT_ERRORFILE, (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"errorformat", "efm", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_QUICKFIX
(char_u *)&p_efm, PV_EFM,
{(char_u *)DFLT_EFM, (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"esckeys", "ek", P_BOOL|P_VIM,
(char_u *)&p_ek, PV_NONE,
{(char_u *)FALSE, (char_u *)TRUE} SCRIPTID_INIT},
{"eventignore", "ei", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_AUTOCMD
(char_u *)&p_ei, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"expandtab", "et", P_BOOL|P_VI_DEF|P_VIM,
(char_u *)&p_et, PV_ET,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"exrc", "ex", P_BOOL|P_VI_DEF|P_SECURE,
(char_u *)&p_exrc, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"fileencoding","fenc", P_STRING|P_ALLOCED|P_VI_DEF|P_RSTAT|P_RBUF
|P_NO_MKRC,
#ifdef FEAT_MBYTE
(char_u *)&p_fenc, PV_FENC,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"fileencodings","fencs", P_STRING|P_VI_DEF|P_ONECOMMA,
#ifdef FEAT_MBYTE
(char_u *)&p_fencs, PV_NONE,
{(char_u *)"ucs-bom", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"fileformat", "ff", P_STRING|P_ALLOCED|P_VI_DEF|P_RSTAT|P_NO_MKRC
|P_CURSWANT,
(char_u *)&p_ff, PV_FF,
{(char_u *)DFLT_FF, (char_u *)0L} SCRIPTID_INIT},
{"fileformats", "ffs", P_STRING|P_VIM|P_ONECOMMA|P_NODUP,
(char_u *)&p_ffs, PV_NONE,
{(char_u *)DFLT_FFS_VI, (char_u *)DFLT_FFS_VIM}
SCRIPTID_INIT},
{"fileignorecase", "fic", P_BOOL|P_VI_DEF,
(char_u *)&p_fic, PV_NONE,
{
#ifdef CASE_INSENSITIVE_FILENAME
(char_u *)TRUE,
#else
(char_u *)FALSE,
#endif
(char_u *)0L} SCRIPTID_INIT},
{"filetype", "ft", P_STRING|P_ALLOCED|P_VI_DEF|P_NOGLOB|P_NFNAME,
#ifdef FEAT_AUTOCMD
(char_u *)&p_ft, PV_FT,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"fillchars", "fcs", P_STRING|P_VI_DEF|P_RALL|P_ONECOMMA|P_NODUP,
#if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING)
(char_u *)&p_fcs, PV_NONE,
{(char_u *)"vert:|,fold:-", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)"", (char_u *)0L}
#endif
SCRIPTID_INIT},
{"fixendofline", "fixeol", P_BOOL|P_VI_DEF|P_RSTAT,
(char_u *)&p_fixeol, PV_FIXEOL,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"fkmap", "fk", P_BOOL|P_VI_DEF,
#ifdef FEAT_FKMAP
(char_u *)&p_fkmap, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"flash", "fl", P_BOOL|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
#ifdef FEAT_FOLDING
{"foldclose", "fcl", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP|P_RWIN,
(char_u *)&p_fcl, PV_NONE,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"foldcolumn", "fdc", P_NUM|P_VI_DEF|P_RWIN,
(char_u *)VAR_WIN, PV_FDC,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"foldenable", "fen", P_BOOL|P_VI_DEF|P_RWIN,
(char_u *)VAR_WIN, PV_FEN,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"foldexpr", "fde", P_STRING|P_ALLOCED|P_VIM|P_VI_DEF|P_RWIN,
# ifdef FEAT_EVAL
(char_u *)VAR_WIN, PV_FDE,
{(char_u *)"0", (char_u *)NULL}
# else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
# endif
SCRIPTID_INIT},
{"foldignore", "fdi", P_STRING|P_ALLOCED|P_VIM|P_VI_DEF|P_RWIN,
(char_u *)VAR_WIN, PV_FDI,
{(char_u *)"#", (char_u *)NULL} SCRIPTID_INIT},
{"foldlevel", "fdl", P_NUM|P_VI_DEF|P_RWIN,
(char_u *)VAR_WIN, PV_FDL,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"foldlevelstart","fdls", P_NUM|P_VI_DEF|P_CURSWANT,
(char_u *)&p_fdls, PV_NONE,
{(char_u *)-1L, (char_u *)0L} SCRIPTID_INIT},
{"foldmarker", "fmr", P_STRING|P_ALLOCED|P_VIM|P_VI_DEF|
P_RWIN|P_ONECOMMA|P_NODUP,
(char_u *)VAR_WIN, PV_FMR,
{(char_u *)"{{{,}}}", (char_u *)NULL}
SCRIPTID_INIT},
{"foldmethod", "fdm", P_STRING|P_ALLOCED|P_VIM|P_VI_DEF|P_RWIN,
(char_u *)VAR_WIN, PV_FDM,
{(char_u *)"manual", (char_u *)NULL} SCRIPTID_INIT},
{"foldminlines","fml", P_NUM|P_VI_DEF|P_RWIN,
(char_u *)VAR_WIN, PV_FML,
{(char_u *)1L, (char_u *)0L} SCRIPTID_INIT},
{"foldnestmax", "fdn", P_NUM|P_VI_DEF|P_RWIN,
(char_u *)VAR_WIN, PV_FDN,
{(char_u *)20L, (char_u *)0L} SCRIPTID_INIT},
{"foldopen", "fdo", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP|P_CURSWANT,
(char_u *)&p_fdo, PV_NONE,
{(char_u *)"block,hor,mark,percent,quickfix,search,tag,undo",
(char_u *)0L} SCRIPTID_INIT},
{"foldtext", "fdt", P_STRING|P_ALLOCED|P_VIM|P_VI_DEF|P_RWIN,
# ifdef FEAT_EVAL
(char_u *)VAR_WIN, PV_FDT,
{(char_u *)"foldtext()", (char_u *)NULL}
# else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
# endif
SCRIPTID_INIT},
#endif
{"formatexpr", "fex", P_STRING|P_ALLOCED|P_VI_DEF|P_VIM,
#ifdef FEAT_EVAL
(char_u *)&p_fex, PV_FEX,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"formatoptions","fo", P_STRING|P_ALLOCED|P_VIM|P_FLAGLIST,
(char_u *)&p_fo, PV_FO,
{(char_u *)DFLT_FO_VI, (char_u *)DFLT_FO_VIM}
SCRIPTID_INIT},
{"formatlistpat","flp", P_STRING|P_ALLOCED|P_VI_DEF,
(char_u *)&p_flp, PV_FLP,
{(char_u *)"^\\s*\\d\\+[\\]:.)}\\t ]\\s*",
(char_u *)0L} SCRIPTID_INIT},
{"formatprg", "fp", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
(char_u *)&p_fp, PV_NONE,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"fsync", "fs", P_BOOL|P_SECURE|P_VI_DEF,
#ifdef HAVE_FSYNC
(char_u *)&p_fs, PV_NONE,
{(char_u *)TRUE, (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)FALSE, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"gdefault", "gd", P_BOOL|P_VI_DEF|P_VIM,
(char_u *)&p_gd, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"graphic", "gr", P_BOOL|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"grepformat", "gfm", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_QUICKFIX
(char_u *)&p_gefm, PV_NONE,
{(char_u *)DFLT_GREPFORMAT, (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"grepprg", "gp", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
#ifdef FEAT_QUICKFIX
(char_u *)&p_gp, PV_GP,
{
# ifdef WIN3264
/* may be changed to "grep -n" in os_win32.c */
(char_u *)"findstr /n",
# else
# ifdef UNIX
/* Add an extra file name so that grep will always
* insert a file name in the match line. */
(char_u *)"grep -n $* /dev/null",
# else
# ifdef VMS
(char_u *)"SEARCH/NUMBERS ",
# else
(char_u *)"grep -n ",
# endif
# endif
# endif
(char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"guicursor", "gcr", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef CURSOR_SHAPE
(char_u *)&p_guicursor, PV_NONE,
{
# ifdef FEAT_GUI
(char_u *)"n-v-c:block-Cursor/lCursor,ve:ver35-Cursor,o:hor50-Cursor,i-ci:ver25-Cursor/lCursor,r-cr:hor20-Cursor/lCursor,sm:block-Cursor-blinkwait175-blinkoff150-blinkon175",
# else /* Win32 console */
(char_u *)"n-v-c:block,o:hor50,i-ci:hor15,r-cr:hor30,sm:block",
# endif
(char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"guifont", "gfn", P_STRING|P_VI_DEF|P_RCLR|P_ONECOMMA|P_NODUP,
#ifdef FEAT_GUI
(char_u *)&p_guifont, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"guifontset", "gfs", P_STRING|P_VI_DEF|P_RCLR|P_ONECOMMA,
#if defined(FEAT_GUI) && defined(FEAT_XFONTSET)
(char_u *)&p_guifontset, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"guifontwide", "gfw", P_STRING|P_VI_DEF|P_RCLR|P_ONECOMMA|P_NODUP,
#if defined(FEAT_GUI) && defined(FEAT_MBYTE)
(char_u *)&p_guifontwide, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"guiheadroom", "ghr", P_NUM|P_VI_DEF,
#if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_X11)
(char_u *)&p_ghr, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)50L, (char_u *)0L} SCRIPTID_INIT},
{"guioptions", "go", P_STRING|P_VI_DEF|P_RALL|P_FLAGLIST,
#if defined(FEAT_GUI)
(char_u *)&p_go, PV_NONE,
# if defined(UNIX) && !defined(MACOS)
{(char_u *)"aegimrLtT", (char_u *)0L}
# else
{(char_u *)"egmrLtT", (char_u *)0L}
# endif
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"guipty", NULL, P_BOOL|P_VI_DEF,
#if defined(FEAT_GUI)
(char_u *)&p_guipty, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"guitablabel", "gtl", P_STRING|P_VI_DEF|P_RWIN,
#if defined(FEAT_GUI_TABLINE)
(char_u *)&p_gtl, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"guitabtooltip", "gtt", P_STRING|P_VI_DEF|P_RWIN,
#if defined(FEAT_GUI_TABLINE)
(char_u *)&p_gtt, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"hardtabs", "ht", P_NUM|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"helpfile", "hf", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
(char_u *)&p_hf, PV_NONE,
{(char_u *)DFLT_HELPFILE, (char_u *)0L}
SCRIPTID_INIT},
{"helpheight", "hh", P_NUM|P_VI_DEF,
#ifdef FEAT_WINDOWS
(char_u *)&p_hh, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)20L, (char_u *)0L} SCRIPTID_INIT},
{"helplang", "hlg", P_STRING|P_VI_DEF|P_ONECOMMA,
#ifdef FEAT_MULTI_LANG
(char_u *)&p_hlg, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"hidden", "hid", P_BOOL|P_VI_DEF,
(char_u *)&p_hid, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"highlight", "hl", P_STRING|P_VI_DEF|P_RCLR|P_ONECOMMA|P_NODUP,
(char_u *)&p_hl, PV_NONE,
{(char_u *)HIGHLIGHT_INIT, (char_u *)0L}
SCRIPTID_INIT},
{"history", "hi", P_NUM|P_VIM,
(char_u *)&p_hi, PV_NONE,
{(char_u *)0L, (char_u *)50L} SCRIPTID_INIT},
{"hkmap", "hk", P_BOOL|P_VI_DEF|P_VIM,
#ifdef FEAT_RIGHTLEFT
(char_u *)&p_hkmap, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"hkmapp", "hkp", P_BOOL|P_VI_DEF|P_VIM,
#ifdef FEAT_RIGHTLEFT
(char_u *)&p_hkmapp, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"hlsearch", "hls", P_BOOL|P_VI_DEF|P_VIM|P_RALL,
(char_u *)&p_hls, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"icon", NULL, P_BOOL|P_VI_DEF,
#ifdef FEAT_TITLE
(char_u *)&p_icon, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"iconstring", NULL, P_STRING|P_VI_DEF,
#ifdef FEAT_TITLE
(char_u *)&p_iconstring, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"ignorecase", "ic", P_BOOL|P_VI_DEF,
(char_u *)&p_ic, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"imactivatefunc","imaf",P_STRING|P_VI_DEF|P_SECURE,
# if defined(FEAT_EVAL) && defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
(char_u *)&p_imaf, PV_NONE,
{(char_u *)"", (char_u *)NULL}
# else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
# endif
SCRIPTID_INIT},
{"imactivatekey","imak",P_STRING|P_VI_DEF,
#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
(char_u *)&p_imak, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"imcmdline", "imc", P_BOOL|P_VI_DEF,
#ifdef USE_IM_CONTROL
(char_u *)&p_imcmdline, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"imdisable", "imd", P_BOOL|P_VI_DEF,
#ifdef USE_IM_CONTROL
(char_u *)&p_imdisable, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
#ifdef __sgi
{(char_u *)TRUE, (char_u *)0L}
#else
{(char_u *)FALSE, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"iminsert", "imi", P_NUM|P_VI_DEF,
(char_u *)&p_iminsert, PV_IMI,
#ifdef B_IMODE_IM
{(char_u *)B_IMODE_IM, (char_u *)0L}
#else
{(char_u *)B_IMODE_NONE, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"imsearch", "ims", P_NUM|P_VI_DEF,
(char_u *)&p_imsearch, PV_IMS,
#ifdef B_IMODE_IM
{(char_u *)B_IMODE_IM, (char_u *)0L}
#else
{(char_u *)B_IMODE_NONE, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"imstatusfunc","imsf",P_STRING|P_VI_DEF|P_SECURE,
# if defined(FEAT_EVAL) && defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
(char_u *)&p_imsf, PV_NONE,
{(char_u *)"", (char_u *)NULL}
# else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
# endif
SCRIPTID_INIT},
{"include", "inc", P_STRING|P_ALLOCED|P_VI_DEF,
#ifdef FEAT_FIND_ID
(char_u *)&p_inc, PV_INC,
{(char_u *)"^\\s*#\\s*include", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"includeexpr", "inex", P_STRING|P_ALLOCED|P_VI_DEF,
#if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
(char_u *)&p_inex, PV_INEX,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"incsearch", "is", P_BOOL|P_VI_DEF|P_VIM,
(char_u *)&p_is, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"indentexpr", "inde", P_STRING|P_ALLOCED|P_VI_DEF|P_VIM,
#if defined(FEAT_CINDENT) && defined(FEAT_EVAL)
(char_u *)&p_inde, PV_INDE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"indentkeys", "indk", P_STRING|P_ALLOCED|P_VI_DEF|P_ONECOMMA|P_NODUP,
#if defined(FEAT_CINDENT) && defined(FEAT_EVAL)
(char_u *)&p_indk, PV_INDK,
{(char_u *)"0{,0},:,0#,!^F,o,O,e", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"infercase", "inf", P_BOOL|P_VI_DEF,
(char_u *)&p_inf, PV_INF,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"insertmode", "im", P_BOOL|P_VI_DEF|P_VIM,
(char_u *)&p_im, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"isfname", "isf", P_STRING|P_VI_DEF|P_COMMA|P_NODUP,
(char_u *)&p_isf, PV_NONE,
{
#ifdef BACKSLASH_IN_FILENAME
/* Excluded are: & and ^ are special in cmd.exe
* ( and ) are used in text separating fnames */
(char_u *)"@,48-57,/,\\,.,-,_,+,,,#,$,%,{,},[,],:,@-@,!,~,=",
#else
# ifdef AMIGA
(char_u *)"@,48-57,/,.,-,_,+,,,$,:",
# else
# ifdef VMS
(char_u *)"@,48-57,/,.,-,_,+,,,#,$,%,<,>,[,],:,;,~",
# else /* UNIX et al. */
# ifdef EBCDIC
(char_u *)"@,240-249,/,.,-,_,+,,,#,$,%,~,=",
# else
(char_u *)"@,48-57,/,.,-,_,+,,,#,$,%,~,=",
# endif
# endif
# endif
#endif
(char_u *)0L} SCRIPTID_INIT},
{"isident", "isi", P_STRING|P_VI_DEF|P_COMMA|P_NODUP,
(char_u *)&p_isi, PV_NONE,
{
#if defined(MSWIN)
(char_u *)"@,48-57,_,128-167,224-235",
#else
# ifdef EBCDIC
/* TODO: EBCDIC Check this! @ == isalpha()*/
(char_u *)"@,240-249,_,66-73,81-89,98-105,"
"112-120,128,140-142,156,158,172,"
"174,186,191,203-207,219-225,235-239,"
"251-254",
# else
(char_u *)"@,48-57,_,192-255",
# endif
#endif
(char_u *)0L} SCRIPTID_INIT},
{"iskeyword", "isk", P_STRING|P_ALLOCED|P_VIM|P_COMMA|P_NODUP,
(char_u *)&p_isk, PV_ISK,
{
#ifdef EBCDIC
(char_u *)"@,240-249,_",
/* TODO: EBCDIC Check this! @ == isalpha()*/
(char_u *)"@,240-249,_,66-73,81-89,98-105,"
"112-120,128,140-142,156,158,172,"
"174,186,191,203-207,219-225,235-239,"
"251-254",
#else
(char_u *)"@,48-57,_",
# if defined(MSWIN)
(char_u *)"@,48-57,_,128-167,224-235"
# else
ISK_LATIN1
# endif
#endif
} SCRIPTID_INIT},
{"isprint", "isp", P_STRING|P_VI_DEF|P_RALL|P_COMMA|P_NODUP,
(char_u *)&p_isp, PV_NONE,
{
#if defined(MSWIN) || (defined(MACOS) && !defined(MACOS_X)) \
|| defined(VMS)
(char_u *)"@,~-255",
#else
# ifdef EBCDIC
/* all chars above 63 are printable */
(char_u *)"63-255",
# else
ISP_LATIN1,
# endif
#endif
(char_u *)0L} SCRIPTID_INIT},
{"joinspaces", "js", P_BOOL|P_VI_DEF|P_VIM,
(char_u *)&p_js, PV_NONE,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"key", NULL, P_STRING|P_ALLOCED|P_VI_DEF|P_NO_MKRC,
#ifdef FEAT_CRYPT
(char_u *)&p_key, PV_KEY,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"keymap", "kmp", P_STRING|P_ALLOCED|P_VI_DEF|P_RBUF|P_RSTAT|P_NFNAME|P_PRI_MKRC,
#ifdef FEAT_KEYMAP
(char_u *)&p_keymap, PV_KMAP,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)"", (char_u *)0L}
#endif
SCRIPTID_INIT},
{"keymodel", "km", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
(char_u *)&p_km, PV_NONE,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"keywordprg", "kp", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
(char_u *)&p_kp, PV_KP,
{
#ifdef MSWIN
(char_u *)":help",
#else
# ifdef VMS
(char_u *)"help",
# else
# ifdef USEMAN_S
(char_u *)"man -s",
# else
(char_u *)"man",
# endif
# endif
#endif
(char_u *)0L} SCRIPTID_INIT},
{"langmap", "lmap", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP|P_SECURE,
#ifdef FEAT_LANGMAP
(char_u *)&p_langmap, PV_NONE,
{(char_u *)"", /* unmatched } */
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL,
#endif
(char_u *)0L} SCRIPTID_INIT},
{"langmenu", "lm", P_STRING|P_VI_DEF|P_NFNAME,
#if defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)
(char_u *)&p_lm, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"langnoremap", "lnr", P_BOOL|P_VI_DEF,
#ifdef FEAT_LANGMAP
(char_u *)&p_lnr, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"langremap", "lrm", P_BOOL|P_VI_DEF,
#ifdef FEAT_LANGMAP
(char_u *)&p_lrm, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"laststatus", "ls", P_NUM|P_VI_DEF|P_RALL,
#ifdef FEAT_WINDOWS
(char_u *)&p_ls, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)1L, (char_u *)0L} SCRIPTID_INIT},
{"lazyredraw", "lz", P_BOOL|P_VI_DEF,
(char_u *)&p_lz, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"linebreak", "lbr", P_BOOL|P_VI_DEF|P_RWIN,
#ifdef FEAT_LINEBREAK
(char_u *)VAR_WIN, PV_LBR,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"lines", NULL, P_NUM|P_NODEFAULT|P_NO_MKRC|P_VI_DEF|P_RCLR,
(char_u *)&Rows, PV_NONE,
{
#if defined(WIN3264)
(char_u *)25L,
#else
(char_u *)24L,
#endif
(char_u *)0L} SCRIPTID_INIT},
{"linespace", "lsp", P_NUM|P_VI_DEF|P_RCLR,
#ifdef FEAT_GUI
(char_u *)&p_linespace, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
#ifdef FEAT_GUI_W32
{(char_u *)1L, (char_u *)0L}
#else
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"lisp", NULL, P_BOOL|P_VI_DEF,
#ifdef FEAT_LISP
(char_u *)&p_lisp, PV_LISP,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"lispwords", "lw", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_LISP
(char_u *)&p_lispwords, PV_LW,
{(char_u *)LISPWORD_VALUE, (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)"", (char_u *)0L}
#endif
SCRIPTID_INIT},
{"list", NULL, P_BOOL|P_VI_DEF|P_RWIN,
(char_u *)VAR_WIN, PV_LIST,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"listchars", "lcs", P_STRING|P_VI_DEF|P_RALL|P_ONECOMMA|P_NODUP,
(char_u *)&p_lcs, PV_NONE,
{(char_u *)"eol:$", (char_u *)0L} SCRIPTID_INIT},
{"loadplugins", "lpl", P_BOOL|P_VI_DEF,
(char_u *)&p_lpl, PV_NONE,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
#if defined(DYNAMIC_LUA)
{"luadll", NULL, P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
(char_u *)&p_luadll, PV_NONE,
{(char_u *)DYNAMIC_LUA_DLL, (char_u *)0L}
SCRIPTID_INIT},
#endif
#ifdef FEAT_GUI_MAC
{"macatsui", NULL, P_BOOL|P_VI_DEF|P_RCLR,
(char_u *)&p_macatsui, PV_NONE,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
#endif
{"magic", NULL, P_BOOL|P_VI_DEF,
(char_u *)&p_magic, PV_NONE,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"makeef", "mef", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
#ifdef FEAT_QUICKFIX
(char_u *)&p_mef, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"makeprg", "mp", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
#ifdef FEAT_QUICKFIX
(char_u *)&p_mp, PV_MP,
# ifdef VMS
{(char_u *)"MMS", (char_u *)0L}
# else
{(char_u *)"make", (char_u *)0L}
# endif
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"matchpairs", "mps", P_STRING|P_ALLOCED|P_VI_DEF|P_ONECOMMA|P_NODUP,
(char_u *)&p_mps, PV_MPS,
{(char_u *)"(:),{:},[:]", (char_u *)0L}
SCRIPTID_INIT},
{"matchtime", "mat", P_NUM|P_VI_DEF,
(char_u *)&p_mat, PV_NONE,
{(char_u *)5L, (char_u *)0L} SCRIPTID_INIT},
{"maxcombine", "mco", P_NUM|P_VI_DEF|P_CURSWANT,
#ifdef FEAT_MBYTE
(char_u *)&p_mco, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)2, (char_u *)0L} SCRIPTID_INIT},
{"maxfuncdepth", "mfd", P_NUM|P_VI_DEF,
#ifdef FEAT_EVAL
(char_u *)&p_mfd, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)100L, (char_u *)0L} SCRIPTID_INIT},
{"maxmapdepth", "mmd", P_NUM|P_VI_DEF,
(char_u *)&p_mmd, PV_NONE,
{(char_u *)1000L, (char_u *)0L} SCRIPTID_INIT},
{"maxmem", "mm", P_NUM|P_VI_DEF,
(char_u *)&p_mm, PV_NONE,
{(char_u *)DFLT_MAXMEM, (char_u *)0L}
SCRIPTID_INIT},
{"maxmempattern","mmp", P_NUM|P_VI_DEF,
(char_u *)&p_mmp, PV_NONE,
{(char_u *)1000L, (char_u *)0L} SCRIPTID_INIT},
{"maxmemtot", "mmt", P_NUM|P_VI_DEF,
(char_u *)&p_mmt, PV_NONE,
{(char_u *)DFLT_MAXMEMTOT, (char_u *)0L}
SCRIPTID_INIT},
{"menuitems", "mis", P_NUM|P_VI_DEF,
#ifdef FEAT_MENU
(char_u *)&p_mis, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)25L, (char_u *)0L} SCRIPTID_INIT},
{"mesg", NULL, P_BOOL|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"mkspellmem", "msm", P_STRING|P_VI_DEF|P_EXPAND|P_SECURE,
#ifdef FEAT_SPELL
(char_u *)&p_msm, PV_NONE,
{(char_u *)"460000,2000,500", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"modeline", "ml", P_BOOL|P_VIM,
(char_u *)&p_ml, PV_ML,
{(char_u *)FALSE, (char_u *)TRUE} SCRIPTID_INIT},
{"modelines", "mls", P_NUM|P_VI_DEF,
(char_u *)&p_mls, PV_NONE,
{(char_u *)5L, (char_u *)0L} SCRIPTID_INIT},
{"modifiable", "ma", P_BOOL|P_VI_DEF|P_NOGLOB,
(char_u *)&p_ma, PV_MA,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"modified", "mod", P_BOOL|P_NO_MKRC|P_VI_DEF|P_RSTAT,
(char_u *)&p_mod, PV_MOD,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"more", NULL, P_BOOL|P_VIM,
(char_u *)&p_more, PV_NONE,
{(char_u *)FALSE, (char_u *)TRUE} SCRIPTID_INIT},
{"mouse", NULL, P_STRING|P_VI_DEF|P_FLAGLIST,
(char_u *)&p_mouse, PV_NONE,
{
#if defined(WIN3264)
(char_u *)"a",
#else
(char_u *)"",
#endif
(char_u *)0L} SCRIPTID_INIT},
{"mousefocus", "mousef", P_BOOL|P_VI_DEF,
#ifdef FEAT_GUI
(char_u *)&p_mousef, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"mousehide", "mh", P_BOOL|P_VI_DEF,
#ifdef FEAT_GUI
(char_u *)&p_mh, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"mousemodel", "mousem", P_STRING|P_VI_DEF,
(char_u *)&p_mousem, PV_NONE,
{
#if defined(MSWIN)
(char_u *)"popup",
#else
# if defined(MACOS)
(char_u *)"popup_setpos",
# else
(char_u *)"extend",
# endif
#endif
(char_u *)0L} SCRIPTID_INIT},
{"mouseshape", "mouses", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_MOUSESHAPE
(char_u *)&p_mouseshape, PV_NONE,
{(char_u *)"i-r:beam,s:updown,sd:udsizing,vs:leftright,vd:lrsizing,m:no,ml:up-arrow,v:rightup-arrow", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"mousetime", "mouset", P_NUM|P_VI_DEF,
(char_u *)&p_mouset, PV_NONE,
{(char_u *)500L, (char_u *)0L} SCRIPTID_INIT},
{"mzquantum", "mzq", P_NUM,
#ifdef FEAT_MZSCHEME
(char_u *)&p_mzq, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)100L, (char_u *)100L} SCRIPTID_INIT},
{"novice", NULL, P_BOOL|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"nrformats", "nf", P_STRING|P_ALLOCED|P_VI_DEF|P_ONECOMMA|P_NODUP,
(char_u *)&p_nf, PV_NF,
{(char_u *)"bin,octal,hex", (char_u *)0L}
SCRIPTID_INIT},
{"number", "nu", P_BOOL|P_VI_DEF|P_RWIN,
(char_u *)VAR_WIN, PV_NU,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"numberwidth", "nuw", P_NUM|P_RWIN|P_VIM,
#ifdef FEAT_LINEBREAK
(char_u *)VAR_WIN, PV_NUW,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)8L, (char_u *)4L} SCRIPTID_INIT},
{"omnifunc", "ofu", P_STRING|P_ALLOCED|P_VI_DEF|P_SECURE,
#ifdef FEAT_COMPL_FUNC
(char_u *)&p_ofu, PV_OFU,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"open", NULL, P_BOOL|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"opendevice", "odev", P_BOOL|P_VI_DEF,
#if defined(MSWIN)
(char_u *)&p_odev, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)FALSE}
SCRIPTID_INIT},
{"operatorfunc", "opfunc", P_STRING|P_VI_DEF|P_SECURE,
(char_u *)&p_opfunc, PV_NONE,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"optimize", "opt", P_BOOL|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"osfiletype", "oft", P_STRING|P_ALLOCED|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"packpath", "pp", P_STRING|P_VI_DEF|P_EXPAND|P_ONECOMMA|P_NODUP
|P_SECURE,
(char_u *)&p_pp, PV_NONE,
{(char_u *)DFLT_RUNTIMEPATH, (char_u *)0L}
SCRIPTID_INIT},
{"paragraphs", "para", P_STRING|P_VI_DEF,
(char_u *)&p_para, PV_NONE,
{(char_u *)"IPLPPPQPP TPHPLIPpLpItpplpipbp",
(char_u *)0L} SCRIPTID_INIT},
{"paste", NULL, P_BOOL|P_VI_DEF|P_PRI_MKRC,
(char_u *)&p_paste, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"pastetoggle", "pt", P_STRING|P_VI_DEF,
(char_u *)&p_pt, PV_NONE,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"patchexpr", "pex", P_STRING|P_VI_DEF|P_SECURE,
#if defined(FEAT_DIFF) && defined(FEAT_EVAL)
(char_u *)&p_pex, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"patchmode", "pm", P_STRING|P_VI_DEF|P_NFNAME,
(char_u *)&p_pm, PV_NONE,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"path", "pa", P_STRING|P_EXPAND|P_VI_DEF|P_COMMA|P_NODUP,
(char_u *)&p_path, PV_PATH,
{
#if defined(AMIGA) || defined(MSWIN)
(char_u *)".,,",
#else
(char_u *)".,/usr/include,,",
#endif
(char_u *)0L} SCRIPTID_INIT},
#if defined(DYNAMIC_PERL)
{"perldll", NULL, P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
(char_u *)&p_perldll, PV_NONE,
{(char_u *)DYNAMIC_PERL_DLL, (char_u *)0L}
SCRIPTID_INIT},
#endif
{"preserveindent", "pi", P_BOOL|P_VI_DEF|P_VIM,
(char_u *)&p_pi, PV_PI,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"previewheight", "pvh", P_NUM|P_VI_DEF,
#if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
(char_u *)&p_pvh, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)12L, (char_u *)0L} SCRIPTID_INIT},
{"previewwindow", "pvw", P_BOOL|P_VI_DEF|P_RSTAT|P_NOGLOB,
#if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
(char_u *)VAR_WIN, PV_PVW,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"printdevice", "pdev", P_STRING|P_VI_DEF|P_SECURE,
#ifdef FEAT_PRINTER
(char_u *)&p_pdev, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"printencoding", "penc", P_STRING|P_VI_DEF,
#ifdef FEAT_POSTSCRIPT
(char_u *)&p_penc, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"printexpr", "pexpr", P_STRING|P_VI_DEF,
#ifdef FEAT_POSTSCRIPT
(char_u *)&p_pexpr, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"printfont", "pfn", P_STRING|P_VI_DEF,
#ifdef FEAT_PRINTER
(char_u *)&p_pfn, PV_NONE,
{
# ifdef MSWIN
(char_u *)"Courier_New:h10",
# else
(char_u *)"courier",
# endif
(char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"printheader", "pheader", P_STRING|P_VI_DEF|P_GETTEXT,
#ifdef FEAT_PRINTER
(char_u *)&p_header, PV_NONE,
{(char_u *)N_("%<%f%h%m%=Page %N"), (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"printmbcharset", "pmbcs", P_STRING|P_VI_DEF,
#if defined(FEAT_POSTSCRIPT) && defined(FEAT_MBYTE)
(char_u *)&p_pmcs, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"printmbfont", "pmbfn", P_STRING|P_VI_DEF,
#if defined(FEAT_POSTSCRIPT) && defined(FEAT_MBYTE)
(char_u *)&p_pmfn, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"printoptions", "popt", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_PRINTER
(char_u *)&p_popt, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"prompt", NULL, P_BOOL|P_VI_DEF,
(char_u *)&p_prompt, PV_NONE,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"pumheight", "ph", P_NUM|P_VI_DEF,
#ifdef FEAT_INS_EXPAND
(char_u *)&p_ph, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
#if defined(DYNAMIC_PYTHON3)
{"pythonthreedll", NULL, P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
(char_u *)&p_py3dll, PV_NONE,
{(char_u *)DYNAMIC_PYTHON3_DLL, (char_u *)0L}
SCRIPTID_INIT},
#endif
#if defined(DYNAMIC_PYTHON)
{"pythondll", NULL, P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
(char_u *)&p_pydll, PV_NONE,
{(char_u *)DYNAMIC_PYTHON_DLL, (char_u *)0L}
SCRIPTID_INIT},
#endif
{"quoteescape", "qe", P_STRING|P_ALLOCED|P_VI_DEF,
#ifdef FEAT_TEXTOBJ
(char_u *)&p_qe, PV_QE,
{(char_u *)"\\", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"readonly", "ro", P_BOOL|P_VI_DEF|P_RSTAT|P_NOGLOB,
(char_u *)&p_ro, PV_RO,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"redraw", NULL, P_BOOL|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"redrawtime", "rdt", P_NUM|P_VI_DEF,
#ifdef FEAT_RELTIME
(char_u *)&p_rdt, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)2000L, (char_u *)0L} SCRIPTID_INIT},
{"regexpengine", "re", P_NUM|P_VI_DEF,
(char_u *)&p_re, PV_NONE,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"relativenumber", "rnu", P_BOOL|P_VI_DEF|P_RWIN,
(char_u *)VAR_WIN, PV_RNU,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"remap", NULL, P_BOOL|P_VI_DEF,
(char_u *)&p_remap, PV_NONE,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"renderoptions", "rop", P_STRING|P_ONECOMMA|P_RCLR|P_VI_DEF,
#ifdef FEAT_RENDER_OPTIONS
(char_u *)&p_rop, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"report", NULL, P_NUM|P_VI_DEF,
(char_u *)&p_report, PV_NONE,
{(char_u *)2L, (char_u *)0L} SCRIPTID_INIT},
{"restorescreen", "rs", P_BOOL|P_VI_DEF,
#ifdef WIN3264
(char_u *)&p_rs, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"revins", "ri", P_BOOL|P_VI_DEF|P_VIM,
#ifdef FEAT_RIGHTLEFT
(char_u *)&p_ri, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"rightleft", "rl", P_BOOL|P_VI_DEF|P_RWIN,
#ifdef FEAT_RIGHTLEFT
(char_u *)VAR_WIN, PV_RL,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"rightleftcmd", "rlc", P_STRING|P_ALLOCED|P_VI_DEF|P_RWIN,
#ifdef FEAT_RIGHTLEFT
(char_u *)VAR_WIN, PV_RLC,
{(char_u *)"search", (char_u *)NULL}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
#if defined(DYNAMIC_RUBY)
{"rubydll", NULL, P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
(char_u *)&p_rubydll, PV_NONE,
{(char_u *)DYNAMIC_RUBY_DLL, (char_u *)0L}
SCRIPTID_INIT},
#endif
{"ruler", "ru", P_BOOL|P_VI_DEF|P_VIM|P_RSTAT,
#ifdef FEAT_CMDL_INFO
(char_u *)&p_ru, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"rulerformat", "ruf", P_STRING|P_VI_DEF|P_ALLOCED|P_RSTAT,
#ifdef FEAT_STL_OPT
(char_u *)&p_ruf, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"runtimepath", "rtp", P_STRING|P_VI_DEF|P_EXPAND|P_ONECOMMA|P_NODUP
|P_SECURE,
(char_u *)&p_rtp, PV_NONE,
{(char_u *)DFLT_RUNTIMEPATH, (char_u *)0L}
SCRIPTID_INIT},
{"scroll", "scr", P_NUM|P_NO_MKRC|P_VI_DEF,
(char_u *)VAR_WIN, PV_SCROLL,
{(char_u *)12L, (char_u *)0L} SCRIPTID_INIT},
{"scrollbind", "scb", P_BOOL|P_VI_DEF,
#ifdef FEAT_SCROLLBIND
(char_u *)VAR_WIN, PV_SCBIND,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"scrolljump", "sj", P_NUM|P_VI_DEF|P_VIM,
(char_u *)&p_sj, PV_NONE,
{(char_u *)1L, (char_u *)0L} SCRIPTID_INIT},
{"scrolloff", "so", P_NUM|P_VI_DEF|P_VIM|P_RALL,
(char_u *)&p_so, PV_NONE,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"scrollopt", "sbo", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_SCROLLBIND
(char_u *)&p_sbo, PV_NONE,
{(char_u *)"ver,jump", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"sections", "sect", P_STRING|P_VI_DEF,
(char_u *)&p_sections, PV_NONE,
{(char_u *)"SHNHH HUnhsh", (char_u *)0L}
SCRIPTID_INIT},
{"secure", NULL, P_BOOL|P_VI_DEF|P_SECURE,
(char_u *)&p_secure, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"selection", "sel", P_STRING|P_VI_DEF,
(char_u *)&p_sel, PV_NONE,
{(char_u *)"inclusive", (char_u *)0L}
SCRIPTID_INIT},
{"selectmode", "slm", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
(char_u *)&p_slm, PV_NONE,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"sessionoptions", "ssop", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_SESSION
(char_u *)&p_ssop, PV_NONE,
{(char_u *)"blank,buffers,curdir,folds,help,options,tabpages,winsize",
(char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"shell", "sh", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
(char_u *)&p_sh, PV_NONE,
{
#ifdef VMS
(char_u *)"-",
#else
# if defined(WIN3264)
(char_u *)"", /* set in set_init_1() */
# else
(char_u *)"sh",
# endif
#endif /* VMS */
(char_u *)0L} SCRIPTID_INIT},
{"shellcmdflag","shcf", P_STRING|P_VI_DEF|P_SECURE,
(char_u *)&p_shcf, PV_NONE,
{
#if defined(MSWIN)
(char_u *)"/c",
#else
(char_u *)"-c",
#endif
(char_u *)0L} SCRIPTID_INIT},
{"shellpipe", "sp", P_STRING|P_VI_DEF|P_SECURE,
#ifdef FEAT_QUICKFIX
(char_u *)&p_sp, PV_NONE,
{
#if defined(UNIX)
(char_u *)"| tee",
#else
(char_u *)">",
#endif
(char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"shellquote", "shq", P_STRING|P_VI_DEF|P_SECURE,
(char_u *)&p_shq, PV_NONE,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"shellredir", "srr", P_STRING|P_VI_DEF|P_SECURE,
(char_u *)&p_srr, PV_NONE,
{(char_u *)">", (char_u *)0L} SCRIPTID_INIT},
{"shellslash", "ssl", P_BOOL|P_VI_DEF,
#ifdef BACKSLASH_IN_FILENAME
(char_u *)&p_ssl, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"shelltemp", "stmp", P_BOOL,
(char_u *)&p_stmp, PV_NONE,
{(char_u *)FALSE, (char_u *)TRUE} SCRIPTID_INIT},
{"shelltype", "st", P_NUM|P_VI_DEF,
#ifdef AMIGA
(char_u *)&p_st, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"shellxquote", "sxq", P_STRING|P_VI_DEF|P_SECURE,
(char_u *)&p_sxq, PV_NONE,
{
#if defined(UNIX) && defined(USE_SYSTEM)
(char_u *)"\"",
#else
(char_u *)"",
#endif
(char_u *)0L} SCRIPTID_INIT},
{"shellxescape", "sxe", P_STRING|P_VI_DEF|P_SECURE,
(char_u *)&p_sxe, PV_NONE,
{
#if defined(WIN3264)
(char_u *)"\"&|<>()@^",
#else
(char_u *)"",
#endif
(char_u *)0L} SCRIPTID_INIT},
{"shiftround", "sr", P_BOOL|P_VI_DEF|P_VIM,
(char_u *)&p_sr, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"shiftwidth", "sw", P_NUM|P_VI_DEF,
(char_u *)&p_sw, PV_SW,
{(char_u *)8L, (char_u *)0L} SCRIPTID_INIT},
{"shortmess", "shm", P_STRING|P_VIM|P_FLAGLIST,
(char_u *)&p_shm, PV_NONE,
{(char_u *)"", (char_u *)"filnxtToO"}
SCRIPTID_INIT},
{"shortname", "sn", P_BOOL|P_VI_DEF,
(char_u *)&p_sn, PV_SN,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"showbreak", "sbr", P_STRING|P_VI_DEF|P_RALL,
#ifdef FEAT_LINEBREAK
(char_u *)&p_sbr, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"showcmd", "sc", P_BOOL|P_VIM,
#ifdef FEAT_CMDL_INFO
(char_u *)&p_sc, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE,
#ifdef UNIX
(char_u *)FALSE
#else
(char_u *)TRUE
#endif
} SCRIPTID_INIT},
{"showfulltag", "sft", P_BOOL|P_VI_DEF,
(char_u *)&p_sft, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"showmatch", "sm", P_BOOL|P_VI_DEF,
(char_u *)&p_sm, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"showmode", "smd", P_BOOL|P_VIM,
(char_u *)&p_smd, PV_NONE,
{(char_u *)FALSE, (char_u *)TRUE} SCRIPTID_INIT},
{"showtabline", "stal", P_NUM|P_VI_DEF|P_RALL,
#ifdef FEAT_WINDOWS
(char_u *)&p_stal, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)1L, (char_u *)0L} SCRIPTID_INIT},
{"sidescroll", "ss", P_NUM|P_VI_DEF,
(char_u *)&p_ss, PV_NONE,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"sidescrolloff", "siso", P_NUM|P_VI_DEF|P_VIM|P_RBUF,
(char_u *)&p_siso, PV_NONE,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"signcolumn", "scl", P_STRING|P_ALLOCED|P_VI_DEF|P_RWIN,
#ifdef FEAT_SIGNS
(char_u *)VAR_WIN, PV_SCL,
{(char_u *)"auto", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"slowopen", "slow", P_BOOL|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"smartcase", "scs", P_BOOL|P_VI_DEF|P_VIM,
(char_u *)&p_scs, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"smartindent", "si", P_BOOL|P_VI_DEF|P_VIM,
#ifdef FEAT_SMARTINDENT
(char_u *)&p_si, PV_SI,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"smarttab", "sta", P_BOOL|P_VI_DEF|P_VIM,
(char_u *)&p_sta, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"softtabstop", "sts", P_NUM|P_VI_DEF|P_VIM,
(char_u *)&p_sts, PV_STS,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"sourceany", NULL, P_BOOL|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"spell", NULL, P_BOOL|P_VI_DEF|P_RWIN,
#ifdef FEAT_SPELL
(char_u *)VAR_WIN, PV_SPELL,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"spellcapcheck", "spc", P_STRING|P_ALLOCED|P_VI_DEF|P_RBUF,
#ifdef FEAT_SPELL
(char_u *)&p_spc, PV_SPC,
{(char_u *)"[.?!]\\_[\\])'\" ]\\+", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"spellfile", "spf", P_STRING|P_EXPAND|P_ALLOCED|P_VI_DEF|P_SECURE
|P_ONECOMMA,
#ifdef FEAT_SPELL
(char_u *)&p_spf, PV_SPF,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"spelllang", "spl", P_STRING|P_ALLOCED|P_VI_DEF|P_ONECOMMA
|P_RBUF|P_EXPAND,
#ifdef FEAT_SPELL
(char_u *)&p_spl, PV_SPL,
{(char_u *)"en", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"spellsuggest", "sps", P_STRING|P_VI_DEF|P_EXPAND|P_SECURE|P_ONECOMMA,
#ifdef FEAT_SPELL
(char_u *)&p_sps, PV_NONE,
{(char_u *)"best", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"splitbelow", "sb", P_BOOL|P_VI_DEF,
#ifdef FEAT_WINDOWS
(char_u *)&p_sb, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"splitright", "spr", P_BOOL|P_VI_DEF,
#ifdef FEAT_WINDOWS
(char_u *)&p_spr, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"startofline", "sol", P_BOOL|P_VI_DEF|P_VIM,
(char_u *)&p_sol, PV_NONE,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"statusline" ,"stl", P_STRING|P_VI_DEF|P_ALLOCED|P_RSTAT,
#ifdef FEAT_STL_OPT
(char_u *)&p_stl, PV_STL,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"suffixes", "su", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
(char_u *)&p_su, PV_NONE,
{(char_u *)".bak,~,.o,.h,.info,.swp,.obj",
(char_u *)0L} SCRIPTID_INIT},
{"suffixesadd", "sua", P_STRING|P_VI_DEF|P_ALLOCED|P_ONECOMMA|P_NODUP,
#ifdef FEAT_SEARCHPATH
(char_u *)&p_sua, PV_SUA,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"swapfile", "swf", P_BOOL|P_VI_DEF|P_RSTAT,
(char_u *)&p_swf, PV_SWF,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"swapsync", "sws", P_STRING|P_VI_DEF,
(char_u *)&p_sws, PV_NONE,
{(char_u *)"fsync", (char_u *)0L} SCRIPTID_INIT},
{"switchbuf", "swb", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
(char_u *)&p_swb, PV_NONE,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"synmaxcol", "smc", P_NUM|P_VI_DEF|P_RBUF,
#ifdef FEAT_SYN_HL
(char_u *)&p_smc, PV_SMC,
{(char_u *)3000L, (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"syntax", "syn", P_STRING|P_ALLOCED|P_VI_DEF|P_NOGLOB|P_NFNAME,
#ifdef FEAT_SYN_HL
(char_u *)&p_syn, PV_SYN,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"tabline", "tal", P_STRING|P_VI_DEF|P_RALL,
#ifdef FEAT_STL_OPT
(char_u *)&p_tal, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"tabpagemax", "tpm", P_NUM|P_VI_DEF,
#ifdef FEAT_WINDOWS
(char_u *)&p_tpm, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)10L, (char_u *)0L} SCRIPTID_INIT},
{"tabstop", "ts", P_NUM|P_VI_DEF|P_RBUF,
(char_u *)&p_ts, PV_TS,
{(char_u *)8L, (char_u *)0L} SCRIPTID_INIT},
{"tagbsearch", "tbs", P_BOOL|P_VI_DEF,
(char_u *)&p_tbs, PV_NONE,
#ifdef VMS /* binary searching doesn't appear to work on VMS */
{(char_u *)0L, (char_u *)0L}
#else
{(char_u *)TRUE, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"tagcase", "tc", P_STRING|P_VIM,
(char_u *)&p_tc, PV_TC,
{(char_u *)"followic", (char_u *)"followic"} SCRIPTID_INIT},
{"taglength", "tl", P_NUM|P_VI_DEF,
(char_u *)&p_tl, PV_NONE,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"tagrelative", "tr", P_BOOL|P_VIM,
(char_u *)&p_tr, PV_NONE,
{(char_u *)FALSE, (char_u *)TRUE} SCRIPTID_INIT},
{"tags", "tag", P_STRING|P_EXPAND|P_VI_DEF|P_ONECOMMA|P_NODUP,
(char_u *)&p_tags, PV_TAGS,
{
#if defined(FEAT_EMACS_TAGS) && !defined(CASE_INSENSITIVE_FILENAME)
(char_u *)"./tags,./TAGS,tags,TAGS",
#else
(char_u *)"./tags,tags",
#endif
(char_u *)0L} SCRIPTID_INIT},
{"tagstack", "tgst", P_BOOL|P_VI_DEF,
(char_u *)&p_tgst, PV_NONE,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
#if defined(DYNAMIC_TCL)
{"tcldll", NULL, P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
(char_u *)&p_tcldll, PV_NONE,
{(char_u *)DYNAMIC_TCL_DLL, (char_u *)0L}
SCRIPTID_INIT},
#endif
{"term", NULL, P_STRING|P_EXPAND|P_NODEFAULT|P_NO_MKRC|P_VI_DEF|P_RALL,
(char_u *)&T_NAME, PV_NONE,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"termbidi", "tbidi", P_BOOL|P_VI_DEF,
#ifdef FEAT_ARABIC
(char_u *)&p_tbidi, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"termencoding", "tenc", P_STRING|P_VI_DEF|P_RCLR,
#ifdef FEAT_MBYTE
(char_u *)&p_tenc, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"termguicolors", "tgc", P_BOOL|P_VI_DEF|P_VIM|P_RCLR,
#ifdef FEAT_TERMGUICOLORS
(char_u *)&p_tgc, PV_NONE,
{(char_u *)FALSE, (char_u *)FALSE}
#else
(char_u*)NULL, PV_NONE,
{(char_u *)FALSE, (char_u *)FALSE}
#endif
SCRIPTID_INIT},
{"terse", NULL, P_BOOL|P_VI_DEF,
(char_u *)&p_terse, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"textauto", "ta", P_BOOL|P_VIM,
(char_u *)&p_ta, PV_NONE,
{(char_u *)DFLT_TEXTAUTO, (char_u *)TRUE}
SCRIPTID_INIT},
{"textmode", "tx", P_BOOL|P_VI_DEF|P_NO_MKRC,
(char_u *)&p_tx, PV_TX,
{
#ifdef USE_CRNL
(char_u *)TRUE,
#else
(char_u *)FALSE,
#endif
(char_u *)0L} SCRIPTID_INIT},
{"textwidth", "tw", P_NUM|P_VI_DEF|P_VIM|P_RBUF,
(char_u *)&p_tw, PV_TW,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"thesaurus", "tsr", P_STRING|P_EXPAND|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_INS_EXPAND
(char_u *)&p_tsr, PV_TSR,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"tildeop", "top", P_BOOL|P_VI_DEF|P_VIM,
(char_u *)&p_to, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"timeout", "to", P_BOOL|P_VI_DEF,
(char_u *)&p_timeout, PV_NONE,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"timeoutlen", "tm", P_NUM|P_VI_DEF,
(char_u *)&p_tm, PV_NONE,
{(char_u *)1000L, (char_u *)0L} SCRIPTID_INIT},
{"title", NULL, P_BOOL|P_VI_DEF,
#ifdef FEAT_TITLE
(char_u *)&p_title, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"titlelen", NULL, P_NUM|P_VI_DEF,
#ifdef FEAT_TITLE
(char_u *)&p_titlelen, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)85L, (char_u *)0L} SCRIPTID_INIT},
{"titleold", NULL, P_STRING|P_VI_DEF|P_GETTEXT|P_SECURE|P_NO_MKRC,
#ifdef FEAT_TITLE
(char_u *)&p_titleold, PV_NONE,
{(char_u *)N_("Thanks for flying Vim"),
(char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"titlestring", NULL, P_STRING|P_VI_DEF,
#ifdef FEAT_TITLE
(char_u *)&p_titlestring, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
#if defined(FEAT_TOOLBAR) && !defined(FEAT_GUI_W32)
{"toolbar", "tb", P_STRING|P_ONECOMMA|P_VI_DEF|P_NODUP,
(char_u *)&p_toolbar, PV_NONE,
{(char_u *)"icons,tooltips", (char_u *)0L}
SCRIPTID_INIT},
#endif
#if defined(FEAT_TOOLBAR) && defined(FEAT_GUI_GTK)
{"toolbariconsize", "tbis", P_STRING|P_VI_DEF,
(char_u *)&p_tbis, PV_NONE,
{(char_u *)"small", (char_u *)0L} SCRIPTID_INIT},
#endif
{"ttimeout", NULL, P_BOOL|P_VI_DEF|P_VIM,
(char_u *)&p_ttimeout, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"ttimeoutlen", "ttm", P_NUM|P_VI_DEF,
(char_u *)&p_ttm, PV_NONE,
{(char_u *)-1L, (char_u *)0L} SCRIPTID_INIT},
{"ttybuiltin", "tbi", P_BOOL|P_VI_DEF,
(char_u *)&p_tbi, PV_NONE,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"ttyfast", "tf", P_BOOL|P_NO_MKRC|P_VI_DEF,
(char_u *)&p_tf, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"ttymouse", "ttym", P_STRING|P_NODEFAULT|P_NO_MKRC|P_VI_DEF,
#if defined(FEAT_MOUSE) && (defined(UNIX) || defined(VMS))
(char_u *)&p_ttym, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"ttyscroll", "tsl", P_NUM|P_VI_DEF,
(char_u *)&p_ttyscroll, PV_NONE,
{(char_u *)999L, (char_u *)0L} SCRIPTID_INIT},
{"ttytype", "tty", P_STRING|P_EXPAND|P_NODEFAULT|P_NO_MKRC|P_VI_DEF|P_RALL,
(char_u *)&T_NAME, PV_NONE,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"undodir", "udir", P_STRING|P_EXPAND|P_ONECOMMA|P_NODUP|P_SECURE
|P_VI_DEF,
#ifdef FEAT_PERSISTENT_UNDO
(char_u *)&p_udir, PV_NONE,
{(char_u *)".", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"undofile", "udf", P_BOOL|P_VI_DEF|P_VIM,
#ifdef FEAT_PERSISTENT_UNDO
(char_u *)&p_udf, PV_UDF,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"undolevels", "ul", P_NUM|P_VI_DEF,
(char_u *)&p_ul, PV_UL,
{
#if defined(UNIX) || defined(WIN3264) || defined(VMS)
(char_u *)1000L,
#else
(char_u *)100L,
#endif
(char_u *)0L} SCRIPTID_INIT},
{"undoreload", "ur", P_NUM|P_VI_DEF,
(char_u *)&p_ur, PV_NONE,
{ (char_u *)10000L, (char_u *)0L} SCRIPTID_INIT},
{"updatecount", "uc", P_NUM|P_VI_DEF,
(char_u *)&p_uc, PV_NONE,
{(char_u *)200L, (char_u *)0L} SCRIPTID_INIT},
{"updatetime", "ut", P_NUM|P_VI_DEF,
(char_u *)&p_ut, PV_NONE,
{(char_u *)4000L, (char_u *)0L} SCRIPTID_INIT},
{"verbose", "vbs", P_NUM|P_VI_DEF,
(char_u *)&p_verbose, PV_NONE,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"verbosefile", "vfile", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
(char_u *)&p_vfile, PV_NONE,
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"viewdir", "vdir", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE,
#ifdef FEAT_SESSION
(char_u *)&p_vdir, PV_NONE,
{(char_u *)DFLT_VDIR, (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"viewoptions", "vop", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_SESSION
(char_u *)&p_vop, PV_NONE,
{(char_u *)"folds,options,cursor", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"viminfo", "vi", P_STRING|P_ONECOMMA|P_NODUP|P_SECURE,
#ifdef FEAT_VIMINFO
(char_u *)&p_viminfo, PV_NONE,
#if defined(MSWIN)
{(char_u *)"", (char_u *)"'100,<50,s10,h,rA:,rB:"}
#else
# ifdef AMIGA
{(char_u *)"",
(char_u *)"'100,<50,s10,h,rdf0:,rdf1:,rdf2:"}
# else
{(char_u *)"", (char_u *)"'100,<50,s10,h"}
# endif
#endif
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"virtualedit", "ve", P_STRING|P_ONECOMMA|P_NODUP|P_VI_DEF
|P_VIM|P_CURSWANT,
#ifdef FEAT_VIRTUALEDIT
(char_u *)&p_ve, PV_NONE,
{(char_u *)"", (char_u *)""}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"visualbell", "vb", P_BOOL|P_VI_DEF,
(char_u *)&p_vb, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"w300", NULL, P_NUM|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"w1200", NULL, P_NUM|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"w9600", NULL, P_NUM|P_VI_DEF,
(char_u *)NULL, PV_NONE,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"warn", NULL, P_BOOL|P_VI_DEF,
(char_u *)&p_warn, PV_NONE,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"weirdinvert", "wiv", P_BOOL|P_VI_DEF|P_RCLR,
(char_u *)&p_wiv, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"whichwrap", "ww", P_STRING|P_VIM|P_ONECOMMA|P_FLAGLIST,
(char_u *)&p_ww, PV_NONE,
{(char_u *)"", (char_u *)"b,s"} SCRIPTID_INIT},
{"wildchar", "wc", P_NUM|P_VIM,
(char_u *)&p_wc, PV_NONE,
{(char_u *)(long)Ctrl_E, (char_u *)(long)TAB}
SCRIPTID_INIT},
{"wildcharm", "wcm", P_NUM|P_VI_DEF,
(char_u *)&p_wcm, PV_NONE,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"wildignore", "wig", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
#ifdef FEAT_WILDIGN
(char_u *)&p_wig, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
{"wildignorecase", "wic", P_BOOL|P_VI_DEF,
(char_u *)&p_wic, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"wildmenu", "wmnu", P_BOOL|P_VI_DEF,
#ifdef FEAT_WILDMENU
(char_u *)&p_wmnu, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"wildmode", "wim", P_STRING|P_VI_DEF|P_ONECOMMA|P_NODUP,
(char_u *)&p_wim, PV_NONE,
{(char_u *)"full", (char_u *)0L} SCRIPTID_INIT},
{"wildoptions", "wop", P_STRING|P_VI_DEF,
#ifdef FEAT_CMDL_COMPL
(char_u *)&p_wop, PV_NONE,
{(char_u *)"", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"winaltkeys", "wak", P_STRING|P_VI_DEF,
#ifdef FEAT_WAK
(char_u *)&p_wak, PV_NONE,
{(char_u *)"menu", (char_u *)0L}
#else
(char_u *)NULL, PV_NONE,
{(char_u *)NULL, (char_u *)0L}
#endif
SCRIPTID_INIT},
{"window", "wi", P_NUM|P_VI_DEF,
(char_u *)&p_window, PV_NONE,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"winheight", "wh", P_NUM|P_VI_DEF,
#ifdef FEAT_WINDOWS
(char_u *)&p_wh, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)1L, (char_u *)0L} SCRIPTID_INIT},
{"winfixheight", "wfh", P_BOOL|P_VI_DEF|P_RSTAT,
#ifdef FEAT_WINDOWS
(char_u *)VAR_WIN, PV_WFH,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"winfixwidth", "wfw", P_BOOL|P_VI_DEF|P_RSTAT,
#ifdef FEAT_WINDOWS
(char_u *)VAR_WIN, PV_WFW,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"winminheight", "wmh", P_NUM|P_VI_DEF,
#ifdef FEAT_WINDOWS
(char_u *)&p_wmh, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)1L, (char_u *)0L} SCRIPTID_INIT},
{"winminwidth", "wmw", P_NUM|P_VI_DEF,
#ifdef FEAT_WINDOWS
(char_u *)&p_wmw, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)1L, (char_u *)0L} SCRIPTID_INIT},
{"winwidth", "wiw", P_NUM|P_VI_DEF,
#ifdef FEAT_WINDOWS
(char_u *)&p_wiw, PV_NONE,
#else
(char_u *)NULL, PV_NONE,
#endif
{(char_u *)20L, (char_u *)0L} SCRIPTID_INIT},
{"wrap", NULL, P_BOOL|P_VI_DEF|P_RWIN,
(char_u *)VAR_WIN, PV_WRAP,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"wrapmargin", "wm", P_NUM|P_VI_DEF,
(char_u *)&p_wm, PV_WM,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
{"wrapscan", "ws", P_BOOL|P_VI_DEF,
(char_u *)&p_ws, PV_NONE,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"write", NULL, P_BOOL|P_VI_DEF,
(char_u *)&p_write, PV_NONE,
{(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT},
{"writeany", "wa", P_BOOL|P_VI_DEF,
(char_u *)&p_wa, PV_NONE,
{(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT},
{"writebackup", "wb", P_BOOL|P_VI_DEF|P_VIM,
(char_u *)&p_wb, PV_NONE,
{
#ifdef FEAT_WRITEBACKUP
(char_u *)TRUE,
#else
(char_u *)FALSE,
#endif
(char_u *)0L} SCRIPTID_INIT},
{"writedelay", "wd", P_NUM|P_VI_DEF,
(char_u *)&p_wd, PV_NONE,
{(char_u *)0L, (char_u *)0L} SCRIPTID_INIT},
/* terminal output codes */
#define p_term(sss, vvv) {sss, NULL, P_STRING|P_VI_DEF|P_RALL|P_SECURE, \
(char_u *)&vvv, PV_NONE, \
{(char_u *)"", (char_u *)0L} SCRIPTID_INIT},
p_term("t_AB", T_CAB)
p_term("t_AF", T_CAF)
p_term("t_AL", T_CAL)
p_term("t_al", T_AL)
p_term("t_bc", T_BC)
p_term("t_cd", T_CD)
p_term("t_ce", T_CE)
p_term("t_cl", T_CL)
p_term("t_cm", T_CM)
p_term("t_Ce", T_UCE)
p_term("t_Co", T_CCO)
p_term("t_CS", T_CCS)
p_term("t_Cs", T_UCS)
p_term("t_cs", T_CS)
#ifdef FEAT_WINDOWS
p_term("t_CV", T_CSV)
#endif
p_term("t_da", T_DA)
p_term("t_db", T_DB)
p_term("t_DL", T_CDL)
p_term("t_dl", T_DL)
p_term("t_EI", T_CEI)
p_term("t_fs", T_FS)
p_term("t_IE", T_CIE)
p_term("t_IS", T_CIS)
p_term("t_ke", T_KE)
p_term("t_ks", T_KS)
p_term("t_le", T_LE)
p_term("t_mb", T_MB)
p_term("t_md", T_MD)
p_term("t_me", T_ME)
p_term("t_mr", T_MR)
p_term("t_ms", T_MS)
p_term("t_nd", T_ND)
p_term("t_op", T_OP)
p_term("t_RB", T_RBG)
p_term("t_RI", T_CRI)
p_term("t_RV", T_CRV)
p_term("t_Sb", T_CSB)
p_term("t_se", T_SE)
p_term("t_Sf", T_CSF)
p_term("t_SI", T_CSI)
p_term("t_so", T_SO)
p_term("t_SR", T_CSR)
p_term("t_sr", T_SR)
p_term("t_te", T_TE)
p_term("t_ti", T_TI)
p_term("t_ts", T_TS)
p_term("t_u7", T_U7)
p_term("t_ue", T_UE)
p_term("t_us", T_US)
p_term("t_ut", T_UT)
p_term("t_vb", T_VB)
p_term("t_ve", T_VE)
p_term("t_vi", T_VI)
p_term("t_vs", T_VS)
p_term("t_WP", T_CWP)
p_term("t_WS", T_CWS)
p_term("t_xn", T_XN)
p_term("t_xs", T_XS)
p_term("t_ZH", T_CZH)
p_term("t_ZR", T_CZR)
p_term("t_8f", T_8F)
p_term("t_8b", T_8B)
/* terminal key codes are not in here */
/* end marker */
{NULL, NULL, 0, NULL, PV_NONE, {NULL, NULL} SCRIPTID_INIT}
};
#define PARAM_COUNT (sizeof(options) / sizeof(struct vimoption))
#ifdef FEAT_MBYTE
static char *(p_ambw_values[]) = {"single", "double", NULL};
#endif
static char *(p_bg_values[]) = {"light", "dark", NULL};
static char *(p_nf_values[]) = {"bin", "octal", "hex", "alpha", NULL};
static char *(p_ff_values[]) = {FF_UNIX, FF_DOS, FF_MAC, NULL};
#ifdef FEAT_CRYPT
static char *(p_cm_values[]) = {"zip", "blowfish", "blowfish2", NULL};
#endif
#ifdef FEAT_CMDL_COMPL
static char *(p_wop_values[]) = {"tagfile", NULL};
#endif
#ifdef FEAT_WAK
static char *(p_wak_values[]) = {"yes", "menu", "no", NULL};
#endif
static char *(p_mousem_values[]) = {"extend", "popup", "popup_setpos", "mac", NULL};
static char *(p_sel_values[]) = {"inclusive", "exclusive", "old", NULL};
static char *(p_slm_values[]) = {"mouse", "key", "cmd", NULL};
static char *(p_km_values[]) = {"startsel", "stopsel", NULL};
#ifdef FEAT_BROWSE
static char *(p_bsdir_values[]) = {"current", "last", "buffer", NULL};
#endif
#ifdef FEAT_SCROLLBIND
static char *(p_scbopt_values[]) = {"ver", "hor", "jump", NULL};
#endif
static char *(p_debug_values[]) = {"msg", "throw", "beep", NULL};
#ifdef FEAT_WINDOWS
static char *(p_ead_values[]) = {"both", "ver", "hor", NULL};
#endif
#if defined(FEAT_QUICKFIX)
# ifdef FEAT_AUTOCMD
static char *(p_buftype_values[]) = {"nofile", "nowrite", "quickfix", "help", "acwrite", NULL};
# else
static char *(p_buftype_values[]) = {"nofile", "nowrite", "quickfix", "help", NULL};
# endif
static char *(p_bufhidden_values[]) = {"hide", "unload", "delete", "wipe", NULL};
#endif
static char *(p_bs_values[]) = {"indent", "eol", "start", NULL};
#ifdef FEAT_FOLDING
static char *(p_fdm_values[]) = {"manual", "expr", "marker", "indent", "syntax",
# ifdef FEAT_DIFF
"diff",
# endif
NULL};
static char *(p_fcl_values[]) = {"all", NULL};
#endif
#ifdef FEAT_INS_EXPAND
static char *(p_cot_values[]) = {"menu", "menuone", "longest", "preview", "noinsert", "noselect", NULL};
#endif
#ifdef FEAT_SIGNS
static char *(p_scl_values[]) = {"yes", "no", "auto", NULL};
#endif
static void set_option_default(int, int opt_flags, int compatible);
static void set_options_default(int opt_flags);
static char_u *term_bg_default(void);
static void did_set_option(int opt_idx, int opt_flags, int new_value);
static char_u *illegal_char(char_u *, int);
static int string_to_key(char_u *arg);
#ifdef FEAT_CMDWIN
static char_u *check_cedit(void);
#endif
#ifdef FEAT_TITLE
static void did_set_title(int icon);
#endif
static char_u *option_expand(int opt_idx, char_u *val);
static void didset_options(void);
static void didset_options2(void);
static void check_string_option(char_u **pp);
#if defined(FEAT_EVAL) || defined(PROTO)
static long_u *insecure_flag(int opt_idx, int opt_flags);
#else
# define insecure_flag(opt_idx, opt_flags) (&options[opt_idx].flags)
#endif
static void set_string_option_global(int opt_idx, char_u **varp);
static char_u *set_string_option(int opt_idx, char_u *value, int opt_flags);
static char_u *did_set_string_option(int opt_idx, char_u **varp, int new_value_alloced, char_u *oldval, char_u *errbuf, int opt_flags);
static char_u *set_chars_option(char_u **varp);
#ifdef FEAT_SYN_HL
static int int_cmp(const void *a, const void *b);
#endif
#ifdef FEAT_CLIPBOARD
static char_u *check_clipboard_option(void);
#endif
#ifdef FEAT_SPELL
static char_u *did_set_spell_option(int is_spellfile);
static char_u *compile_cap_prog(synblock_T *synblock);
#endif
#ifdef FEAT_EVAL
static void set_option_scriptID_idx(int opt_idx, int opt_flags, int id);
#endif
static char_u *set_bool_option(int opt_idx, char_u *varp, int value, int opt_flags);
static char_u *set_num_option(int opt_idx, char_u *varp, long value, char_u *errbuf, size_t errbuflen, int opt_flags);
static void check_redraw(long_u flags);
static int findoption(char_u *);
static int find_key_option(char_u *);
static void showoptions(int all, int opt_flags);
static int optval_default(struct vimoption *, char_u *varp);
static void showoneopt(struct vimoption *, int opt_flags);
static int put_setstring(FILE *fd, char *cmd, char *name, char_u **valuep, int expand);
static int put_setnum(FILE *fd, char *cmd, char *name, long *valuep);
static int put_setbool(FILE *fd, char *cmd, char *name, int value);
static int istermoption(struct vimoption *);
static char_u *get_varp_scope(struct vimoption *p, int opt_flags);
static char_u *get_varp(struct vimoption *);
static void option_value2string(struct vimoption *, int opt_flags);
static void check_winopt(winopt_T *wop);
static int wc_use_keyname(char_u *varp, long *wcp);
#ifdef FEAT_LANGMAP
static void langmap_init(void);
static void langmap_set(void);
#endif
static void paste_option_changed(void);
static void compatible_set(void);
#ifdef FEAT_LINEBREAK
static void fill_breakat_flags(void);
#endif
static int opt_strings_flags(char_u *val, char **values, unsigned *flagp, int list);
static int check_opt_strings(char_u *val, char **values, int);
static int check_opt_wim(void);
#ifdef FEAT_LINEBREAK
static int briopt_check(win_T *wp);
#endif
/*
* Initialize the options, first part.
*
* Called only once from main(), just after creating the first buffer.
*/
void
set_init_1(void)
{
char_u *p;
int opt_idx;
long_u n;
#ifdef FEAT_LANGMAP
langmap_init();
#endif
/* Be Vi compatible by default */
p_cp = TRUE;
/* Use POSIX compatibility when $VIM_POSIX is set. */
if (mch_getenv((char_u *)"VIM_POSIX") != NULL)
{
set_string_default("cpo", (char_u *)CPO_ALL);
set_string_default("shm", (char_u *)"A");
}
/*
* Find default value for 'shell' option.
* Don't use it if it is empty.
*/
if (((p = mch_getenv((char_u *)"SHELL")) != NULL && *p != NUL)
#if defined(MSWIN)
|| ((p = mch_getenv((char_u *)"COMSPEC")) != NULL && *p != NUL)
# ifdef WIN3264
|| ((p = (char_u *)default_shell()) != NULL && *p != NUL)
# endif
#endif
)
set_string_default("sh", p);
#ifdef FEAT_WILDIGN
/*
* Set the default for 'backupskip' to include environment variables for
* temp files.
*/
{
# ifdef UNIX
static char *(names[4]) = {"", "TMPDIR", "TEMP", "TMP"};
# else
static char *(names[3]) = {"TMPDIR", "TEMP", "TMP"};
# endif
int len;
garray_T ga;
int mustfree;
ga_init2(&ga, 1, 100);
for (n = 0; n < (long)(sizeof(names) / sizeof(char *)); ++n)
{
mustfree = FALSE;
# ifdef UNIX
if (*names[n] == NUL)
p = (char_u *)"/tmp";
else
# endif
p = vim_getenv((char_u *)names[n], &mustfree);
if (p != NULL && *p != NUL)
{
/* First time count the NUL, otherwise count the ','. */
len = (int)STRLEN(p) + 3;
if (ga_grow(&ga, len) == OK)
{
if (ga.ga_len > 0)
STRCAT(ga.ga_data, ",");
STRCAT(ga.ga_data, p);
add_pathsep(ga.ga_data);
STRCAT(ga.ga_data, "*");
ga.ga_len += len;
}
}
if (mustfree)
vim_free(p);
}
if (ga.ga_data != NULL)
{
set_string_default("bsk", ga.ga_data);
vim_free(ga.ga_data);
}
}
#endif
/*
* 'maxmemtot' and 'maxmem' may have to be adjusted for available memory
*/
opt_idx = findoption((char_u *)"maxmemtot");
if (opt_idx >= 0)
{
#if !defined(HAVE_AVAIL_MEM) && !defined(HAVE_TOTAL_MEM)
if (options[opt_idx].def_val[VI_DEFAULT] == (char_u *)0L)
#endif
{
#ifdef HAVE_AVAIL_MEM
/* Use amount of memory available at this moment. */
n = (mch_avail_mem(FALSE) >> 1);
#else
# ifdef HAVE_TOTAL_MEM
/* Use amount of memory available to Vim. */
n = (mch_total_mem(FALSE) >> 1);
# else
n = (0x7fffffff >> 11);
# endif
#endif
options[opt_idx].def_val[VI_DEFAULT] = (char_u *)n;
opt_idx = findoption((char_u *)"maxmem");
if (opt_idx >= 0)
{
#if !defined(HAVE_AVAIL_MEM) && !defined(HAVE_TOTAL_MEM)
if ((long)(long_i)options[opt_idx].def_val[VI_DEFAULT] > (long)n
|| (long)(long_i)options[opt_idx].def_val[VI_DEFAULT] == 0L)
#endif
options[opt_idx].def_val[VI_DEFAULT] = (char_u *)n;
}
}
}
#ifdef FEAT_SEARCHPATH
{
char_u *cdpath;
char_u *buf;
int i;
int j;
int mustfree = FALSE;
/* Initialize the 'cdpath' option's default value. */
cdpath = vim_getenv((char_u *)"CDPATH", &mustfree);
if (cdpath != NULL)
{
buf = alloc((unsigned)((STRLEN(cdpath) << 1) + 2));
if (buf != NULL)
{
buf[0] = ','; /* start with ",", current dir first */
j = 1;
for (i = 0; cdpath[i] != NUL; ++i)
{
if (vim_ispathlistsep(cdpath[i]))
buf[j++] = ',';
else
{
if (cdpath[i] == ' ' || cdpath[i] == ',')
buf[j++] = '\\';
buf[j++] = cdpath[i];
}
}
buf[j] = NUL;
opt_idx = findoption((char_u *)"cdpath");
if (opt_idx >= 0)
{
options[opt_idx].def_val[VI_DEFAULT] = buf;
options[opt_idx].flags |= P_DEF_ALLOCED;
}
else
vim_free(buf); /* cannot happen */
}
if (mustfree)
vim_free(cdpath);
}
}
#endif
#if defined(FEAT_POSTSCRIPT) && (defined(MSWIN) || defined(VMS) || defined(EBCDIC) || defined(MAC) || defined(hpux))
/* Set print encoding on platforms that don't default to latin1 */
set_string_default("penc",
# if defined(MSWIN)
(char_u *)"cp1252"
# else
# ifdef VMS
(char_u *)"dec-mcs"
# else
# ifdef EBCDIC
(char_u *)"ebcdic-uk"
# else
# ifdef MAC
(char_u *)"mac-roman"
# else /* HPUX */
(char_u *)"hp-roman8"
# endif
# endif
# endif
# endif
);
#endif
#ifdef FEAT_POSTSCRIPT
/* 'printexpr' must be allocated to be able to evaluate it. */
set_string_default("pexpr",
# if defined(MSWIN)
(char_u *)"system('copy' . ' ' . v:fname_in . (&printdevice == '' ? ' LPT1:' : (' \"' . &printdevice . '\"'))) . delete(v:fname_in)"
# else
# ifdef VMS
(char_u *)"system('print/delete' . (&printdevice == '' ? '' : ' /queue=' . &printdevice) . ' ' . v:fname_in)"
# else
(char_u *)"system('lpr' . (&printdevice == '' ? '' : ' -P' . &printdevice) . ' ' . v:fname_in) . delete(v:fname_in) + v:shell_error"
# endif
# endif
);
#endif
/*
* Set all the options (except the terminal options) to their default
* value. Also set the global value for local options.
*/
set_options_default(0);
#ifdef FEAT_GUI
if (found_reverse_arg)
set_option_value((char_u *)"bg", 0L, (char_u *)"dark", 0);
#endif
curbuf->b_p_initialized = TRUE;
curbuf->b_p_ar = -1; /* no local 'autoread' value */
curbuf->b_p_ul = NO_LOCAL_UNDOLEVEL;
check_buf_options(curbuf);
check_win_options(curwin);
check_options();
/* Must be before option_expand(), because that one needs vim_isIDc() */
didset_options();
#ifdef FEAT_SPELL
/* Use the current chartab for the generic chartab. This is not in
* didset_options() because it only depends on 'encoding'. */
init_spell_chartab();
#endif
/*
* Expand environment variables and things like "~" for the defaults.
* If option_expand() returns non-NULL the variable is expanded. This can
* only happen for non-indirect options.
* Also set the default to the expanded value, so ":set" does not list
* them.
* Don't set the P_ALLOCED flag, because we don't want to free the
* default.
*/
for (opt_idx = 0; !istermoption(&options[opt_idx]); opt_idx++)
{
if ((options[opt_idx].flags & P_GETTEXT)
&& options[opt_idx].var != NULL)
p = (char_u *)_(*(char **)options[opt_idx].var);
else
p = option_expand(opt_idx, NULL);
if (p != NULL && (p = vim_strsave(p)) != NULL)
{
*(char_u **)options[opt_idx].var = p;
/* VIMEXP
* Defaults for all expanded options are currently the same for Vi
* and Vim. When this changes, add some code here! Also need to
* split P_DEF_ALLOCED in two.
*/
if (options[opt_idx].flags & P_DEF_ALLOCED)
vim_free(options[opt_idx].def_val[VI_DEFAULT]);
options[opt_idx].def_val[VI_DEFAULT] = p;
options[opt_idx].flags |= P_DEF_ALLOCED;
}
}
save_file_ff(curbuf); /* Buffer is unchanged */
#if defined(FEAT_ARABIC)
/* Detect use of mlterm.
* Mlterm is a terminal emulator akin to xterm that has some special
* abilities (bidi namely).
* NOTE: mlterm's author is being asked to 'set' a variable
* instead of an environment variable due to inheritance.
*/
if (mch_getenv((char_u *)"MLTERM") != NULL)
set_option_value((char_u *)"tbidi", 1L, NULL, 0);
#endif
didset_options2();
#ifdef FEAT_MBYTE
# if defined(WIN3264) && defined(FEAT_GETTEXT)
/*
* If $LANG isn't set, try to get a good value for it. This makes the
* right language be used automatically. Don't do this for English.
*/
if (mch_getenv((char_u *)"LANG") == NULL)
{
char buf[20];
/* Could use LOCALE_SISO639LANGNAME, but it's not in Win95.
* LOCALE_SABBREVLANGNAME gives us three letters, like "enu", we use
* only the first two. */
n = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SABBREVLANGNAME,
(LPTSTR)buf, 20);
if (n >= 2 && STRNICMP(buf, "en", 2) != 0)
{
/* There are a few exceptions (probably more) */
if (STRNICMP(buf, "cht", 3) == 0 || STRNICMP(buf, "zht", 3) == 0)
STRCPY(buf, "zh_TW");
else if (STRNICMP(buf, "chs", 3) == 0
|| STRNICMP(buf, "zhc", 3) == 0)
STRCPY(buf, "zh_CN");
else if (STRNICMP(buf, "jp", 2) == 0)
STRCPY(buf, "ja");
else
buf[2] = NUL; /* truncate to two-letter code */
vim_setenv((char_u *)"LANG", (char_u *)buf);
}
}
# else
# ifdef MACOS_CONVERT
/* Moved to os_mac_conv.c to avoid dependency problems. */
mac_lang_init();
# endif
# endif
/* enc_locale() will try to find the encoding of the current locale. */
p = enc_locale();
if (p != NULL)
{
char_u *save_enc;
/* Try setting 'encoding' and check if the value is valid.
* If not, go back to the default "latin1". */
save_enc = p_enc;
p_enc = p;
if (STRCMP(p_enc, "gb18030") == 0)
{
/* We don't support "gb18030", but "cp936" is a good substitute
* for practical purposes, thus use that. It's not an alias to
* still support conversion between gb18030 and utf-8. */
p_enc = vim_strsave((char_u *)"cp936");
vim_free(p);
}
if (mb_init() == NULL)
{
opt_idx = findoption((char_u *)"encoding");
if (opt_idx >= 0)
{
options[opt_idx].def_val[VI_DEFAULT] = p_enc;
options[opt_idx].flags |= P_DEF_ALLOCED;
}
#if defined(MSWIN) || defined(MACOS) || defined(VMS)
if (STRCMP(p_enc, "latin1") == 0
# ifdef FEAT_MBYTE
|| enc_utf8
# endif
)
{
/* Adjust the default for 'isprint' and 'iskeyword' to match
* latin1. Also set the defaults for when 'nocompatible' is
* set. */
set_string_option_direct((char_u *)"isp", -1,
ISP_LATIN1, OPT_FREE, SID_NONE);
set_string_option_direct((char_u *)"isk", -1,
ISK_LATIN1, OPT_FREE, SID_NONE);
opt_idx = findoption((char_u *)"isp");
if (opt_idx >= 0)
options[opt_idx].def_val[VIM_DEFAULT] = ISP_LATIN1;
opt_idx = findoption((char_u *)"isk");
if (opt_idx >= 0)
options[opt_idx].def_val[VIM_DEFAULT] = ISK_LATIN1;
(void)init_chartab();
}
#endif
# if defined(WIN3264) && !defined(FEAT_GUI)
/* Win32 console: When GetACP() returns a different value from
* GetConsoleCP() set 'termencoding'. */
if (GetACP() != GetConsoleCP())
{
char buf[50];
sprintf(buf, "cp%ld", (long)GetConsoleCP());
p_tenc = vim_strsave((char_u *)buf);
if (p_tenc != NULL)
{
opt_idx = findoption((char_u *)"termencoding");
if (opt_idx >= 0)
{
options[opt_idx].def_val[VI_DEFAULT] = p_tenc;
options[opt_idx].flags |= P_DEF_ALLOCED;
}
convert_setup(&input_conv, p_tenc, p_enc);
convert_setup(&output_conv, p_enc, p_tenc);
}
else
p_tenc = empty_option;
}
# endif
# if defined(WIN3264) && defined(FEAT_MBYTE)
/* $HOME may have characters in active code page. */
init_homedir();
# endif
}
else
{
vim_free(p_enc);
p_enc = save_enc;
}
}
#endif
#ifdef FEAT_MULTI_LANG
/* Set the default for 'helplang'. */
set_helplang_default(get_mess_lang());
#endif
}
/*
* Set an option to its default value.
* This does not take care of side effects!
*/
static void
set_option_default(
int opt_idx,
int opt_flags, /* OPT_FREE, OPT_LOCAL and/or OPT_GLOBAL */
int compatible) /* use Vi default value */
{
char_u *varp; /* pointer to variable for current option */
int dvi; /* index in def_val[] */
long_u flags;
long_u *flagsp;
int both = (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0;
varp = get_varp_scope(&(options[opt_idx]), both ? OPT_LOCAL : opt_flags);
flags = options[opt_idx].flags;
if (varp != NULL) /* skip hidden option, nothing to do for it */
{
dvi = ((flags & P_VI_DEF) || compatible) ? VI_DEFAULT : VIM_DEFAULT;
if (flags & P_STRING)
{
/* Use set_string_option_direct() for local options to handle
* freeing and allocating the value. */
if (options[opt_idx].indir != PV_NONE)
set_string_option_direct(NULL, opt_idx,
options[opt_idx].def_val[dvi], opt_flags, 0);
else
{
if ((opt_flags & OPT_FREE) && (flags & P_ALLOCED))
free_string_option(*(char_u **)(varp));
*(char_u **)varp = options[opt_idx].def_val[dvi];
options[opt_idx].flags &= ~P_ALLOCED;
}
}
else if (flags & P_NUM)
{
if (options[opt_idx].indir == PV_SCROLL)
win_comp_scroll(curwin);
else
{
*(long *)varp = (long)(long_i)options[opt_idx].def_val[dvi];
/* May also set global value for local option. */
if (both)
*(long *)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL) =
*(long *)varp;
}
}
else /* P_BOOL */
{
/* the cast to long is required for Manx C, long_i is needed for
* MSVC */
*(int *)varp = (int)(long)(long_i)options[opt_idx].def_val[dvi];
#ifdef UNIX
/* 'modeline' defaults to off for root */
if (options[opt_idx].indir == PV_ML && getuid() == ROOT_UID)
*(int *)varp = FALSE;
#endif
/* May also set global value for local option. */
if (both)
*(int *)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL) =
*(int *)varp;
}
/* The default value is not insecure. */
flagsp = insecure_flag(opt_idx, opt_flags);
*flagsp = *flagsp & ~P_INSECURE;
}
#ifdef FEAT_EVAL
set_option_scriptID_idx(opt_idx, opt_flags, current_SID);
#endif
}
/*
* Set all options (except terminal options) to their default value.
* When "opt_flags" is non-zero skip 'encoding'.
*/
static void
set_options_default(
int opt_flags) /* OPT_FREE, OPT_LOCAL and/or OPT_GLOBAL */
{
int i;
#ifdef FEAT_WINDOWS
win_T *wp;
tabpage_T *tp;
#endif
for (i = 0; !istermoption(&options[i]); i++)
if (!(options[i].flags & P_NODEFAULT)
#if defined(FEAT_MBYTE) || defined(FEAT_CRYPT)
&& (opt_flags == 0
|| (TRUE
# if defined(FEAT_MBYTE)
&& options[i].var != (char_u *)&p_enc
# endif
# if defined(FEAT_CRYPT)
&& options[i].var != (char_u *)&p_cm
&& options[i].var != (char_u *)&p_key
# endif
))
#endif
)
set_option_default(i, opt_flags, p_cp);
#ifdef FEAT_WINDOWS
/* The 'scroll' option must be computed for all windows. */
FOR_ALL_TAB_WINDOWS(tp, wp)
win_comp_scroll(wp);
#else
win_comp_scroll(curwin);
#endif
#ifdef FEAT_CINDENT
parse_cino(curbuf);
#endif
}
/*
* Set the Vi-default value of a string option.
* Used for 'sh', 'backupskip' and 'term'.
*/
void
set_string_default(char *name, char_u *val)
{
char_u *p;
int opt_idx;
p = vim_strsave(val);
if (p != NULL) /* we don't want a NULL */
{
opt_idx = findoption((char_u *)name);
if (opt_idx >= 0)
{
if (options[opt_idx].flags & P_DEF_ALLOCED)
vim_free(options[opt_idx].def_val[VI_DEFAULT]);
options[opt_idx].def_val[VI_DEFAULT] = p;
options[opt_idx].flags |= P_DEF_ALLOCED;
}
}
}
/*
* Set the Vi-default value of a number option.
* Used for 'lines' and 'columns'.
*/
void
set_number_default(char *name, long val)
{
int opt_idx;
opt_idx = findoption((char_u *)name);
if (opt_idx >= 0)
options[opt_idx].def_val[VI_DEFAULT] = (char_u *)(long_i)val;
}
#if defined(EXITFREE) || defined(PROTO)
/*
* Free all options.
*/
void
free_all_options(void)
{
int i;
for (i = 0; !istermoption(&options[i]); i++)
{
if (options[i].indir == PV_NONE)
{
/* global option: free value and default value. */
if (options[i].flags & P_ALLOCED && options[i].var != NULL)
free_string_option(*(char_u **)options[i].var);
if (options[i].flags & P_DEF_ALLOCED)
free_string_option(options[i].def_val[VI_DEFAULT]);
}
else if (options[i].var != VAR_WIN
&& (options[i].flags & P_STRING))
/* buffer-local option: free global value */
free_string_option(*(char_u **)options[i].var);
}
}
#endif
/*
* Initialize the options, part two: After getting Rows and Columns and
* setting 'term'.
*/
void
set_init_2(void)
{
int idx;
/*
* 'scroll' defaults to half the window height. Note that this default is
* wrong when the window height changes.
*/
set_number_default("scroll", (long)((long_u)Rows >> 1));
idx = findoption((char_u *)"scroll");
if (idx >= 0 && !(options[idx].flags & P_WAS_SET))
set_option_default(idx, OPT_LOCAL, p_cp);
comp_col();
/*
* 'window' is only for backwards compatibility with Vi.
* Default is Rows - 1.
*/
if (!option_was_set((char_u *)"window"))
p_window = Rows - 1;
set_number_default("window", Rows - 1);
/* For DOS console the default is always black. */
#if !((defined(WIN3264)) && !defined(FEAT_GUI))
/*
* If 'background' wasn't set by the user, try guessing the value,
* depending on the terminal name. Only need to check for terminals
* with a dark background, that can handle color.
*/
idx = findoption((char_u *)"bg");
if (idx >= 0 && !(options[idx].flags & P_WAS_SET)
&& *term_bg_default() == 'd')
{
set_string_option_direct(NULL, idx, (char_u *)"dark", OPT_FREE, 0);
/* don't mark it as set, when starting the GUI it may be
* changed again */
options[idx].flags &= ~P_WAS_SET;
}
#endif
#ifdef CURSOR_SHAPE
parse_shape_opt(SHAPE_CURSOR); /* set cursor shapes from 'guicursor' */
#endif
#ifdef FEAT_MOUSESHAPE
parse_shape_opt(SHAPE_MOUSE); /* set mouse shapes from 'mouseshape' */
#endif
#ifdef FEAT_PRINTER
(void)parse_printoptions(); /* parse 'printoptions' default value */
#endif
}
/*
* Return "dark" or "light" depending on the kind of terminal.
* This is just guessing! Recognized are:
* "linux" Linux console
* "screen.linux" Linux console with screen
* "cygwin" Cygwin shell
* "putty" Putty program
* We also check the COLORFGBG environment variable, which is set by
* rxvt and derivatives. This variable contains either two or three
* values separated by semicolons; we want the last value in either
* case. If this value is 0-6 or 8, our background is dark.
*/
static char_u *
term_bg_default(void)
{
#if defined(WIN3264)
/* DOS console nearly always black */
return (char_u *)"dark";
#else
char_u *p;
if (STRCMP(T_NAME, "linux") == 0
|| STRCMP(T_NAME, "screen.linux") == 0
|| STRCMP(T_NAME, "cygwin") == 0
|| STRCMP(T_NAME, "putty") == 0
|| ((p = mch_getenv((char_u *)"COLORFGBG")) != NULL
&& (p = vim_strrchr(p, ';')) != NULL
&& ((p[1] >= '0' && p[1] <= '6') || p[1] == '8')
&& p[2] == NUL))
return (char_u *)"dark";
return (char_u *)"light";
#endif
}
/*
* Initialize the options, part three: After reading the .vimrc
*/
void
set_init_3(void)
{
#if defined(UNIX) || defined(WIN3264)
/*
* Set 'shellpipe' and 'shellredir', depending on the 'shell' option.
* This is done after other initializations, where 'shell' might have been
* set, but only if they have not been set before.
*/
char_u *p;
int idx_srr;
int do_srr;
# ifdef FEAT_QUICKFIX
int idx_sp;
int do_sp;
# endif
idx_srr = findoption((char_u *)"srr");
if (idx_srr < 0)
do_srr = FALSE;
else
do_srr = !(options[idx_srr].flags & P_WAS_SET);
# ifdef FEAT_QUICKFIX
idx_sp = findoption((char_u *)"sp");
if (idx_sp < 0)
do_sp = FALSE;
else
do_sp = !(options[idx_sp].flags & P_WAS_SET);
# endif
p = get_isolated_shell_name();
if (p != NULL)
{
/*
* Default for p_sp is "| tee", for p_srr is ">".
* For known shells it is changed here to include stderr.
*/
if ( fnamecmp(p, "csh") == 0
|| fnamecmp(p, "tcsh") == 0
# if defined(WIN3264) /* also check with .exe extension */
|| fnamecmp(p, "csh.exe") == 0
|| fnamecmp(p, "tcsh.exe") == 0
# endif
)
{
# if defined(FEAT_QUICKFIX)
if (do_sp)
{
# ifdef WIN3264
p_sp = (char_u *)">&";
# else
p_sp = (char_u *)"|& tee";
# endif
options[idx_sp].def_val[VI_DEFAULT] = p_sp;
}
# endif
if (do_srr)
{
p_srr = (char_u *)">&";
options[idx_srr].def_val[VI_DEFAULT] = p_srr;
}
}
else
/* Always use bourne shell style redirection if we reach this */
if ( fnamecmp(p, "sh") == 0
|| fnamecmp(p, "ksh") == 0
|| fnamecmp(p, "mksh") == 0
|| fnamecmp(p, "pdksh") == 0
|| fnamecmp(p, "zsh") == 0
|| fnamecmp(p, "zsh-beta") == 0
|| fnamecmp(p, "bash") == 0
|| fnamecmp(p, "fish") == 0
# ifdef WIN3264
|| fnamecmp(p, "cmd") == 0
|| fnamecmp(p, "sh.exe") == 0
|| fnamecmp(p, "ksh.exe") == 0
|| fnamecmp(p, "mksh.exe") == 0
|| fnamecmp(p, "pdksh.exe") == 0
|| fnamecmp(p, "zsh.exe") == 0
|| fnamecmp(p, "zsh-beta.exe") == 0
|| fnamecmp(p, "bash.exe") == 0
|| fnamecmp(p, "cmd.exe") == 0
# endif
)
{
# if defined(FEAT_QUICKFIX)
if (do_sp)
{
# ifdef WIN3264
p_sp = (char_u *)">%s 2>&1";
# else
p_sp = (char_u *)"2>&1| tee";
# endif
options[idx_sp].def_val[VI_DEFAULT] = p_sp;
}
# endif
if (do_srr)
{
p_srr = (char_u *)">%s 2>&1";
options[idx_srr].def_val[VI_DEFAULT] = p_srr;
}
}
vim_free(p);
}
#endif
#if defined(WIN3264)
/*
* Set 'shellcmdflag', 'shellxquote', and 'shellquote' depending on the
* 'shell' option.
* This is done after other initializations, where 'shell' might have been
* set, but only if they have not been set before. Default for p_shcf is
* "/c", for p_shq is "". For "sh" like shells it is changed here to
* "-c" and "\"". And for Win32 we need to set p_sxq instead.
*/
if (strstr((char *)gettail(p_sh), "sh") != NULL)
{
int idx3;
idx3 = findoption((char_u *)"shcf");
if (idx3 >= 0 && !(options[idx3].flags & P_WAS_SET))
{
p_shcf = (char_u *)"-c";
options[idx3].def_val[VI_DEFAULT] = p_shcf;
}
# ifdef WIN3264
/* Somehow Win32 requires the quotes around the redirection too */
idx3 = findoption((char_u *)"sxq");
if (idx3 >= 0 && !(options[idx3].flags & P_WAS_SET))
{
p_sxq = (char_u *)"\"";
options[idx3].def_val[VI_DEFAULT] = p_sxq;
}
# else
idx3 = findoption((char_u *)"shq");
if (idx3 >= 0 && !(options[idx3].flags & P_WAS_SET))
{
p_shq = (char_u *)"\"";
options[idx3].def_val[VI_DEFAULT] = p_shq;
}
# endif
}
else if (strstr((char *)gettail(p_sh), "cmd.exe") != NULL)
{
int idx3;
/*
* cmd.exe on Windows will strip the first and last double quote given
* on the command line, e.g. most of the time things like:
* cmd /c "my path/to/echo" "my args to echo"
* become:
* my path/to/echo" "my args to echo
* when executed.
*
* To avoid this, set shellxquote to surround the command in
* parenthesis. This appears to make most commands work, without
* breaking commands that worked previously, such as
* '"path with spaces/cmd" "a&b"'.
*/
idx3 = findoption((char_u *)"sxq");
if (idx3 >= 0 && !(options[idx3].flags & P_WAS_SET))
{
p_sxq = (char_u *)"(";
options[idx3].def_val[VI_DEFAULT] = p_sxq;
}
idx3 = findoption((char_u *)"shcf");
if (idx3 >= 0 && !(options[idx3].flags & P_WAS_SET))
{
p_shcf = (char_u *)"/c";
options[idx3].def_val[VI_DEFAULT] = p_shcf;
}
}
#endif
if (bufempty())
{
int idx_ffs = findoption((char_u *)"ffs");
/* Apply the first entry of 'fileformats' to the initial buffer. */
if (idx_ffs >= 0 && (options[idx_ffs].flags & P_WAS_SET))
set_fileformat(default_fileformat(), OPT_LOCAL);
}
#ifdef FEAT_TITLE
set_title_defaults();
#endif
}
#if defined(FEAT_MULTI_LANG) || defined(PROTO)
/*
* When 'helplang' is still at its default value, set it to "lang".
* Only the first two characters of "lang" are used.
*/
void
set_helplang_default(char_u *lang)
{
int idx;
if (lang == NULL || STRLEN(lang) < 2) /* safety check */
return;
idx = findoption((char_u *)"hlg");
if (idx >= 0 && !(options[idx].flags & P_WAS_SET))
{
if (options[idx].flags & P_ALLOCED)
free_string_option(p_hlg);
p_hlg = vim_strsave(lang);
if (p_hlg == NULL)
p_hlg = empty_option;
else
{
/* zh_CN becomes "cn", zh_TW becomes "tw". */
if (STRNICMP(p_hlg, "zh_", 3) == 0 && STRLEN(p_hlg) >= 5)
{
p_hlg[0] = TOLOWER_ASC(p_hlg[3]);
p_hlg[1] = TOLOWER_ASC(p_hlg[4]);
}
p_hlg[2] = NUL;
}
options[idx].flags |= P_ALLOCED;
}
}
#endif
#ifdef FEAT_GUI
static char_u *gui_bg_default(void);
static char_u *
gui_bg_default(void)
{
if (gui_get_lightness(gui.back_pixel) < 127)
return (char_u *)"dark";
return (char_u *)"light";
}
/*
* Option initializations that can only be done after opening the GUI window.
*/
void
init_gui_options(void)
{
/* Set the 'background' option according to the lightness of the
* background color, unless the user has set it already. */
if (!option_was_set((char_u *)"bg") && STRCMP(p_bg, gui_bg_default()) != 0)
{
set_option_value((char_u *)"bg", 0L, gui_bg_default(), 0);
highlight_changed();
}
}
#endif
#ifdef FEAT_TITLE
/*
* 'title' and 'icon' only default to true if they have not been set or reset
* in .vimrc and we can read the old value.
* When 'title' and 'icon' have been reset in .vimrc, we won't even check if
* they can be reset. This reduces startup time when using X on a remote
* machine.
*/
void
set_title_defaults(void)
{
int idx1;
long val;
/*
* If GUI is (going to be) used, we can always set the window title and
* icon name. Saves a bit of time, because the X11 display server does
* not need to be contacted.
*/
idx1 = findoption((char_u *)"title");
if (idx1 >= 0 && !(options[idx1].flags & P_WAS_SET))
{
#ifdef FEAT_GUI
if (gui.starting || gui.in_use)
val = TRUE;
else
#endif
val = mch_can_restore_title();
options[idx1].def_val[VI_DEFAULT] = (char_u *)(long_i)val;
p_title = val;
}
idx1 = findoption((char_u *)"icon");
if (idx1 >= 0 && !(options[idx1].flags & P_WAS_SET))
{
#ifdef FEAT_GUI
if (gui.starting || gui.in_use)
val = TRUE;
else
#endif
val = mch_can_restore_icon();
options[idx1].def_val[VI_DEFAULT] = (char_u *)(long_i)val;
p_icon = val;
}
}
#endif
/*
* Parse 'arg' for option settings.
*
* 'arg' may be IObuff, but only when no errors can be present and option
* does not need to be expanded with option_expand().
* "opt_flags":
* 0 for ":set"
* OPT_GLOBAL for ":setglobal"
* OPT_LOCAL for ":setlocal" and a modeline
* OPT_MODELINE for a modeline
* OPT_WINONLY to only set window-local options
* OPT_NOWIN to skip setting window-local options
*
* returns FAIL if an error is detected, OK otherwise
*/
int
do_set(
char_u *arg, /* option string (may be written to!) */
int opt_flags)
{
int opt_idx;
char_u *errmsg;
char_u errbuf[80];
char_u *startarg;
int prefix; /* 1: nothing, 0: "no", 2: "inv" in front of name */
int nextchar; /* next non-white char after option name */
int afterchar; /* character just after option name */
int len;
int i;
varnumber_T value;
int key;
long_u flags; /* flags for current option */
char_u *varp = NULL; /* pointer to variable for current option */
int did_show = FALSE; /* already showed one value */
int adding; /* "opt+=arg" */
int prepending; /* "opt^=arg" */
int removing; /* "opt-=arg" */
int cp_val = 0;
char_u key_name[2];
if (*arg == NUL)
{
showoptions(0, opt_flags);
did_show = TRUE;
goto theend;
}
while (*arg != NUL) /* loop to process all options */
{
errmsg = NULL;
startarg = arg; /* remember for error message */
if (STRNCMP(arg, "all", 3) == 0 && !isalpha(arg[3])
&& !(opt_flags & OPT_MODELINE))
{
/*
* ":set all" show all options.
* ":set all&" set all options to their default value.
*/
arg += 3;
if (*arg == '&')
{
++arg;
/* Only for :set command set global value of local options. */
set_options_default(OPT_FREE | opt_flags);
didset_options();
didset_options2();
redraw_all_later(CLEAR);
}
else
{
showoptions(1, opt_flags);
did_show = TRUE;
}
}
else if (STRNCMP(arg, "termcap", 7) == 0 && !(opt_flags & OPT_MODELINE))
{
showoptions(2, opt_flags);
show_termcodes();
did_show = TRUE;
arg += 7;
}
else
{
prefix = 1;
if (STRNCMP(arg, "no", 2) == 0 && STRNCMP(arg, "novice", 6) != 0)
{
prefix = 0;
arg += 2;
}
else if (STRNCMP(arg, "inv", 3) == 0)
{
prefix = 2;
arg += 3;
}
/* find end of name */
key = 0;
if (*arg == '<')
{
nextchar = 0;
opt_idx = -1;
/* look out for <t_>;> */
if (arg[1] == 't' && arg[2] == '_' && arg[3] && arg[4])
len = 5;
else
{
len = 1;
while (arg[len] != NUL && arg[len] != '>')
++len;
}
if (arg[len] != '>')
{
errmsg = e_invarg;
goto skip;
}
arg[len] = NUL; /* put NUL after name */
if (arg[1] == 't' && arg[2] == '_') /* could be term code */
opt_idx = findoption(arg + 1);
arg[len++] = '>'; /* restore '>' */
if (opt_idx == -1)
key = find_key_option(arg + 1);
}
else
{
len = 0;
/*
* The two characters after "t_" may not be alphanumeric.
*/
if (arg[0] == 't' && arg[1] == '_' && arg[2] && arg[3])
len = 4;
else
while (ASCII_ISALNUM(arg[len]) || arg[len] == '_')
++len;
nextchar = arg[len];
arg[len] = NUL; /* put NUL after name */
opt_idx = findoption(arg);
arg[len] = nextchar; /* restore nextchar */
if (opt_idx == -1)
key = find_key_option(arg);
}
/* remember character after option name */
afterchar = arg[len];
/* skip white space, allow ":set ai ?" */
while (vim_iswhite(arg[len]))
++len;
adding = FALSE;
prepending = FALSE;
removing = FALSE;
if (arg[len] != NUL && arg[len + 1] == '=')
{
if (arg[len] == '+')
{
adding = TRUE; /* "+=" */
++len;
}
else if (arg[len] == '^')
{
prepending = TRUE; /* "^=" */
++len;
}
else if (arg[len] == '-')
{
removing = TRUE; /* "-=" */
++len;
}
}
nextchar = arg[len];
if (opt_idx == -1 && key == 0) /* found a mismatch: skip */
{
errmsg = (char_u *)N_("E518: Unknown option");
goto skip;
}
if (opt_idx >= 0)
{
if (options[opt_idx].var == NULL) /* hidden option: skip */
{
/* Only give an error message when requesting the value of
* a hidden option, ignore setting it. */
if (vim_strchr((char_u *)"=:!&<", nextchar) == NULL
&& (!(options[opt_idx].flags & P_BOOL)
|| nextchar == '?'))
errmsg = (char_u *)N_("E519: Option not supported");
goto skip;
}
flags = options[opt_idx].flags;
varp = get_varp_scope(&(options[opt_idx]), opt_flags);
}
else
{
flags = P_STRING;
if (key < 0)
{
key_name[0] = KEY2TERMCAP0(key);
key_name[1] = KEY2TERMCAP1(key);
}
else
{
key_name[0] = KS_KEY;
key_name[1] = (key & 0xff);
}
}
/* Skip all options that are not window-local (used when showing
* an already loaded buffer in a window). */
if ((opt_flags & OPT_WINONLY)
&& (opt_idx < 0 || options[opt_idx].var != VAR_WIN))
goto skip;
/* Skip all options that are window-local (used for :vimgrep). */
if ((opt_flags & OPT_NOWIN) && opt_idx >= 0
&& options[opt_idx].var == VAR_WIN)
goto skip;
/* Disallow changing some options from modelines. */
if (opt_flags & OPT_MODELINE)
{
if (flags & (P_SECURE | P_NO_ML))
{
errmsg = (char_u *)_("E520: Not allowed in a modeline");
goto skip;
}
#ifdef FEAT_DIFF
/* In diff mode some options are overruled. This avoids that
* 'foldmethod' becomes "marker" instead of "diff" and that
* "wrap" gets set. */
if (curwin->w_p_diff
&& opt_idx >= 0 /* shut up coverity warning */
&& (options[opt_idx].indir == PV_FDM
|| options[opt_idx].indir == PV_WRAP))
goto skip;
#endif
}
#ifdef HAVE_SANDBOX
/* Disallow changing some options in the sandbox */
if (sandbox != 0 && (flags & P_SECURE))
{
errmsg = (char_u *)_(e_sandbox);
goto skip;
}
#endif
if (vim_strchr((char_u *)"?=:!&<", nextchar) != NULL)
{
arg += len;
cp_val = p_cp;
if (nextchar == '&' && arg[1] == 'v' && arg[2] == 'i')
{
if (arg[3] == 'm') /* "opt&vim": set to Vim default */
{
cp_val = FALSE;
arg += 3;
}
else /* "opt&vi": set to Vi default */
{
cp_val = TRUE;
arg += 2;
}
}
if (vim_strchr((char_u *)"?!&<", nextchar) != NULL
&& arg[1] != NUL && !vim_iswhite(arg[1]))
{
errmsg = e_trailing;
goto skip;
}
}
/*
* allow '=' and ':' for hystorical reasons (MSDOS command.com
* allows only one '=' character per "set" command line. grrr. (jw)
*/
if (nextchar == '?'
|| (prefix == 1
&& vim_strchr((char_u *)"=:&<", nextchar) == NULL
&& !(flags & P_BOOL)))
{
/*
* print value
*/
if (did_show)
msg_putchar('\n'); /* cursor below last one */
else
{
gotocmdline(TRUE); /* cursor at status line */
did_show = TRUE; /* remember that we did a line */
}
if (opt_idx >= 0)
{
showoneopt(&options[opt_idx], opt_flags);
#ifdef FEAT_EVAL
if (p_verbose > 0)
{
/* Mention where the option was last set. */
if (varp == options[opt_idx].var)
last_set_msg(options[opt_idx].scriptID);
else if ((int)options[opt_idx].indir & PV_WIN)
last_set_msg(curwin->w_p_scriptID[
(int)options[opt_idx].indir & PV_MASK]);
else if ((int)options[opt_idx].indir & PV_BUF)
last_set_msg(curbuf->b_p_scriptID[
(int)options[opt_idx].indir & PV_MASK]);
}
#endif
}
else
{
char_u *p;
p = find_termcode(key_name);
if (p == NULL)
{
errmsg = (char_u *)N_("E846: Key code not set");
goto skip;
}
else
(void)show_one_termcode(key_name, p, TRUE);
}
if (nextchar != '?'
&& nextchar != NUL && !vim_iswhite(afterchar))
errmsg = e_trailing;
}
else
{
if (flags & P_BOOL) /* boolean */
{
if (nextchar == '=' || nextchar == ':')
{
errmsg = e_invarg;
goto skip;
}
/*
* ":set opt!": invert
* ":set opt&": reset to default value
* ":set opt<": reset to global value
*/
if (nextchar == '!')
value = *(int *)(varp) ^ 1;
else if (nextchar == '&')
value = (int)(long)(long_i)options[opt_idx].def_val[
((flags & P_VI_DEF) || cp_val)
? VI_DEFAULT : VIM_DEFAULT];
else if (nextchar == '<')
{
/* For 'autoread' -1 means to use global value. */
if ((int *)varp == &curbuf->b_p_ar
&& opt_flags == OPT_LOCAL)
value = -1;
else
value = *(int *)get_varp_scope(&(options[opt_idx]),
OPT_GLOBAL);
}
else
{
/*
* ":set invopt": invert
* ":set opt" or ":set noopt": set or reset
*/
if (nextchar != NUL && !vim_iswhite(afterchar))
{
errmsg = e_trailing;
goto skip;
}
if (prefix == 2) /* inv */
value = *(int *)(varp) ^ 1;
else
value = prefix;
}
errmsg = set_bool_option(opt_idx, varp, (int)value,
opt_flags);
}
else /* numeric or string */
{
if (vim_strchr((char_u *)"=:&<", nextchar) == NULL
|| prefix != 1)
{
errmsg = e_invarg;
goto skip;
}
if (flags & P_NUM) /* numeric */
{
/*
* Different ways to set a number option:
* & set to default value
* < set to global value
* <xx> accept special key codes for 'wildchar'
* c accept any non-digit for 'wildchar'
* [-]0-9 set number
* other error
*/
++arg;
if (nextchar == '&')
value = (long)(long_i)options[opt_idx].def_val[
((flags & P_VI_DEF) || cp_val)
? VI_DEFAULT : VIM_DEFAULT];
else if (nextchar == '<')
{
/* For 'undolevels' NO_LOCAL_UNDOLEVEL means to
* use the global value. */
if ((long *)varp == &curbuf->b_p_ul
&& opt_flags == OPT_LOCAL)
value = NO_LOCAL_UNDOLEVEL;
else
value = *(long *)get_varp_scope(
&(options[opt_idx]), OPT_GLOBAL);
}
else if (((long *)varp == &p_wc
|| (long *)varp == &p_wcm)
&& (*arg == '<'
|| *arg == '^'
|| ((!arg[1] || vim_iswhite(arg[1]))
&& !VIM_ISDIGIT(*arg))))
{
value = string_to_key(arg);
if (value == 0 && (long *)varp != &p_wcm)
{
errmsg = e_invarg;
goto skip;
}
}
else if (*arg == '-' || VIM_ISDIGIT(*arg))
{
/* Allow negative (for 'undolevels'), octal and
* hex numbers. */
vim_str2nr(arg, NULL, &i, STR2NR_ALL,
&value, NULL, 0);
if (arg[i] != NUL && !vim_iswhite(arg[i]))
{
errmsg = e_invarg;
goto skip;
}
}
else
{
errmsg = (char_u *)N_("E521: Number required after =");
goto skip;
}
if (adding)
value = *(long *)varp + value;
if (prepending)
value = *(long *)varp * value;
if (removing)
value = *(long *)varp - value;
errmsg = set_num_option(opt_idx, varp, value,
errbuf, sizeof(errbuf), opt_flags);
}
else if (opt_idx >= 0) /* string */
{
char_u *save_arg = NULL;
char_u *s = NULL;
char_u *oldval = NULL; /* previous value if *varp */
char_u *newval;
char_u *origval = NULL;
#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
char_u *saved_origval = NULL;
#endif
unsigned newlen;
int comma;
int bs;
int new_value_alloced; /* new string option
was allocated */
/* When using ":set opt=val" for a global option
* with a local value the local value will be
* reset, use the global value here. */
if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0
&& ((int)options[opt_idx].indir & PV_BOTH))
varp = options[opt_idx].var;
/* The old value is kept until we are sure that the
* new value is valid. */
oldval = *(char_u **)varp;
if (nextchar == '&') /* set to default val */
{
newval = options[opt_idx].def_val[
((flags & P_VI_DEF) || cp_val)
? VI_DEFAULT : VIM_DEFAULT];
if ((char_u **)varp == &p_bg)
{
/* guess the value of 'background' */
#ifdef FEAT_GUI
if (gui.in_use)
newval = gui_bg_default();
else
#endif
newval = term_bg_default();
}
/* expand environment variables and ~ (since the
* default value was already expanded, only
* required when an environment variable was set
* later */
if (newval == NULL)
newval = empty_option;
else
{
s = option_expand(opt_idx, newval);
if (s == NULL)
s = newval;
newval = vim_strsave(s);
}
new_value_alloced = TRUE;
}
else if (nextchar == '<') /* set to global val */
{
newval = vim_strsave(*(char_u **)get_varp_scope(
&(options[opt_idx]), OPT_GLOBAL));
new_value_alloced = TRUE;
}
else
{
++arg; /* jump to after the '=' or ':' */
/*
* Set 'keywordprg' to ":help" if an empty
* value was passed to :set by the user.
* Misuse errbuf[] for the resulting string.
*/
if (varp == (char_u *)&p_kp
&& (*arg == NUL || *arg == ' '))
{
STRCPY(errbuf, ":help");
save_arg = arg;
arg = errbuf;
}
/*
* Convert 'backspace' number to string, for
* adding, prepending and removing string.
*/
else if (varp == (char_u *)&p_bs
&& VIM_ISDIGIT(**(char_u **)varp))
{
i = getdigits((char_u **)varp);
switch (i)
{
case 0:
*(char_u **)varp = empty_option;
break;
case 1:
*(char_u **)varp = vim_strsave(
(char_u *)"indent,eol");
break;
case 2:
*(char_u **)varp = vim_strsave(
(char_u *)"indent,eol,start");
break;
}
vim_free(oldval);
oldval = *(char_u **)varp;
}
/*
* Convert 'whichwrap' number to string, for
* backwards compatibility with Vim 3.0.
* Misuse errbuf[] for the resulting string.
*/
else if (varp == (char_u *)&p_ww
&& VIM_ISDIGIT(*arg))
{
*errbuf = NUL;
i = getdigits(&arg);
if (i & 1)
STRCAT(errbuf, "b,");
if (i & 2)
STRCAT(errbuf, "s,");
if (i & 4)
STRCAT(errbuf, "h,l,");
if (i & 8)
STRCAT(errbuf, "<,>,");
if (i & 16)
STRCAT(errbuf, "[,],");
if (*errbuf != NUL) /* remove trailing , */
errbuf[STRLEN(errbuf) - 1] = NUL;
save_arg = arg;
arg = errbuf;
}
/*
* Remove '>' before 'dir' and 'bdir', for
* backwards compatibility with version 3.0
*/
else if ( *arg == '>'
&& (varp == (char_u *)&p_dir
|| varp == (char_u *)&p_bdir))
{
++arg;
}
/* When setting the local value of a global
* option, the old value may be the global value. */
if (((int)options[opt_idx].indir & PV_BOTH)
&& (opt_flags & OPT_LOCAL))
origval = *(char_u **)get_varp(
&options[opt_idx]);
else
origval = oldval;
/*
* Copy the new string into allocated memory.
* Can't use set_string_option_direct(), because
* we need to remove the backslashes.
*/
/* get a bit too much */
newlen = (unsigned)STRLEN(arg) + 1;
if (adding || prepending || removing)
newlen += (unsigned)STRLEN(origval) + 1;
newval = alloc(newlen);
if (newval == NULL) /* out of mem, don't change */
break;
s = newval;
/*
* Copy the string, skip over escaped chars.
* For MS-DOS and WIN32 backslashes before normal
* file name characters are not removed, and keep
* backslash at start, for "\\machine\path", but
* do remove it for "\\\\machine\\path".
* The reverse is found in ExpandOldSetting().
*/
while (*arg && !vim_iswhite(*arg))
{
if (*arg == '\\' && arg[1] != NUL
#ifdef BACKSLASH_IN_FILENAME
&& !((flags & P_EXPAND)
&& vim_isfilec(arg[1])
&& (arg[1] != '\\'
|| (s == newval
&& arg[2] != '\\')))
#endif
)
++arg; /* remove backslash */
#ifdef FEAT_MBYTE
if (has_mbyte
&& (i = (*mb_ptr2len)(arg)) > 1)
{
/* copy multibyte char */
mch_memmove(s, arg, (size_t)i);
arg += i;
s += i;
}
else
#endif
*s++ = *arg++;
}
*s = NUL;
/*
* Expand environment variables and ~.
* Don't do it when adding without inserting a
* comma.
*/
if (!(adding || prepending || removing)
|| (flags & P_COMMA))
{
s = option_expand(opt_idx, newval);
if (s != NULL)
{
vim_free(newval);
newlen = (unsigned)STRLEN(s) + 1;
if (adding || prepending || removing)
newlen += (unsigned)STRLEN(origval) + 1;
newval = alloc(newlen);
if (newval == NULL)
break;
STRCPY(newval, s);
}
}
/* locate newval[] in origval[] when removing it
* and when adding to avoid duplicates */
i = 0; /* init for GCC */
if (removing || (flags & P_NODUP))
{
i = (int)STRLEN(newval);
bs = 0;
for (s = origval; *s; ++s)
{
if ((!(flags & P_COMMA)
|| s == origval
|| (s[-1] == ',' && !(bs & 1)))
&& STRNCMP(s, newval, i) == 0
&& (!(flags & P_COMMA)
|| s[i] == ','
|| s[i] == NUL))
break;
/* Count backslashes. Only a comma with an
* even number of backslashes or a single
* backslash preceded by a comma before it
* is recognized as a separator */
if ((s > origval + 1
&& s[-1] == '\\'
&& s[-2] != ',')
|| (s == origval + 1
&& s[-1] == '\\'))
++bs;
else
bs = 0;
}
/* do not add if already there */
if ((adding || prepending) && *s)
{
prepending = FALSE;
adding = FALSE;
STRCPY(newval, origval);
}
}
/* concatenate the two strings; add a ',' if
* needed */
if (adding || prepending)
{
comma = ((flags & P_COMMA) && *origval != NUL
&& *newval != NUL);
if (adding)
{
i = (int)STRLEN(origval);
/* strip a trailing comma, would get 2 */
if (comma && i > 1
&& (flags & P_ONECOMMA) == P_ONECOMMA
&& origval[i - 1] == ','
&& origval[i - 2] != '\\')
i--;
mch_memmove(newval + i + comma, newval,
STRLEN(newval) + 1);
mch_memmove(newval, origval, (size_t)i);
}
else
{
i = (int)STRLEN(newval);
STRMOVE(newval + i + comma, origval);
}
if (comma)
newval[i] = ',';
}
/* Remove newval[] from origval[]. (Note: "i" has
* been set above and is used here). */
if (removing)
{
STRCPY(newval, origval);
if (*s)
{
/* may need to remove a comma */
if (flags & P_COMMA)
{
if (s == origval)
{
/* include comma after string */
if (s[i] == ',')
++i;
}
else
{
/* include comma before string */
--s;
++i;
}
}
STRMOVE(newval + (s - origval), s + i);
}
}
if (flags & P_FLAGLIST)
{
/* Remove flags that appear twice. */
for (s = newval; *s; ++s)
{
/* if options have P_FLAGLIST and
* P_ONECOMMA such as 'whichwrap' */
if (flags & P_ONECOMMA)
{
if (*s != ',' && *(s + 1) == ','
&& vim_strchr(s + 2, *s) != NULL)
{
/* Remove the duplicated value and
* the next comma. */
STRMOVE(s, s + 2);
s -= 2;
}
}
else
{
if ((!(flags & P_COMMA) || *s != ',')
&& vim_strchr(s + 1, *s) != NULL)
{
STRMOVE(s, s + 1);
--s;
}
}
}
}
if (save_arg != NULL) /* number for 'whichwrap' */
arg = save_arg;
new_value_alloced = TRUE;
}
/* Set the new value. */
*(char_u **)(varp) = newval;
#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
if (!starting
# ifdef FEAT_CRYPT
&& options[opt_idx].indir != PV_KEY
# endif
&& origval != NULL)
/* origval may be freed by
* did_set_string_option(), make a copy. */
saved_origval = vim_strsave(origval);
#endif
/* Handle side effects, and set the global value for
* ":set" on local options. */
errmsg = did_set_string_option(opt_idx, (char_u **)varp,
new_value_alloced, oldval, errbuf, opt_flags);
/* If error detected, print the error message. */
if (errmsg != NULL)
{
#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
vim_free(saved_origval);
#endif
goto skip;
}
#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
if (saved_origval != NULL)
{
char_u buf_type[7];
sprintf((char *)buf_type, "%s",
(opt_flags & OPT_LOCAL) ? "local" : "global");
set_vim_var_string(VV_OPTION_NEW,
*(char_u **)varp, -1);
set_vim_var_string(VV_OPTION_OLD, saved_origval, -1);
set_vim_var_string(VV_OPTION_TYPE, buf_type, -1);
apply_autocmds(EVENT_OPTIONSET,
(char_u *)options[opt_idx].fullname,
NULL, FALSE, NULL);
reset_v_option_vars();
vim_free(saved_origval);
}
#endif
}
else /* key code option */
{
char_u *p;
if (nextchar == '&')
{
if (add_termcap_entry(key_name, TRUE) == FAIL)
errmsg = (char_u *)N_("E522: Not found in termcap");
}
else
{
++arg; /* jump to after the '=' or ':' */
for (p = arg; *p && !vim_iswhite(*p); ++p)
if (*p == '\\' && p[1] != NUL)
++p;
nextchar = *p;
*p = NUL;
add_termcode(key_name, arg, FALSE);
*p = nextchar;
}
if (full_screen)
ttest(FALSE);
redraw_all_later(CLEAR);
}
}
if (opt_idx >= 0)
did_set_option(opt_idx, opt_flags,
!prepending && !adding && !removing);
}
skip:
/*
* Advance to next argument.
* - skip until a blank found, taking care of backslashes
* - skip blanks
* - skip one "=val" argument (for hidden options ":set gfn =xx")
*/
for (i = 0; i < 2 ; ++i)
{
while (*arg != NUL && !vim_iswhite(*arg))
if (*arg++ == '\\' && *arg != NUL)
++arg;
arg = skipwhite(arg);
if (*arg != '=')
break;
}
}
if (errmsg != NULL)
{
vim_strncpy(IObuff, (char_u *)_(errmsg), IOSIZE - 1);
i = (int)STRLEN(IObuff) + 2;
if (i + (arg - startarg) < IOSIZE)
{
/* append the argument with the error */
STRCAT(IObuff, ": ");
mch_memmove(IObuff + i, startarg, (arg - startarg));
IObuff[i + (arg - startarg)] = NUL;
}
/* make sure all characters are printable */
trans_characters(IObuff, IOSIZE);
++no_wait_return; /* wait_return done later */
emsg(IObuff); /* show error highlighted */
--no_wait_return;
return FAIL;
}
arg = skipwhite(arg);
}
theend:
if (silent_mode && did_show)
{
/* After displaying option values in silent mode. */
silent_mode = FALSE;
info_message = TRUE; /* use mch_msg(), not mch_errmsg() */
msg_putchar('\n');
cursor_on(); /* msg_start() switches it off */
out_flush();
silent_mode = TRUE;
info_message = FALSE; /* use mch_msg(), not mch_errmsg() */
}
return OK;
}
/*
* Call this when an option has been given a new value through a user command.
* Sets the P_WAS_SET flag and takes care of the P_INSECURE flag.
*/
static void
did_set_option(
int opt_idx,
int opt_flags, /* possibly with OPT_MODELINE */
int new_value) /* value was replaced completely */
{
long_u *p;
options[opt_idx].flags |= P_WAS_SET;
/* When an option is set in the sandbox, from a modeline or in secure mode
* set the P_INSECURE flag. Otherwise, if a new value is stored reset the
* flag. */
p = insecure_flag(opt_idx, opt_flags);
if (secure
#ifdef HAVE_SANDBOX
|| sandbox != 0
#endif
|| (opt_flags & OPT_MODELINE))
*p = *p | P_INSECURE;
else if (new_value)
*p = *p & ~P_INSECURE;
}
static char_u *
illegal_char(char_u *errbuf, int c)
{
if (errbuf == NULL)
return (char_u *)"";
sprintf((char *)errbuf, _("E539: Illegal character <%s>"),
(char *)transchar(c));
return errbuf;
}
/*
* Convert a key name or string into a key value.
* Used for 'wildchar' and 'cedit' options.
*/
static int
string_to_key(char_u *arg)
{
if (*arg == '<')
return find_key_option(arg + 1);
if (*arg == '^')
return Ctrl_chr(arg[1]);
return *arg;
}
#ifdef FEAT_CMDWIN
/*
* Check value of 'cedit' and set cedit_key.
* Returns NULL if value is OK, error message otherwise.
*/
static char_u *
check_cedit(void)
{
int n;
if (*p_cedit == NUL)
cedit_key = -1;
else
{
n = string_to_key(p_cedit);
if (vim_isprintc(n))
return e_invarg;
cedit_key = n;
}
return NULL;
}
#endif
#ifdef FEAT_TITLE
/*
* When changing 'title', 'titlestring', 'icon' or 'iconstring', call
* maketitle() to create and display it.
* When switching the title or icon off, call mch_restore_title() to get
* the old value back.
*/
static void
did_set_title(
int icon) /* Did set icon instead of title */
{
if (starting != NO_SCREEN
#ifdef FEAT_GUI
&& !gui.starting
#endif
)
{
maketitle();
if (icon)
{
if (!p_icon)
mch_restore_title(2);
}
else
{
if (!p_title)
mch_restore_title(1);
}
}
}
#endif
/*
* set_options_bin - called when 'bin' changes value.
*/
void
set_options_bin(
int oldval,
int newval,
int opt_flags) /* OPT_LOCAL and/or OPT_GLOBAL */
{
/*
* The option values that are changed when 'bin' changes are
* copied when 'bin is set and restored when 'bin' is reset.
*/
if (newval)
{
if (!oldval) /* switched on */
{
if (!(opt_flags & OPT_GLOBAL))
{
curbuf->b_p_tw_nobin = curbuf->b_p_tw;
curbuf->b_p_wm_nobin = curbuf->b_p_wm;
curbuf->b_p_ml_nobin = curbuf->b_p_ml;
curbuf->b_p_et_nobin = curbuf->b_p_et;
}
if (!(opt_flags & OPT_LOCAL))
{
p_tw_nobin = p_tw;
p_wm_nobin = p_wm;
p_ml_nobin = p_ml;
p_et_nobin = p_et;
}
}
if (!(opt_flags & OPT_GLOBAL))
{
curbuf->b_p_tw = 0; /* no automatic line wrap */
curbuf->b_p_wm = 0; /* no automatic line wrap */
curbuf->b_p_ml = 0; /* no modelines */
curbuf->b_p_et = 0; /* no expandtab */
}
if (!(opt_flags & OPT_LOCAL))
{
p_tw = 0;
p_wm = 0;
p_ml = FALSE;
p_et = FALSE;
p_bin = TRUE; /* needed when called for the "-b" argument */
}
}
else if (oldval) /* switched off */
{
if (!(opt_flags & OPT_GLOBAL))
{
curbuf->b_p_tw = curbuf->b_p_tw_nobin;
curbuf->b_p_wm = curbuf->b_p_wm_nobin;
curbuf->b_p_ml = curbuf->b_p_ml_nobin;
curbuf->b_p_et = curbuf->b_p_et_nobin;
}
if (!(opt_flags & OPT_LOCAL))
{
p_tw = p_tw_nobin;
p_wm = p_wm_nobin;
p_ml = p_ml_nobin;
p_et = p_et_nobin;
}
}
}
#ifdef FEAT_VIMINFO
/*
* Find the parameter represented by the given character (eg ', :, ", or /),
* and return its associated value in the 'viminfo' string.
* Only works for number parameters, not for 'r' or 'n'.
* If the parameter is not specified in the string or there is no following
* number, return -1.
*/
int
get_viminfo_parameter(int type)
{
char_u *p;
p = find_viminfo_parameter(type);
if (p != NULL && VIM_ISDIGIT(*p))
return atoi((char *)p);
return -1;
}
/*
* Find the parameter represented by the given character (eg ''', ':', '"', or
* '/') in the 'viminfo' option and return a pointer to the string after it.
* Return NULL if the parameter is not specified in the string.
*/
char_u *
find_viminfo_parameter(int type)
{
char_u *p;
for (p = p_viminfo; *p; ++p)
{
if (*p == type)
return p + 1;
if (*p == 'n') /* 'n' is always the last one */
break;
p = vim_strchr(p, ','); /* skip until next ',' */
if (p == NULL) /* hit the end without finding parameter */
break;
}
return NULL;
}
#endif
/*
* Expand environment variables for some string options.
* These string options cannot be indirect!
* If "val" is NULL expand the current value of the option.
* Return pointer to NameBuff, or NULL when not expanded.
*/
static char_u *
option_expand(int opt_idx, char_u *val)
{
/* if option doesn't need expansion nothing to do */
if (!(options[opt_idx].flags & P_EXPAND) || options[opt_idx].var == NULL)
return NULL;
/* If val is longer than MAXPATHL no meaningful expansion can be done,
* expand_env() would truncate the string. */
if (val != NULL && STRLEN(val) > MAXPATHL)
return NULL;
if (val == NULL)
val = *(char_u **)options[opt_idx].var;
/*
* Expanding this with NameBuff, expand_env() must not be passed IObuff.
* Escape spaces when expanding 'tags', they are used to separate file
* names.
* For 'spellsuggest' expand after "file:".
*/
expand_env_esc(val, NameBuff, MAXPATHL,
(char_u **)options[opt_idx].var == &p_tags, FALSE,
#ifdef FEAT_SPELL
(char_u **)options[opt_idx].var == &p_sps ? (char_u *)"file:" :
#endif
NULL);
if (STRCMP(NameBuff, val) == 0) /* they are the same */
return NULL;
return NameBuff;
}
/*
* After setting various option values: recompute variables that depend on
* option values.
*/
static void
didset_options(void)
{
/* initialize the table for 'iskeyword' et.al. */
(void)init_chartab();
#ifdef FEAT_MBYTE
(void)opt_strings_flags(p_cmp, p_cmp_values, &cmp_flags, TRUE);
#endif
(void)opt_strings_flags(p_bkc, p_bkc_values, &bkc_flags, TRUE);
(void)opt_strings_flags(p_bo, p_bo_values, &bo_flags, TRUE);
#ifdef FEAT_SESSION
(void)opt_strings_flags(p_ssop, p_ssop_values, &ssop_flags, TRUE);
(void)opt_strings_flags(p_vop, p_ssop_values, &vop_flags, TRUE);
#endif
#ifdef FEAT_FOLDING
(void)opt_strings_flags(p_fdo, p_fdo_values, &fdo_flags, TRUE);
#endif
(void)opt_strings_flags(p_dy, p_dy_values, &dy_flags, TRUE);
(void)opt_strings_flags(p_tc, p_tc_values, &tc_flags, FALSE);
#ifdef FEAT_VIRTUALEDIT
(void)opt_strings_flags(p_ve, p_ve_values, &ve_flags, TRUE);
#endif
#if defined(FEAT_MOUSE) && (defined(UNIX) || defined(VMS))
(void)opt_strings_flags(p_ttym, p_ttym_values, &ttym_flags, FALSE);
#endif
#ifdef FEAT_SPELL
(void)spell_check_msm();
(void)spell_check_sps();
(void)compile_cap_prog(curwin->w_s);
(void)did_set_spell_option(TRUE);
#endif
#if defined(FEAT_TOOLBAR) && !defined(FEAT_GUI_W32)
(void)opt_strings_flags(p_toolbar, p_toolbar_values, &toolbar_flags, TRUE);
#endif
#if defined(FEAT_TOOLBAR) && defined(FEAT_GUI_GTK)
(void)opt_strings_flags(p_tbis, p_tbis_values, &tbis_flags, FALSE);
#endif
#ifdef FEAT_CMDWIN
/* set cedit_key */
(void)check_cedit();
#endif
#ifdef FEAT_LINEBREAK
briopt_check(curwin);
#endif
#ifdef FEAT_LINEBREAK
/* initialize the table for 'breakat'. */
fill_breakat_flags();
#endif
}
/*
* More side effects of setting options.
*/
static void
didset_options2(void)
{
/* Initialize the highlight_attr[] table. */
(void)highlight_changed();
/* Parse default for 'wildmode' */
check_opt_wim();
(void)set_chars_option(&p_lcs);
#if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING)
/* Parse default for 'fillchars'. */
(void)set_chars_option(&p_fcs);
#endif
#ifdef FEAT_CLIPBOARD
/* Parse default for 'clipboard' */
(void)check_clipboard_option();
#endif
}
/*
* Check for string options that are NULL (normally only termcap options).
*/
void
check_options(void)
{
int opt_idx;
for (opt_idx = 0; options[opt_idx].fullname != NULL; opt_idx++)
if ((options[opt_idx].flags & P_STRING) && options[opt_idx].var != NULL)
check_string_option((char_u **)get_varp(&(options[opt_idx])));
}
/*
* Check string options in a buffer for NULL value.
*/
void
check_buf_options(buf_T *buf)
{
#if defined(FEAT_QUICKFIX)
check_string_option(&buf->b_p_bh);
check_string_option(&buf->b_p_bt);
#endif
#ifdef FEAT_MBYTE
check_string_option(&buf->b_p_fenc);
#endif
check_string_option(&buf->b_p_ff);
#ifdef FEAT_FIND_ID
check_string_option(&buf->b_p_def);
check_string_option(&buf->b_p_inc);
# ifdef FEAT_EVAL
check_string_option(&buf->b_p_inex);
# endif
#endif
#if defined(FEAT_CINDENT) && defined(FEAT_EVAL)
check_string_option(&buf->b_p_inde);
check_string_option(&buf->b_p_indk);
#endif
#if defined(FEAT_BEVAL) && defined(FEAT_EVAL)
check_string_option(&buf->b_p_bexpr);
#endif
#if defined(FEAT_CRYPT)
check_string_option(&buf->b_p_cm);
#endif
#if defined(FEAT_EVAL)
check_string_option(&buf->b_p_fex);
#endif
#ifdef FEAT_CRYPT
check_string_option(&buf->b_p_key);
#endif
check_string_option(&buf->b_p_kp);
check_string_option(&buf->b_p_mps);
check_string_option(&buf->b_p_fo);
check_string_option(&buf->b_p_flp);
check_string_option(&buf->b_p_isk);
#ifdef FEAT_COMMENTS
check_string_option(&buf->b_p_com);
#endif
#ifdef FEAT_FOLDING
check_string_option(&buf->b_p_cms);
#endif
check_string_option(&buf->b_p_nf);
#ifdef FEAT_TEXTOBJ
check_string_option(&buf->b_p_qe);
#endif
#ifdef FEAT_SYN_HL
check_string_option(&buf->b_p_syn);
check_string_option(&buf->b_s.b_syn_isk);
#endif
#ifdef FEAT_SPELL
check_string_option(&buf->b_s.b_p_spc);
check_string_option(&buf->b_s.b_p_spf);
check_string_option(&buf->b_s.b_p_spl);
#endif
#ifdef FEAT_SEARCHPATH
check_string_option(&buf->b_p_sua);
#endif
#ifdef FEAT_CINDENT
check_string_option(&buf->b_p_cink);
check_string_option(&buf->b_p_cino);
parse_cino(buf);
#endif
#ifdef FEAT_AUTOCMD
check_string_option(&buf->b_p_ft);
#endif
#if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT)
check_string_option(&buf->b_p_cinw);
#endif
#ifdef FEAT_INS_EXPAND
check_string_option(&buf->b_p_cpt);
#endif
#ifdef FEAT_COMPL_FUNC
check_string_option(&buf->b_p_cfu);
check_string_option(&buf->b_p_ofu);
#endif
#ifdef FEAT_KEYMAP
check_string_option(&buf->b_p_keymap);
#endif
#ifdef FEAT_QUICKFIX
check_string_option(&buf->b_p_gp);
check_string_option(&buf->b_p_mp);
check_string_option(&buf->b_p_efm);
#endif
check_string_option(&buf->b_p_ep);
check_string_option(&buf->b_p_path);
check_string_option(&buf->b_p_tags);
check_string_option(&buf->b_p_tc);
#ifdef FEAT_INS_EXPAND
check_string_option(&buf->b_p_dict);
check_string_option(&buf->b_p_tsr);
#endif
#ifdef FEAT_LISP
check_string_option(&buf->b_p_lw);
#endif
check_string_option(&buf->b_p_bkc);
}
/*
* Free the string allocated for an option.
* Checks for the string being empty_option. This may happen if we're out of
* memory, vim_strsave() returned NULL, which was replaced by empty_option by
* check_options().
* Does NOT check for P_ALLOCED flag!
*/
void
free_string_option(char_u *p)
{
if (p != empty_option)
vim_free(p);
}
void
clear_string_option(char_u **pp)
{
if (*pp != empty_option)
vim_free(*pp);
*pp = empty_option;
}
static void
check_string_option(char_u **pp)
{
if (*pp == NULL)
*pp = empty_option;
}
/*
* Mark a terminal option as allocated, found by a pointer into term_strings[].
*/
void
set_term_option_alloced(char_u **p)
{
int opt_idx;
for (opt_idx = 1; options[opt_idx].fullname != NULL; opt_idx++)
if (options[opt_idx].var == (char_u *)p)
{
options[opt_idx].flags |= P_ALLOCED;
return;
}
return; /* cannot happen: didn't find it! */
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Return TRUE when option "opt" was set from a modeline or in secure mode.
* Return FALSE when it wasn't.
* Return -1 for an unknown option.
*/
int
was_set_insecurely(char_u *opt, int opt_flags)
{
int idx = findoption(opt);
long_u *flagp;
if (idx >= 0)
{
flagp = insecure_flag(idx, opt_flags);
return (*flagp & P_INSECURE) != 0;
}
EMSG2(_(e_intern2), "was_set_insecurely()");
return -1;
}
/*
* Get a pointer to the flags used for the P_INSECURE flag of option
* "opt_idx". For some local options a local flags field is used.
*/
static long_u *
insecure_flag(int opt_idx, int opt_flags)
{
if (opt_flags & OPT_LOCAL)
switch ((int)options[opt_idx].indir)
{
#ifdef FEAT_STL_OPT
case PV_STL: return &curwin->w_p_stl_flags;
#endif
#ifdef FEAT_EVAL
# ifdef FEAT_FOLDING
case PV_FDE: return &curwin->w_p_fde_flags;
case PV_FDT: return &curwin->w_p_fdt_flags;
# endif
# ifdef FEAT_BEVAL
case PV_BEXPR: return &curbuf->b_p_bexpr_flags;
# endif
# if defined(FEAT_CINDENT)
case PV_INDE: return &curbuf->b_p_inde_flags;
# endif
case PV_FEX: return &curbuf->b_p_fex_flags;
# ifdef FEAT_FIND_ID
case PV_INEX: return &curbuf->b_p_inex_flags;
# endif
#endif
}
/* Nothing special, return global flags field. */
return &options[opt_idx].flags;
}
#endif
#ifdef FEAT_TITLE
static void redraw_titles(void);
/*
* Redraw the window title and/or tab page text later.
*/
static void redraw_titles(void)
{
need_maketitle = TRUE;
# ifdef FEAT_WINDOWS
redraw_tabline = TRUE;
# endif
}
#endif
/*
* Set a string option to a new value (without checking the effect).
* The string is copied into allocated memory.
* if ("opt_idx" == -1) "name" is used, otherwise "opt_idx" is used.
* When "set_sid" is zero set the scriptID to current_SID. When "set_sid" is
* SID_NONE don't set the scriptID. Otherwise set the scriptID to "set_sid".
*/
void
set_string_option_direct(
char_u *name,
int opt_idx,
char_u *val,
int opt_flags, /* OPT_FREE, OPT_LOCAL and/or OPT_GLOBAL */
int set_sid UNUSED)
{
char_u *s;
char_u **varp;
int both = (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0;
int idx = opt_idx;
if (idx == -1) /* use name */
{
idx = findoption(name);
if (idx < 0) /* not found (should not happen) */
{
EMSG2(_(e_intern2), "set_string_option_direct()");
EMSG2(_("For option %s"), name);
return;
}
}
if (options[idx].var == NULL) /* can't set hidden option */
return;
s = vim_strsave(val);
if (s != NULL)
{
varp = (char_u **)get_varp_scope(&(options[idx]),
both ? OPT_LOCAL : opt_flags);
if ((opt_flags & OPT_FREE) && (options[idx].flags & P_ALLOCED))
free_string_option(*varp);
*varp = s;
/* For buffer/window local option may also set the global value. */
if (both)
set_string_option_global(idx, varp);
options[idx].flags |= P_ALLOCED;
/* When setting both values of a global option with a local value,
* make the local value empty, so that the global value is used. */
if (((int)options[idx].indir & PV_BOTH) && both)
{
free_string_option(*varp);
*varp = empty_option;
}
# ifdef FEAT_EVAL
if (set_sid != SID_NONE)
set_option_scriptID_idx(idx, opt_flags,
set_sid == 0 ? current_SID : set_sid);
# endif
}
}
/*
* Set global value for string option when it's a local option.
*/
static void
set_string_option_global(
int opt_idx, /* option index */
char_u **varp) /* pointer to option variable */
{
char_u **p, *s;
/* the global value is always allocated */
if (options[opt_idx].var == VAR_WIN)
p = (char_u **)GLOBAL_WO(varp);
else
p = (char_u **)options[opt_idx].var;
if (options[opt_idx].indir != PV_NONE
&& p != varp
&& (s = vim_strsave(*varp)) != NULL)
{
free_string_option(*p);
*p = s;
}
}
/*
* Set a string option to a new value, and handle the effects.
*
* Returns NULL on success or error message on error.
*/
static char_u *
set_string_option(
int opt_idx,
char_u *value,
int opt_flags) /* OPT_LOCAL and/or OPT_GLOBAL */
{
char_u *s;
char_u **varp;
char_u *oldval;
#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
char_u *saved_oldval = NULL;
#endif
char_u *r = NULL;
if (options[opt_idx].var == NULL) /* don't set hidden option */
return NULL;
s = vim_strsave(value);
if (s != NULL)
{
varp = (char_u **)get_varp_scope(&(options[opt_idx]),
(opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0
? (((int)options[opt_idx].indir & PV_BOTH)
? OPT_GLOBAL : OPT_LOCAL)
: opt_flags);
oldval = *varp;
*varp = s;
#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
if (!starting
# ifdef FEAT_CRYPT
&& options[opt_idx].indir != PV_KEY
# endif
)
saved_oldval = vim_strsave(oldval);
#endif
if ((r = did_set_string_option(opt_idx, varp, TRUE, oldval, NULL,
opt_flags)) == NULL)
did_set_option(opt_idx, opt_flags, TRUE);
/* call autocomamnd after handling side effects */
#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
if (saved_oldval != NULL)
{
char_u buf_type[7];
sprintf((char *)buf_type, "%s",
(opt_flags & OPT_LOCAL) ? "local" : "global");
set_vim_var_string(VV_OPTION_NEW, *varp, -1);
set_vim_var_string(VV_OPTION_OLD, saved_oldval, -1);
set_vim_var_string(VV_OPTION_TYPE, buf_type, -1);
apply_autocmds(EVENT_OPTIONSET, (char_u *)options[opt_idx].fullname, NULL, FALSE, NULL);
reset_v_option_vars();
vim_free(saved_oldval);
}
#endif
}
return r;
}
/*
* Return TRUE if "val" is a valid 'filetype' name.
* Also used for 'syntax' and 'keymap'.
*/
static int
valid_filetype(char_u *val)
{
char_u *s;
for (s = val; *s != NUL; ++s)
if (!ASCII_ISALNUM(*s) && vim_strchr((char_u *)".-_", *s) == NULL)
return FALSE;
return TRUE;
}
/*
* Handle string options that need some action to perform when changed.
* Returns NULL for success, or an error message for an error.
*/
static char_u *
did_set_string_option(
int opt_idx, /* index in options[] table */
char_u **varp, /* pointer to the option variable */
int new_value_alloced, /* new value was allocated */
char_u *oldval, /* previous value of the option */
char_u *errbuf, /* buffer for errors, or NULL */
int opt_flags) /* OPT_LOCAL and/or OPT_GLOBAL */
{
char_u *errmsg = NULL;
char_u *s, *p;
int did_chartab = FALSE;
char_u **gvarp;
long_u free_oldval = (options[opt_idx].flags & P_ALLOCED);
#ifdef FEAT_GUI
/* set when changing an option that only requires a redraw in the GUI */
int redraw_gui_only = FALSE;
#endif
/* Get the global option to compare with, otherwise we would have to check
* two values for all local options. */
gvarp = (char_u **)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL);
/* Disallow changing some options from secure mode */
if ((secure
#ifdef HAVE_SANDBOX
|| sandbox != 0
#endif
) && (options[opt_idx].flags & P_SECURE))
{
errmsg = e_secure;
}
/* Check for a "normal" file name in some options. Disallow a path
* separator (slash and/or backslash), wildcards and characters that are
* often illegal in a file name. */
else if ((options[opt_idx].flags & P_NFNAME)
&& vim_strpbrk(*varp, (char_u *)"/\\*?[|<>") != NULL)
{
errmsg = e_invarg;
}
/* 'term' */
else if (varp == &T_NAME)
{
if (T_NAME[0] == NUL)
errmsg = (char_u *)N_("E529: Cannot set 'term' to empty string");
#ifdef FEAT_GUI
if (gui.in_use)
errmsg = (char_u *)N_("E530: Cannot change term in GUI");
else if (term_is_gui(T_NAME))
errmsg = (char_u *)N_("E531: Use \":gui\" to start the GUI");
#endif
else if (set_termname(T_NAME) == FAIL)
errmsg = (char_u *)N_("E522: Not found in termcap");
else
/* Screen colors may have changed. */
redraw_later_clear();
}
/* 'backupcopy' */
else if (gvarp == &p_bkc)
{
char_u *bkc = p_bkc;
unsigned int *flags = &bkc_flags;
if (opt_flags & OPT_LOCAL)
{
bkc = curbuf->b_p_bkc;
flags = &curbuf->b_bkc_flags;
}
if ((opt_flags & OPT_LOCAL) && *bkc == NUL)
/* make the local value empty: use the global value */
*flags = 0;
else
{
if (opt_strings_flags(bkc, p_bkc_values, flags, TRUE) != OK)
errmsg = e_invarg;
if ((((int)*flags & BKC_AUTO) != 0)
+ (((int)*flags & BKC_YES) != 0)
+ (((int)*flags & BKC_NO) != 0) != 1)
{
/* Must have exactly one of "auto", "yes" and "no". */
(void)opt_strings_flags(oldval, p_bkc_values, flags, TRUE);
errmsg = e_invarg;
}
}
}
/* 'backupext' and 'patchmode' */
else if (varp == &p_bex || varp == &p_pm)
{
if (STRCMP(*p_bex == '.' ? p_bex + 1 : p_bex,
*p_pm == '.' ? p_pm + 1 : p_pm) == 0)
errmsg = (char_u *)N_("E589: 'backupext' and 'patchmode' are equal");
}
#ifdef FEAT_LINEBREAK
/* 'breakindentopt' */
else if (varp == &curwin->w_p_briopt)
{
if (briopt_check(curwin) == FAIL)
errmsg = e_invarg;
}
#endif
/*
* 'isident', 'iskeyword', 'isprint or 'isfname' option: refill g_chartab[]
* If the new option is invalid, use old value. 'lisp' option: refill
* g_chartab[] for '-' char
*/
else if ( varp == &p_isi
|| varp == &(curbuf->b_p_isk)
|| varp == &p_isp
|| varp == &p_isf)
{
if (init_chartab() == FAIL)
{
did_chartab = TRUE; /* need to restore it below */
errmsg = e_invarg; /* error in value */
}
}
/* 'helpfile' */
else if (varp == &p_hf)
{
/* May compute new values for $VIM and $VIMRUNTIME */
if (didset_vim)
{
vim_setenv((char_u *)"VIM", (char_u *)"");
didset_vim = FALSE;
}
if (didset_vimruntime)
{
vim_setenv((char_u *)"VIMRUNTIME", (char_u *)"");
didset_vimruntime = FALSE;
}
}
#ifdef FEAT_SYN_HL
/* 'colorcolumn' */
else if (varp == &curwin->w_p_cc)
errmsg = check_colorcolumn(curwin);
#endif
#ifdef FEAT_MULTI_LANG
/* 'helplang' */
else if (varp == &p_hlg)
{
/* Check for "", "ab", "ab,cd", etc. */
for (s = p_hlg; *s != NUL; s += 3)
{
if (s[1] == NUL || ((s[2] != ',' || s[3] == NUL) && s[2] != NUL))
{
errmsg = e_invarg;
break;
}
if (s[2] == NUL)
break;
}
}
#endif
/* 'highlight' */
else if (varp == &p_hl)
{
if (highlight_changed() == FAIL)
errmsg = e_invarg; /* invalid flags */
}
/* 'nrformats' */
else if (gvarp == &p_nf)
{
if (check_opt_strings(*varp, p_nf_values, TRUE) != OK)
errmsg = e_invarg;
}
#ifdef FEAT_SESSION
/* 'sessionoptions' */
else if (varp == &p_ssop)
{
if (opt_strings_flags(p_ssop, p_ssop_values, &ssop_flags, TRUE) != OK)
errmsg = e_invarg;
if ((ssop_flags & SSOP_CURDIR) && (ssop_flags & SSOP_SESDIR))
{
/* Don't allow both "sesdir" and "curdir". */
(void)opt_strings_flags(oldval, p_ssop_values, &ssop_flags, TRUE);
errmsg = e_invarg;
}
}
/* 'viewoptions' */
else if (varp == &p_vop)
{
if (opt_strings_flags(p_vop, p_ssop_values, &vop_flags, TRUE) != OK)
errmsg = e_invarg;
}
#endif
/* 'scrollopt' */
#ifdef FEAT_SCROLLBIND
else if (varp == &p_sbo)
{
if (check_opt_strings(p_sbo, p_scbopt_values, TRUE) != OK)
errmsg = e_invarg;
}
#endif
/* 'ambiwidth' */
#ifdef FEAT_MBYTE
else if (varp == &p_ambw || varp == &p_emoji)
{
if (check_opt_strings(p_ambw, p_ambw_values, FALSE) != OK)
errmsg = e_invarg;
else if (set_chars_option(&p_lcs) != NULL)
errmsg = (char_u *)_("E834: Conflicts with value of 'listchars'");
# if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING)
else if (set_chars_option(&p_fcs) != NULL)
errmsg = (char_u *)_("E835: Conflicts with value of 'fillchars'");
# endif
}
#endif
/* 'background' */
else if (varp == &p_bg)
{
if (check_opt_strings(p_bg, p_bg_values, FALSE) == OK)
{
#ifdef FEAT_EVAL
int dark = (*p_bg == 'd');
#endif
init_highlight(FALSE, FALSE);
#ifdef FEAT_EVAL
if (dark != (*p_bg == 'd')
&& get_var_value((char_u *)"g:colors_name") != NULL)
{
/* The color scheme must have set 'background' back to another
* value, that's not what we want here. Disable the color
* scheme and set the colors again. */
do_unlet((char_u *)"g:colors_name", TRUE);
free_string_option(p_bg);
p_bg = vim_strsave((char_u *)(dark ? "dark" : "light"));
check_string_option(&p_bg);
init_highlight(FALSE, FALSE);
}
#endif
}
else
errmsg = e_invarg;
}
/* 'wildmode' */
else if (varp == &p_wim)
{
if (check_opt_wim() == FAIL)
errmsg = e_invarg;
}
#ifdef FEAT_CMDL_COMPL
/* 'wildoptions' */
else if (varp == &p_wop)
{
if (check_opt_strings(p_wop, p_wop_values, TRUE) != OK)
errmsg = e_invarg;
}
#endif
#ifdef FEAT_WAK
/* 'winaltkeys' */
else if (varp == &p_wak)
{
if (*p_wak == NUL
|| check_opt_strings(p_wak, p_wak_values, FALSE) != OK)
errmsg = e_invarg;
# ifdef FEAT_MENU
# ifdef FEAT_GUI_MOTIF
else if (gui.in_use)
gui_motif_set_mnemonics(p_wak[0] == 'y' || p_wak[0] == 'm');
# else
# ifdef FEAT_GUI_GTK
else if (gui.in_use)
gui_gtk_set_mnemonics(p_wak[0] == 'y' || p_wak[0] == 'm');
# endif
# endif
# endif
}
#endif
#ifdef FEAT_AUTOCMD
/* 'eventignore' */
else if (varp == &p_ei)
{
if (check_ei() == FAIL)
errmsg = e_invarg;
}
#endif
#ifdef FEAT_MBYTE
/* 'encoding' and 'fileencoding' */
else if (varp == &p_enc || gvarp == &p_fenc || varp == &p_tenc)
{
if (gvarp == &p_fenc)
{
if (!curbuf->b_p_ma && opt_flags != OPT_GLOBAL)
errmsg = e_modifiable;
else if (vim_strchr(*varp, ',') != NULL)
/* No comma allowed in 'fileencoding'; catches confusing it
* with 'fileencodings'. */
errmsg = e_invarg;
else
{
# ifdef FEAT_TITLE
/* May show a "+" in the title now. */
redraw_titles();
# endif
/* Add 'fileencoding' to the swap file. */
ml_setflags(curbuf);
}
}
if (errmsg == NULL)
{
/* canonize the value, so that STRCMP() can be used on it */
p = enc_canonize(*varp);
if (p != NULL)
{
vim_free(*varp);
*varp = p;
}
if (varp == &p_enc)
{
errmsg = mb_init();
# ifdef FEAT_TITLE
redraw_titles();
# endif
}
}
# if defined(FEAT_GUI_GTK)
if (errmsg == NULL && varp == &p_tenc && gui.in_use)
{
/* GTK+ 2 uses only a single encoding, and that is UTF-8. */
if (STRCMP(p_tenc, "utf-8") != 0)
errmsg = (char_u *)N_("E617: Cannot be changed in the GTK+ 2 GUI");
}
# endif
if (errmsg == NULL)
{
# ifdef FEAT_KEYMAP
/* When 'keymap' is used and 'encoding' changes, reload the keymap
* (with another encoding). */
if (varp == &p_enc && *curbuf->b_p_keymap != NUL)
(void)keymap_init();
# endif
/* When 'termencoding' is not empty and 'encoding' changes or when
* 'termencoding' changes, need to setup for keyboard input and
* display output conversion. */
if (((varp == &p_enc && *p_tenc != NUL) || varp == &p_tenc))
{
convert_setup(&input_conv, p_tenc, p_enc);
convert_setup(&output_conv, p_enc, p_tenc);
}
# if defined(WIN3264) && defined(FEAT_MBYTE)
/* $HOME may have characters in active code page. */
if (varp == &p_enc)
init_homedir();
# endif
}
}
#endif
#if defined(FEAT_POSTSCRIPT)
else if (varp == &p_penc)
{
/* Canonize printencoding if VIM standard one */
p = enc_canonize(p_penc);
if (p != NULL)
{
vim_free(p_penc);
p_penc = p;
}
else
{
/* Ensure lower case and '-' for '_' */
for (s = p_penc; *s != NUL; s++)
{
if (*s == '_')
*s = '-';
else
*s = TOLOWER_ASC(*s);
}
}
}
#endif
#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
else if (varp == &p_imak)
{
if (gui.in_use && !im_xim_isvalid_imactivate())
errmsg = e_invarg;
}
#endif
#ifdef FEAT_KEYMAP
else if (varp == &curbuf->b_p_keymap)
{
if (!valid_filetype(*varp))
errmsg = e_invarg;
else
/* load or unload key mapping tables */
errmsg = keymap_init();
if (errmsg == NULL)
{
if (*curbuf->b_p_keymap != NUL)
{
/* Installed a new keymap, switch on using it. */
curbuf->b_p_iminsert = B_IMODE_LMAP;
if (curbuf->b_p_imsearch != B_IMODE_USE_INSERT)
curbuf->b_p_imsearch = B_IMODE_LMAP;
}
else
{
/* Cleared the keymap, may reset 'iminsert' and 'imsearch'. */
if (curbuf->b_p_iminsert == B_IMODE_LMAP)
curbuf->b_p_iminsert = B_IMODE_NONE;
if (curbuf->b_p_imsearch == B_IMODE_LMAP)
curbuf->b_p_imsearch = B_IMODE_USE_INSERT;
}
if ((opt_flags & OPT_LOCAL) == 0)
{
set_iminsert_global();
set_imsearch_global();
}
# ifdef FEAT_WINDOWS
status_redraw_curbuf();
# endif
}
}
#endif
/* 'fileformat' */
else if (gvarp == &p_ff)
{
if (!curbuf->b_p_ma && !(opt_flags & OPT_GLOBAL))
errmsg = e_modifiable;
else if (check_opt_strings(*varp, p_ff_values, FALSE) != OK)
errmsg = e_invarg;
else
{
/* may also change 'textmode' */
if (get_fileformat(curbuf) == EOL_DOS)
curbuf->b_p_tx = TRUE;
else
curbuf->b_p_tx = FALSE;
#ifdef FEAT_TITLE
redraw_titles();
#endif
/* update flag in swap file */
ml_setflags(curbuf);
/* Redraw needed when switching to/from "mac": a CR in the text
* will be displayed differently. */
if (get_fileformat(curbuf) == EOL_MAC || *oldval == 'm')
redraw_curbuf_later(NOT_VALID);
}
}
/* 'fileformats' */
else if (varp == &p_ffs)
{
if (check_opt_strings(p_ffs, p_ff_values, TRUE) != OK)
errmsg = e_invarg;
else
{
/* also change 'textauto' */
if (*p_ffs == NUL)
p_ta = FALSE;
else
p_ta = TRUE;
}
}
#if defined(FEAT_CRYPT)
/* 'cryptkey' */
else if (gvarp == &p_key)
{
# if defined(FEAT_CMDHIST)
/* Make sure the ":set" command doesn't show the new value in the
* history. */
remove_key_from_history();
# endif
if (STRCMP(curbuf->b_p_key, oldval) != 0)
/* Need to update the swapfile. */
ml_set_crypt_key(curbuf, oldval,
*curbuf->b_p_cm == NUL ? p_cm : curbuf->b_p_cm);
}
else if (gvarp == &p_cm)
{
if (opt_flags & OPT_LOCAL)
p = curbuf->b_p_cm;
else
p = p_cm;
if (check_opt_strings(p, p_cm_values, TRUE) != OK)
errmsg = e_invarg;
else if (crypt_self_test() == FAIL)
errmsg = e_invarg;
else
{
/* When setting the global value to empty, make it "zip". */
if (*p_cm == NUL)
{
if (new_value_alloced)
free_string_option(p_cm);
p_cm = vim_strsave((char_u *)"zip");
new_value_alloced = TRUE;
}
/* When using ":set cm=name" the local value is going to be empty.
* Do that here, otherwise the crypt functions will still use the
* local value. */
if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0)
{
free_string_option(curbuf->b_p_cm);
curbuf->b_p_cm = empty_option;
}
/* Need to update the swapfile when the effective method changed.
* Set "s" to the effective old value, "p" to the effective new
* method and compare. */
if ((opt_flags & OPT_LOCAL) && *oldval == NUL)
s = p_cm; /* was previously using the global value */
else
s = oldval;
if (*curbuf->b_p_cm == NUL)
p = p_cm; /* is now using the global value */
else
p = curbuf->b_p_cm;
if (STRCMP(s, p) != 0)
ml_set_crypt_key(curbuf, curbuf->b_p_key, s);
/* If the global value changes need to update the swapfile for all
* buffers using that value. */
if ((opt_flags & OPT_GLOBAL) && STRCMP(p_cm, oldval) != 0)
{
buf_T *buf;
FOR_ALL_BUFFERS(buf)
if (buf != curbuf && *buf->b_p_cm == NUL)
ml_set_crypt_key(buf, buf->b_p_key, oldval);
}
}
}
#endif
/* 'matchpairs' */
else if (gvarp == &p_mps)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
{
for (p = *varp; *p != NUL; ++p)
{
int x2 = -1;
int x3 = -1;
if (*p != NUL)
p += mb_ptr2len(p);
if (*p != NUL)
x2 = *p++;
if (*p != NUL)
{
x3 = mb_ptr2char(p);
p += mb_ptr2len(p);
}
if (x2 != ':' || x3 == -1 || (*p != NUL && *p != ','))
{
errmsg = e_invarg;
break;
}
if (*p == NUL)
break;
}
}
else
#endif
{
/* Check for "x:y,x:y" */
for (p = *varp; *p != NUL; p += 4)
{
if (p[1] != ':' || p[2] == NUL || (p[3] != NUL && p[3] != ','))
{
errmsg = e_invarg;
break;
}
if (p[3] == NUL)
break;
}
}
}
#ifdef FEAT_COMMENTS
/* 'comments' */
else if (gvarp == &p_com)
{
for (s = *varp; *s; )
{
while (*s && *s != ':')
{
if (vim_strchr((char_u *)COM_ALL, *s) == NULL
&& !VIM_ISDIGIT(*s) && *s != '-')
{
errmsg = illegal_char(errbuf, *s);
break;
}
++s;
}
if (*s++ == NUL)
errmsg = (char_u *)N_("E524: Missing colon");
else if (*s == ',' || *s == NUL)
errmsg = (char_u *)N_("E525: Zero length string");
if (errmsg != NULL)
break;
while (*s && *s != ',')
{
if (*s == '\\' && s[1] != NUL)
++s;
++s;
}
s = skip_to_option_part(s);
}
}
#endif
/* 'listchars' */
else if (varp == &p_lcs)
{
errmsg = set_chars_option(varp);
}
#if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING)
/* 'fillchars' */
else if (varp == &p_fcs)
{
errmsg = set_chars_option(varp);
}
#endif
#ifdef FEAT_CMDWIN
/* 'cedit' */
else if (varp == &p_cedit)
{
errmsg = check_cedit();
}
#endif
/* 'verbosefile' */
else if (varp == &p_vfile)
{
verbose_stop();
if (*p_vfile != NUL && verbose_open() == FAIL)
errmsg = e_invarg;
}
#ifdef FEAT_VIMINFO
/* 'viminfo' */
else if (varp == &p_viminfo)
{
for (s = p_viminfo; *s;)
{
/* Check it's a valid character */
if (vim_strchr((char_u *)"!\"%'/:<@cfhnrs", *s) == NULL)
{
errmsg = illegal_char(errbuf, *s);
break;
}
if (*s == 'n') /* name is always last one */
{
break;
}
else if (*s == 'r') /* skip until next ',' */
{
while (*++s && *s != ',')
;
}
else if (*s == '%')
{
/* optional number */
while (vim_isdigit(*++s))
;
}
else if (*s == '!' || *s == 'h' || *s == 'c')
++s; /* no extra chars */
else /* must have a number */
{
while (vim_isdigit(*++s))
;
if (!VIM_ISDIGIT(*(s - 1)))
{
if (errbuf != NULL)
{
sprintf((char *)errbuf,
_("E526: Missing number after <%s>"),
transchar_byte(*(s - 1)));
errmsg = errbuf;
}
else
errmsg = (char_u *)"";
break;
}
}
if (*s == ',')
++s;
else if (*s)
{
if (errbuf != NULL)
errmsg = (char_u *)N_("E527: Missing comma");
else
errmsg = (char_u *)"";
break;
}
}
if (*p_viminfo && errmsg == NULL && get_viminfo_parameter('\'') < 0)
errmsg = (char_u *)N_("E528: Must specify a ' value");
}
#endif /* FEAT_VIMINFO */
/* terminal options */
else if (istermoption(&options[opt_idx]) && full_screen)
{
/* ":set t_Co=0" and ":set t_Co=1" do ":set t_Co=" */
if (varp == &T_CCO)
{
int colors = atoi((char *)T_CCO);
/* Only reinitialize colors if t_Co value has really changed to
* avoid expensive reload of colorscheme if t_Co is set to the
* same value multiple times. */
if (colors != t_colors)
{
t_colors = colors;
if (t_colors <= 1)
{
if (new_value_alloced)
vim_free(T_CCO);
T_CCO = empty_option;
}
/* We now have a different color setup, initialize it again. */
init_highlight(TRUE, FALSE);
}
}
ttest(FALSE);
if (varp == &T_ME)
{
out_str(T_ME);
redraw_later(CLEAR);
#if defined(WIN3264) && !defined(FEAT_GUI_W32)
/* Since t_me has been set, this probably means that the user
* wants to use this as default colors. Need to reset default
* background/foreground colors. */
mch_set_normal_colors();
#endif
}
}
#ifdef FEAT_LINEBREAK
/* 'showbreak' */
else if (varp == &p_sbr)
{
for (s = p_sbr; *s; )
{
if (ptr2cells(s) != 1)
errmsg = (char_u *)N_("E595: contains unprintable or wide character");
mb_ptr_adv(s);
}
}
#endif
#ifdef FEAT_GUI
/* 'guifont' */
else if (varp == &p_guifont)
{
if (gui.in_use)
{
p = p_guifont;
# if defined(FEAT_GUI_GTK)
/*
* Put up a font dialog and let the user select a new value.
* If this is cancelled go back to the old value but don't
* give an error message.
*/
if (STRCMP(p, "*") == 0)
{
p = gui_mch_font_dialog(oldval);
if (new_value_alloced)
free_string_option(p_guifont);
p_guifont = (p != NULL) ? p : vim_strsave(oldval);
new_value_alloced = TRUE;
}
# endif
if (p != NULL && gui_init_font(p_guifont, FALSE) != OK)
{
# if defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_PHOTON)
if (STRCMP(p_guifont, "*") == 0)
{
/* Dialog was cancelled: Keep the old value without giving
* an error message. */
if (new_value_alloced)
free_string_option(p_guifont);
p_guifont = vim_strsave(oldval);
new_value_alloced = TRUE;
}
else
# endif
errmsg = (char_u *)N_("E596: Invalid font(s)");
}
}
redraw_gui_only = TRUE;
}
# ifdef FEAT_XFONTSET
else if (varp == &p_guifontset)
{
if (STRCMP(p_guifontset, "*") == 0)
errmsg = (char_u *)N_("E597: can't select fontset");
else if (gui.in_use && gui_init_font(p_guifontset, TRUE) != OK)
errmsg = (char_u *)N_("E598: Invalid fontset");
redraw_gui_only = TRUE;
}
# endif
# ifdef FEAT_MBYTE
else if (varp == &p_guifontwide)
{
if (STRCMP(p_guifontwide, "*") == 0)
errmsg = (char_u *)N_("E533: can't select wide font");
else if (gui_get_wide_font() == FAIL)
errmsg = (char_u *)N_("E534: Invalid wide font");
redraw_gui_only = TRUE;
}
# endif
#endif
#ifdef CURSOR_SHAPE
/* 'guicursor' */
else if (varp == &p_guicursor)
errmsg = parse_shape_opt(SHAPE_CURSOR);
#endif
#ifdef FEAT_MOUSESHAPE
/* 'mouseshape' */
else if (varp == &p_mouseshape)
{
errmsg = parse_shape_opt(SHAPE_MOUSE);
update_mouseshape(-1);
}
#endif
#ifdef FEAT_PRINTER
else if (varp == &p_popt)
errmsg = parse_printoptions();
# if defined(FEAT_MBYTE) && defined(FEAT_POSTSCRIPT)
else if (varp == &p_pmfn)
errmsg = parse_printmbfont();
# endif
#endif
#ifdef FEAT_LANGMAP
/* 'langmap' */
else if (varp == &p_langmap)
langmap_set();
#endif
#ifdef FEAT_LINEBREAK
/* 'breakat' */
else if (varp == &p_breakat)
fill_breakat_flags();
#endif
#ifdef FEAT_TITLE
/* 'titlestring' and 'iconstring' */
else if (varp == &p_titlestring || varp == &p_iconstring)
{
# ifdef FEAT_STL_OPT
int flagval = (varp == &p_titlestring) ? STL_IN_TITLE : STL_IN_ICON;
/* NULL => statusline syntax */
if (vim_strchr(*varp, '%') && check_stl_option(*varp) == NULL)
stl_syntax |= flagval;
else
stl_syntax &= ~flagval;
# endif
did_set_title(varp == &p_iconstring);
}
#endif
#ifdef FEAT_GUI
/* 'guioptions' */
else if (varp == &p_go)
{
gui_init_which_components(oldval);
redraw_gui_only = TRUE;
}
#endif
#if defined(FEAT_GUI_TABLINE)
/* 'guitablabel' */
else if (varp == &p_gtl)
{
redraw_tabline = TRUE;
redraw_gui_only = TRUE;
}
/* 'guitabtooltip' */
else if (varp == &p_gtt)
{
redraw_gui_only = TRUE;
}
#endif
#if defined(FEAT_MOUSE_TTY) && (defined(UNIX) || defined(VMS))
/* 'ttymouse' */
else if (varp == &p_ttym)
{
/* Switch the mouse off before changing the escape sequences used for
* that. */
mch_setmouse(FALSE);
if (opt_strings_flags(p_ttym, p_ttym_values, &ttym_flags, FALSE) != OK)
errmsg = e_invarg;
else
check_mouse_termcode();
if (termcap_active)
setmouse(); /* may switch it on again */
}
#endif
/* 'selection' */
else if (varp == &p_sel)
{
if (*p_sel == NUL
|| check_opt_strings(p_sel, p_sel_values, FALSE) != OK)
errmsg = e_invarg;
}
/* 'selectmode' */
else if (varp == &p_slm)
{
if (check_opt_strings(p_slm, p_slm_values, TRUE) != OK)
errmsg = e_invarg;
}
#ifdef FEAT_BROWSE
/* 'browsedir' */
else if (varp == &p_bsdir)
{
if (check_opt_strings(p_bsdir, p_bsdir_values, FALSE) != OK
&& !mch_isdir(p_bsdir))
errmsg = e_invarg;
}
#endif
/* 'keymodel' */
else if (varp == &p_km)
{
if (check_opt_strings(p_km, p_km_values, TRUE) != OK)
errmsg = e_invarg;
else
{
km_stopsel = (vim_strchr(p_km, 'o') != NULL);
km_startsel = (vim_strchr(p_km, 'a') != NULL);
}
}
/* 'mousemodel' */
else if (varp == &p_mousem)
{
if (check_opt_strings(p_mousem, p_mousem_values, FALSE) != OK)
errmsg = e_invarg;
#if defined(FEAT_GUI_MOTIF) && defined(FEAT_MENU) && (XmVersion <= 1002)
else if (*p_mousem != *oldval)
/* Changed from "extend" to "popup" or "popup_setpos" or vv: need
* to create or delete the popup menus. */
gui_motif_update_mousemodel(root_menu);
#endif
}
/* 'switchbuf' */
else if (varp == &p_swb)
{
if (opt_strings_flags(p_swb, p_swb_values, &swb_flags, TRUE) != OK)
errmsg = e_invarg;
}
/* 'debug' */
else if (varp == &p_debug)
{
if (check_opt_strings(p_debug, p_debug_values, TRUE) != OK)
errmsg = e_invarg;
}
/* 'display' */
else if (varp == &p_dy)
{
if (opt_strings_flags(p_dy, p_dy_values, &dy_flags, TRUE) != OK)
errmsg = e_invarg;
else
(void)init_chartab();
}
#ifdef FEAT_WINDOWS
/* 'eadirection' */
else if (varp == &p_ead)
{
if (check_opt_strings(p_ead, p_ead_values, FALSE) != OK)
errmsg = e_invarg;
}
#endif
#ifdef FEAT_CLIPBOARD
/* 'clipboard' */
else if (varp == &p_cb)
errmsg = check_clipboard_option();
#endif
#ifdef FEAT_SPELL
/* When 'spelllang' or 'spellfile' is set and there is a window for this
* buffer in which 'spell' is set load the wordlists. */
else if (varp == &(curwin->w_s->b_p_spl)
|| varp == &(curwin->w_s->b_p_spf))
{
errmsg = did_set_spell_option(varp == &(curwin->w_s->b_p_spf));
}
/* When 'spellcapcheck' is set compile the regexp program. */
else if (varp == &(curwin->w_s->b_p_spc))
{
errmsg = compile_cap_prog(curwin->w_s);
}
/* 'spellsuggest' */
else if (varp == &p_sps)
{
if (spell_check_sps() != OK)
errmsg = e_invarg;
}
/* 'mkspellmem' */
else if (varp == &p_msm)
{
if (spell_check_msm() != OK)
errmsg = e_invarg;
}
#endif
#ifdef FEAT_QUICKFIX
/* When 'bufhidden' is set, check for valid value. */
else if (gvarp == &p_bh)
{
if (check_opt_strings(curbuf->b_p_bh, p_bufhidden_values, FALSE) != OK)
errmsg = e_invarg;
}
/* When 'buftype' is set, check for valid value. */
else if (gvarp == &p_bt)
{
if (check_opt_strings(curbuf->b_p_bt, p_buftype_values, FALSE) != OK)
errmsg = e_invarg;
else
{
# ifdef FEAT_WINDOWS
if (curwin->w_status_height)
{
curwin->w_redr_status = TRUE;
redraw_later(VALID);
}
# endif
curbuf->b_help = (curbuf->b_p_bt[0] == 'h');
# ifdef FEAT_TITLE
redraw_titles();
# endif
}
}
#endif
#ifdef FEAT_STL_OPT
/* 'statusline' or 'rulerformat' */
else if (gvarp == &p_stl || varp == &p_ruf)
{
int wid;
if (varp == &p_ruf) /* reset ru_wid first */
ru_wid = 0;
s = *varp;
if (varp == &p_ruf && *s == '%')
{
/* set ru_wid if 'ruf' starts with "%99(" */
if (*++s == '-') /* ignore a '-' */
s++;
wid = getdigits(&s);
if (wid && *s == '(' && (errmsg = check_stl_option(p_ruf)) == NULL)
ru_wid = wid;
else
errmsg = check_stl_option(p_ruf);
}
/* check 'statusline' only if it doesn't start with "%!" */
else if (varp == &p_ruf || s[0] != '%' || s[1] != '!')
errmsg = check_stl_option(s);
if (varp == &p_ruf && errmsg == NULL)
comp_col();
}
#endif
#ifdef FEAT_INS_EXPAND
/* check if it is a valid value for 'complete' -- Acevedo */
else if (gvarp == &p_cpt)
{
for (s = *varp; *s;)
{
while (*s == ',' || *s == ' ')
s++;
if (!*s)
break;
if (vim_strchr((char_u *)".wbuksid]tU", *s) == NULL)
{
errmsg = illegal_char(errbuf, *s);
break;
}
if (*++s != NUL && *s != ',' && *s != ' ')
{
if (s[-1] == 'k' || s[-1] == 's')
{
/* skip optional filename after 'k' and 's' */
while (*s && *s != ',' && *s != ' ')
{
if (*s == '\\')
++s;
++s;
}
}
else
{
if (errbuf != NULL)
{
sprintf((char *)errbuf,
_("E535: Illegal character after <%c>"),
*--s);
errmsg = errbuf;
}
else
errmsg = (char_u *)"";
break;
}
}
}
}
/* 'completeopt' */
else if (varp == &p_cot)
{
if (check_opt_strings(p_cot, p_cot_values, TRUE) != OK)
errmsg = e_invarg;
else
completeopt_was_set();
}
#endif /* FEAT_INS_EXPAND */
#ifdef FEAT_SIGNS
/* 'signcolumn' */
else if (varp == &curwin->w_p_scl)
{
if (check_opt_strings(*varp, p_scl_values, FALSE) != OK)
errmsg = e_invarg;
}
#endif
#if defined(FEAT_TOOLBAR) && !defined(FEAT_GUI_W32)
else if (varp == &p_toolbar)
{
if (opt_strings_flags(p_toolbar, p_toolbar_values,
&toolbar_flags, TRUE) != OK)
errmsg = e_invarg;
else
{
out_flush();
gui_mch_show_toolbar((toolbar_flags &
(TOOLBAR_TEXT | TOOLBAR_ICONS)) != 0);
}
}
#endif
#if defined(FEAT_TOOLBAR) && defined(FEAT_GUI_GTK)
/* 'toolbariconsize': GTK+ 2 only */
else if (varp == &p_tbis)
{
if (opt_strings_flags(p_tbis, p_tbis_values, &tbis_flags, FALSE) != OK)
errmsg = e_invarg;
else
{
out_flush();
gui_mch_show_toolbar((toolbar_flags &
(TOOLBAR_TEXT | TOOLBAR_ICONS)) != 0);
}
}
#endif
/* 'pastetoggle': translate key codes like in a mapping */
else if (varp == &p_pt)
{
if (*p_pt)
{
(void)replace_termcodes(p_pt, &p, TRUE, TRUE, FALSE);
if (p != NULL)
{
if (new_value_alloced)
free_string_option(p_pt);
p_pt = p;
new_value_alloced = TRUE;
}
}
}
/* 'backspace' */
else if (varp == &p_bs)
{
if (VIM_ISDIGIT(*p_bs))
{
if (*p_bs > '2' || p_bs[1] != NUL)
errmsg = e_invarg;
}
else if (check_opt_strings(p_bs, p_bs_values, TRUE) != OK)
errmsg = e_invarg;
}
else if (varp == &p_bo)
{
if (opt_strings_flags(p_bo, p_bo_values, &bo_flags, TRUE) != OK)
errmsg = e_invarg;
}
/* 'tagcase' */
else if (gvarp == &p_tc)
{
unsigned int *flags;
if (opt_flags & OPT_LOCAL)
{
p = curbuf->b_p_tc;
flags = &curbuf->b_tc_flags;
}
else
{
p = p_tc;
flags = &tc_flags;
}
if ((opt_flags & OPT_LOCAL) && *p == NUL)
/* make the local value empty: use the global value */
*flags = 0;
else if (*p == NUL
|| opt_strings_flags(p, p_tc_values, flags, FALSE) != OK)
errmsg = e_invarg;
}
#ifdef FEAT_MBYTE
/* 'casemap' */
else if (varp == &p_cmp)
{
if (opt_strings_flags(p_cmp, p_cmp_values, &cmp_flags, TRUE) != OK)
errmsg = e_invarg;
}
#endif
#ifdef FEAT_DIFF
/* 'diffopt' */
else if (varp == &p_dip)
{
if (diffopt_changed() == FAIL)
errmsg = e_invarg;
}
#endif
#ifdef FEAT_FOLDING
/* 'foldmethod' */
else if (gvarp == &curwin->w_allbuf_opt.wo_fdm)
{
if (check_opt_strings(*varp, p_fdm_values, FALSE) != OK
|| *curwin->w_p_fdm == NUL)
errmsg = e_invarg;
else
{
foldUpdateAll(curwin);
if (foldmethodIsDiff(curwin))
newFoldLevel();
}
}
# ifdef FEAT_EVAL
/* 'foldexpr' */
else if (varp == &curwin->w_p_fde)
{
if (foldmethodIsExpr(curwin))
foldUpdateAll(curwin);
}
# endif
/* 'foldmarker' */
else if (gvarp == &curwin->w_allbuf_opt.wo_fmr)
{
p = vim_strchr(*varp, ',');
if (p == NULL)
errmsg = (char_u *)N_("E536: comma required");
else if (p == *varp || p[1] == NUL)
errmsg = e_invarg;
else if (foldmethodIsMarker(curwin))
foldUpdateAll(curwin);
}
/* 'commentstring' */
else if (gvarp == &p_cms)
{
if (**varp != NUL && strstr((char *)*varp, "%s") == NULL)
errmsg = (char_u *)N_("E537: 'commentstring' must be empty or contain %s");
}
/* 'foldopen' */
else if (varp == &p_fdo)
{
if (opt_strings_flags(p_fdo, p_fdo_values, &fdo_flags, TRUE) != OK)
errmsg = e_invarg;
}
/* 'foldclose' */
else if (varp == &p_fcl)
{
if (check_opt_strings(p_fcl, p_fcl_values, TRUE) != OK)
errmsg = e_invarg;
}
/* 'foldignore' */
else if (gvarp == &curwin->w_allbuf_opt.wo_fdi)
{
if (foldmethodIsIndent(curwin))
foldUpdateAll(curwin);
}
#endif
#ifdef FEAT_VIRTUALEDIT
/* 'virtualedit' */
else if (varp == &p_ve)
{
if (opt_strings_flags(p_ve, p_ve_values, &ve_flags, TRUE) != OK)
errmsg = e_invarg;
else if (STRCMP(p_ve, oldval) != 0)
{
/* Recompute cursor position in case the new 've' setting
* changes something. */
validate_virtcol();
coladvance(curwin->w_virtcol);
}
}
#endif
#if defined(FEAT_CSCOPE) && defined(FEAT_QUICKFIX)
else if (varp == &p_csqf)
{
if (p_csqf != NULL)
{
p = p_csqf;
while (*p != NUL)
{
if (vim_strchr((char_u *)CSQF_CMDS, *p) == NULL
|| p[1] == NUL
|| vim_strchr((char_u *)CSQF_FLAGS, p[1]) == NULL
|| (p[2] != NUL && p[2] != ','))
{
errmsg = e_invarg;
break;
}
else if (p[2] == NUL)
break;
else
p += 3;
}
}
}
#endif
#ifdef FEAT_CINDENT
/* 'cinoptions' */
else if (gvarp == &p_cino)
{
/* TODO: recognize errors */
parse_cino(curbuf);
}
#endif
#if defined(FEAT_RENDER_OPTIONS)
else if (varp == &p_rop && gui.in_use)
{
if (!gui_mch_set_rendering_options(p_rop))
errmsg = e_invarg;
}
#endif
#ifdef FEAT_AUTOCMD
else if (gvarp == &p_ft)
{
if (!valid_filetype(*varp))
errmsg = e_invarg;
}
#endif
#ifdef FEAT_SYN_HL
else if (gvarp == &p_syn)
{
if (!valid_filetype(*varp))
errmsg = e_invarg;
}
#endif
/* Options that are a list of flags. */
else
{
p = NULL;
if (varp == &p_ww)
p = (char_u *)WW_ALL;
if (varp == &p_shm)
p = (char_u *)SHM_ALL;
else if (varp == &(p_cpo))
p = (char_u *)CPO_ALL;
else if (varp == &(curbuf->b_p_fo))
p = (char_u *)FO_ALL;
#ifdef FEAT_CONCEAL
else if (varp == &curwin->w_p_cocu)
p = (char_u *)COCU_ALL;
#endif
else if (varp == &p_mouse)
{
#ifdef FEAT_MOUSE
p = (char_u *)MOUSE_ALL;
#else
if (*p_mouse != NUL)
errmsg = (char_u *)N_("E538: No mouse support");
#endif
}
#if defined(FEAT_GUI)
else if (varp == &p_go)
p = (char_u *)GO_ALL;
#endif
if (p != NULL)
{
for (s = *varp; *s; ++s)
if (vim_strchr(p, *s) == NULL)
{
errmsg = illegal_char(errbuf, *s);
break;
}
}
}
/*
* If error detected, restore the previous value.
*/
if (errmsg != NULL)
{
if (new_value_alloced)
free_string_option(*varp);
*varp = oldval;
/*
* When resetting some values, need to act on it.
*/
if (did_chartab)
(void)init_chartab();
if (varp == &p_hl)
(void)highlight_changed();
}
else
{
#ifdef FEAT_EVAL
/* Remember where the option was set. */
set_option_scriptID_idx(opt_idx, opt_flags, current_SID);
#endif
/*
* Free string options that are in allocated memory.
* Use "free_oldval", because recursiveness may change the flags under
* our fingers (esp. init_highlight()).
*/
if (free_oldval)
free_string_option(oldval);
if (new_value_alloced)
options[opt_idx].flags |= P_ALLOCED;
else
options[opt_idx].flags &= ~P_ALLOCED;
if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0
&& ((int)options[opt_idx].indir & PV_BOTH))
{
/* global option with local value set to use global value; free
* the local value and make it empty */
p = get_varp_scope(&(options[opt_idx]), OPT_LOCAL);
free_string_option(*(char_u **)p);
*(char_u **)p = empty_option;
}
/* May set global value for local option. */
else if (!(opt_flags & OPT_LOCAL) && opt_flags != OPT_GLOBAL)
set_string_option_global(opt_idx, varp);
#ifdef FEAT_AUTOCMD
/*
* Trigger the autocommand only after setting the flags.
*/
# ifdef FEAT_SYN_HL
/* When 'syntax' is set, load the syntax of that name */
if (varp == &(curbuf->b_p_syn))
{
apply_autocmds(EVENT_SYNTAX, curbuf->b_p_syn,
curbuf->b_fname, TRUE, curbuf);
}
# endif
else if (varp == &(curbuf->b_p_ft))
{
/* 'filetype' is set, trigger the FileType autocommand */
did_filetype = TRUE;
apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft,
curbuf->b_fname, TRUE, curbuf);
}
#endif
#ifdef FEAT_SPELL
if (varp == &(curwin->w_s->b_p_spl))
{
char_u fname[200];
char_u *q = curwin->w_s->b_p_spl;
/* Skip the first name if it is "cjk". */
if (STRNCMP(q, "cjk,", 4) == 0)
q += 4;
/*
* Source the spell/LANG.vim in 'runtimepath'.
* They could set 'spellcapcheck' depending on the language.
* Use the first name in 'spelllang' up to '_region' or
* '.encoding'.
*/
for (p = q; *p != NUL; ++p)
if (vim_strchr((char_u *)"_.,", *p) != NULL)
break;
vim_snprintf((char *)fname, 200, "spell/%.*s.vim", (int)(p - q), q);
source_runtime(fname, DIP_ALL);
}
#endif
}
#ifdef FEAT_MOUSE
if (varp == &p_mouse)
{
# ifdef FEAT_MOUSE_TTY
if (*p_mouse == NUL)
mch_setmouse(FALSE); /* switch mouse off */
else
# endif
setmouse(); /* in case 'mouse' changed */
}
#endif
if (curwin->w_curswant != MAXCOL
&& (options[opt_idx].flags & (P_CURSWANT | P_RALL)) != 0)
curwin->w_set_curswant = TRUE;
#ifdef FEAT_GUI
/* check redraw when it's not a GUI option or the GUI is active. */
if (!redraw_gui_only || gui.in_use)
#endif
check_redraw(options[opt_idx].flags);
return errmsg;
}
#if defined(FEAT_SYN_HL) || defined(PROTO)
/*
* Simple int comparison function for use with qsort()
*/
static int
int_cmp(const void *a, const void *b)
{
return *(const int *)a - *(const int *)b;
}
/*
* Handle setting 'colorcolumn' or 'textwidth' in window "wp".
* Returns error message, NULL if it's OK.
*/
char_u *
check_colorcolumn(win_T *wp)
{
char_u *s;
int col;
int count = 0;
int color_cols[256];
int i;
int j = 0;
if (wp->w_buffer == NULL)
return NULL; /* buffer was closed */
for (s = wp->w_p_cc; *s != NUL && count < 255;)
{
if (*s == '-' || *s == '+')
{
/* -N and +N: add to 'textwidth' */
col = (*s == '-') ? -1 : 1;
++s;
if (!VIM_ISDIGIT(*s))
return e_invarg;
col = col * getdigits(&s);
if (wp->w_buffer->b_p_tw == 0)
goto skip; /* 'textwidth' not set, skip this item */
col += wp->w_buffer->b_p_tw;
if (col < 0)
goto skip;
}
else if (VIM_ISDIGIT(*s))
col = getdigits(&s);
else
return e_invarg;
color_cols[count++] = col - 1; /* 1-based to 0-based */
skip:
if (*s == NUL)
break;
if (*s != ',')
return e_invarg;
if (*++s == NUL)
return e_invarg; /* illegal trailing comma as in "set cc=80," */
}
vim_free(wp->w_p_cc_cols);
if (count == 0)
wp->w_p_cc_cols = NULL;
else
{
wp->w_p_cc_cols = (int *)alloc((unsigned)sizeof(int) * (count + 1));
if (wp->w_p_cc_cols != NULL)
{
/* sort the columns for faster usage on screen redraw inside
* win_line() */
qsort(color_cols, count, sizeof(int), int_cmp);
for (i = 0; i < count; ++i)
/* skip duplicates */
if (j == 0 || wp->w_p_cc_cols[j - 1] != color_cols[i])
wp->w_p_cc_cols[j++] = color_cols[i];
wp->w_p_cc_cols[j] = -1; /* end marker */
}
}
return NULL; /* no error */
}
#endif
/*
* Handle setting 'listchars' or 'fillchars'.
* Returns error message, NULL if it's OK.
*/
static char_u *
set_chars_option(char_u **varp)
{
int round, i, len, entries;
char_u *p, *s;
int c1, c2 = 0;
struct charstab
{
int *cp;
char *name;
};
#if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING)
static struct charstab filltab[] =
{
{&fill_stl, "stl"},
{&fill_stlnc, "stlnc"},
{&fill_vert, "vert"},
{&fill_fold, "fold"},
{&fill_diff, "diff"},
};
#endif
static struct charstab lcstab[] =
{
{&lcs_eol, "eol"},
{&lcs_ext, "extends"},
{&lcs_nbsp, "nbsp"},
{&lcs_prec, "precedes"},
{&lcs_space, "space"},
{&lcs_tab2, "tab"},
{&lcs_trail, "trail"},
#ifdef FEAT_CONCEAL
{&lcs_conceal, "conceal"},
#else
{NULL, "conceal"},
#endif
};
struct charstab *tab;
#if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING)
if (varp == &p_lcs)
#endif
{
tab = lcstab;
entries = sizeof(lcstab) / sizeof(struct charstab);
}
#if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING)
else
{
tab = filltab;
entries = sizeof(filltab) / sizeof(struct charstab);
}
#endif
/* first round: check for valid value, second round: assign values */
for (round = 0; round <= 1; ++round)
{
if (round > 0)
{
/* After checking that the value is valid: set defaults: space for
* 'fillchars', NUL for 'listchars' */
for (i = 0; i < entries; ++i)
if (tab[i].cp != NULL)
*(tab[i].cp) = (varp == &p_lcs ? NUL : ' ');
if (varp == &p_lcs)
lcs_tab1 = NUL;
#if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING)
else
fill_diff = '-';
#endif
}
p = *varp;
while (*p)
{
for (i = 0; i < entries; ++i)
{
len = (int)STRLEN(tab[i].name);
if (STRNCMP(p, tab[i].name, len) == 0
&& p[len] == ':'
&& p[len + 1] != NUL)
{
s = p + len + 1;
#ifdef FEAT_MBYTE
c1 = mb_ptr2char_adv(&s);
if (mb_char2cells(c1) > 1)
continue;
#else
c1 = *s++;
#endif
if (tab[i].cp == &lcs_tab2)
{
if (*s == NUL)
continue;
#ifdef FEAT_MBYTE
c2 = mb_ptr2char_adv(&s);
if (mb_char2cells(c2) > 1)
continue;
#else
c2 = *s++;
#endif
}
if (*s == ',' || *s == NUL)
{
if (round)
{
if (tab[i].cp == &lcs_tab2)
{
lcs_tab1 = c1;
lcs_tab2 = c2;
}
else if (tab[i].cp != NULL)
*(tab[i].cp) = c1;
}
p = s;
break;
}
}
}
if (i == entries)
return e_invarg;
if (*p == ',')
++p;
}
}
return NULL; /* no error */
}
#ifdef FEAT_STL_OPT
/*
* Check validity of options with the 'statusline' format.
* Return error message or NULL.
*/
char_u *
check_stl_option(char_u *s)
{
int itemcnt = 0;
int groupdepth = 0;
static char_u errbuf[80];
while (*s && itemcnt < STL_MAX_ITEM)
{
/* Check for valid keys after % sequences */
while (*s && *s != '%')
s++;
if (!*s)
break;
s++;
if (*s != '%' && *s != ')')
++itemcnt;
if (*s == '%' || *s == STL_TRUNCMARK || *s == STL_MIDDLEMARK)
{
s++;
continue;
}
if (*s == ')')
{
s++;
if (--groupdepth < 0)
break;
continue;
}
if (*s == '-')
s++;
while (VIM_ISDIGIT(*s))
s++;
if (*s == STL_USER_HL)
continue;
if (*s == '.')
{
s++;
while (*s && VIM_ISDIGIT(*s))
s++;
}
if (*s == '(')
{
groupdepth++;
continue;
}
if (vim_strchr(STL_ALL, *s) == NULL)
{
return illegal_char(errbuf, *s);
}
if (*s == '{')
{
s++;
while (*s != '}' && *s)
s++;
if (*s != '}')
return (char_u *)N_("E540: Unclosed expression sequence");
}
}
if (itemcnt >= STL_MAX_ITEM)
return (char_u *)N_("E541: too many items");
if (groupdepth != 0)
return (char_u *)N_("E542: unbalanced groups");
return NULL;
}
#endif
#ifdef FEAT_CLIPBOARD
/*
* Extract the items in the 'clipboard' option and set global values.
*/
static char_u *
check_clipboard_option(void)
{
int new_unnamed = 0;
int new_autoselect_star = FALSE;
int new_autoselect_plus = FALSE;
int new_autoselectml = FALSE;
int new_html = FALSE;
regprog_T *new_exclude_prog = NULL;
char_u *errmsg = NULL;
char_u *p;
for (p = p_cb; *p != NUL; )
{
if (STRNCMP(p, "unnamed", 7) == 0 && (p[7] == ',' || p[7] == NUL))
{
new_unnamed |= CLIP_UNNAMED;
p += 7;
}
else if (STRNCMP(p, "unnamedplus", 11) == 0
&& (p[11] == ',' || p[11] == NUL))
{
new_unnamed |= CLIP_UNNAMED_PLUS;
p += 11;
}
else if (STRNCMP(p, "autoselect", 10) == 0
&& (p[10] == ',' || p[10] == NUL))
{
new_autoselect_star = TRUE;
p += 10;
}
else if (STRNCMP(p, "autoselectplus", 14) == 0
&& (p[14] == ',' || p[14] == NUL))
{
new_autoselect_plus = TRUE;
p += 14;
}
else if (STRNCMP(p, "autoselectml", 12) == 0
&& (p[12] == ',' || p[12] == NUL))
{
new_autoselectml = TRUE;
p += 12;
}
else if (STRNCMP(p, "html", 4) == 0 && (p[4] == ',' || p[4] == NUL))
{
new_html = TRUE;
p += 4;
}
else if (STRNCMP(p, "exclude:", 8) == 0 && new_exclude_prog == NULL)
{
p += 8;
new_exclude_prog = vim_regcomp(p, RE_MAGIC);
if (new_exclude_prog == NULL)
errmsg = e_invarg;
break;
}
else
{
errmsg = e_invarg;
break;
}
if (*p == ',')
++p;
}
if (errmsg == NULL)
{
clip_unnamed = new_unnamed;
clip_autoselect_star = new_autoselect_star;
clip_autoselect_plus = new_autoselect_plus;
clip_autoselectml = new_autoselectml;
clip_html = new_html;
vim_regfree(clip_exclude_prog);
clip_exclude_prog = new_exclude_prog;
#ifdef FEAT_GUI_GTK
if (gui.in_use)
{
gui_gtk_set_selection_targets();
gui_gtk_set_dnd_targets();
}
#endif
}
else
vim_regfree(new_exclude_prog);
return errmsg;
}
#endif
#ifdef FEAT_SPELL
static char_u *
did_set_spell_option(int is_spellfile)
{
char_u *errmsg = NULL;
win_T *wp;
int l;
if (is_spellfile)
{
l = (int)STRLEN(curwin->w_s->b_p_spf);
if (l > 0 && (l < 4
|| STRCMP(curwin->w_s->b_p_spf + l - 4, ".add") != 0))
errmsg = e_invarg;
}
if (errmsg == NULL)
{
FOR_ALL_WINDOWS(wp)
if (wp->w_buffer == curbuf && wp->w_p_spell)
{
errmsg = did_set_spelllang(wp);
# ifdef FEAT_WINDOWS
break;
# endif
}
}
return errmsg;
}
/*
* Set curbuf->b_cap_prog to the regexp program for 'spellcapcheck'.
* Return error message when failed, NULL when OK.
*/
static char_u *
compile_cap_prog(synblock_T *synblock)
{
regprog_T *rp = synblock->b_cap_prog;
char_u *re;
if (*synblock->b_p_spc == NUL)
synblock->b_cap_prog = NULL;
else
{
/* Prepend a ^ so that we only match at one column */
re = concat_str((char_u *)"^", synblock->b_p_spc);
if (re != NULL)
{
synblock->b_cap_prog = vim_regcomp(re, RE_MAGIC);
vim_free(re);
if (synblock->b_cap_prog == NULL)
{
synblock->b_cap_prog = rp; /* restore the previous program */
return e_invarg;
}
}
}
vim_regfree(rp);
return NULL;
}
#endif
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Set the scriptID for an option, taking care of setting the buffer- or
* window-local value.
*/
static void
set_option_scriptID_idx(int opt_idx, int opt_flags, int id)
{
int both = (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0;
int indir = (int)options[opt_idx].indir;
/* Remember where the option was set. For local options need to do that
* in the buffer or window structure. */
if (both || (opt_flags & OPT_GLOBAL) || (indir & (PV_BUF|PV_WIN)) == 0)
options[opt_idx].scriptID = id;
if (both || (opt_flags & OPT_LOCAL))
{
if (indir & PV_BUF)
curbuf->b_p_scriptID[indir & PV_MASK] = id;
else if (indir & PV_WIN)
curwin->w_p_scriptID[indir & PV_MASK] = id;
}
}
#endif
/*
* Set the value of a boolean option, and take care of side effects.
* Returns NULL for success, or an error message for an error.
*/
static char_u *
set_bool_option(
int opt_idx, /* index in options[] table */
char_u *varp, /* pointer to the option variable */
int value, /* new value */
int opt_flags) /* OPT_LOCAL and/or OPT_GLOBAL */
{
int old_value = *(int *)varp;
/* Disallow changing some options from secure mode */
if ((secure
#ifdef HAVE_SANDBOX
|| sandbox != 0
#endif
) && (options[opt_idx].flags & P_SECURE))
return e_secure;
*(int *)varp = value; /* set the new value */
#ifdef FEAT_EVAL
/* Remember where the option was set. */
set_option_scriptID_idx(opt_idx, opt_flags, current_SID);
#endif
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
/* May set global value for local option. */
if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0)
*(int *)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL) = value;
/*
* Handle side effects of changing a bool option.
*/
/* 'compatible' */
if ((int *)varp == &p_cp)
{
compatible_set();
}
#ifdef FEAT_LANGMAP
if ((int *)varp == &p_lrm)
/* 'langremap' -> !'langnoremap' */
p_lnr = !p_lrm;
else if ((int *)varp == &p_lnr)
/* 'langnoremap' -> !'langremap' */
p_lrm = !p_lnr;
#endif
#ifdef FEAT_PERSISTENT_UNDO
/* 'undofile' */
else if ((int *)varp == &curbuf->b_p_udf || (int *)varp == &p_udf)
{
/* Only take action when the option was set. When reset we do not
* delete the undo file, the option may be set again without making
* any changes in between. */
if (curbuf->b_p_udf || p_udf)
{
char_u hash[UNDO_HASH_SIZE];
buf_T *save_curbuf = curbuf;
FOR_ALL_BUFFERS(curbuf)
{
/* When 'undofile' is set globally: for every buffer, otherwise
* only for the current buffer: Try to read in the undofile,
* if one exists, the buffer wasn't changed and the buffer was
* loaded */
if ((curbuf == save_curbuf
|| (opt_flags & OPT_GLOBAL) || opt_flags == 0)
&& !curbufIsChanged() && curbuf->b_ml.ml_mfp != NULL)
{
u_compute_hash(hash);
u_read_undo(NULL, hash, curbuf->b_fname);
}
}
curbuf = save_curbuf;
}
}
#endif
else if ((int *)varp == &curbuf->b_p_ro)
{
/* when 'readonly' is reset globally, also reset readonlymode */
if (!curbuf->b_p_ro && (opt_flags & OPT_LOCAL) == 0)
readonlymode = FALSE;
/* when 'readonly' is set may give W10 again */
if (curbuf->b_p_ro)
curbuf->b_did_warn = FALSE;
#ifdef FEAT_TITLE
redraw_titles();
#endif
}
#ifdef FEAT_GUI
else if ((int *)varp == &p_mh)
{
if (!p_mh)
gui_mch_mousehide(FALSE);
}
#endif
#ifdef FEAT_TITLE
/* when 'modifiable' is changed, redraw the window title */
else if ((int *)varp == &curbuf->b_p_ma)
{
redraw_titles();
}
/* when 'endofline' is changed, redraw the window title */
else if ((int *)varp == &curbuf->b_p_eol)
{
redraw_titles();
}
/* when 'fixeol' is changed, redraw the window title */
else if ((int *)varp == &curbuf->b_p_fixeol)
{
redraw_titles();
}
# ifdef FEAT_MBYTE
/* when 'bomb' is changed, redraw the window title and tab page text */
else if ((int *)varp == &curbuf->b_p_bomb)
{
redraw_titles();
}
# endif
#endif
/* when 'bin' is set also set some other options */
else if ((int *)varp == &curbuf->b_p_bin)
{
set_options_bin(old_value, curbuf->b_p_bin, opt_flags);
#ifdef FEAT_TITLE
redraw_titles();
#endif
}
#ifdef FEAT_AUTOCMD
/* when 'buflisted' changes, trigger autocommands */
else if ((int *)varp == &curbuf->b_p_bl && old_value != curbuf->b_p_bl)
{
apply_autocmds(curbuf->b_p_bl ? EVENT_BUFADD : EVENT_BUFDELETE,
NULL, NULL, TRUE, curbuf);
}
#endif
/* when 'swf' is set, create swapfile, when reset remove swapfile */
else if ((int *)varp == &curbuf->b_p_swf)
{
if (curbuf->b_p_swf && p_uc)
ml_open_file(curbuf); /* create the swap file */
else
/* no need to reset curbuf->b_may_swap, ml_open_file() will check
* buf->b_p_swf */
mf_close_file(curbuf, TRUE); /* remove the swap file */
}
/* when 'terse' is set change 'shortmess' */
else if ((int *)varp == &p_terse)
{
char_u *p;
p = vim_strchr(p_shm, SHM_SEARCH);
/* insert 's' in p_shm */
if (p_terse && p == NULL)
{
STRCPY(IObuff, p_shm);
STRCAT(IObuff, "s");
set_string_option_direct((char_u *)"shm", -1, IObuff, OPT_FREE, 0);
}
/* remove 's' from p_shm */
else if (!p_terse && p != NULL)
STRMOVE(p, p + 1);
}
/* when 'paste' is set or reset also change other options */
else if ((int *)varp == &p_paste)
{
paste_option_changed();
}
/* when 'insertmode' is set from an autocommand need to do work here */
else if ((int *)varp == &p_im)
{
if (p_im)
{
if ((State & INSERT) == 0)
need_start_insertmode = TRUE;
stop_insert_mode = FALSE;
}
/* only reset if it was set previously */
else if (old_value)
{
need_start_insertmode = FALSE;
stop_insert_mode = TRUE;
if (restart_edit != 0 && mode_displayed)
clear_cmdline = TRUE; /* remove "(insert)" */
restart_edit = 0;
}
}
/* when 'ignorecase' is set or reset and 'hlsearch' is set, redraw */
else if ((int *)varp == &p_ic && p_hls)
{
redraw_all_later(SOME_VALID);
}
#ifdef FEAT_SEARCH_EXTRA
/* when 'hlsearch' is set or reset: reset no_hlsearch */
else if ((int *)varp == &p_hls)
{
SET_NO_HLSEARCH(FALSE);
}
#endif
#ifdef FEAT_SCROLLBIND
/* when 'scrollbind' is set: snapshot the current position to avoid a jump
* at the end of normal_cmd() */
else if ((int *)varp == &curwin->w_p_scb)
{
if (curwin->w_p_scb)
{
do_check_scrollbind(FALSE);
curwin->w_scbind_pos = curwin->w_topline;
}
}
#endif
#if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
/* There can be only one window with 'previewwindow' set. */
else if ((int *)varp == &curwin->w_p_pvw)
{
if (curwin->w_p_pvw)
{
win_T *win;
FOR_ALL_WINDOWS(win)
if (win->w_p_pvw && win != curwin)
{
curwin->w_p_pvw = FALSE;
return (char_u *)N_("E590: A preview window already exists");
}
}
}
#endif
/* when 'textmode' is set or reset also change 'fileformat' */
else if ((int *)varp == &curbuf->b_p_tx)
{
set_fileformat(curbuf->b_p_tx ? EOL_DOS : EOL_UNIX, opt_flags);
}
/* when 'textauto' is set or reset also change 'fileformats' */
else if ((int *)varp == &p_ta)
set_string_option_direct((char_u *)"ffs", -1,
p_ta ? (char_u *)DFLT_FFS_VIM : (char_u *)"",
OPT_FREE | opt_flags, 0);
/*
* When 'lisp' option changes include/exclude '-' in
* keyword characters.
*/
#ifdef FEAT_LISP
else if (varp == (char_u *)&(curbuf->b_p_lisp))
{
(void)buf_init_chartab(curbuf, FALSE); /* ignore errors */
}
#endif
#ifdef FEAT_TITLE
/* when 'title' changed, may need to change the title; same for 'icon' */
else if ((int *)varp == &p_title)
{
did_set_title(FALSE);
}
else if ((int *)varp == &p_icon)
{
did_set_title(TRUE);
}
#endif
else if ((int *)varp == &curbuf->b_changed)
{
if (!value)
save_file_ff(curbuf); /* Buffer is unchanged */
#ifdef FEAT_TITLE
redraw_titles();
#endif
#ifdef FEAT_AUTOCMD
modified_was_set = value;
#endif
}
#ifdef BACKSLASH_IN_FILENAME
else if ((int *)varp == &p_ssl)
{
if (p_ssl)
{
psepc = '/';
psepcN = '\\';
pseps[0] = '/';
}
else
{
psepc = '\\';
psepcN = '/';
pseps[0] = '\\';
}
/* need to adjust the file name arguments and buffer names. */
buflist_slash_adjust();
alist_slash_adjust();
# ifdef FEAT_EVAL
scriptnames_slash_adjust();
# endif
}
#endif
/* If 'wrap' is set, set w_leftcol to zero. */
else if ((int *)varp == &curwin->w_p_wrap)
{
if (curwin->w_p_wrap)
curwin->w_leftcol = 0;
}
#ifdef FEAT_WINDOWS
else if ((int *)varp == &p_ea)
{
if (p_ea && !old_value)
win_equal(curwin, FALSE, 0);
}
#endif
else if ((int *)varp == &p_wiv)
{
/*
* When 'weirdinvert' changed, set/reset 't_xs'.
* Then set 'weirdinvert' according to value of 't_xs'.
*/
if (p_wiv && !old_value)
T_XS = (char_u *)"y";
else if (!p_wiv && old_value)
T_XS = empty_option;
p_wiv = (*T_XS != NUL);
}
#ifdef FEAT_BEVAL
else if ((int *)varp == &p_beval)
{
if (p_beval && !old_value)
gui_mch_enable_beval_area(balloonEval);
else if (!p_beval && old_value)
gui_mch_disable_beval_area(balloonEval);
}
#endif
#ifdef FEAT_AUTOCHDIR
else if ((int *)varp == &p_acd)
{
/* Change directories when the 'acd' option is set now. */
DO_AUTOCHDIR
}
#endif
#ifdef FEAT_DIFF
/* 'diff' */
else if ((int *)varp == &curwin->w_p_diff)
{
/* May add or remove the buffer from the list of diff buffers. */
diff_buf_adjust(curwin);
# ifdef FEAT_FOLDING
if (foldmethodIsDiff(curwin))
foldUpdateAll(curwin);
# endif
}
#endif
#ifdef USE_IM_CONTROL
/* 'imdisable' */
else if ((int *)varp == &p_imdisable)
{
/* Only de-activate it here, it will be enabled when changing mode. */
if (p_imdisable)
im_set_active(FALSE);
else if (State & INSERT)
/* When the option is set from an autocommand, it may need to take
* effect right away. */
im_set_active(curbuf->b_p_iminsert == B_IMODE_IM);
}
#endif
#ifdef FEAT_SPELL
/* 'spell' */
else if ((int *)varp == &curwin->w_p_spell)
{
if (curwin->w_p_spell)
{
char_u *errmsg = did_set_spelllang(curwin);
if (errmsg != NULL)
EMSG(_(errmsg));
}
}
#endif
#ifdef FEAT_FKMAP
else if ((int *)varp == &p_altkeymap)
{
if (old_value != p_altkeymap)
{
if (!p_altkeymap)
{
p_hkmap = p_fkmap;
p_fkmap = 0;
}
else
{
p_fkmap = p_hkmap;
p_hkmap = 0;
}
(void)init_chartab();
}
}
/*
* In case some second language keymapping options have changed, check
* and correct the setting in a consistent way.
*/
/*
* If hkmap or fkmap are set, reset Arabic keymapping.
*/
if ((p_hkmap || p_fkmap) && p_altkeymap)
{
p_altkeymap = p_fkmap;
# ifdef FEAT_ARABIC
curwin->w_p_arab = FALSE;
# endif
(void)init_chartab();
}
/*
* If hkmap set, reset Farsi keymapping.
*/
if (p_hkmap && p_altkeymap)
{
p_altkeymap = 0;
p_fkmap = 0;
# ifdef FEAT_ARABIC
curwin->w_p_arab = FALSE;
# endif
(void)init_chartab();
}
/*
* If fkmap set, reset Hebrew keymapping.
*/
if (p_fkmap && !p_altkeymap)
{
p_altkeymap = 1;
p_hkmap = 0;
# ifdef FEAT_ARABIC
curwin->w_p_arab = FALSE;
# endif
(void)init_chartab();
}
#endif
#ifdef FEAT_ARABIC
if ((int *)varp == &curwin->w_p_arab)
{
if (curwin->w_p_arab)
{
/*
* 'arabic' is set, handle various sub-settings.
*/
if (!p_tbidi)
{
/* set rightleft mode */
if (!curwin->w_p_rl)
{
curwin->w_p_rl = TRUE;
changed_window_setting();
}
/* Enable Arabic shaping (major part of what Arabic requires) */
if (!p_arshape)
{
p_arshape = TRUE;
redraw_later_clear();
}
}
/* Arabic requires a utf-8 encoding, inform the user if its not
* set. */
if (STRCMP(p_enc, "utf-8") != 0)
{
static char *w_arabic = N_("W17: Arabic requires UTF-8, do ':set encoding=utf-8'");
msg_source(hl_attr(HLF_W));
MSG_ATTR(_(w_arabic), hl_attr(HLF_W));
#ifdef FEAT_EVAL
set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_arabic), -1);
#endif
}
# ifdef FEAT_MBYTE
/* set 'delcombine' */
p_deco = TRUE;
# endif
# ifdef FEAT_KEYMAP
/* Force-set the necessary keymap for arabic */
set_option_value((char_u *)"keymap", 0L, (char_u *)"arabic",
OPT_LOCAL);
# endif
# ifdef FEAT_FKMAP
p_altkeymap = 0;
p_hkmap = 0;
p_fkmap = 0;
(void)init_chartab();
# endif
}
else
{
/*
* 'arabic' is reset, handle various sub-settings.
*/
if (!p_tbidi)
{
/* reset rightleft mode */
if (curwin->w_p_rl)
{
curwin->w_p_rl = FALSE;
changed_window_setting();
}
/* 'arabicshape' isn't reset, it is a global option and
* another window may still need it "on". */
}
/* 'delcombine' isn't reset, it is a global option and another
* window may still want it "on". */
# ifdef FEAT_KEYMAP
/* Revert to the default keymap */
curbuf->b_p_iminsert = B_IMODE_NONE;
curbuf->b_p_imsearch = B_IMODE_USE_INSERT;
# endif
}
}
#endif
#ifdef FEAT_TERMGUICOLORS
/* 'termguicolors' */
else if ((int *)varp == &p_tgc)
{
# ifdef FEAT_GUI
if (!gui.in_use && !gui.starting)
# endif
highlight_gui_started();
}
#endif
/*
* End of handling side effects for bool options.
*/
/* after handling side effects, call autocommand */
options[opt_idx].flags |= P_WAS_SET;
#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
if (!starting)
{
char_u buf_old[2], buf_new[2], buf_type[7];
vim_snprintf((char *)buf_old, 2, "%d", old_value ? TRUE: FALSE);
vim_snprintf((char *)buf_new, 2, "%d", value ? TRUE: FALSE);
vim_snprintf((char *)buf_type, 7, "%s", (opt_flags & OPT_LOCAL) ? "local" : "global");
set_vim_var_string(VV_OPTION_NEW, buf_new, -1);
set_vim_var_string(VV_OPTION_OLD, buf_old, -1);
set_vim_var_string(VV_OPTION_TYPE, buf_type, -1);
apply_autocmds(EVENT_OPTIONSET, (char_u *) options[opt_idx].fullname, NULL, FALSE, NULL);
reset_v_option_vars();
}
#endif
comp_col(); /* in case 'ruler' or 'showcmd' changed */
if (curwin->w_curswant != MAXCOL
&& (options[opt_idx].flags & (P_CURSWANT | P_RALL)) != 0)
curwin->w_set_curswant = TRUE;
check_redraw(options[opt_idx].flags);
return NULL;
}
/*
* Set the value of a number option, and take care of side effects.
* Returns NULL for success, or an error message for an error.
*/
static char_u *
set_num_option(
int opt_idx, /* index in options[] table */
char_u *varp, /* pointer to the option variable */
long value, /* new value */
char_u *errbuf, /* buffer for error messages */
size_t errbuflen, /* length of "errbuf" */
int opt_flags) /* OPT_LOCAL, OPT_GLOBAL and
OPT_MODELINE */
{
char_u *errmsg = NULL;
long old_value = *(long *)varp;
long old_Rows = Rows; /* remember old Rows */
long old_Columns = Columns; /* remember old Columns */
long *pp = (long *)varp;
/* Disallow changing some options from secure mode. */
if ((secure
#ifdef HAVE_SANDBOX
|| sandbox != 0
#endif
) && (options[opt_idx].flags & P_SECURE))
return e_secure;
*pp = value;
#ifdef FEAT_EVAL
/* Remember where the option was set. */
set_option_scriptID_idx(opt_idx, opt_flags, current_SID);
#endif
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
if (curbuf->b_p_sw < 0)
{
errmsg = e_positive;
curbuf->b_p_sw = curbuf->b_p_ts;
}
/*
* Number options that need some action when changed
*/
#ifdef FEAT_WINDOWS
if (pp == &p_wh || pp == &p_hh)
{
if (p_wh < 1)
{
errmsg = e_positive;
p_wh = 1;
}
if (p_wmh > p_wh)
{
errmsg = e_winheight;
p_wh = p_wmh;
}
if (p_hh < 0)
{
errmsg = e_positive;
p_hh = 0;
}
/* Change window height NOW */
if (lastwin != firstwin)
{
if (pp == &p_wh && curwin->w_height < p_wh)
win_setheight((int)p_wh);
if (pp == &p_hh && curbuf->b_help && curwin->w_height < p_hh)
win_setheight((int)p_hh);
}
}
/* 'winminheight' */
else if (pp == &p_wmh)
{
if (p_wmh < 0)
{
errmsg = e_positive;
p_wmh = 0;
}
if (p_wmh > p_wh)
{
errmsg = e_winheight;
p_wmh = p_wh;
}
win_setminheight();
}
# ifdef FEAT_WINDOWS
else if (pp == &p_wiw)
{
if (p_wiw < 1)
{
errmsg = e_positive;
p_wiw = 1;
}
if (p_wmw > p_wiw)
{
errmsg = e_winwidth;
p_wiw = p_wmw;
}
/* Change window width NOW */
if (lastwin != firstwin && curwin->w_width < p_wiw)
win_setwidth((int)p_wiw);
}
/* 'winminwidth' */
else if (pp == &p_wmw)
{
if (p_wmw < 0)
{
errmsg = e_positive;
p_wmw = 0;
}
if (p_wmw > p_wiw)
{
errmsg = e_winwidth;
p_wmw = p_wiw;
}
win_setminheight();
}
# endif
#endif
#ifdef FEAT_WINDOWS
/* (re)set last window status line */
else if (pp == &p_ls)
{
last_status(FALSE);
}
/* (re)set tab page line */
else if (pp == &p_stal)
{
shell_new_rows(); /* recompute window positions and heights */
}
#endif
#ifdef FEAT_GUI
else if (pp == &p_linespace)
{
/* Recompute gui.char_height and resize the Vim window to keep the
* same number of lines. */
if (gui.in_use && gui_mch_adjust_charheight() == OK)
gui_set_shellsize(FALSE, FALSE, RESIZE_VERT);
}
#endif
#ifdef FEAT_FOLDING
/* 'foldlevel' */
else if (pp == &curwin->w_p_fdl)
{
if (curwin->w_p_fdl < 0)
curwin->w_p_fdl = 0;
newFoldLevel();
}
/* 'foldminlines' */
else if (pp == &curwin->w_p_fml)
{
foldUpdateAll(curwin);
}
/* 'foldnestmax' */
else if (pp == &curwin->w_p_fdn)
{
if (foldmethodIsSyntax(curwin) || foldmethodIsIndent(curwin))
foldUpdateAll(curwin);
}
/* 'foldcolumn' */
else if (pp == &curwin->w_p_fdc)
{
if (curwin->w_p_fdc < 0)
{
errmsg = e_positive;
curwin->w_p_fdc = 0;
}
else if (curwin->w_p_fdc > 12)
{
errmsg = e_invarg;
curwin->w_p_fdc = 12;
}
}
#endif /* FEAT_FOLDING */
#if defined(FEAT_FOLDING) || defined(FEAT_CINDENT)
/* 'shiftwidth' or 'tabstop' */
else if (pp == &curbuf->b_p_sw || pp == &curbuf->b_p_ts)
{
# ifdef FEAT_FOLDING
if (foldmethodIsIndent(curwin))
foldUpdateAll(curwin);
# endif
# ifdef FEAT_CINDENT
/* When 'shiftwidth' changes, or it's zero and 'tabstop' changes:
* parse 'cinoptions'. */
if (pp == &curbuf->b_p_sw || curbuf->b_p_sw == 0)
parse_cino(curbuf);
# endif
}
#endif
#ifdef FEAT_MBYTE
/* 'maxcombine' */
else if (pp == &p_mco)
{
if (p_mco > MAX_MCO)
p_mco = MAX_MCO;
else if (p_mco < 0)
p_mco = 0;
screenclear(); /* will re-allocate the screen */
}
#endif
else if (pp == &curbuf->b_p_iminsert)
{
if (curbuf->b_p_iminsert < 0 || curbuf->b_p_iminsert > B_IMODE_LAST)
{
errmsg = e_invarg;
curbuf->b_p_iminsert = B_IMODE_NONE;
}
p_iminsert = curbuf->b_p_iminsert;
if (termcap_active) /* don't do this in the alternate screen */
showmode();
#if defined(FEAT_WINDOWS) && defined(FEAT_KEYMAP)
/* Show/unshow value of 'keymap' in status lines. */
status_redraw_curbuf();
#endif
}
else if (pp == &p_window)
{
if (p_window < 1)
p_window = 1;
else if (p_window >= Rows)
p_window = Rows - 1;
}
else if (pp == &curbuf->b_p_imsearch)
{
if (curbuf->b_p_imsearch < -1 || curbuf->b_p_imsearch > B_IMODE_LAST)
{
errmsg = e_invarg;
curbuf->b_p_imsearch = B_IMODE_NONE;
}
p_imsearch = curbuf->b_p_imsearch;
}
#ifdef FEAT_TITLE
/* if 'titlelen' has changed, redraw the title */
else if (pp == &p_titlelen)
{
if (p_titlelen < 0)
{
errmsg = e_positive;
p_titlelen = 85;
}
if (starting != NO_SCREEN && old_value != p_titlelen)
need_maketitle = TRUE;
}
#endif
/* if p_ch changed value, change the command line height */
else if (pp == &p_ch)
{
if (p_ch < 1)
{
errmsg = e_positive;
p_ch = 1;
}
if (p_ch > Rows - min_rows() + 1)
p_ch = Rows - min_rows() + 1;
/* Only compute the new window layout when startup has been
* completed. Otherwise the frame sizes may be wrong. */
if (p_ch != old_value && full_screen
#ifdef FEAT_GUI
&& !gui.starting
#endif
)
command_height();
}
/* when 'updatecount' changes from zero to non-zero, open swap files */
else if (pp == &p_uc)
{
if (p_uc < 0)
{
errmsg = e_positive;
p_uc = 100;
}
if (p_uc && !old_value)
ml_open_files();
}
#ifdef FEAT_CONCEAL
else if (pp == &curwin->w_p_cole)
{
if (curwin->w_p_cole < 0)
{
errmsg = e_positive;
curwin->w_p_cole = 0;
}
else if (curwin->w_p_cole > 3)
{
errmsg = e_invarg;
curwin->w_p_cole = 3;
}
}
#endif
#ifdef MZSCHEME_GUI_THREADS
else if (pp == &p_mzq)
mzvim_reset_timer();
#endif
/* sync undo before 'undolevels' changes */
else if (pp == &p_ul)
{
/* use the old value, otherwise u_sync() may not work properly */
p_ul = old_value;
u_sync(TRUE);
p_ul = value;
}
else if (pp == &curbuf->b_p_ul)
{
/* use the old value, otherwise u_sync() may not work properly */
curbuf->b_p_ul = old_value;
u_sync(TRUE);
curbuf->b_p_ul = value;
}
#ifdef FEAT_LINEBREAK
/* 'numberwidth' must be positive */
else if (pp == &curwin->w_p_nuw)
{
if (curwin->w_p_nuw < 1)
{
errmsg = e_positive;
curwin->w_p_nuw = 1;
}
if (curwin->w_p_nuw > 10)
{
errmsg = e_invarg;
curwin->w_p_nuw = 10;
}
curwin->w_nrwidth_line_count = 0; /* trigger a redraw */
}
#endif
else if (pp == &curbuf->b_p_tw)
{
if (curbuf->b_p_tw < 0)
{
errmsg = e_positive;
curbuf->b_p_tw = 0;
}
#ifdef FEAT_SYN_HL
# ifdef FEAT_WINDOWS
{
win_T *wp;
tabpage_T *tp;
FOR_ALL_TAB_WINDOWS(tp, wp)
check_colorcolumn(wp);
}
# else
check_colorcolumn(curwin);
# endif
#endif
}
/*
* Check the bounds for numeric options here
*/
if (Rows < min_rows() && full_screen)
{
if (errbuf != NULL)
{
vim_snprintf((char *)errbuf, errbuflen,
_("E593: Need at least %d lines"), min_rows());
errmsg = errbuf;
}
Rows = min_rows();
}
if (Columns < MIN_COLUMNS && full_screen)
{
if (errbuf != NULL)
{
vim_snprintf((char *)errbuf, errbuflen,
_("E594: Need at least %d columns"), MIN_COLUMNS);
errmsg = errbuf;
}
Columns = MIN_COLUMNS;
}
limit_screen_size();
/*
* If the screen (shell) height has been changed, assume it is the
* physical screenheight.
*/
if (old_Rows != Rows || old_Columns != Columns)
{
/* Changing the screen size is not allowed while updating the screen. */
if (updating_screen)
*pp = old_value;
else if (full_screen
#ifdef FEAT_GUI
&& !gui.starting
#endif
)
set_shellsize((int)Columns, (int)Rows, TRUE);
else
{
/* Postpone the resizing; check the size and cmdline position for
* messages. */
check_shellsize();
if (cmdline_row > Rows - p_ch && Rows > p_ch)
cmdline_row = Rows - p_ch;
}
if (p_window >= Rows || !option_was_set((char_u *)"window"))
p_window = Rows - 1;
}
if (curbuf->b_p_ts <= 0)
{
errmsg = e_positive;
curbuf->b_p_ts = 8;
}
if (p_tm < 0)
{
errmsg = e_positive;
p_tm = 0;
}
if ((curwin->w_p_scr <= 0
|| (curwin->w_p_scr > curwin->w_height
&& curwin->w_height > 0))
&& full_screen)
{
if (pp == &(curwin->w_p_scr))
{
if (curwin->w_p_scr != 0)
errmsg = e_scroll;
win_comp_scroll(curwin);
}
/* If 'scroll' became invalid because of a side effect silently adjust
* it. */
else if (curwin->w_p_scr <= 0)
curwin->w_p_scr = 1;
else /* curwin->w_p_scr > curwin->w_height */
curwin->w_p_scr = curwin->w_height;
}
if (p_hi < 0)
{
errmsg = e_positive;
p_hi = 0;
}
else if (p_hi > 10000)
{
errmsg = e_invarg;
p_hi = 10000;
}
if (p_re < 0 || p_re > 2)
{
errmsg = e_invarg;
p_re = 0;
}
if (p_report < 0)
{
errmsg = e_positive;
p_report = 1;
}
if ((p_sj < -100 || p_sj >= Rows) && full_screen)
{
if (Rows != old_Rows) /* Rows changed, just adjust p_sj */
p_sj = Rows / 2;
else
{
errmsg = e_scroll;
p_sj = 1;
}
}
if (p_so < 0 && full_screen)
{
errmsg = e_scroll;
p_so = 0;
}
if (p_siso < 0 && full_screen)
{
errmsg = e_positive;
p_siso = 0;
}
#ifdef FEAT_CMDWIN
if (p_cwh < 1)
{
errmsg = e_positive;
p_cwh = 1;
}
#endif
if (p_ut < 0)
{
errmsg = e_positive;
p_ut = 2000;
}
if (p_ss < 0)
{
errmsg = e_positive;
p_ss = 0;
}
/* May set global value for local option. */
if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0)
*(long *)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL) = *pp;
options[opt_idx].flags |= P_WAS_SET;
#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
if (!starting && errmsg == NULL)
{
char_u buf_old[11], buf_new[11], buf_type[7];
vim_snprintf((char *)buf_old, 10, "%ld", old_value);
vim_snprintf((char *)buf_new, 10, "%ld", value);
vim_snprintf((char *)buf_type, 7, "%s", (opt_flags & OPT_LOCAL) ? "local" : "global");
set_vim_var_string(VV_OPTION_NEW, buf_new, -1);
set_vim_var_string(VV_OPTION_OLD, buf_old, -1);
set_vim_var_string(VV_OPTION_TYPE, buf_type, -1);
apply_autocmds(EVENT_OPTIONSET, (char_u *) options[opt_idx].fullname, NULL, FALSE, NULL);
reset_v_option_vars();
}
#endif
comp_col(); /* in case 'columns' or 'ls' changed */
if (curwin->w_curswant != MAXCOL
&& (options[opt_idx].flags & (P_CURSWANT | P_RALL)) != 0)
curwin->w_set_curswant = TRUE;
check_redraw(options[opt_idx].flags);
return errmsg;
}
/*
* Called after an option changed: check if something needs to be redrawn.
*/
static void
check_redraw(long_u flags)
{
/* Careful: P_RCLR and P_RALL are a combination of other P_ flags */
int doclear = (flags & P_RCLR) == P_RCLR;
int all = ((flags & P_RALL) == P_RALL || doclear);
#ifdef FEAT_WINDOWS
if ((flags & P_RSTAT) || all) /* mark all status lines dirty */
status_redraw_all();
#endif
if ((flags & P_RBUF) || (flags & P_RWIN) || all)
changed_window_setting();
if (flags & P_RBUF)
redraw_curbuf_later(NOT_VALID);
if (doclear)
redraw_all_later(CLEAR);
else if (all)
redraw_all_later(NOT_VALID);
}
/*
* Find index for option 'arg'.
* Return -1 if not found.
*/
static int
findoption(char_u *arg)
{
int opt_idx;
char *s, *p;
static short quick_tab[27] = {0, 0}; /* quick access table */
int is_term_opt;
/*
* For first call: Initialize the quick-access table.
* It contains the index for the first option that starts with a certain
* letter. There are 26 letters, plus the first "t_" option.
*/
if (quick_tab[1] == 0)
{
p = options[0].fullname;
for (opt_idx = 1; (s = options[opt_idx].fullname) != NULL; opt_idx++)
{
if (s[0] != p[0])
{
if (s[0] == 't' && s[1] == '_')
quick_tab[26] = opt_idx;
else
quick_tab[CharOrdLow(s[0])] = opt_idx;
}
p = s;
}
}
/*
* Check for name starting with an illegal character.
*/
#ifdef EBCDIC
if (!islower(arg[0]))
#else
if (arg[0] < 'a' || arg[0] > 'z')
#endif
return -1;
is_term_opt = (arg[0] == 't' && arg[1] == '_');
if (is_term_opt)
opt_idx = quick_tab[26];
else
opt_idx = quick_tab[CharOrdLow(arg[0])];
for ( ; (s = options[opt_idx].fullname) != NULL; opt_idx++)
{
if (STRCMP(arg, s) == 0) /* match full name */
break;
}
if (s == NULL && !is_term_opt)
{
opt_idx = quick_tab[CharOrdLow(arg[0])];
for ( ; options[opt_idx].fullname != NULL; opt_idx++)
{
s = options[opt_idx].shortname;
if (s != NULL && STRCMP(arg, s) == 0) /* match short name */
break;
s = NULL;
}
}
if (s == NULL)
opt_idx = -1;
return opt_idx;
}
#if defined(FEAT_EVAL) || defined(FEAT_TCL) || defined(FEAT_MZSCHEME)
/*
* Get the value for an option.
*
* Returns:
* Number or Toggle option: 1, *numval gets value.
* String option: 0, *stringval gets allocated string.
* Hidden Number or Toggle option: -1.
* hidden String option: -2.
* unknown option: -3.
*/
int
get_option_value(
char_u *name,
long *numval,
char_u **stringval, /* NULL when only checking existence */
int opt_flags)
{
int opt_idx;
char_u *varp;
opt_idx = findoption(name);
if (opt_idx < 0) /* unknown option */
return -3;
varp = get_varp_scope(&(options[opt_idx]), opt_flags);
if (options[opt_idx].flags & P_STRING)
{
if (varp == NULL) /* hidden option */
return -2;
if (stringval != NULL)
{
#ifdef FEAT_CRYPT
/* never return the value of the crypt key */
if ((char_u **)varp == &curbuf->b_p_key
&& **(char_u **)(varp) != NUL)
*stringval = vim_strsave((char_u *)"*****");
else
#endif
*stringval = vim_strsave(*(char_u **)(varp));
}
return 0;
}
if (varp == NULL) /* hidden option */
return -1;
if (options[opt_idx].flags & P_NUM)
*numval = *(long *)varp;
else
{
/* Special case: 'modified' is b_changed, but we also want to consider
* it set when 'ff' or 'fenc' changed. */
if ((int *)varp == &curbuf->b_changed)
*numval = curbufIsChanged();
else
*numval = (long) *(int *)varp;
}
return 1;
}
#endif
#if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO)
/*
* Returns the option attributes and its value. Unlike the above function it
* will return either global value or local value of the option depending on
* what was requested, but it will never return global value if it was
* requested to return local one and vice versa. Neither it will return
* buffer-local value if it was requested to return window-local one.
*
* Pretends that option is absent if it is not present in the requested scope
* (i.e. has no global, window-local or buffer-local value depending on
* opt_type). Uses
*
* Returned flags:
* 0 hidden or unknown option, also option that does not have requested
* type (see SREQ_* in vim.h)
* see SOPT_* in vim.h for other flags
*
* Possible opt_type values: see SREQ_* in vim.h
*/
int
get_option_value_strict(
char_u *name,
long *numval,
char_u **stringval, /* NULL when only obtaining attributes */
int opt_type,
void *from)
{
int opt_idx;
char_u *varp = NULL;
struct vimoption *p;
int r = 0;
opt_idx = findoption(name);
if (opt_idx < 0)
return 0;
p = &(options[opt_idx]);
/* Hidden option */
if (p->var == NULL)
return 0;
if (p->flags & P_BOOL)
r |= SOPT_BOOL;
else if (p->flags & P_NUM)
r |= SOPT_NUM;
else if (p->flags & P_STRING)
r |= SOPT_STRING;
if (p->indir == PV_NONE)
{
if (opt_type == SREQ_GLOBAL)
r |= SOPT_GLOBAL;
else
return 0; /* Did not request global-only option */
}
else
{
if (p->indir & PV_BOTH)
r |= SOPT_GLOBAL;
else if (opt_type == SREQ_GLOBAL)
return 0; /* Requested global option */
if (p->indir & PV_WIN)
{
if (opt_type == SREQ_BUF)
return 0; /* Did not request window-local option */
else
r |= SOPT_WIN;
}
else if (p->indir & PV_BUF)
{
if (opt_type == SREQ_WIN)
return 0; /* Did not request buffer-local option */
else
r |= SOPT_BUF;
}
}
if (stringval == NULL)
return r;
if (opt_type == SREQ_GLOBAL)
varp = p->var;
else
{
if (opt_type == SREQ_BUF)
{
/* Special case: 'modified' is b_changed, but we also want to
* consider it set when 'ff' or 'fenc' changed. */
if (p->indir == PV_MOD)
{
*numval = bufIsChanged((buf_T *) from);
varp = NULL;
}
#ifdef FEAT_CRYPT
else if (p->indir == PV_KEY)
{
/* never return the value of the crypt key */
*stringval = NULL;
varp = NULL;
}
#endif
else
{
aco_save_T aco;
aucmd_prepbuf(&aco, (buf_T *) from);
varp = get_varp(p);
aucmd_restbuf(&aco);
}
}
else if (opt_type == SREQ_WIN)
{
win_T *save_curwin;
save_curwin = curwin;
curwin = (win_T *) from;
curbuf = curwin->w_buffer;
varp = get_varp(p);
curwin = save_curwin;
curbuf = curwin->w_buffer;
}
if (varp == p->var)
return (r | SOPT_UNSET);
}
if (varp != NULL)
{
if (p->flags & P_STRING)
*stringval = vim_strsave(*(char_u **)(varp));
else if (p->flags & P_NUM)
*numval = *(long *) varp;
else
*numval = *(int *)varp;
}
return r;
}
/*
* Iterate over options. First argument is a pointer to a pointer to a
* structure inside options[] array, second is option type like in the above
* function.
*
* If first argument points to NULL it is assumed that iteration just started
* and caller needs the very first value.
* If first argument points to the end marker function returns NULL and sets
* first argument to NULL.
*
* Returns full option name for current option on each call.
*/
char_u *
option_iter_next(void **option, int opt_type)
{
struct vimoption *ret = NULL;
do
{
if (*option == NULL)
*option = (void *) options;
else if (((struct vimoption *) (*option))->fullname == NULL)
{
*option = NULL;
return NULL;
}
else
*option = (void *) (((struct vimoption *) (*option)) + 1);
ret = ((struct vimoption *) (*option));
/* Hidden option */
if (ret->var == NULL)
{
ret = NULL;
continue;
}
switch (opt_type)
{
case SREQ_GLOBAL:
if (!(ret->indir == PV_NONE || ret->indir & PV_BOTH))
ret = NULL;
break;
case SREQ_BUF:
if (!(ret->indir & PV_BUF))
ret = NULL;
break;
case SREQ_WIN:
if (!(ret->indir & PV_WIN))
ret = NULL;
break;
default:
EMSG2(_(e_intern2), "option_iter_next()");
return NULL;
}
}
while (ret == NULL);
return (char_u *)ret->fullname;
}
#endif
/*
* Set the value of option "name".
* Use "string" for string options, use "number" for other options.
*
* Returns NULL on success or error message on error.
*/
char_u *
set_option_value(
char_u *name,
long number,
char_u *string,
int opt_flags) /* OPT_LOCAL or 0 (both) */
{
int opt_idx;
char_u *varp;
long_u flags;
opt_idx = findoption(name);
if (opt_idx < 0)
EMSG2(_("E355: Unknown option: %s"), name);
else
{
flags = options[opt_idx].flags;
#ifdef HAVE_SANDBOX
/* Disallow changing some options in the sandbox */
if (sandbox > 0 && (flags & P_SECURE))
{
EMSG(_(e_sandbox));
return NULL;
}
#endif
if (flags & P_STRING)
return set_string_option(opt_idx, string, opt_flags);
else
{
varp = get_varp_scope(&(options[opt_idx]), opt_flags);
if (varp != NULL) /* hidden option is not changed */
{
if (number == 0 && string != NULL)
{
int idx;
/* Either we are given a string or we are setting option
* to zero. */
for (idx = 0; string[idx] == '0'; ++idx)
;
if (string[idx] != NUL || idx == 0)
{
/* There's another character after zeros or the string
* is empty. In both cases, we are trying to set a
* num option using a string. */
EMSG3(_("E521: Number required: &%s = '%s'"),
name, string);
return NULL; /* do nothing as we hit an error */
}
}
if (flags & P_NUM)
return set_num_option(opt_idx, varp, number,
NULL, 0, opt_flags);
else
return set_bool_option(opt_idx, varp, (int)number,
opt_flags);
}
}
}
return NULL;
}
/*
* Get the terminal code for a terminal option.
* Returns NULL when not found.
*/
char_u *
get_term_code(char_u *tname)
{
int opt_idx;
char_u *varp;
if (tname[0] != 't' || tname[1] != '_' ||
tname[2] == NUL || tname[3] == NUL)
return NULL;
if ((opt_idx = findoption(tname)) >= 0)
{
varp = get_varp(&(options[opt_idx]));
if (varp != NULL)
varp = *(char_u **)(varp);
return varp;
}
return find_termcode(tname + 2);
}
char_u *
get_highlight_default(void)
{
int i;
i = findoption((char_u *)"hl");
if (i >= 0)
return options[i].def_val[VI_DEFAULT];
return (char_u *)NULL;
}
#if defined(FEAT_MBYTE) || defined(PROTO)
char_u *
get_encoding_default(void)
{
int i;
i = findoption((char_u *)"enc");
if (i >= 0)
return options[i].def_val[VI_DEFAULT];
return (char_u *)NULL;
}
#endif
/*
* Translate a string like "t_xx", "<t_xx>" or "<S-Tab>" to a key number.
*/
static int
find_key_option(char_u *arg)
{
int key;
int modifiers;
/*
* Don't use get_special_key_code() for t_xx, we don't want it to call
* add_termcap_entry().
*/
if (arg[0] == 't' && arg[1] == '_' && arg[2] && arg[3])
key = TERMCAP2KEY(arg[2], arg[3]);
else
{
--arg; /* put arg at the '<' */
modifiers = 0;
key = find_special_key(&arg, &modifiers, TRUE, TRUE, FALSE);
if (modifiers) /* can't handle modifiers here */
key = 0;
}
return key;
}
/*
* if 'all' == 0: show changed options
* if 'all' == 1: show all normal options
* if 'all' == 2: show all terminal options
*/
static void
showoptions(
int all,
int opt_flags) /* OPT_LOCAL and/or OPT_GLOBAL */
{
struct vimoption *p;
int col;
int isterm;
char_u *varp;
struct vimoption **items;
int item_count;
int run;
int row, rows;
int cols;
int i;
int len;
#define INC 20
#define GAP 3
items = (struct vimoption **)alloc((unsigned)(sizeof(struct vimoption *) *
PARAM_COUNT));
if (items == NULL)
return;
/* Highlight title */
if (all == 2)
MSG_PUTS_TITLE(_("\n--- Terminal codes ---"));
else if (opt_flags & OPT_GLOBAL)
MSG_PUTS_TITLE(_("\n--- Global option values ---"));
else if (opt_flags & OPT_LOCAL)
MSG_PUTS_TITLE(_("\n--- Local option values ---"));
else
MSG_PUTS_TITLE(_("\n--- Options ---"));
/*
* do the loop two times:
* 1. display the short items
* 2. display the long items (only strings and numbers)
*/
for (run = 1; run <= 2 && !got_int; ++run)
{
/*
* collect the items in items[]
*/
item_count = 0;
for (p = &options[0]; p->fullname != NULL; p++)
{
varp = NULL;
isterm = istermoption(p);
if (opt_flags != 0)
{
if (p->indir != PV_NONE && !isterm)
varp = get_varp_scope(p, opt_flags);
}
else
varp = get_varp(p);
if (varp != NULL
&& ((all == 2 && isterm)
|| (all == 1 && !isterm)
|| (all == 0 && !optval_default(p, varp))))
{
if (p->flags & P_BOOL)
len = 1; /* a toggle option fits always */
else
{
option_value2string(p, opt_flags);
len = (int)STRLEN(p->fullname) + vim_strsize(NameBuff) + 1;
}
if ((len <= INC - GAP && run == 1) ||
(len > INC - GAP && run == 2))
items[item_count++] = p;
}
}
/*
* display the items
*/
if (run == 1)
{
cols = (Columns + GAP - 3) / INC;
if (cols == 0)
cols = 1;
rows = (item_count + cols - 1) / cols;
}
else /* run == 2 */
rows = item_count;
for (row = 0; row < rows && !got_int; ++row)
{
msg_putchar('\n'); /* go to next line */
if (got_int) /* 'q' typed in more */
break;
col = 0;
for (i = row; i < item_count; i += rows)
{
msg_col = col; /* make columns */
showoneopt(items[i], opt_flags);
col += INC;
}
out_flush();
ui_breakcheck();
}
}
vim_free(items);
}
/*
* Return TRUE if option "p" has its default value.
*/
static int
optval_default(struct vimoption *p, char_u *varp)
{
int dvi;
if (varp == NULL)
return TRUE; /* hidden option is always at default */
dvi = ((p->flags & P_VI_DEF) || p_cp) ? VI_DEFAULT : VIM_DEFAULT;
if (p->flags & P_NUM)
return (*(long *)varp == (long)(long_i)p->def_val[dvi]);
if (p->flags & P_BOOL)
/* the cast to long is required for Manx C, long_i is
* needed for MSVC */
return (*(int *)varp == (int)(long)(long_i)p->def_val[dvi]);
/* P_STRING */
return (STRCMP(*(char_u **)varp, p->def_val[dvi]) == 0);
}
/*
* showoneopt: show the value of one option
* must not be called with a hidden option!
*/
static void
showoneopt(
struct vimoption *p,
int opt_flags) /* OPT_LOCAL or OPT_GLOBAL */
{
char_u *varp;
int save_silent = silent_mode;
silent_mode = FALSE;
info_message = TRUE; /* use mch_msg(), not mch_errmsg() */
varp = get_varp_scope(p, opt_flags);
/* for 'modified' we also need to check if 'ff' or 'fenc' changed. */
if ((p->flags & P_BOOL) && ((int *)varp == &curbuf->b_changed
? !curbufIsChanged() : !*(int *)varp))
MSG_PUTS("no");
else if ((p->flags & P_BOOL) && *(int *)varp < 0)
MSG_PUTS("--");
else
MSG_PUTS(" ");
MSG_PUTS(p->fullname);
if (!(p->flags & P_BOOL))
{
msg_putchar('=');
/* put value string in NameBuff */
option_value2string(p, opt_flags);
msg_outtrans(NameBuff);
}
silent_mode = save_silent;
info_message = FALSE;
}
/*
* Write modified options as ":set" commands to a file.
*
* There are three values for "opt_flags":
* OPT_GLOBAL: Write global option values and fresh values of
* buffer-local options (used for start of a session
* file).
* OPT_GLOBAL + OPT_LOCAL: Idem, add fresh values of window-local options for
* curwin (used for a vimrc file).
* OPT_LOCAL: Write buffer-local option values for curbuf, fresh
* and local values for window-local options of
* curwin. Local values are also written when at the
* default value, because a modeline or autocommand
* may have set them when doing ":edit file" and the
* user has set them back at the default or fresh
* value.
* When "local_only" is TRUE, don't write fresh
* values, only local values (for ":mkview").
* (fresh value = value used for a new buffer or window for a local option).
*
* Return FAIL on error, OK otherwise.
*/
int
makeset(FILE *fd, int opt_flags, int local_only)
{
struct vimoption *p;
char_u *varp; /* currently used value */
char_u *varp_fresh; /* local value */
char_u *varp_local = NULL; /* fresh value */
char *cmd;
int round;
int pri;
/*
* The options that don't have a default (terminal name, columns, lines)
* are never written. Terminal options are also not written.
* Do the loop over "options[]" twice: once for options with the
* P_PRI_MKRC flag and once without.
*/
for (pri = 1; pri >= 0; --pri)
{
for (p = &options[0]; !istermoption(p); p++)
if (!(p->flags & P_NO_MKRC)
&& !istermoption(p)
&& ((pri == 1) == ((p->flags & P_PRI_MKRC) != 0)))
{
/* skip global option when only doing locals */
if (p->indir == PV_NONE && !(opt_flags & OPT_GLOBAL))
continue;
/* Do not store options like 'bufhidden' and 'syntax' in a vimrc
* file, they are always buffer-specific. */
if ((opt_flags & OPT_GLOBAL) && (p->flags & P_NOGLOB))
continue;
/* Global values are only written when not at the default value. */
varp = get_varp_scope(p, opt_flags);
if ((opt_flags & OPT_GLOBAL) && optval_default(p, varp))
continue;
round = 2;
if (p->indir != PV_NONE)
{
if (p->var == VAR_WIN)
{
/* skip window-local option when only doing globals */
if (!(opt_flags & OPT_LOCAL))
continue;
/* When fresh value of window-local option is not at the
* default, need to write it too. */
if (!(opt_flags & OPT_GLOBAL) && !local_only)
{
varp_fresh = get_varp_scope(p, OPT_GLOBAL);
if (!optval_default(p, varp_fresh))
{
round = 1;
varp_local = varp;
varp = varp_fresh;
}
}
}
}
/* Round 1: fresh value for window-local options.
* Round 2: other values */
for ( ; round <= 2; varp = varp_local, ++round)
{
if (round == 1 || (opt_flags & OPT_GLOBAL))
cmd = "set";
else
cmd = "setlocal";
if (p->flags & P_BOOL)
{
if (put_setbool(fd, cmd, p->fullname, *(int *)varp) == FAIL)
return FAIL;
}
else if (p->flags & P_NUM)
{
if (put_setnum(fd, cmd, p->fullname, (long *)varp) == FAIL)
return FAIL;
}
else /* P_STRING */
{
#if defined(FEAT_SYN_HL) || defined(FEAT_AUTOCMD)
int do_endif = FALSE;
/* Don't set 'syntax' and 'filetype' again if the value is
* already right, avoids reloading the syntax file. */
if (
# if defined(FEAT_SYN_HL)
p->indir == PV_SYN
# if defined(FEAT_AUTOCMD)
||
# endif
# endif
# if defined(FEAT_AUTOCMD)
p->indir == PV_FT
# endif
)
{
if (fprintf(fd, "if &%s != '%s'", p->fullname,
*(char_u **)(varp)) < 0
|| put_eol(fd) < 0)
return FAIL;
do_endif = TRUE;
}
#endif
if (put_setstring(fd, cmd, p->fullname, (char_u **)varp,
(p->flags & P_EXPAND) != 0) == FAIL)
return FAIL;
#if defined(FEAT_SYN_HL) || defined(FEAT_AUTOCMD)
if (do_endif)
{
if (put_line(fd, "endif") == FAIL)
return FAIL;
}
#endif
}
}
}
}
return OK;
}
#if defined(FEAT_FOLDING) || defined(PROTO)
/*
* Generate set commands for the local fold options only. Used when
* 'sessionoptions' or 'viewoptions' contains "folds" but not "options".
*/
int
makefoldset(FILE *fd)
{
if (put_setstring(fd, "setlocal", "fdm", &curwin->w_p_fdm, FALSE) == FAIL
# ifdef FEAT_EVAL
|| put_setstring(fd, "setlocal", "fde", &curwin->w_p_fde, FALSE)
== FAIL
# endif
|| put_setstring(fd, "setlocal", "fmr", &curwin->w_p_fmr, FALSE)
== FAIL
|| put_setstring(fd, "setlocal", "fdi", &curwin->w_p_fdi, FALSE)
== FAIL
|| put_setnum(fd, "setlocal", "fdl", &curwin->w_p_fdl) == FAIL
|| put_setnum(fd, "setlocal", "fml", &curwin->w_p_fml) == FAIL
|| put_setnum(fd, "setlocal", "fdn", &curwin->w_p_fdn) == FAIL
|| put_setbool(fd, "setlocal", "fen", curwin->w_p_fen) == FAIL
)
return FAIL;
return OK;
}
#endif
static int
put_setstring(
FILE *fd,
char *cmd,
char *name,
char_u **valuep,
int expand)
{
char_u *s;
char_u *buf;
if (fprintf(fd, "%s %s=", cmd, name) < 0)
return FAIL;
if (*valuep != NULL)
{
/* Output 'pastetoggle' as key names. For other
* options some characters have to be escaped with
* CTRL-V or backslash */
if (valuep == &p_pt)
{
s = *valuep;
while (*s != NUL)
if (put_escstr(fd, str2special(&s, FALSE), 2) == FAIL)
return FAIL;
}
else if (expand)
{
buf = alloc(MAXPATHL);
if (buf == NULL)
return FAIL;
home_replace(NULL, *valuep, buf, MAXPATHL, FALSE);
if (put_escstr(fd, buf, 2) == FAIL)
{
vim_free(buf);
return FAIL;
}
vim_free(buf);
}
else if (put_escstr(fd, *valuep, 2) == FAIL)
return FAIL;
}
if (put_eol(fd) < 0)
return FAIL;
return OK;
}
static int
put_setnum(
FILE *fd,
char *cmd,
char *name,
long *valuep)
{
long wc;
if (fprintf(fd, "%s %s=", cmd, name) < 0)
return FAIL;
if (wc_use_keyname((char_u *)valuep, &wc))
{
/* print 'wildchar' and 'wildcharm' as a key name */
if (fputs((char *)get_special_key_name((int)wc, 0), fd) < 0)
return FAIL;
}
else if (fprintf(fd, "%ld", *valuep) < 0)
return FAIL;
if (put_eol(fd) < 0)
return FAIL;
return OK;
}
static int
put_setbool(
FILE *fd,
char *cmd,
char *name,
int value)
{
if (value < 0) /* global/local option using global value */
return OK;
if (fprintf(fd, "%s %s%s", cmd, value ? "" : "no", name) < 0
|| put_eol(fd) < 0)
return FAIL;
return OK;
}
/*
* Clear all the terminal options.
* If the option has been allocated, free the memory.
* Terminal options are never hidden or indirect.
*/
void
clear_termoptions(void)
{
/*
* Reset a few things before clearing the old options. This may cause
* outputting a few things that the terminal doesn't understand, but the
* screen will be cleared later, so this is OK.
*/
#ifdef FEAT_MOUSE_TTY
mch_setmouse(FALSE); /* switch mouse off */
#endif
#ifdef FEAT_TITLE
mch_restore_title(3); /* restore window titles */
#endif
#if defined(FEAT_XCLIPBOARD) && defined(FEAT_GUI)
/* When starting the GUI close the display opened for the clipboard.
* After restoring the title, because that will need the display. */
if (gui.starting)
clear_xterm_clip();
#endif
stoptermcap(); /* stop termcap mode */
free_termoptions();
}
void
free_termoptions(void)
{
struct vimoption *p;
for (p = &options[0]; p->fullname != NULL; p++)
if (istermoption(p))
{
if (p->flags & P_ALLOCED)
free_string_option(*(char_u **)(p->var));
if (p->flags & P_DEF_ALLOCED)
free_string_option(p->def_val[VI_DEFAULT]);
*(char_u **)(p->var) = empty_option;
p->def_val[VI_DEFAULT] = empty_option;
p->flags &= ~(P_ALLOCED|P_DEF_ALLOCED);
}
clear_termcodes();
}
/*
* Free the string for one term option, if it was allocated.
* Set the string to empty_option and clear allocated flag.
* "var" points to the option value.
*/
void
free_one_termoption(char_u *var)
{
struct vimoption *p;
for (p = &options[0]; p->fullname != NULL; p++)
if (p->var == var)
{
if (p->flags & P_ALLOCED)
free_string_option(*(char_u **)(p->var));
*(char_u **)(p->var) = empty_option;
p->flags &= ~P_ALLOCED;
break;
}
}
/*
* Set the terminal option defaults to the current value.
* Used after setting the terminal name.
*/
void
set_term_defaults(void)
{
struct vimoption *p;
for (p = &options[0]; p->fullname != NULL; p++)
{
if (istermoption(p) && p->def_val[VI_DEFAULT] != *(char_u **)(p->var))
{
if (p->flags & P_DEF_ALLOCED)
{
free_string_option(p->def_val[VI_DEFAULT]);
p->flags &= ~P_DEF_ALLOCED;
}
p->def_val[VI_DEFAULT] = *(char_u **)(p->var);
if (p->flags & P_ALLOCED)
{
p->flags |= P_DEF_ALLOCED;
p->flags &= ~P_ALLOCED; /* don't free the value now */
}
}
}
}
/*
* return TRUE if 'p' starts with 't_'
*/
static int
istermoption(struct vimoption *p)
{
return (p->fullname[0] == 't' && p->fullname[1] == '_');
}
/*
* Compute columns for ruler and shown command. 'sc_col' is also used to
* decide what the maximum length of a message on the status line can be.
* If there is a status line for the last window, 'sc_col' is independent
* of 'ru_col'.
*/
#define COL_RULER 17 /* columns needed by standard ruler */
void
comp_col(void)
{
#if defined(FEAT_CMDL_INFO) && defined(FEAT_WINDOWS)
int last_has_status = (p_ls == 2 || (p_ls == 1 && firstwin != lastwin));
sc_col = 0;
ru_col = 0;
if (p_ru)
{
#ifdef FEAT_STL_OPT
ru_col = (ru_wid ? ru_wid : COL_RULER) + 1;
#else
ru_col = COL_RULER + 1;
#endif
/* no last status line, adjust sc_col */
if (!last_has_status)
sc_col = ru_col;
}
if (p_sc)
{
sc_col += SHOWCMD_COLS;
if (!p_ru || last_has_status) /* no need for separating space */
++sc_col;
}
sc_col = Columns - sc_col;
ru_col = Columns - ru_col;
if (sc_col <= 0) /* screen too narrow, will become a mess */
sc_col = 1;
if (ru_col <= 0)
ru_col = 1;
#else
sc_col = Columns;
ru_col = Columns;
#endif
}
/*
* Unset local option value, similar to ":set opt<".
*/
void
unset_global_local_option(char_u *name, void *from)
{
struct vimoption *p;
int opt_idx;
buf_T *buf = (buf_T *)from;
opt_idx = findoption(name);
if (opt_idx < 0)
return;
p = &(options[opt_idx]);
switch ((int)p->indir)
{
/* global option with local value: use local value if it's been set */
case PV_EP:
clear_string_option(&buf->b_p_ep);
break;
case PV_KP:
clear_string_option(&buf->b_p_kp);
break;
case PV_PATH:
clear_string_option(&buf->b_p_path);
break;
case PV_AR:
buf->b_p_ar = -1;
break;
case PV_BKC:
clear_string_option(&buf->b_p_bkc);
buf->b_bkc_flags = 0;
break;
case PV_TAGS:
clear_string_option(&buf->b_p_tags);
break;
case PV_TC:
clear_string_option(&buf->b_p_tc);
buf->b_tc_flags = 0;
break;
#ifdef FEAT_FIND_ID
case PV_DEF:
clear_string_option(&buf->b_p_def);
break;
case PV_INC:
clear_string_option(&buf->b_p_inc);
break;
#endif
#ifdef FEAT_INS_EXPAND
case PV_DICT:
clear_string_option(&buf->b_p_dict);
break;
case PV_TSR:
clear_string_option(&buf->b_p_tsr);
break;
#endif
#ifdef FEAT_QUICKFIX
case PV_EFM:
clear_string_option(&buf->b_p_efm);
break;
case PV_GP:
clear_string_option(&buf->b_p_gp);
break;
case PV_MP:
clear_string_option(&buf->b_p_mp);
break;
#endif
#if defined(FEAT_BEVAL) && defined(FEAT_EVAL)
case PV_BEXPR:
clear_string_option(&buf->b_p_bexpr);
break;
#endif
#if defined(FEAT_CRYPT)
case PV_CM:
clear_string_option(&buf->b_p_cm);
break;
#endif
#ifdef FEAT_STL_OPT
case PV_STL:
clear_string_option(&((win_T *)from)->w_p_stl);
break;
#endif
case PV_UL:
buf->b_p_ul = NO_LOCAL_UNDOLEVEL;
break;
#ifdef FEAT_LISP
case PV_LW:
clear_string_option(&buf->b_p_lw);
break;
#endif
}
}
/*
* Get pointer to option variable, depending on local or global scope.
*/
static char_u *
get_varp_scope(struct vimoption *p, int opt_flags)
{
if ((opt_flags & OPT_GLOBAL) && p->indir != PV_NONE)
{
if (p->var == VAR_WIN)
return (char_u *)GLOBAL_WO(get_varp(p));
return p->var;
}
if ((opt_flags & OPT_LOCAL) && ((int)p->indir & PV_BOTH))
{
switch ((int)p->indir)
{
#ifdef FEAT_QUICKFIX
case PV_EFM: return (char_u *)&(curbuf->b_p_efm);
case PV_GP: return (char_u *)&(curbuf->b_p_gp);
case PV_MP: return (char_u *)&(curbuf->b_p_mp);
#endif
case PV_EP: return (char_u *)&(curbuf->b_p_ep);
case PV_KP: return (char_u *)&(curbuf->b_p_kp);
case PV_PATH: return (char_u *)&(curbuf->b_p_path);
case PV_AR: return (char_u *)&(curbuf->b_p_ar);
case PV_TAGS: return (char_u *)&(curbuf->b_p_tags);
case PV_TC: return (char_u *)&(curbuf->b_p_tc);
#ifdef FEAT_FIND_ID
case PV_DEF: return (char_u *)&(curbuf->b_p_def);
case PV_INC: return (char_u *)&(curbuf->b_p_inc);
#endif
#ifdef FEAT_INS_EXPAND
case PV_DICT: return (char_u *)&(curbuf->b_p_dict);
case PV_TSR: return (char_u *)&(curbuf->b_p_tsr);
#endif
#if defined(FEAT_BEVAL) && defined(FEAT_EVAL)
case PV_BEXPR: return (char_u *)&(curbuf->b_p_bexpr);
#endif
#if defined(FEAT_CRYPT)
case PV_CM: return (char_u *)&(curbuf->b_p_cm);
#endif
#ifdef FEAT_STL_OPT
case PV_STL: return (char_u *)&(curwin->w_p_stl);
#endif
case PV_UL: return (char_u *)&(curbuf->b_p_ul);
#ifdef FEAT_LISP
case PV_LW: return (char_u *)&(curbuf->b_p_lw);
#endif
case PV_BKC: return (char_u *)&(curbuf->b_p_bkc);
}
return NULL; /* "cannot happen" */
}
return get_varp(p);
}
/*
* Get pointer to option variable.
*/
static char_u *
get_varp(struct vimoption *p)
{
/* hidden option, always return NULL */
if (p->var == NULL)
return NULL;
switch ((int)p->indir)
{
case PV_NONE: return p->var;
/* global option with local value: use local value if it's been set */
case PV_EP: return *curbuf->b_p_ep != NUL
? (char_u *)&curbuf->b_p_ep : p->var;
case PV_KP: return *curbuf->b_p_kp != NUL
? (char_u *)&curbuf->b_p_kp : p->var;
case PV_PATH: return *curbuf->b_p_path != NUL
? (char_u *)&(curbuf->b_p_path) : p->var;
case PV_AR: return curbuf->b_p_ar >= 0
? (char_u *)&(curbuf->b_p_ar) : p->var;
case PV_TAGS: return *curbuf->b_p_tags != NUL
? (char_u *)&(curbuf->b_p_tags) : p->var;
case PV_TC: return *curbuf->b_p_tc != NUL
? (char_u *)&(curbuf->b_p_tc) : p->var;
case PV_BKC: return *curbuf->b_p_bkc != NUL
? (char_u *)&(curbuf->b_p_bkc) : p->var;
#ifdef FEAT_FIND_ID
case PV_DEF: return *curbuf->b_p_def != NUL
? (char_u *)&(curbuf->b_p_def) : p->var;
case PV_INC: return *curbuf->b_p_inc != NUL
? (char_u *)&(curbuf->b_p_inc) : p->var;
#endif
#ifdef FEAT_INS_EXPAND
case PV_DICT: return *curbuf->b_p_dict != NUL
? (char_u *)&(curbuf->b_p_dict) : p->var;
case PV_TSR: return *curbuf->b_p_tsr != NUL
? (char_u *)&(curbuf->b_p_tsr) : p->var;
#endif
#ifdef FEAT_QUICKFIX
case PV_EFM: return *curbuf->b_p_efm != NUL
? (char_u *)&(curbuf->b_p_efm) : p->var;
case PV_GP: return *curbuf->b_p_gp != NUL
? (char_u *)&(curbuf->b_p_gp) : p->var;
case PV_MP: return *curbuf->b_p_mp != NUL
? (char_u *)&(curbuf->b_p_mp) : p->var;
#endif
#if defined(FEAT_BEVAL) && defined(FEAT_EVAL)
case PV_BEXPR: return *curbuf->b_p_bexpr != NUL
? (char_u *)&(curbuf->b_p_bexpr) : p->var;
#endif
#if defined(FEAT_CRYPT)
case PV_CM: return *curbuf->b_p_cm != NUL
? (char_u *)&(curbuf->b_p_cm) : p->var;
#endif
#ifdef FEAT_STL_OPT
case PV_STL: return *curwin->w_p_stl != NUL
? (char_u *)&(curwin->w_p_stl) : p->var;
#endif
case PV_UL: return curbuf->b_p_ul != NO_LOCAL_UNDOLEVEL
? (char_u *)&(curbuf->b_p_ul) : p->var;
#ifdef FEAT_LISP
case PV_LW: return *curbuf->b_p_lw != NUL
? (char_u *)&(curbuf->b_p_lw) : p->var;
#endif
#ifdef FEAT_ARABIC
case PV_ARAB: return (char_u *)&(curwin->w_p_arab);
#endif
case PV_LIST: return (char_u *)&(curwin->w_p_list);
#ifdef FEAT_SPELL
case PV_SPELL: return (char_u *)&(curwin->w_p_spell);
#endif
#ifdef FEAT_SYN_HL
case PV_CUC: return (char_u *)&(curwin->w_p_cuc);
case PV_CUL: return (char_u *)&(curwin->w_p_cul);
case PV_CC: return (char_u *)&(curwin->w_p_cc);
#endif
#ifdef FEAT_DIFF
case PV_DIFF: return (char_u *)&(curwin->w_p_diff);
#endif
#ifdef FEAT_FOLDING
case PV_FDC: return (char_u *)&(curwin->w_p_fdc);
case PV_FEN: return (char_u *)&(curwin->w_p_fen);
case PV_FDI: return (char_u *)&(curwin->w_p_fdi);
case PV_FDL: return (char_u *)&(curwin->w_p_fdl);
case PV_FDM: return (char_u *)&(curwin->w_p_fdm);
case PV_FML: return (char_u *)&(curwin->w_p_fml);
case PV_FDN: return (char_u *)&(curwin->w_p_fdn);
# ifdef FEAT_EVAL
case PV_FDE: return (char_u *)&(curwin->w_p_fde);
case PV_FDT: return (char_u *)&(curwin->w_p_fdt);
# endif
case PV_FMR: return (char_u *)&(curwin->w_p_fmr);
#endif
case PV_NU: return (char_u *)&(curwin->w_p_nu);
case PV_RNU: return (char_u *)&(curwin->w_p_rnu);
#ifdef FEAT_LINEBREAK
case PV_NUW: return (char_u *)&(curwin->w_p_nuw);
#endif
#ifdef FEAT_WINDOWS
case PV_WFH: return (char_u *)&(curwin->w_p_wfh);
case PV_WFW: return (char_u *)&(curwin->w_p_wfw);
#endif
#if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
case PV_PVW: return (char_u *)&(curwin->w_p_pvw);
#endif
#ifdef FEAT_RIGHTLEFT
case PV_RL: return (char_u *)&(curwin->w_p_rl);
case PV_RLC: return (char_u *)&(curwin->w_p_rlc);
#endif
case PV_SCROLL: return (char_u *)&(curwin->w_p_scr);
case PV_WRAP: return (char_u *)&(curwin->w_p_wrap);
#ifdef FEAT_LINEBREAK
case PV_LBR: return (char_u *)&(curwin->w_p_lbr);
case PV_BRI: return (char_u *)&(curwin->w_p_bri);
case PV_BRIOPT: return (char_u *)&(curwin->w_p_briopt);
#endif
#ifdef FEAT_SCROLLBIND
case PV_SCBIND: return (char_u *)&(curwin->w_p_scb);
#endif
#ifdef FEAT_CURSORBIND
case PV_CRBIND: return (char_u *)&(curwin->w_p_crb);
#endif
#ifdef FEAT_CONCEAL
case PV_COCU: return (char_u *)&(curwin->w_p_cocu);
case PV_COLE: return (char_u *)&(curwin->w_p_cole);
#endif
case PV_AI: return (char_u *)&(curbuf->b_p_ai);
case PV_BIN: return (char_u *)&(curbuf->b_p_bin);
#ifdef FEAT_MBYTE
case PV_BOMB: return (char_u *)&(curbuf->b_p_bomb);
#endif
#if defined(FEAT_QUICKFIX)
case PV_BH: return (char_u *)&(curbuf->b_p_bh);
case PV_BT: return (char_u *)&(curbuf->b_p_bt);
#endif
case PV_BL: return (char_u *)&(curbuf->b_p_bl);
case PV_CI: return (char_u *)&(curbuf->b_p_ci);
#ifdef FEAT_CINDENT
case PV_CIN: return (char_u *)&(curbuf->b_p_cin);
case PV_CINK: return (char_u *)&(curbuf->b_p_cink);
case PV_CINO: return (char_u *)&(curbuf->b_p_cino);
#endif
#if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT)
case PV_CINW: return (char_u *)&(curbuf->b_p_cinw);
#endif
#ifdef FEAT_COMMENTS
case PV_COM: return (char_u *)&(curbuf->b_p_com);
#endif
#ifdef FEAT_FOLDING
case PV_CMS: return (char_u *)&(curbuf->b_p_cms);
#endif
#ifdef FEAT_INS_EXPAND
case PV_CPT: return (char_u *)&(curbuf->b_p_cpt);
#endif
#ifdef FEAT_COMPL_FUNC
case PV_CFU: return (char_u *)&(curbuf->b_p_cfu);
case PV_OFU: return (char_u *)&(curbuf->b_p_ofu);
#endif
case PV_EOL: return (char_u *)&(curbuf->b_p_eol);
case PV_FIXEOL: return (char_u *)&(curbuf->b_p_fixeol);
case PV_ET: return (char_u *)&(curbuf->b_p_et);
#ifdef FEAT_MBYTE
case PV_FENC: return (char_u *)&(curbuf->b_p_fenc);
#endif
case PV_FF: return (char_u *)&(curbuf->b_p_ff);
#ifdef FEAT_AUTOCMD
case PV_FT: return (char_u *)&(curbuf->b_p_ft);
#endif
case PV_FO: return (char_u *)&(curbuf->b_p_fo);
case PV_FLP: return (char_u *)&(curbuf->b_p_flp);
case PV_IMI: return (char_u *)&(curbuf->b_p_iminsert);
case PV_IMS: return (char_u *)&(curbuf->b_p_imsearch);
case PV_INF: return (char_u *)&(curbuf->b_p_inf);
case PV_ISK: return (char_u *)&(curbuf->b_p_isk);
#ifdef FEAT_FIND_ID
# ifdef FEAT_EVAL
case PV_INEX: return (char_u *)&(curbuf->b_p_inex);
# endif
#endif
#if defined(FEAT_CINDENT) && defined(FEAT_EVAL)
case PV_INDE: return (char_u *)&(curbuf->b_p_inde);
case PV_INDK: return (char_u *)&(curbuf->b_p_indk);
#endif
#ifdef FEAT_EVAL
case PV_FEX: return (char_u *)&(curbuf->b_p_fex);
#endif
#ifdef FEAT_CRYPT
case PV_KEY: return (char_u *)&(curbuf->b_p_key);
#endif
#ifdef FEAT_LISP
case PV_LISP: return (char_u *)&(curbuf->b_p_lisp);
#endif
case PV_ML: return (char_u *)&(curbuf->b_p_ml);
case PV_MPS: return (char_u *)&(curbuf->b_p_mps);
case PV_MA: return (char_u *)&(curbuf->b_p_ma);
case PV_MOD: return (char_u *)&(curbuf->b_changed);
case PV_NF: return (char_u *)&(curbuf->b_p_nf);
case PV_PI: return (char_u *)&(curbuf->b_p_pi);
#ifdef FEAT_TEXTOBJ
case PV_QE: return (char_u *)&(curbuf->b_p_qe);
#endif
case PV_RO: return (char_u *)&(curbuf->b_p_ro);
#ifdef FEAT_SMARTINDENT
case PV_SI: return (char_u *)&(curbuf->b_p_si);
#endif
case PV_SN: return (char_u *)&(curbuf->b_p_sn);
case PV_STS: return (char_u *)&(curbuf->b_p_sts);
#ifdef FEAT_SEARCHPATH
case PV_SUA: return (char_u *)&(curbuf->b_p_sua);
#endif
case PV_SWF: return (char_u *)&(curbuf->b_p_swf);
#ifdef FEAT_SYN_HL
case PV_SMC: return (char_u *)&(curbuf->b_p_smc);
case PV_SYN: return (char_u *)&(curbuf->b_p_syn);
#endif
#ifdef FEAT_SPELL
case PV_SPC: return (char_u *)&(curwin->w_s->b_p_spc);
case PV_SPF: return (char_u *)&(curwin->w_s->b_p_spf);
case PV_SPL: return (char_u *)&(curwin->w_s->b_p_spl);
#endif
case PV_SW: return (char_u *)&(curbuf->b_p_sw);
case PV_TS: return (char_u *)&(curbuf->b_p_ts);
case PV_TW: return (char_u *)&(curbuf->b_p_tw);
case PV_TX: return (char_u *)&(curbuf->b_p_tx);
#ifdef FEAT_PERSISTENT_UNDO
case PV_UDF: return (char_u *)&(curbuf->b_p_udf);
#endif
case PV_WM: return (char_u *)&(curbuf->b_p_wm);
#ifdef FEAT_KEYMAP
case PV_KMAP: return (char_u *)&(curbuf->b_p_keymap);
#endif
#ifdef FEAT_SIGNS
case PV_SCL: return (char_u *)&(curwin->w_p_scl);
#endif
default: EMSG(_("E356: get_varp ERROR"));
}
/* always return a valid pointer to avoid a crash! */
return (char_u *)&(curbuf->b_p_wm);
}
/*
* Get the value of 'equalprg', either the buffer-local one or the global one.
*/
char_u *
get_equalprg(void)
{
if (*curbuf->b_p_ep == NUL)
return p_ep;
return curbuf->b_p_ep;
}
#if defined(FEAT_WINDOWS) || defined(PROTO)
/*
* Copy options from one window to another.
* Used when splitting a window.
*/
void
win_copy_options(win_T *wp_from, win_T *wp_to)
{
copy_winopt(&wp_from->w_onebuf_opt, &wp_to->w_onebuf_opt);
copy_winopt(&wp_from->w_allbuf_opt, &wp_to->w_allbuf_opt);
# ifdef FEAT_RIGHTLEFT
# ifdef FEAT_FKMAP
/* Is this right? */
wp_to->w_farsi = wp_from->w_farsi;
# endif
# endif
#if defined(FEAT_LINEBREAK)
briopt_check(wp_to);
#endif
}
#endif
/*
* Copy the options from one winopt_T to another.
* Doesn't free the old option values in "to", use clear_winopt() for that.
* The 'scroll' option is not copied, because it depends on the window height.
* The 'previewwindow' option is reset, there can be only one preview window.
*/
void
copy_winopt(winopt_T *from, winopt_T *to)
{
#ifdef FEAT_ARABIC
to->wo_arab = from->wo_arab;
#endif
to->wo_list = from->wo_list;
to->wo_nu = from->wo_nu;
to->wo_rnu = from->wo_rnu;
#ifdef FEAT_LINEBREAK
to->wo_nuw = from->wo_nuw;
#endif
#ifdef FEAT_RIGHTLEFT
to->wo_rl = from->wo_rl;
to->wo_rlc = vim_strsave(from->wo_rlc);
#endif
#ifdef FEAT_STL_OPT
to->wo_stl = vim_strsave(from->wo_stl);
#endif
to->wo_wrap = from->wo_wrap;
#ifdef FEAT_DIFF
to->wo_wrap_save = from->wo_wrap_save;
#endif
#ifdef FEAT_LINEBREAK
to->wo_lbr = from->wo_lbr;
to->wo_bri = from->wo_bri;
to->wo_briopt = vim_strsave(from->wo_briopt);
#endif
#ifdef FEAT_SCROLLBIND
to->wo_scb = from->wo_scb;
to->wo_scb_save = from->wo_scb_save;
#endif
#ifdef FEAT_CURSORBIND
to->wo_crb = from->wo_crb;
to->wo_crb_save = from->wo_crb_save;
#endif
#ifdef FEAT_SPELL
to->wo_spell = from->wo_spell;
#endif
#ifdef FEAT_SYN_HL
to->wo_cuc = from->wo_cuc;
to->wo_cul = from->wo_cul;
to->wo_cc = vim_strsave(from->wo_cc);
#endif
#ifdef FEAT_DIFF
to->wo_diff = from->wo_diff;
to->wo_diff_saved = from->wo_diff_saved;
#endif
#ifdef FEAT_CONCEAL
to->wo_cocu = vim_strsave(from->wo_cocu);
to->wo_cole = from->wo_cole;
#endif
#ifdef FEAT_FOLDING
to->wo_fdc = from->wo_fdc;
to->wo_fdc_save = from->wo_fdc_save;
to->wo_fen = from->wo_fen;
to->wo_fen_save = from->wo_fen_save;
to->wo_fdi = vim_strsave(from->wo_fdi);
to->wo_fml = from->wo_fml;
to->wo_fdl = from->wo_fdl;
to->wo_fdl_save = from->wo_fdl_save;
to->wo_fdm = vim_strsave(from->wo_fdm);
to->wo_fdm_save = from->wo_diff_saved
? vim_strsave(from->wo_fdm_save) : empty_option;
to->wo_fdn = from->wo_fdn;
# ifdef FEAT_EVAL
to->wo_fde = vim_strsave(from->wo_fde);
to->wo_fdt = vim_strsave(from->wo_fdt);
# endif
to->wo_fmr = vim_strsave(from->wo_fmr);
#endif
#ifdef FEAT_SIGNS
to->wo_scl = vim_strsave(from->wo_scl);
#endif
check_winopt(to); /* don't want NULL pointers */
}
/*
* Check string options in a window for a NULL value.
*/
void
check_win_options(win_T *win)
{
check_winopt(&win->w_onebuf_opt);
check_winopt(&win->w_allbuf_opt);
}
/*
* Check for NULL pointers in a winopt_T and replace them with empty_option.
*/
static void
check_winopt(winopt_T *wop UNUSED)
{
#ifdef FEAT_FOLDING
check_string_option(&wop->wo_fdi);
check_string_option(&wop->wo_fdm);
check_string_option(&wop->wo_fdm_save);
# ifdef FEAT_EVAL
check_string_option(&wop->wo_fde);
check_string_option(&wop->wo_fdt);
# endif
check_string_option(&wop->wo_fmr);
#endif
#ifdef FEAT_SIGNS
check_string_option(&wop->wo_scl);
#endif
#ifdef FEAT_RIGHTLEFT
check_string_option(&wop->wo_rlc);
#endif
#ifdef FEAT_STL_OPT
check_string_option(&wop->wo_stl);
#endif
#ifdef FEAT_SYN_HL
check_string_option(&wop->wo_cc);
#endif
#ifdef FEAT_CONCEAL
check_string_option(&wop->wo_cocu);
#endif
#ifdef FEAT_LINEBREAK
check_string_option(&wop->wo_briopt);
#endif
}
/*
* Free the allocated memory inside a winopt_T.
*/
void
clear_winopt(winopt_T *wop UNUSED)
{
#ifdef FEAT_FOLDING
clear_string_option(&wop->wo_fdi);
clear_string_option(&wop->wo_fdm);
clear_string_option(&wop->wo_fdm_save);
# ifdef FEAT_EVAL
clear_string_option(&wop->wo_fde);
clear_string_option(&wop->wo_fdt);
# endif
clear_string_option(&wop->wo_fmr);
#endif
#ifdef FEAT_SIGNS
clear_string_option(&wop->wo_scl);
#endif
#ifdef FEAT_LINEBREAK
clear_string_option(&wop->wo_briopt);
#endif
#ifdef FEAT_RIGHTLEFT
clear_string_option(&wop->wo_rlc);
#endif
#ifdef FEAT_STL_OPT
clear_string_option(&wop->wo_stl);
#endif
#ifdef FEAT_SYN_HL
clear_string_option(&wop->wo_cc);
#endif
#ifdef FEAT_CONCEAL
clear_string_option(&wop->wo_cocu);
#endif
}
/*
* Copy global option values to local options for one buffer.
* Used when creating a new buffer and sometimes when entering a buffer.
* flags:
* BCO_ENTER We will enter the buf buffer.
* BCO_ALWAYS Always copy the options, but only set b_p_initialized when
* appropriate.
* BCO_NOHELP Don't copy the values to a help buffer.
*/
void
buf_copy_options(buf_T *buf, int flags)
{
int should_copy = TRUE;
char_u *save_p_isk = NULL; /* init for GCC */
int dont_do_help;
int did_isk = FALSE;
/*
* Skip this when the option defaults have not been set yet. Happens when
* main() allocates the first buffer.
*/
if (p_cpo != NULL)
{
/*
* Always copy when entering and 'cpo' contains 'S'.
* Don't copy when already initialized.
* Don't copy when 'cpo' contains 's' and not entering.
* 'S' BCO_ENTER initialized 's' should_copy
* yes yes X X TRUE
* yes no yes X FALSE
* no X yes X FALSE
* X no no yes FALSE
* X no no no TRUE
* no yes no X TRUE
*/
if ((vim_strchr(p_cpo, CPO_BUFOPTGLOB) == NULL || !(flags & BCO_ENTER))
&& (buf->b_p_initialized
|| (!(flags & BCO_ENTER)
&& vim_strchr(p_cpo, CPO_BUFOPT) != NULL)))
should_copy = FALSE;
if (should_copy || (flags & BCO_ALWAYS))
{
/* Don't copy the options specific to a help buffer when
* BCO_NOHELP is given or the options were initialized already
* (jumping back to a help file with CTRL-T or CTRL-O) */
dont_do_help = ((flags & BCO_NOHELP) && buf->b_help)
|| buf->b_p_initialized;
if (dont_do_help) /* don't free b_p_isk */
{
save_p_isk = buf->b_p_isk;
buf->b_p_isk = NULL;
}
/*
* Always free the allocated strings.
* If not already initialized, set 'readonly' and copy 'fileformat'.
*/
if (!buf->b_p_initialized)
{
free_buf_options(buf, TRUE);
buf->b_p_ro = FALSE; /* don't copy readonly */
buf->b_p_tx = p_tx;
#ifdef FEAT_MBYTE
buf->b_p_fenc = vim_strsave(p_fenc);
#endif
switch (*p_ffs)
{
case 'm':
buf->b_p_ff = vim_strsave((char_u *)FF_MAC); break;
case 'd':
buf->b_p_ff = vim_strsave((char_u *)FF_DOS); break;
case 'u':
buf->b_p_ff = vim_strsave((char_u *)FF_UNIX); break;
default:
buf->b_p_ff = vim_strsave(p_ff);
}
if (buf->b_p_ff != NULL)
buf->b_start_ffc = *buf->b_p_ff;
#if defined(FEAT_QUICKFIX)
buf->b_p_bh = empty_option;
buf->b_p_bt = empty_option;
#endif
}
else
free_buf_options(buf, FALSE);
buf->b_p_ai = p_ai;
buf->b_p_ai_nopaste = p_ai_nopaste;
buf->b_p_sw = p_sw;
buf->b_p_tw = p_tw;
buf->b_p_tw_nopaste = p_tw_nopaste;
buf->b_p_tw_nobin = p_tw_nobin;
buf->b_p_wm = p_wm;
buf->b_p_wm_nopaste = p_wm_nopaste;
buf->b_p_wm_nobin = p_wm_nobin;
buf->b_p_bin = p_bin;
#ifdef FEAT_MBYTE
buf->b_p_bomb = p_bomb;
#endif
buf->b_p_fixeol = p_fixeol;
buf->b_p_et = p_et;
buf->b_p_et_nobin = p_et_nobin;
buf->b_p_et_nopaste = p_et_nopaste;
buf->b_p_ml = p_ml;
buf->b_p_ml_nobin = p_ml_nobin;
buf->b_p_inf = p_inf;
buf->b_p_swf = p_swf;
#ifdef FEAT_INS_EXPAND
buf->b_p_cpt = vim_strsave(p_cpt);
#endif
#ifdef FEAT_COMPL_FUNC
buf->b_p_cfu = vim_strsave(p_cfu);
buf->b_p_ofu = vim_strsave(p_ofu);
#endif
buf->b_p_sts = p_sts;
buf->b_p_sts_nopaste = p_sts_nopaste;
buf->b_p_sn = p_sn;
#ifdef FEAT_COMMENTS
buf->b_p_com = vim_strsave(p_com);
#endif
#ifdef FEAT_FOLDING
buf->b_p_cms = vim_strsave(p_cms);
#endif
buf->b_p_fo = vim_strsave(p_fo);
buf->b_p_flp = vim_strsave(p_flp);
buf->b_p_nf = vim_strsave(p_nf);
buf->b_p_mps = vim_strsave(p_mps);
#ifdef FEAT_SMARTINDENT
buf->b_p_si = p_si;
#endif
buf->b_p_ci = p_ci;
#ifdef FEAT_CINDENT
buf->b_p_cin = p_cin;
buf->b_p_cink = vim_strsave(p_cink);
buf->b_p_cino = vim_strsave(p_cino);
#endif
#ifdef FEAT_AUTOCMD
/* Don't copy 'filetype', it must be detected */
buf->b_p_ft = empty_option;
#endif
buf->b_p_pi = p_pi;
#if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT)
buf->b_p_cinw = vim_strsave(p_cinw);
#endif
#ifdef FEAT_LISP
buf->b_p_lisp = p_lisp;
#endif
#ifdef FEAT_SYN_HL
/* Don't copy 'syntax', it must be set */
buf->b_p_syn = empty_option;
buf->b_p_smc = p_smc;
buf->b_s.b_syn_isk = empty_option;
#endif
#ifdef FEAT_SPELL
buf->b_s.b_p_spc = vim_strsave(p_spc);
(void)compile_cap_prog(&buf->b_s);
buf->b_s.b_p_spf = vim_strsave(p_spf);
buf->b_s.b_p_spl = vim_strsave(p_spl);
#endif
#if defined(FEAT_CINDENT) && defined(FEAT_EVAL)
buf->b_p_inde = vim_strsave(p_inde);
buf->b_p_indk = vim_strsave(p_indk);
#endif
#if defined(FEAT_EVAL)
buf->b_p_fex = vim_strsave(p_fex);
#endif
#ifdef FEAT_CRYPT
buf->b_p_key = vim_strsave(p_key);
#endif
#ifdef FEAT_SEARCHPATH
buf->b_p_sua = vim_strsave(p_sua);
#endif
#ifdef FEAT_KEYMAP
buf->b_p_keymap = vim_strsave(p_keymap);
buf->b_kmap_state |= KEYMAP_INIT;
#endif
/* This isn't really an option, but copying the langmap and IME
* state from the current buffer is better than resetting it. */
buf->b_p_iminsert = p_iminsert;
buf->b_p_imsearch = p_imsearch;
/* options that are normally global but also have a local value
* are not copied, start using the global value */
buf->b_p_ar = -1;
buf->b_p_ul = NO_LOCAL_UNDOLEVEL;
buf->b_p_bkc = empty_option;
buf->b_bkc_flags = 0;
#ifdef FEAT_QUICKFIX
buf->b_p_gp = empty_option;
buf->b_p_mp = empty_option;
buf->b_p_efm = empty_option;
#endif
buf->b_p_ep = empty_option;
buf->b_p_kp = empty_option;
buf->b_p_path = empty_option;
buf->b_p_tags = empty_option;
buf->b_p_tc = empty_option;
buf->b_tc_flags = 0;
#ifdef FEAT_FIND_ID
buf->b_p_def = empty_option;
buf->b_p_inc = empty_option;
# ifdef FEAT_EVAL
buf->b_p_inex = vim_strsave(p_inex);
# endif
#endif
#ifdef FEAT_INS_EXPAND
buf->b_p_dict = empty_option;
buf->b_p_tsr = empty_option;
#endif
#ifdef FEAT_TEXTOBJ
buf->b_p_qe = vim_strsave(p_qe);
#endif
#if defined(FEAT_BEVAL) && defined(FEAT_EVAL)
buf->b_p_bexpr = empty_option;
#endif
#if defined(FEAT_CRYPT)
buf->b_p_cm = empty_option;
#endif
#ifdef FEAT_PERSISTENT_UNDO
buf->b_p_udf = p_udf;
#endif
#ifdef FEAT_LISP
buf->b_p_lw = empty_option;
#endif
/*
* Don't copy the options set by ex_help(), use the saved values,
* when going from a help buffer to a non-help buffer.
* Don't touch these at all when BCO_NOHELP is used and going from
* or to a help buffer.
*/
if (dont_do_help)
buf->b_p_isk = save_p_isk;
else
{
buf->b_p_isk = vim_strsave(p_isk);
did_isk = TRUE;
buf->b_p_ts = p_ts;
buf->b_help = FALSE;
#ifdef FEAT_QUICKFIX
if (buf->b_p_bt[0] == 'h')
clear_string_option(&buf->b_p_bt);
#endif
buf->b_p_ma = p_ma;
}
}
/*
* When the options should be copied (ignoring BCO_ALWAYS), set the
* flag that indicates that the options have been initialized.
*/
if (should_copy)
buf->b_p_initialized = TRUE;
}
check_buf_options(buf); /* make sure we don't have NULLs */
if (did_isk)
(void)buf_init_chartab(buf, FALSE);
}
/*
* Reset the 'modifiable' option and its default value.
*/
void
reset_modifiable(void)
{
int opt_idx;
curbuf->b_p_ma = FALSE;
p_ma = FALSE;
opt_idx = findoption((char_u *)"ma");
if (opt_idx >= 0)
options[opt_idx].def_val[VI_DEFAULT] = FALSE;
}
/*
* Set the global value for 'iminsert' to the local value.
*/
void
set_iminsert_global(void)
{
p_iminsert = curbuf->b_p_iminsert;
}
/*
* Set the global value for 'imsearch' to the local value.
*/
void
set_imsearch_global(void)
{
p_imsearch = curbuf->b_p_imsearch;
}
#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
static int expand_option_idx = -1;
static char_u expand_option_name[5] = {'t', '_', NUL, NUL, NUL};
static int expand_option_flags = 0;
void
set_context_in_set_cmd(
expand_T *xp,
char_u *arg,
int opt_flags) /* OPT_GLOBAL and/or OPT_LOCAL */
{
int nextchar;
long_u flags = 0; /* init for GCC */
int opt_idx = 0; /* init for GCC */
char_u *p;
char_u *s;
int is_term_option = FALSE;
int key;
expand_option_flags = opt_flags;
xp->xp_context = EXPAND_SETTINGS;
if (*arg == NUL)
{
xp->xp_pattern = arg;
return;
}
p = arg + STRLEN(arg) - 1;
if (*p == ' ' && *(p - 1) != '\\')
{
xp->xp_pattern = p + 1;
return;
}
while (p > arg)
{
s = p;
/* count number of backslashes before ' ' or ',' */
if (*p == ' ' || *p == ',')
{
while (s > arg && *(s - 1) == '\\')
--s;
}
/* break at a space with an even number of backslashes */
if (*p == ' ' && ((p - s) & 1) == 0)
{
++p;
break;
}
--p;
}
if (STRNCMP(p, "no", 2) == 0 && STRNCMP(p, "novice", 6) != 0)
{
xp->xp_context = EXPAND_BOOL_SETTINGS;
p += 2;
}
if (STRNCMP(p, "inv", 3) == 0)
{
xp->xp_context = EXPAND_BOOL_SETTINGS;
p += 3;
}
xp->xp_pattern = arg = p;
if (*arg == '<')
{
while (*p != '>')
if (*p++ == NUL) /* expand terminal option name */
return;
key = get_special_key_code(arg + 1);
if (key == 0) /* unknown name */
{
xp->xp_context = EXPAND_NOTHING;
return;
}
nextchar = *++p;
is_term_option = TRUE;
expand_option_name[2] = KEY2TERMCAP0(key);
expand_option_name[3] = KEY2TERMCAP1(key);
}
else
{
if (p[0] == 't' && p[1] == '_')
{
p += 2;
if (*p != NUL)
++p;
if (*p == NUL)
return; /* expand option name */
nextchar = *++p;
is_term_option = TRUE;
expand_option_name[2] = p[-2];
expand_option_name[3] = p[-1];
}
else
{
/* Allow * wildcard */
while (ASCII_ISALNUM(*p) || *p == '_' || *p == '*')
p++;
if (*p == NUL)
return;
nextchar = *p;
*p = NUL;
opt_idx = findoption(arg);
*p = nextchar;
if (opt_idx == -1 || options[opt_idx].var == NULL)
{
xp->xp_context = EXPAND_NOTHING;
return;
}
flags = options[opt_idx].flags;
if (flags & P_BOOL)
{
xp->xp_context = EXPAND_NOTHING;
return;
}
}
}
/* handle "-=" and "+=" */
if ((nextchar == '-' || nextchar == '+' || nextchar == '^') && p[1] == '=')
{
++p;
nextchar = '=';
}
if ((nextchar != '=' && nextchar != ':')
|| xp->xp_context == EXPAND_BOOL_SETTINGS)
{
xp->xp_context = EXPAND_UNSUCCESSFUL;
return;
}
if (xp->xp_context != EXPAND_BOOL_SETTINGS && p[1] == NUL)
{
xp->xp_context = EXPAND_OLD_SETTING;
if (is_term_option)
expand_option_idx = -1;
else
expand_option_idx = opt_idx;
xp->xp_pattern = p + 1;
return;
}
xp->xp_context = EXPAND_NOTHING;
if (is_term_option || (flags & P_NUM))
return;
xp->xp_pattern = p + 1;
if (flags & P_EXPAND)
{
p = options[opt_idx].var;
if (p == (char_u *)&p_bdir
|| p == (char_u *)&p_dir
|| p == (char_u *)&p_path
|| p == (char_u *)&p_pp
|| p == (char_u *)&p_rtp
#ifdef FEAT_SEARCHPATH
|| p == (char_u *)&p_cdpath
#endif
#ifdef FEAT_SESSION
|| p == (char_u *)&p_vdir
#endif
)
{
xp->xp_context = EXPAND_DIRECTORIES;
if (p == (char_u *)&p_path
#ifdef FEAT_SEARCHPATH
|| p == (char_u *)&p_cdpath
#endif
)
xp->xp_backslash = XP_BS_THREE;
else
xp->xp_backslash = XP_BS_ONE;
}
else
{
xp->xp_context = EXPAND_FILES;
/* for 'tags' need three backslashes for a space */
if (p == (char_u *)&p_tags)
xp->xp_backslash = XP_BS_THREE;
else
xp->xp_backslash = XP_BS_ONE;
}
}
/* For an option that is a list of file names, find the start of the
* last file name. */
for (p = arg + STRLEN(arg) - 1; p > xp->xp_pattern; --p)
{
/* count number of backslashes before ' ' or ',' */
if (*p == ' ' || *p == ',')
{
s = p;
while (s > xp->xp_pattern && *(s - 1) == '\\')
--s;
if ((*p == ' ' && (xp->xp_backslash == XP_BS_THREE && (p - s) < 3))
|| (*p == ',' && (flags & P_COMMA) && ((p - s) & 1) == 0))
{
xp->xp_pattern = p + 1;
break;
}
}
#ifdef FEAT_SPELL
/* for 'spellsuggest' start at "file:" */
if (options[opt_idx].var == (char_u *)&p_sps
&& STRNCMP(p, "file:", 5) == 0)
{
xp->xp_pattern = p + 5;
break;
}
#endif
}
return;
}
int
ExpandSettings(
expand_T *xp,
regmatch_T *regmatch,
int *num_file,
char_u ***file)
{
int num_normal = 0; /* Nr of matching non-term-code settings */
int num_term = 0; /* Nr of matching terminal code settings */
int opt_idx;
int match;
int count = 0;
char_u *str;
int loop;
int is_term_opt;
char_u name_buf[MAX_KEY_NAME_LEN];
static char *(names[]) = {"all", "termcap"};
int ic = regmatch->rm_ic; /* remember the ignore-case flag */
/* do this loop twice:
* loop == 0: count the number of matching options
* loop == 1: copy the matching options into allocated memory
*/
for (loop = 0; loop <= 1; ++loop)
{
regmatch->rm_ic = ic;
if (xp->xp_context != EXPAND_BOOL_SETTINGS)
{
for (match = 0; match < (int)(sizeof(names) / sizeof(char *));
++match)
if (vim_regexec(regmatch, (char_u *)names[match], (colnr_T)0))
{
if (loop == 0)
num_normal++;
else
(*file)[count++] = vim_strsave((char_u *)names[match]);
}
}
for (opt_idx = 0; (str = (char_u *)options[opt_idx].fullname) != NULL;
opt_idx++)
{
if (options[opt_idx].var == NULL)
continue;
if (xp->xp_context == EXPAND_BOOL_SETTINGS
&& !(options[opt_idx].flags & P_BOOL))
continue;
is_term_opt = istermoption(&options[opt_idx]);
if (is_term_opt && num_normal > 0)
continue;
match = FALSE;
if (vim_regexec(regmatch, str, (colnr_T)0)
|| (options[opt_idx].shortname != NULL
&& vim_regexec(regmatch,
(char_u *)options[opt_idx].shortname, (colnr_T)0)))
match = TRUE;
else if (is_term_opt)
{
name_buf[0] = '<';
name_buf[1] = 't';
name_buf[2] = '_';
name_buf[3] = str[2];
name_buf[4] = str[3];
name_buf[5] = '>';
name_buf[6] = NUL;
if (vim_regexec(regmatch, name_buf, (colnr_T)0))
{
match = TRUE;
str = name_buf;
}
}
if (match)
{
if (loop == 0)
{
if (is_term_opt)
num_term++;
else
num_normal++;
}
else
(*file)[count++] = vim_strsave(str);
}
}
/*
* Check terminal key codes, these are not in the option table
*/
if (xp->xp_context != EXPAND_BOOL_SETTINGS && num_normal == 0)
{
for (opt_idx = 0; (str = get_termcode(opt_idx)) != NULL; opt_idx++)
{
if (!isprint(str[0]) || !isprint(str[1]))
continue;
name_buf[0] = 't';
name_buf[1] = '_';
name_buf[2] = str[0];
name_buf[3] = str[1];
name_buf[4] = NUL;
match = FALSE;
if (vim_regexec(regmatch, name_buf, (colnr_T)0))
match = TRUE;
else
{
name_buf[0] = '<';
name_buf[1] = 't';
name_buf[2] = '_';
name_buf[3] = str[0];
name_buf[4] = str[1];
name_buf[5] = '>';
name_buf[6] = NUL;
if (vim_regexec(regmatch, name_buf, (colnr_T)0))
match = TRUE;
}
if (match)
{
if (loop == 0)
num_term++;
else
(*file)[count++] = vim_strsave(name_buf);
}
}
/*
* Check special key names.
*/
regmatch->rm_ic = TRUE; /* ignore case here */
for (opt_idx = 0; (str = get_key_name(opt_idx)) != NULL; opt_idx++)
{
name_buf[0] = '<';
STRCPY(name_buf + 1, str);
STRCAT(name_buf, ">");
if (vim_regexec(regmatch, name_buf, (colnr_T)0))
{
if (loop == 0)
num_term++;
else
(*file)[count++] = vim_strsave(name_buf);
}
}
}
if (loop == 0)
{
if (num_normal > 0)
*num_file = num_normal;
else if (num_term > 0)
*num_file = num_term;
else
return OK;
*file = (char_u **)alloc((unsigned)(*num_file * sizeof(char_u *)));
if (*file == NULL)
{
*file = (char_u **)"";
return FAIL;
}
}
}
return OK;
}
int
ExpandOldSetting(int *num_file, char_u ***file)
{
char_u *var = NULL; /* init for GCC */
char_u *buf;
*num_file = 0;
*file = (char_u **)alloc((unsigned)sizeof(char_u *));
if (*file == NULL)
return FAIL;
/*
* For a terminal key code expand_option_idx is < 0.
*/
if (expand_option_idx < 0)
{
var = find_termcode(expand_option_name + 2);
if (var == NULL)
expand_option_idx = findoption(expand_option_name);
}
if (expand_option_idx >= 0)
{
/* put string of option value in NameBuff */
option_value2string(&options[expand_option_idx], expand_option_flags);
var = NameBuff;
}
else if (var == NULL)
var = (char_u *)"";
/* A backslash is required before some characters. This is the reverse of
* what happens in do_set(). */
buf = vim_strsave_escaped(var, escape_chars);
if (buf == NULL)
{
vim_free(*file);
*file = NULL;
return FAIL;
}
#ifdef BACKSLASH_IN_FILENAME
/* For MS-Windows et al. we don't double backslashes at the start and
* before a file name character. */
for (var = buf; *var != NUL; mb_ptr_adv(var))
if (var[0] == '\\' && var[1] == '\\'
&& expand_option_idx >= 0
&& (options[expand_option_idx].flags & P_EXPAND)
&& vim_isfilec(var[2])
&& (var[2] != '\\' || (var == buf && var[4] != '\\')))
STRMOVE(var, var + 1);
#endif
*file[0] = buf;
*num_file = 1;
return OK;
}
#endif
/*
* Get the value for the numeric or string option *opp in a nice format into
* NameBuff[]. Must not be called with a hidden option!
*/
static void
option_value2string(
struct vimoption *opp,
int opt_flags) /* OPT_GLOBAL and/or OPT_LOCAL */
{
char_u *varp;
varp = get_varp_scope(opp, opt_flags);
if (opp->flags & P_NUM)
{
long wc = 0;
if (wc_use_keyname(varp, &wc))
STRCPY(NameBuff, get_special_key_name((int)wc, 0));
else if (wc != 0)
STRCPY(NameBuff, transchar((int)wc));
else
sprintf((char *)NameBuff, "%ld", *(long *)varp);
}
else /* P_STRING */
{
varp = *(char_u **)(varp);
if (varp == NULL) /* just in case */
NameBuff[0] = NUL;
#ifdef FEAT_CRYPT
/* don't show the actual value of 'key', only that it's set */
else if (opp->var == (char_u *)&p_key && *varp)
STRCPY(NameBuff, "*****");
#endif
else if (opp->flags & P_EXPAND)
home_replace(NULL, varp, NameBuff, MAXPATHL, FALSE);
/* Translate 'pastetoggle' into special key names */
else if ((char_u **)opp->var == &p_pt)
str2specialbuf(p_pt, NameBuff, MAXPATHL);
else
vim_strncpy(NameBuff, varp, MAXPATHL - 1);
}
}
/*
* Return TRUE if "varp" points to 'wildchar' or 'wildcharm' and it can be
* printed as a keyname.
* "*wcp" is set to the value of the option if it's 'wildchar' or 'wildcharm'.
*/
static int
wc_use_keyname(char_u *varp, long *wcp)
{
if (((long *)varp == &p_wc) || ((long *)varp == &p_wcm))
{
*wcp = *(long *)varp;
if (IS_SPECIAL(*wcp) || find_special_key_in_table((int)*wcp) >= 0)
return TRUE;
}
return FALSE;
}
#if defined(FEAT_LANGMAP) || defined(PROTO)
/*
* Any character has an equivalent 'langmap' character. This is used for
* keyboards that have a special language mode that sends characters above
* 128 (although other characters can be translated too). The "to" field is a
* Vim command character. This avoids having to switch the keyboard back to
* ASCII mode when leaving Insert mode.
*
* langmap_mapchar[] maps any of 256 chars to an ASCII char used for Vim
* commands.
* When FEAT_MBYTE is defined langmap_mapga.ga_data is a sorted table of
* langmap_entry_T. This does the same as langmap_mapchar[] for characters >=
* 256.
*/
# if defined(FEAT_MBYTE) || defined(PROTO)
/*
* With multi-byte support use growarray for 'langmap' chars >= 256
*/
typedef struct
{
int from;
int to;
} langmap_entry_T;
static garray_T langmap_mapga;
static void langmap_set_entry(int from, int to);
/*
* Search for an entry in "langmap_mapga" for "from". If found set the "to"
* field. If not found insert a new entry at the appropriate location.
*/
static void
langmap_set_entry(int from, int to)
{
langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
int a = 0;
int b = langmap_mapga.ga_len;
/* Do a binary search for an existing entry. */
while (a != b)
{
int i = (a + b) / 2;
int d = entries[i].from - from;
if (d == 0)
{
entries[i].to = to;
return;
}
if (d < 0)
a = i + 1;
else
b = i;
}
if (ga_grow(&langmap_mapga, 1) != OK)
return; /* out of memory */
/* insert new entry at position "a" */
entries = (langmap_entry_T *)(langmap_mapga.ga_data) + a;
mch_memmove(entries + 1, entries,
(langmap_mapga.ga_len - a) * sizeof(langmap_entry_T));
++langmap_mapga.ga_len;
entries[0].from = from;
entries[0].to = to;
}
/*
* Apply 'langmap' to multi-byte character "c" and return the result.
*/
int
langmap_adjust_mb(int c)
{
langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
int a = 0;
int b = langmap_mapga.ga_len;
while (a != b)
{
int i = (a + b) / 2;
int d = entries[i].from - c;
if (d == 0)
return entries[i].to; /* found matching entry */
if (d < 0)
a = i + 1;
else
b = i;
}
return c; /* no entry found, return "c" unmodified */
}
# endif
static void
langmap_init(void)
{
int i;
for (i = 0; i < 256; i++)
langmap_mapchar[i] = i; /* we init with a one-to-one map */
# ifdef FEAT_MBYTE
ga_init2(&langmap_mapga, sizeof(langmap_entry_T), 8);
# endif
}
/*
* Called when langmap option is set; the language map can be
* changed at any time!
*/
static void
langmap_set(void)
{
char_u *p;
char_u *p2;
int from, to;
#ifdef FEAT_MBYTE
ga_clear(&langmap_mapga); /* clear the previous map first */
#endif
langmap_init(); /* back to one-to-one map */
for (p = p_langmap; p[0] != NUL; )
{
for (p2 = p; p2[0] != NUL && p2[0] != ',' && p2[0] != ';';
mb_ptr_adv(p2))
{
if (p2[0] == '\\' && p2[1] != NUL)
++p2;
}
if (p2[0] == ';')
++p2; /* abcd;ABCD form, p2 points to A */
else
p2 = NULL; /* aAbBcCdD form, p2 is NULL */
while (p[0])
{
if (p[0] == ',')
{
++p;
break;
}
if (p[0] == '\\' && p[1] != NUL)
++p;
#ifdef FEAT_MBYTE
from = (*mb_ptr2char)(p);
#else
from = p[0];
#endif
to = NUL;
if (p2 == NULL)
{
mb_ptr_adv(p);
if (p[0] != ',')
{
if (p[0] == '\\')
++p;
#ifdef FEAT_MBYTE
to = (*mb_ptr2char)(p);
#else
to = p[0];
#endif
}
}
else
{
if (p2[0] != ',')
{
if (p2[0] == '\\')
++p2;
#ifdef FEAT_MBYTE
to = (*mb_ptr2char)(p2);
#else
to = p2[0];
#endif
}
}
if (to == NUL)
{
EMSG2(_("E357: 'langmap': Matching character missing for %s"),
transchar(from));
return;
}
#ifdef FEAT_MBYTE
if (from >= 256)
langmap_set_entry(from, to);
else
#endif
langmap_mapchar[from & 255] = to;
/* Advance to next pair */
mb_ptr_adv(p);
if (p2 != NULL)
{
mb_ptr_adv(p2);
if (*p == ';')
{
p = p2;
if (p[0] != NUL)
{
if (p[0] != ',')
{
EMSG2(_("E358: 'langmap': Extra characters after semicolon: %s"), p);
return;
}
++p;
}
break;
}
}
}
}
}
#endif
/*
* Return TRUE if format option 'x' is in effect.
* Take care of no formatting when 'paste' is set.
*/
int
has_format_option(int x)
{
if (p_paste)
return FALSE;
return (vim_strchr(curbuf->b_p_fo, x) != NULL);
}
/*
* Return TRUE if "x" is present in 'shortmess' option, or
* 'shortmess' contains 'a' and "x" is present in SHM_A.
*/
int
shortmess(int x)
{
return p_shm != NULL &&
( vim_strchr(p_shm, x) != NULL
|| (vim_strchr(p_shm, 'a') != NULL
&& vim_strchr((char_u *)SHM_A, x) != NULL));
}
/*
* paste_option_changed() - Called after p_paste was set or reset.
*/
static void
paste_option_changed(void)
{
static int old_p_paste = FALSE;
static int save_sm = 0;
static int save_sta = 0;
#ifdef FEAT_CMDL_INFO
static int save_ru = 0;
#endif
#ifdef FEAT_RIGHTLEFT
static int save_ri = 0;
static int save_hkmap = 0;
#endif
buf_T *buf;
if (p_paste)
{
/*
* Paste switched from off to on.
* Save the current values, so they can be restored later.
*/
if (!old_p_paste)
{
/* save options for each buffer */
FOR_ALL_BUFFERS(buf)
{
buf->b_p_tw_nopaste = buf->b_p_tw;
buf->b_p_wm_nopaste = buf->b_p_wm;
buf->b_p_sts_nopaste = buf->b_p_sts;
buf->b_p_ai_nopaste = buf->b_p_ai;
buf->b_p_et_nopaste = buf->b_p_et;
}
/* save global options */
save_sm = p_sm;
save_sta = p_sta;
#ifdef FEAT_CMDL_INFO
save_ru = p_ru;
#endif
#ifdef FEAT_RIGHTLEFT
save_ri = p_ri;
save_hkmap = p_hkmap;
#endif
/* save global values for local buffer options */
p_ai_nopaste = p_ai;
p_et_nopaste = p_et;
p_sts_nopaste = p_sts;
p_tw_nopaste = p_tw;
p_wm_nopaste = p_wm;
}
/*
* Always set the option values, also when 'paste' is set when it is
* already on.
*/
/* set options for each buffer */
FOR_ALL_BUFFERS(buf)
{
buf->b_p_tw = 0; /* textwidth is 0 */
buf->b_p_wm = 0; /* wrapmargin is 0 */
buf->b_p_sts = 0; /* softtabstop is 0 */
buf->b_p_ai = 0; /* no auto-indent */
buf->b_p_et = 0; /* no expandtab */
}
/* set global options */
p_sm = 0; /* no showmatch */
p_sta = 0; /* no smarttab */
#ifdef FEAT_CMDL_INFO
# ifdef FEAT_WINDOWS
if (p_ru)
status_redraw_all(); /* redraw to remove the ruler */
# endif
p_ru = 0; /* no ruler */
#endif
#ifdef FEAT_RIGHTLEFT
p_ri = 0; /* no reverse insert */
p_hkmap = 0; /* no Hebrew keyboard */
#endif
/* set global values for local buffer options */
p_tw = 0;
p_wm = 0;
p_sts = 0;
p_ai = 0;
}
/*
* Paste switched from on to off: Restore saved values.
*/
else if (old_p_paste)
{
/* restore options for each buffer */
FOR_ALL_BUFFERS(buf)
{
buf->b_p_tw = buf->b_p_tw_nopaste;
buf->b_p_wm = buf->b_p_wm_nopaste;
buf->b_p_sts = buf->b_p_sts_nopaste;
buf->b_p_ai = buf->b_p_ai_nopaste;
buf->b_p_et = buf->b_p_et_nopaste;
}
/* restore global options */
p_sm = save_sm;
p_sta = save_sta;
#ifdef FEAT_CMDL_INFO
# ifdef FEAT_WINDOWS
if (p_ru != save_ru)
status_redraw_all(); /* redraw to draw the ruler */
# endif
p_ru = save_ru;
#endif
#ifdef FEAT_RIGHTLEFT
p_ri = save_ri;
p_hkmap = save_hkmap;
#endif
/* set global values for local buffer options */
p_ai = p_ai_nopaste;
p_et = p_et_nopaste;
p_sts = p_sts_nopaste;
p_tw = p_tw_nopaste;
p_wm = p_wm_nopaste;
}
old_p_paste = p_paste;
}
/*
* vimrc_found() - Called when a ".vimrc" or "VIMINIT" has been found.
*
* Reset 'compatible' and set the values for options that didn't get set yet
* to the Vim defaults.
* Don't do this if the 'compatible' option has been set or reset before.
* When "fname" is not NULL, use it to set $"envname" when it wasn't set yet.
*/
void
vimrc_found(char_u *fname, char_u *envname)
{
int opt_idx;
int dofree = FALSE;
char_u *p;
if (!option_was_set((char_u *)"cp"))
{
p_cp = FALSE;
for (opt_idx = 0; !istermoption(&options[opt_idx]); opt_idx++)
if (!(options[opt_idx].flags & (P_WAS_SET|P_VI_DEF)))
set_option_default(opt_idx, OPT_FREE, FALSE);
didset_options();
didset_options2();
}
if (fname != NULL)
{
p = vim_getenv(envname, &dofree);
if (p == NULL)
{
/* Set $MYVIMRC to the first vimrc file found. */
p = FullName_save(fname, FALSE);
if (p != NULL)
{
vim_setenv(envname, p);
vim_free(p);
}
}
else if (dofree)
vim_free(p);
}
}
/*
* Set 'compatible' on or off. Called for "-C" and "-N" command line arg.
*/
void
change_compatible(int on)
{
int opt_idx;
if (p_cp != on)
{
p_cp = on;
compatible_set();
}
opt_idx = findoption((char_u *)"cp");
if (opt_idx >= 0)
options[opt_idx].flags |= P_WAS_SET;
}
/*
* Return TRUE when option "name" has been set.
* Only works correctly for global options.
*/
int
option_was_set(char_u *name)
{
int idx;
idx = findoption(name);
if (idx < 0) /* unknown option */
return FALSE;
if (options[idx].flags & P_WAS_SET)
return TRUE;
return FALSE;
}
/*
* Reset the flag indicating option "name" was set.
*/
void
reset_option_was_set(char_u *name)
{
int idx = findoption(name);
if (idx >= 0)
options[idx].flags &= ~P_WAS_SET;
}
/*
* compatible_set() - Called when 'compatible' has been set or unset.
*
* When 'compatible' set: Set all relevant options (those that have the P_VIM)
* flag) to a Vi compatible value.
* When 'compatible' is unset: Set all options that have a different default
* for Vim (without the P_VI_DEF flag) to that default.
*/
static void
compatible_set(void)
{
int opt_idx;
for (opt_idx = 0; !istermoption(&options[opt_idx]); opt_idx++)
if ( ((options[opt_idx].flags & P_VIM) && p_cp)
|| (!(options[opt_idx].flags & P_VI_DEF) && !p_cp))
set_option_default(opt_idx, OPT_FREE, p_cp);
didset_options();
didset_options2();
}
#ifdef FEAT_LINEBREAK
# if defined(__BORLANDC__) && (__BORLANDC__ < 0x500)
/* Borland C++ screws up loop optimisation here (negri) */
#pragma option -O-l
# endif
/*
* fill_breakat_flags() -- called when 'breakat' changes value.
*/
static void
fill_breakat_flags(void)
{
char_u *p;
int i;
for (i = 0; i < 256; i++)
breakat_flags[i] = FALSE;
if (p_breakat != NULL)
for (p = p_breakat; *p; p++)
breakat_flags[*p] = TRUE;
}
# if defined(__BORLANDC__) && (__BORLANDC__ < 0x500)
#pragma option -O.l
# endif
#endif
/*
* Check an option that can be a range of string values.
*
* Return OK for correct value, FAIL otherwise.
* Empty is always OK.
*/
static int
check_opt_strings(
char_u *val,
char **values,
int list) /* when TRUE: accept a list of values */
{
return opt_strings_flags(val, values, NULL, list);
}
/*
* Handle an option that can be a range of string values.
* Set a flag in "*flagp" for each string present.
*
* Return OK for correct value, FAIL otherwise.
* Empty is always OK.
*/
static int
opt_strings_flags(
char_u *val, /* new value */
char **values, /* array of valid string values */
unsigned *flagp,
int list) /* when TRUE: accept a list of values */
{
int i;
int len;
unsigned new_flags = 0;
while (*val)
{
for (i = 0; ; ++i)
{
if (values[i] == NULL) /* val not found in values[] */
return FAIL;
len = (int)STRLEN(values[i]);
if (STRNCMP(values[i], val, len) == 0
&& ((list && val[len] == ',') || val[len] == NUL))
{
val += len + (val[len] == ',');
new_flags |= (1 << i);
break; /* check next item in val list */
}
}
}
if (flagp != NULL)
*flagp = new_flags;
return OK;
}
/*
* Read the 'wildmode' option, fill wim_flags[].
*/
static int
check_opt_wim(void)
{
char_u new_wim_flags[4];
char_u *p;
int i;
int idx = 0;
for (i = 0; i < 4; ++i)
new_wim_flags[i] = 0;
for (p = p_wim; *p; ++p)
{
for (i = 0; ASCII_ISALPHA(p[i]); ++i)
;
if (p[i] != NUL && p[i] != ',' && p[i] != ':')
return FAIL;
if (i == 7 && STRNCMP(p, "longest", 7) == 0)
new_wim_flags[idx] |= WIM_LONGEST;
else if (i == 4 && STRNCMP(p, "full", 4) == 0)
new_wim_flags[idx] |= WIM_FULL;
else if (i == 4 && STRNCMP(p, "list", 4) == 0)
new_wim_flags[idx] |= WIM_LIST;
else
return FAIL;
p += i;
if (*p == NUL)
break;
if (*p == ',')
{
if (idx == 3)
return FAIL;
++idx;
}
}
/* fill remaining entries with last flag */
while (idx < 3)
{
new_wim_flags[idx + 1] = new_wim_flags[idx];
++idx;
}
/* only when there are no errors, wim_flags[] is changed */
for (i = 0; i < 4; ++i)
wim_flags[i] = new_wim_flags[i];
return OK;
}
/*
* Check if backspacing over something is allowed.
*/
int
can_bs(
int what) /* BS_INDENT, BS_EOL or BS_START */
{
switch (*p_bs)
{
case '2': return TRUE;
case '1': return (what != BS_START);
case '0': return FALSE;
}
return vim_strchr(p_bs, what) != NULL;
}
/*
* Save the current values of 'fileformat' and 'fileencoding', so that we know
* the file must be considered changed when the value is different.
*/
void
save_file_ff(buf_T *buf)
{
buf->b_start_ffc = *buf->b_p_ff;
buf->b_start_eol = buf->b_p_eol;
#ifdef FEAT_MBYTE
buf->b_start_bomb = buf->b_p_bomb;
/* Only use free/alloc when necessary, they take time. */
if (buf->b_start_fenc == NULL
|| STRCMP(buf->b_start_fenc, buf->b_p_fenc) != 0)
{
vim_free(buf->b_start_fenc);
buf->b_start_fenc = vim_strsave(buf->b_p_fenc);
}
#endif
}
/*
* Return TRUE if 'fileformat' and/or 'fileencoding' has a different value
* from when editing started (save_file_ff() called).
* Also when 'endofline' was changed and 'binary' is set, or when 'bomb' was
* changed and 'binary' is not set.
* Also when 'endofline' was changed and 'fixeol' is not set.
* When "ignore_empty" is true don't consider a new, empty buffer to be
* changed.
*/
int
file_ff_differs(buf_T *buf, int ignore_empty)
{
/* In a buffer that was never loaded the options are not valid. */
if (buf->b_flags & BF_NEVERLOADED)
return FALSE;
if (ignore_empty
&& (buf->b_flags & BF_NEW)
&& buf->b_ml.ml_line_count == 1
&& *ml_get_buf(buf, (linenr_T)1, FALSE) == NUL)
return FALSE;
if (buf->b_start_ffc != *buf->b_p_ff)
return TRUE;
if ((buf->b_p_bin || !buf->b_p_fixeol) && buf->b_start_eol != buf->b_p_eol)
return TRUE;
#ifdef FEAT_MBYTE
if (!buf->b_p_bin && buf->b_start_bomb != buf->b_p_bomb)
return TRUE;
if (buf->b_start_fenc == NULL)
return (*buf->b_p_fenc != NUL);
return (STRCMP(buf->b_start_fenc, buf->b_p_fenc) != 0);
#else
return FALSE;
#endif
}
/*
* return OK if "p" is a valid fileformat name, FAIL otherwise.
*/
int
check_ff_value(char_u *p)
{
return check_opt_strings(p, p_ff_values, FALSE);
}
/*
* Return the effective shiftwidth value for current buffer, using the
* 'tabstop' value when 'shiftwidth' is zero.
*/
long
get_sw_value(buf_T *buf)
{
return buf->b_p_sw ? buf->b_p_sw : buf->b_p_ts;
}
/*
* Return the effective softtabstop value for the current buffer, using the
* 'tabstop' value when 'softtabstop' is negative.
*/
long
get_sts_value(void)
{
return curbuf->b_p_sts < 0 ? get_sw_value(curbuf) : curbuf->b_p_sts;
}
/*
* Check matchpairs option for "*initc".
* If there is a match set "*initc" to the matching character and "*findc" to
* the opposite character. Set "*backwards" to the direction.
* When "switchit" is TRUE swap the direction.
*/
void
find_mps_values(
int *initc,
int *findc,
int *backwards,
int switchit)
{
char_u *ptr;
ptr = curbuf->b_p_mps;
while (*ptr != NUL)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
{
char_u *prev;
if (mb_ptr2char(ptr) == *initc)
{
if (switchit)
{
*findc = *initc;
*initc = mb_ptr2char(ptr + mb_ptr2len(ptr) + 1);
*backwards = TRUE;
}
else
{
*findc = mb_ptr2char(ptr + mb_ptr2len(ptr) + 1);
*backwards = FALSE;
}
return;
}
prev = ptr;
ptr += mb_ptr2len(ptr) + 1;
if (mb_ptr2char(ptr) == *initc)
{
if (switchit)
{
*findc = *initc;
*initc = mb_ptr2char(prev);
*backwards = FALSE;
}
else
{
*findc = mb_ptr2char(prev);
*backwards = TRUE;
}
return;
}
ptr += mb_ptr2len(ptr);
}
else
#endif
{
if (*ptr == *initc)
{
if (switchit)
{
*backwards = TRUE;
*findc = *initc;
*initc = ptr[2];
}
else
{
*backwards = FALSE;
*findc = ptr[2];
}
return;
}
ptr += 2;
if (*ptr == *initc)
{
if (switchit)
{
*backwards = FALSE;
*findc = *initc;
*initc = ptr[-2];
}
else
{
*backwards = TRUE;
*findc = ptr[-2];
}
return;
}
++ptr;
}
if (*ptr == ',')
++ptr;
}
}
#if defined(FEAT_LINEBREAK) || defined(PROTO)
/*
* This is called when 'breakindentopt' is changed and when a window is
* initialized.
*/
static int
briopt_check(win_T *wp)
{
char_u *p;
int bri_shift = 0;
long bri_min = 20;
int bri_sbr = FALSE;
p = wp->w_p_briopt;
while (*p != NUL)
{
if (STRNCMP(p, "shift:", 6) == 0
&& ((p[6] == '-' && VIM_ISDIGIT(p[7])) || VIM_ISDIGIT(p[6])))
{
p += 6;
bri_shift = getdigits(&p);
}
else if (STRNCMP(p, "min:", 4) == 0 && VIM_ISDIGIT(p[4]))
{
p += 4;
bri_min = getdigits(&p);
}
else if (STRNCMP(p, "sbr", 3) == 0)
{
p += 3;
bri_sbr = TRUE;
}
if (*p != ',' && *p != NUL)
return FAIL;
if (*p == ',')
++p;
}
wp->w_p_brishift = bri_shift;
wp->w_p_brimin = bri_min;
wp->w_p_brisbr = bri_sbr;
return OK;
}
#endif
/*
* Get the local or global value of 'backupcopy'.
*/
unsigned int
get_bkc_value(buf_T *buf)
{
return buf->b_bkc_flags ? buf->b_bkc_flags : bkc_flags;
}
#if defined(FEAT_SIGNS) || defined(PROTO)
/*
* Return TRUE when window "wp" has a column to draw signs in.
*/
int
signcolumn_on(win_T *wp)
{
if (*wp->w_p_scl == 'n')
return FALSE;
if (*wp->w_p_scl == 'y')
return TRUE;
return (wp->w_buffer->b_signlist != NULL
# ifdef FEAT_NETBEANS_INTG
|| wp->w_buffer->b_has_sign_column
# endif
);
}
#endif
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Get window or buffer local options.
*/
dict_T *
get_winbuf_options(int bufopt)
{
dict_T *d;
int opt_idx;
d = dict_alloc();
if (d == NULL)
return NULL;
for (opt_idx = 0; !istermoption(&options[opt_idx]); opt_idx++)
{
struct vimoption *opt = &options[opt_idx];
if ((bufopt && (opt->indir & PV_BUF))
|| (!bufopt && (opt->indir & PV_WIN)))
{
char_u *varp = get_varp(opt);
if (varp != NULL)
{
if (opt->flags & P_STRING)
dict_add_nr_str(d, opt->fullname, 0L, *(char_u **)varp);
else if (opt->flags & P_NUM)
dict_add_nr_str(d, opt->fullname, *(long *)varp, NULL);
else
dict_add_nr_str(d, opt->fullname, *(int *)varp, NULL);
}
}
}
return d;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_4900_0 |
crossvul-cpp_data_good_4701_2 | /*
server.c : irssi
Copyright (C) 1999-2000 Timo Sirainen
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "module.h"
#include "signals.h"
#include "commands.h"
#include "net-disconnect.h"
#include "net-nonblock.h"
#include "net-sendbuffer.h"
#include "misc.h"
#include "rawlog.h"
#include "settings.h"
#include "chat-protocols.h"
#include "servers.h"
#include "servers-reconnect.h"
#include "servers-setup.h"
#include "channels.h"
#include "queries.h"
GSList *servers, *lookup_servers;
/* connection to server failed */
void server_connect_failed(SERVER_REC *server, const char *msg)
{
g_return_if_fail(IS_SERVER(server));
lookup_servers = g_slist_remove(lookup_servers, server);
signal_emit("server connect failed", 2, server, msg);
if (server->connect_tag != -1) {
g_source_remove(server->connect_tag);
server->connect_tag = -1;
}
if (server->handle != NULL) {
net_sendbuffer_destroy(server->handle, TRUE);
server->handle = NULL;
}
if (server->connect_pipe[0] != NULL) {
g_io_channel_close(server->connect_pipe[0]);
g_io_channel_unref(server->connect_pipe[0]);
g_io_channel_close(server->connect_pipe[1]);
g_io_channel_unref(server->connect_pipe[1]);
server->connect_pipe[0] = NULL;
server->connect_pipe[1] = NULL;
}
server_unref(server);
}
/* generate tag from server's address */
static char *server_create_address_tag(const char *address)
{
const char *start, *end;
g_return_val_if_fail(address != NULL, NULL);
/* try to generate a reasonable server tag */
if (strchr(address, '.') == NULL) {
start = end = NULL;
} else if (g_ascii_strncasecmp(address, "irc", 3) == 0 ||
g_ascii_strncasecmp(address, "chat", 4) == 0) {
/* irc-2.cs.hut.fi -> hut, chat.bt.net -> bt */
end = strrchr(address, '.');
start = end-1;
while (start > address && *start != '.') start--;
} else {
/* efnet.cs.hut.fi -> efnet */
end = strchr(address, '.');
start = end;
}
if (start == end) start = address; else start++;
if (end == NULL) end = address + strlen(address);
return g_strndup(start, (int) (end-start));
}
/* create unique tag for server. prefer ircnet's name or
generate it from server's address */
static char *server_create_tag(SERVER_CONNECT_REC *conn)
{
GString *str;
char *tag;
int num;
g_return_val_if_fail(IS_SERVER_CONNECT(conn), NULL);
tag = conn->chatnet != NULL && *conn->chatnet != '\0' ?
g_strdup(conn->chatnet) :
server_create_address_tag(conn->address);
if (conn->tag != NULL && server_find_tag(conn->tag) == NULL &&
server_find_lookup_tag(conn->tag) == NULL &&
strncmp(conn->tag, tag, strlen(tag)) == 0) {
/* use the existing tag if it begins with the same ID -
this is useful when you have several connections to
same server and you want to keep the same tags with
the servers (or it would cause problems when rejoining
/LAYOUT SAVEd channels). */
g_free(tag);
return g_strdup(conn->tag);
}
/* then just append numbers after tag until unused is found.. */
str = g_string_new(tag);
num = 2;
while (server_find_tag(str->str) != NULL ||
server_find_lookup_tag(str->str) != NULL) {
g_string_printf(str, "%s%d", tag, num);
num++;
}
g_free(tag);
tag = str->str;
g_string_free(str, FALSE);
return tag;
}
/* Connection to server finished, fill the rest of the fields */
void server_connect_finished(SERVER_REC *server)
{
server->connect_time = time(NULL);
servers = g_slist_append(servers, server);
signal_emit("server connected", 1, server);
}
static void server_connect_callback_init(SERVER_REC *server, GIOChannel *handle)
{
int error;
g_return_if_fail(IS_SERVER(server));
error = net_geterror(handle);
if (error != 0) {
server->connection_lost = TRUE;
server_connect_failed(server, g_strerror(error));
return;
}
lookup_servers = g_slist_remove(lookup_servers, server);
g_source_remove(server->connect_tag);
server->connect_tag = -1;
server_connect_finished(server);
}
#ifdef HAVE_OPENSSL
static void server_connect_callback_init_ssl(SERVER_REC *server, GIOChannel *handle)
{
int error;
g_return_if_fail(IS_SERVER(server));
error = irssi_ssl_handshake(handle);
if (error == -1) {
server->connection_lost = TRUE;
server_connect_failed(server, NULL);
return;
}
if (error & 1) {
if (server->connect_tag != -1)
g_source_remove(server->connect_tag);
server->connect_tag = g_input_add(handle, error == 1 ? G_INPUT_READ : G_INPUT_WRITE,
(GInputFunction)
server_connect_callback_init_ssl,
server);
return;
}
lookup_servers = g_slist_remove(lookup_servers, server);
if (server->connect_tag != -1) {
g_source_remove(server->connect_tag);
server->connect_tag = -1;
}
server_connect_finished(server);
}
#endif
static void server_real_connect(SERVER_REC *server, IPADDR *ip,
const char *unix_socket)
{
GIOChannel *handle;
IPADDR *own_ip = NULL;
const char *errmsg;
char *errmsg2;
char ipaddr[MAX_IP_LEN];
int port;
g_return_if_fail(ip != NULL || unix_socket != NULL);
signal_emit("server connecting", 2, server, ip);
if (server->connrec->no_connect)
return;
if (ip != NULL) {
own_ip = ip == NULL ? NULL :
(IPADDR_IS_V6(ip) ? server->connrec->own_ip6 :
server->connrec->own_ip4);
port = server->connrec->proxy != NULL ?
server->connrec->proxy_port : server->connrec->port;
handle = server->connrec->use_ssl ?
net_connect_ip_ssl(ip, port, server->connrec->address, own_ip, server->connrec->ssl_cert, server->connrec->ssl_pkey,
server->connrec->ssl_cafile, server->connrec->ssl_capath, server->connrec->ssl_verify) :
net_connect_ip(ip, port, own_ip);
} else {
handle = net_connect_unix(unix_socket);
}
if (handle == NULL) {
/* failed */
errmsg = g_strerror(errno);
errmsg2 = NULL;
if (errno == EADDRNOTAVAIL) {
if (own_ip != NULL) {
/* show the IP which is causing the error */
net_ip2host(own_ip, ipaddr);
errmsg2 = g_strconcat(errmsg, ": ", ipaddr, NULL);
}
server->no_reconnect = TRUE;
}
if (server->connrec->use_ssl && errno == ENOSYS)
server->no_reconnect = TRUE;
server->connection_lost = TRUE;
server_connect_failed(server, errmsg2 ? errmsg2 : errmsg);
g_free(errmsg2);
} else {
server->handle = net_sendbuffer_create(handle, 0);
#ifdef HAVE_OPENSSL
if (server->connrec->use_ssl)
server_connect_callback_init_ssl(server, handle);
else
#endif
server->connect_tag =
g_input_add(handle, G_INPUT_WRITE | G_INPUT_READ,
(GInputFunction)
server_connect_callback_init,
server);
}
}
static void server_connect_callback_readpipe(SERVER_REC *server)
{
RESOLVED_IP_REC iprec;
IPADDR *ip;
const char *errormsg;
char *servername = NULL;
g_source_remove(server->connect_tag);
server->connect_tag = -1;
net_gethostbyname_return(server->connect_pipe[0], &iprec);
g_io_channel_close(server->connect_pipe[0]);
g_io_channel_unref(server->connect_pipe[0]);
g_io_channel_close(server->connect_pipe[1]);
g_io_channel_unref(server->connect_pipe[1]);
server->connect_pipe[0] = NULL;
server->connect_pipe[1] = NULL;
/* figure out if we should use IPv4 or v6 address */
if (iprec.error != 0) {
/* error */
ip = NULL;
} else if (server->connrec->family == AF_INET) {
/* force IPv4 connection */
ip = iprec.ip4.family == 0 ? NULL : &iprec.ip4;
servername = iprec.host4;
} else if (server->connrec->family == AF_INET6) {
/* force IPv6 connection */
ip = iprec.ip6.family == 0 ? NULL : &iprec.ip6;
servername = iprec.host6;
} else {
/* pick the one that was found, or if both do it like
/SET resolve_prefer_ipv6 says. */
if (iprec.ip4.family == 0 ||
(iprec.ip6.family != 0 &&
settings_get_bool("resolve_prefer_ipv6"))) {
ip = &iprec.ip6;
servername = iprec.host6;
} else {
ip = &iprec.ip4;
servername = iprec.host4;
}
}
if (ip != NULL) {
/* host lookup ok */
if (servername) {
g_free(server->connrec->address);
server->connrec->address = g_strdup(servername);
}
server_real_connect(server, ip, NULL);
errormsg = NULL;
} else {
if (iprec.error == 0 || net_hosterror_notfound(iprec.error)) {
/* IP wasn't found for the host, don't try to
reconnect back to this server */
server->dns_error = TRUE;
}
if (iprec.error == 0) {
/* forced IPv4 or IPv6 address but it wasn't found */
errormsg = server->connrec->family == AF_INET ?
"IPv4 address not found for host" :
"IPv6 address not found for host";
} else {
/* gethostbyname() failed */
errormsg = iprec.errorstr != NULL ? iprec.errorstr :
"Host lookup failed";
}
server->connection_lost = TRUE;
server_connect_failed(server, errormsg);
}
g_free(iprec.errorstr);
g_free(iprec.host4);
g_free(iprec.host6);
}
SERVER_REC *server_connect(SERVER_CONNECT_REC *conn)
{
CHAT_PROTOCOL_REC *proto;
SERVER_REC *server;
proto = CHAT_PROTOCOL(conn);
server = proto->server_init_connect(conn);
proto->server_connect(server);
return server;
}
/* initializes server record but doesn't start connecting */
void server_connect_init(SERVER_REC *server)
{
const char *str;
g_return_if_fail(server != NULL);
MODULE_DATA_INIT(server);
server->type = module_get_uniq_id("SERVER", 0);
server_ref(server);
server->nick = g_strdup(server->connrec->nick);
if (server->connrec->username == NULL || *server->connrec->username == '\0') {
g_free_not_null(server->connrec->username);
str = g_get_user_name();
if (*str == '\0') str = "unknown";
server->connrec->username = g_strdup(str);
}
if (server->connrec->realname == NULL || *server->connrec->realname == '\0') {
g_free_not_null(server->connrec->realname);
str = g_get_real_name();
if (*str == '\0') str = server->connrec->username;
server->connrec->realname = g_strdup(str);
}
server->tag = server_create_tag(server->connrec);
server->connect_tag = -1;
}
/* starts connecting to server */
int server_start_connect(SERVER_REC *server)
{
const char *connect_address;
int fd[2];
g_return_val_if_fail(server != NULL, FALSE);
if (!server->connrec->unix_socket && server->connrec->port <= 0)
return FALSE;
server->rawlog = rawlog_create();
if (server->connrec->connect_handle != NULL) {
/* already connected */
GIOChannel *handle = server->connrec->connect_handle;
server->connrec->connect_handle = NULL;
server->handle = net_sendbuffer_create(handle, 0);
server_connect_finished(server);
} else if (server->connrec->unix_socket) {
/* connect with unix socket */
server_real_connect(server, NULL, server->connrec->address);
} else {
/* resolve host name */
if (pipe(fd) != 0) {
g_warning("server_connect(): pipe() failed.");
g_free(server->tag);
g_free(server->nick);
return FALSE;
}
server->connect_pipe[0] = g_io_channel_unix_new(fd[0]);
server->connect_pipe[1] = g_io_channel_unix_new(fd[1]);
connect_address = server->connrec->proxy != NULL ?
server->connrec->proxy : server->connrec->address;
server->connect_pid =
net_gethostbyname_nonblock(connect_address,
server->connect_pipe[1],
settings_get_bool("resolve_reverse_lookup"));
server->connect_tag =
g_input_add(server->connect_pipe[0], G_INPUT_READ,
(GInputFunction)
server_connect_callback_readpipe,
server);
lookup_servers = g_slist_append(lookup_servers, server);
signal_emit("server looking", 1, server);
}
return TRUE;
}
static int server_remove_channels(SERVER_REC *server)
{
GSList *tmp, *next;
int found;
g_return_val_if_fail(server != NULL, FALSE);
found = FALSE;
for (tmp = server->channels; tmp != NULL; tmp = next) {
CHANNEL_REC *channel = tmp->data;
next = tmp->next;
channel_destroy(channel);
found = TRUE;
}
while (server->queries != NULL)
query_change_server(server->queries->data, NULL);
g_slist_free(server->channels);
g_slist_free(server->queries);
return found;
}
void server_disconnect(SERVER_REC *server)
{
int chans;
g_return_if_fail(IS_SERVER(server));
if (server->disconnected)
return;
if (server->connect_tag != -1) {
/* still connecting to server.. */
if (server->connect_pid != -1)
net_disconnect_nonblock(server->connect_pid);
server_connect_failed(server, NULL);
return;
}
servers = g_slist_remove(servers, server);
server->disconnected = TRUE;
signal_emit("server disconnected", 1, server);
/* close all channels */
chans = server_remove_channels(server);
if (server->handle != NULL) {
if (!chans || server->connection_lost)
net_sendbuffer_destroy(server->handle, TRUE);
else {
/* we were on some channels, try to let the server
disconnect so that our quit message is guaranteed
to get displayed */
net_disconnect_later(net_sendbuffer_handle(server->handle));
net_sendbuffer_destroy(server->handle, FALSE);
}
server->handle = NULL;
}
if (server->readtag > 0) {
g_source_remove(server->readtag);
server->readtag = -1;
}
server_unref(server);
}
void server_ref(SERVER_REC *server)
{
g_return_if_fail(IS_SERVER(server));
server->refcount++;
}
int server_unref(SERVER_REC *server)
{
g_return_val_if_fail(IS_SERVER(server), FALSE);
if (--server->refcount > 0)
return TRUE;
if (g_slist_find(servers, server) != NULL) {
g_warning("Non-referenced server wasn't disconnected");
server_disconnect(server);
return TRUE;
}
MODULE_DATA_DEINIT(server);
server_connect_unref(server->connrec);
if (server->rawlog != NULL) rawlog_destroy(server->rawlog);
g_free(server->version);
g_free(server->away_reason);
g_free(server->nick);
g_free(server->tag);
server->type = 0;
g_free(server);
return FALSE;
}
SERVER_REC *server_find_tag(const char *tag)
{
GSList *tmp;
g_return_val_if_fail(tag != NULL, NULL);
if (*tag == '\0') return NULL;
for (tmp = servers; tmp != NULL; tmp = tmp->next) {
SERVER_REC *server = tmp->data;
if (g_strcasecmp(server->tag, tag) == 0)
return server;
}
return NULL;
}
SERVER_REC *server_find_lookup_tag(const char *tag)
{
GSList *tmp;
g_return_val_if_fail(tag != NULL, NULL);
if (*tag == '\0') return NULL;
for (tmp = lookup_servers; tmp != NULL; tmp = tmp->next) {
SERVER_REC *server = tmp->data;
if (g_strcasecmp(server->tag, tag) == 0)
return server;
}
return NULL;
}
SERVER_REC *server_find_chatnet(const char *chatnet)
{
GSList *tmp;
g_return_val_if_fail(chatnet != NULL, NULL);
if (*chatnet == '\0') return NULL;
for (tmp = servers; tmp != NULL; tmp = tmp->next) {
SERVER_REC *server = tmp->data;
if (server->connrec->chatnet != NULL &&
g_strcasecmp(server->connrec->chatnet, chatnet) == 0)
return server;
}
return NULL;
}
void server_connect_ref(SERVER_CONNECT_REC *conn)
{
conn->refcount++;
}
void server_connect_unref(SERVER_CONNECT_REC *conn)
{
g_return_if_fail(IS_SERVER_CONNECT(conn));
if (--conn->refcount > 0)
return;
if (conn->refcount < 0) {
g_warning("Connection '%s' refcount = %d",
conn->tag, conn->refcount);
}
CHAT_PROTOCOL(conn)->destroy_server_connect(conn);
if (conn->connect_handle != NULL)
net_disconnect(conn->connect_handle);
g_free_not_null(conn->proxy);
g_free_not_null(conn->proxy_string);
g_free_not_null(conn->proxy_string_after);
g_free_not_null(conn->proxy_password);
g_free_not_null(conn->tag);
g_free_not_null(conn->address);
g_free_not_null(conn->chatnet);
g_free_not_null(conn->own_ip4);
g_free_not_null(conn->own_ip6);
g_free_not_null(conn->password);
g_free_not_null(conn->nick);
g_free_not_null(conn->username);
g_free_not_null(conn->realname);
g_free_not_null(conn->ssl_cert);
g_free_not_null(conn->ssl_pkey);
g_free_not_null(conn->ssl_cafile);
g_free_not_null(conn->ssl_capath);
g_free_not_null(conn->channels);
g_free_not_null(conn->away_reason);
conn->type = 0;
g_free(conn);
}
void server_change_nick(SERVER_REC *server, const char *nick)
{
g_free(server->nick);
server->nick = g_strdup(nick);
signal_emit("server nick changed", 1, server);
}
/* Update own IPv4 and IPv6 records */
void server_connect_own_ip_save(SERVER_CONNECT_REC *conn,
IPADDR *ip4, IPADDR *ip6)
{
if (ip4 == NULL || ip4->family == 0)
g_free_and_null(conn->own_ip4);
if (ip6 == NULL || ip6->family == 0)
g_free_and_null(conn->own_ip6);
if (ip4 != NULL && ip4->family != 0) {
/* IPv4 address was found */
if (conn->own_ip4 == NULL)
conn->own_ip4 = g_new0(IPADDR, 1);
memcpy(conn->own_ip4, ip4, sizeof(IPADDR));
}
if (ip6 != NULL && ip6->family != 0) {
/* IPv6 address was found */
if (conn->own_ip6 == NULL)
conn->own_ip6 = g_new0(IPADDR, 1);
memcpy(conn->own_ip6, ip6, sizeof(IPADDR));
}
}
/* `optlist' should contain only one unknown key - the server tag.
returns NULL if there was unknown -option */
SERVER_REC *cmd_options_get_server(const char *cmd,
GHashTable *optlist,
SERVER_REC *defserver)
{
SERVER_REC *server;
GSList *list, *tmp, *next;
/* get all the options, then remove the known ones. there should
be only one left - the server tag. */
list = hashtable_get_keys(optlist);
if (cmd != NULL) {
for (tmp = list; tmp != NULL; tmp = next) {
char *option = tmp->data;
next = tmp->next;
if (command_have_option(cmd, option))
list = g_slist_remove(list, option);
}
}
if (list == NULL)
return defserver;
server = server_find_tag(list->data);
if (server == NULL || list->next != NULL) {
/* unknown option (not server tag) */
signal_emit("error command", 2,
GINT_TO_POINTER(CMDERR_OPTION_UNKNOWN),
server == NULL ? list->data : list->next->data);
signal_stop();
server = NULL;
}
g_slist_free(list);
return server;
}
static void disconnect_servers(GSList *servers, int chat_type)
{
GSList *tmp, *next;
for (tmp = servers; tmp != NULL; tmp = next) {
SERVER_REC *rec = tmp->data;
next = tmp->next;
if (rec->chat_type == chat_type)
server_disconnect(rec);
}
}
static void sig_chat_protocol_deinit(CHAT_PROTOCOL_REC *proto)
{
disconnect_servers(servers, proto->id);
disconnect_servers(lookup_servers, proto->id);
}
void servers_init(void)
{
settings_add_bool("server", "resolve_prefer_ipv6", FALSE);
settings_add_bool("server", "resolve_reverse_lookup", FALSE);
lookup_servers = servers = NULL;
signal_add("chat protocol deinit", (SIGNAL_FUNC) sig_chat_protocol_deinit);
servers_reconnect_init();
servers_setup_init();
}
void servers_deinit(void)
{
signal_remove("chat protocol deinit", (SIGNAL_FUNC) sig_chat_protocol_deinit);
servers_setup_deinit();
servers_reconnect_deinit();
module_uniq_destroy("SERVER");
module_uniq_destroy("SERVER CONNECT");
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_4701_2 |
crossvul-cpp_data_bad_2214_0 | /*
* LZ4 Decompressor for Linux kernel
*
* Copyright (C) 2013, LG Electronics, Kyungsik Lee <kyungsik.lee@lge.com>
*
* Based on LZ4 implementation by Yann Collet.
*
* LZ4 - Fast LZ compression algorithm
* Copyright (C) 2011-2012, Yann Collet.
* BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You can contact the author at :
* - LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html
* - LZ4 source repository : http://code.google.com/p/lz4/
*/
#ifndef STATIC
#include <linux/module.h>
#include <linux/kernel.h>
#endif
#include <linux/lz4.h>
#include <asm/unaligned.h>
#include "lz4defs.h"
static int lz4_uncompress(const char *source, char *dest, int osize)
{
const BYTE *ip = (const BYTE *) source;
const BYTE *ref;
BYTE *op = (BYTE *) dest;
BYTE * const oend = op + osize;
BYTE *cpy;
unsigned token;
size_t length;
size_t dec32table[] = {0, 3, 2, 3, 0, 0, 0, 0};
#if LZ4_ARCH64
size_t dec64table[] = {0, 0, 0, -1, 0, 1, 2, 3};
#endif
while (1) {
/* get runlength */
token = *ip++;
length = (token >> ML_BITS);
if (length == RUN_MASK) {
size_t len;
len = *ip++;
for (; len == 255; length += 255)
len = *ip++;
length += len;
}
/* copy literals */
cpy = op + length;
if (unlikely(cpy > oend - COPYLENGTH)) {
/*
* Error: not enough place for another match
* (min 4) + 5 literals
*/
if (cpy != oend)
goto _output_error;
memcpy(op, ip, length);
ip += length;
break; /* EOF */
}
LZ4_WILDCOPY(ip, op, cpy);
ip -= (op - cpy);
op = cpy;
/* get offset */
LZ4_READ_LITTLEENDIAN_16(ref, cpy, ip);
ip += 2;
/* Error: offset create reference outside destination buffer */
if (unlikely(ref < (BYTE *const) dest))
goto _output_error;
/* get matchlength */
length = token & ML_MASK;
if (length == ML_MASK) {
for (; *ip == 255; length += 255)
ip++;
length += *ip++;
}
/* copy repeated sequence */
if (unlikely((op - ref) < STEPSIZE)) {
#if LZ4_ARCH64
size_t dec64 = dec64table[op - ref];
#else
const int dec64 = 0;
#endif
op[0] = ref[0];
op[1] = ref[1];
op[2] = ref[2];
op[3] = ref[3];
op += 4;
ref += 4;
ref -= dec32table[op-ref];
PUT4(ref, op);
op += STEPSIZE - 4;
ref -= dec64;
} else {
LZ4_COPYSTEP(ref, op);
}
cpy = op + length - (STEPSIZE - 4);
if (cpy > (oend - COPYLENGTH)) {
/* Error: request to write beyond destination buffer */
if (cpy > oend)
goto _output_error;
LZ4_SECURECOPY(ref, op, (oend - COPYLENGTH));
while (op < cpy)
*op++ = *ref++;
op = cpy;
/*
* Check EOF (should never happen, since last 5 bytes
* are supposed to be literals)
*/
if (op == oend)
goto _output_error;
continue;
}
LZ4_SECURECOPY(ref, op, cpy);
op = cpy; /* correction */
}
/* end of decoding */
return (int) (((char *)ip) - source);
/* write overflow error detected */
_output_error:
return (int) (-(((char *)ip) - source));
}
static int lz4_uncompress_unknownoutputsize(const char *source, char *dest,
int isize, size_t maxoutputsize)
{
const BYTE *ip = (const BYTE *) source;
const BYTE *const iend = ip + isize;
const BYTE *ref;
BYTE *op = (BYTE *) dest;
BYTE * const oend = op + maxoutputsize;
BYTE *cpy;
size_t dec32table[] = {0, 3, 2, 3, 0, 0, 0, 0};
#if LZ4_ARCH64
size_t dec64table[] = {0, 0, 0, -1, 0, 1, 2, 3};
#endif
/* Main Loop */
while (ip < iend) {
unsigned token;
size_t length;
/* get runlength */
token = *ip++;
length = (token >> ML_BITS);
if (length == RUN_MASK) {
int s = 255;
while ((ip < iend) && (s == 255)) {
s = *ip++;
length += s;
}
}
/* copy literals */
cpy = op + length;
if ((cpy > oend - COPYLENGTH) ||
(ip + length > iend - COPYLENGTH)) {
if (cpy > oend)
goto _output_error;/* writes beyond buffer */
if (ip + length != iend)
goto _output_error;/*
* Error: LZ4 format requires
* to consume all input
* at this stage
*/
memcpy(op, ip, length);
op += length;
break;/* Necessarily EOF, due to parsing restrictions */
}
LZ4_WILDCOPY(ip, op, cpy);
ip -= (op - cpy);
op = cpy;
/* get offset */
LZ4_READ_LITTLEENDIAN_16(ref, cpy, ip);
ip += 2;
if (ref < (BYTE * const) dest)
goto _output_error;
/*
* Error : offset creates reference
* outside of destination buffer
*/
/* get matchlength */
length = (token & ML_MASK);
if (length == ML_MASK) {
while (ip < iend) {
int s = *ip++;
length += s;
if (s == 255)
continue;
break;
}
}
/* copy repeated sequence */
if (unlikely((op - ref) < STEPSIZE)) {
#if LZ4_ARCH64
size_t dec64 = dec64table[op - ref];
#else
const int dec64 = 0;
#endif
op[0] = ref[0];
op[1] = ref[1];
op[2] = ref[2];
op[3] = ref[3];
op += 4;
ref += 4;
ref -= dec32table[op - ref];
PUT4(ref, op);
op += STEPSIZE - 4;
ref -= dec64;
} else {
LZ4_COPYSTEP(ref, op);
}
cpy = op + length - (STEPSIZE-4);
if (cpy > oend - COPYLENGTH) {
if (cpy > oend)
goto _output_error; /* write outside of buf */
LZ4_SECURECOPY(ref, op, (oend - COPYLENGTH));
while (op < cpy)
*op++ = *ref++;
op = cpy;
/*
* Check EOF (should never happen, since last 5 bytes
* are supposed to be literals)
*/
if (op == oend)
goto _output_error;
continue;
}
LZ4_SECURECOPY(ref, op, cpy);
op = cpy; /* correction */
}
/* end of decoding */
return (int) (((char *) op) - dest);
/* write overflow error detected */
_output_error:
return (int) (-(((char *) ip) - source));
}
int lz4_decompress(const unsigned char *src, size_t *src_len,
unsigned char *dest, size_t actual_dest_len)
{
int ret = -1;
int input_len = 0;
input_len = lz4_uncompress(src, dest, actual_dest_len);
if (input_len < 0)
goto exit_0;
*src_len = input_len;
return 0;
exit_0:
return ret;
}
#ifndef STATIC
EXPORT_SYMBOL(lz4_decompress);
#endif
int lz4_decompress_unknownoutputsize(const unsigned char *src, size_t src_len,
unsigned char *dest, size_t *dest_len)
{
int ret = -1;
int out_len = 0;
out_len = lz4_uncompress_unknownoutputsize(src, dest, src_len,
*dest_len);
if (out_len < 0)
goto exit_0;
*dest_len = out_len;
return 0;
exit_0:
return ret;
}
#ifndef STATIC
EXPORT_SYMBOL(lz4_decompress_unknownoutputsize);
MODULE_LICENSE("Dual BSD/GPL");
MODULE_DESCRIPTION("LZ4 Decompressor");
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2214_0 |
crossvul-cpp_data_bad_2738_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% JJJ PPPP 222 %
% J P P 2 2 %
% J PPPP 22 %
% J J P 2 %
% JJ P 22222 %
% %
% %
% Read/Write JPEG-2000 Image Format %
% %
% Cristy %
% Nathan Brown %
% June 2001 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/semaphore.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/module.h"
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
#include <openjpeg.h>
#endif
/*
Forward declarations.
*/
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
static MagickBooleanType
WriteJP2Image(const ImageInfo *,Image *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s J 2 K %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsJ2K() returns MagickTrue if the image format type, identified by the
% magick string, is J2K.
%
% The format of the IsJ2K method is:
%
% MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\xff\x4f\xff\x51",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s J P 2 %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsJP2() returns MagickTrue if the image format type, identified by the
% magick string, is JP2.
%
% The format of the IsJP2 method is:
%
% MagickBooleanType IsJP2(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsJP2(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\x0d\x0a\x87\x0a",4) == 0)
return(MagickTrue);
if (length < 12)
return(MagickFalse);
if (memcmp(magick,"\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a",12) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d J P 2 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadJP2Image() reads a JPEG 2000 Image file (JP2) or JPEG 2000
% codestream (JPC) image file and returns it. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image or set of images.
%
% JP2 support is originally written by Nathan Brown, nathanbrown@letu.edu.
%
% The format of the ReadJP2Image method is:
%
% Image *ReadJP2Image(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
static void JP2ErrorHandler(const char *message,void *client_data)
{
ExceptionInfo
*exception;
exception=(ExceptionInfo *) client_data;
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
message,"`%s'","OpenJP2");
}
static OPJ_SIZE_T JP2ReadHandler(void *buffer,OPJ_SIZE_T length,void *context)
{
Image
*image;
ssize_t
count;
image=(Image *) context;
count=ReadBlob(image,(ssize_t) length,(unsigned char *) buffer);
if (count == 0)
return((OPJ_SIZE_T) -1);
return((OPJ_SIZE_T) count);
}
static OPJ_BOOL JP2SeekHandler(OPJ_OFF_T offset,void *context)
{
Image
*image;
image=(Image *) context;
return(SeekBlob(image,offset,SEEK_SET) < 0 ? OPJ_FALSE : OPJ_TRUE);
}
static OPJ_OFF_T JP2SkipHandler(OPJ_OFF_T offset,void *context)
{
Image
*image;
image=(Image *) context;
return(SeekBlob(image,offset,SEEK_CUR) < 0 ? -1 : offset);
}
static void JP2WarningHandler(const char *message,void *client_data)
{
ExceptionInfo
*exception;
exception=(ExceptionInfo *) client_data;
(void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
message,"`%s'","OpenJP2");
}
static OPJ_SIZE_T JP2WriteHandler(void *buffer,OPJ_SIZE_T length,void *context)
{
Image
*image;
ssize_t
count;
image=(Image *) context;
count=WriteBlob(image,(ssize_t) length,(unsigned char *) buffer);
return((OPJ_SIZE_T) count);
}
static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception)
{
const char
*option;
Image
*image;
int
jp2_status;
MagickBooleanType
status;
opj_codec_t
*jp2_codec;
opj_codestream_index_t
*codestream_index = (opj_codestream_index_t *) NULL;
opj_dparameters_t
parameters;
opj_image_t
*jp2_image;
opj_stream_t
*jp2_stream;
register ssize_t
i;
ssize_t
y;
unsigned char
sans[4];
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize JP2 codec.
*/
if (ReadBlob(image,4,sans) != 4)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) SeekBlob(image,SEEK_SET,0);
if (LocaleCompare(image_info->magick,"JPT") == 0)
jp2_codec=opj_create_decompress(OPJ_CODEC_JPT);
else
if (IsJ2K(sans,4) != MagickFalse)
jp2_codec=opj_create_decompress(OPJ_CODEC_J2K);
else
jp2_codec=opj_create_decompress(OPJ_CODEC_JP2);
opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
opj_set_default_decoder_parameters(¶meters);
option=GetImageOption(image_info,"jp2:reduce-factor");
if (option != (const char *) NULL)
parameters.cp_reduce=StringToInteger(option);
option=GetImageOption(image_info,"jp2:quality-layers");
if (option == (const char *) NULL)
option=GetImageOption(image_info,"jp2:layer-number");
if (option != (const char *) NULL)
parameters.cp_layer=StringToInteger(option);
if (opj_setup_decoder(jp2_codec,¶meters) == 0)
{
opj_destroy_codec(jp2_codec);
ThrowReaderException(DelegateError,"UnableToManageJP2Stream");
}
jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE);
opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
opj_stream_set_user_data(jp2_stream,image,NULL);
opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image));
if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
jp2_status=1;
if ((image->columns != 0) && (image->rows != 0))
{
/*
Extract an area from the image.
*/
jp2_status=opj_set_decode_area(jp2_codec,jp2_image,
(OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y,
(OPJ_INT32) image->extract_info.x+(ssize_t) image->columns,
(OPJ_INT32) image->extract_info.y+(ssize_t) image->rows);
if (jp2_status == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
}
if ((image_info->number_scenes != 0) && (image_info->scene != 0))
jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image,
(unsigned int) image_info->scene-1);
else
if (image->ping == MagickFalse)
{
jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image);
if (jp2_status != 0)
jp2_status=opj_end_decompress(jp2_codec,jp2_stream);
}
if (jp2_status == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
opj_stream_destroy(jp2_stream);
for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
{
if ((jp2_image->comps[0].dx == 0) || (jp2_image->comps[0].dy == 0) ||
(jp2_image->comps[0].dx != jp2_image->comps[i].dx) ||
(jp2_image->comps[0].dy != jp2_image->comps[i].dy) ||
(jp2_image->comps[0].prec != jp2_image->comps[i].prec) ||
(jp2_image->comps[0].sgnd != jp2_image->comps[i].sgnd))
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported")
}
}
/*
Convert JP2 image.
*/
image->columns=(size_t) jp2_image->comps[0].w;
image->rows=(size_t) jp2_image->comps[0].h;
image->depth=jp2_image->comps[0].prec;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->compression=JPEG2000Compression;
if (jp2_image->color_space == 2)
{
SetImageColorspace(image,GRAYColorspace);
if (jp2_image->numcomps > 1)
image->matte=MagickTrue;
}
else
if (jp2_image->color_space == 3)
SetImageColorspace(image,Rec601YCbCrColorspace);
if (jp2_image->numcomps > 3)
image->matte=MagickTrue;
if (jp2_image->icc_profile_buf != (unsigned char *) NULL)
{
StringInfo
*profile;
profile=BlobToStringInfo(jp2_image->icc_profile_buf,
jp2_image->icc_profile_len);
if (profile != (StringInfo *) NULL)
SetImageProfile(image,"icc",profile);
}
if (image->ping != MagickFalse)
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
opj_destroy_cstr_index(&codestream_index);
return(GetFirstImageInList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
{
double
pixel,
scale;
scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1);
pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy*
image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+
(jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0));
switch (i)
{
case 0:
{
q->red=ClampToQuantum(pixel);
q->green=q->red;
q->blue=q->red;
q->opacity=OpaqueOpacity;
break;
}
case 1:
{
if (jp2_image->numcomps == 2)
{
q->opacity=ClampToQuantum(QuantumRange-pixel);
break;
}
q->green=ClampToQuantum(pixel);
break;
}
case 2:
{
q->blue=ClampToQuantum(pixel);
break;
}
case 3:
{
q->opacity=ClampToQuantum(QuantumRange-pixel);
break;
}
}
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
/*
Free resources.
*/
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
opj_destroy_cstr_index(&codestream_index);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r J P 2 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterJP2Image() adds attributes for the JP2 image format to the list of
% supported formats. The attributes include the image format tag, a method
% method to read and/or write the format, whether the format supports the
% saving of more than one frame to the same file or blob, whether the format
% supports native in-memory I/O, and a brief description of the format.
%
% The format of the RegisterJP2Image method is:
%
% size_t RegisterJP2Image(void)
%
*/
ModuleExport size_t RegisterJP2Image(void)
{
char
version[MaxTextExtent];
MagickInfo
*entry;
*version='\0';
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
(void) FormatLocaleString(version,MaxTextExtent,"%s",opj_version());
#endif
entry=SetMagickInfo("JP2");
entry->description=ConstantString("JPEG-2000 File Format Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJP2;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("J2C");
entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJ2K;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("J2K");
entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJ2K;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JPM");
entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJP2;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JPT");
entry->description=ConstantString("JPEG-2000 File Format Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJP2;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JPC");
entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJP2;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r J P 2 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterJP2Image() removes format registrations made by the JP2 module
% from the list of supported formats.
%
% The format of the UnregisterJP2Image method is:
%
% UnregisterJP2Image(void)
%
*/
ModuleExport void UnregisterJP2Image(void)
{
(void) UnregisterMagickInfo("JPC");
(void) UnregisterMagickInfo("JPT");
(void) UnregisterMagickInfo("JPM");
(void) UnregisterMagickInfo("JP2");
(void) UnregisterMagickInfo("J2K");
}
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e J P 2 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteJP2Image() writes an image in the JPEG 2000 image format.
%
% JP2 support originally written by Nathan Brown, nathanbrown@letu.edu
%
% The format of the WriteJP2Image method is:
%
% MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static void CinemaProfileCompliance(const opj_image_t *jp2_image,
opj_cparameters_t *parameters)
{
/*
Digital Cinema 4K profile compliant codestream.
*/
parameters->tile_size_on=OPJ_FALSE;
parameters->cp_tdx=1;
parameters->cp_tdy=1;
parameters->tp_flag='C';
parameters->tp_on=1;
parameters->cp_tx0=0;
parameters->cp_ty0=0;
parameters->image_offset_x0=0;
parameters->image_offset_y0=0;
parameters->cblockw_init=32;
parameters->cblockh_init=32;
parameters->csty|=0x01;
parameters->prog_order=OPJ_CPRL;
parameters->roi_compno=(-1);
parameters->subsampling_dx=1;
parameters->subsampling_dy=1;
parameters->irreversible=1;
if ((jp2_image->comps[0].w == 2048) || (jp2_image->comps[0].h == 1080))
{
/*
Digital Cinema 2K.
*/
parameters->cp_cinema=OPJ_CINEMA2K_24;
parameters->cp_rsiz=OPJ_CINEMA2K;
parameters->max_comp_size=1041666;
if (parameters->numresolution > 6)
parameters->numresolution=6;
}
if ((jp2_image->comps[0].w == 4096) || (jp2_image->comps[0].h == 2160))
{
/*
Digital Cinema 4K.
*/
parameters->cp_cinema=OPJ_CINEMA4K_24;
parameters->cp_rsiz=OPJ_CINEMA4K;
parameters->max_comp_size=1041666;
if (parameters->numresolution < 1)
parameters->numresolution=1;
if (parameters->numresolution > 7)
parameters->numresolution=7;
parameters->numpocs=2;
parameters->POC[0].tile=1;
parameters->POC[0].resno0=0;
parameters->POC[0].compno0=0;
parameters->POC[0].layno1=1;
parameters->POC[0].resno1=parameters->numresolution-1;
parameters->POC[0].compno1=3;
parameters->POC[0].prg1=OPJ_CPRL;
parameters->POC[1].tile=1;
parameters->POC[1].resno0=parameters->numresolution-1;
parameters->POC[1].compno0=0;
parameters->POC[1].layno1=1;
parameters->POC[1].resno1=parameters->numresolution;
parameters->POC[1].compno1=3;
parameters->POC[1].prg1=OPJ_CPRL;
}
parameters->tcp_numlayers=1;
parameters->tcp_rates[0]=((float) (jp2_image->numcomps*jp2_image->comps[0].w*
jp2_image->comps[0].h*jp2_image->comps[0].prec))/(parameters->max_comp_size*
8*jp2_image->comps[0].dx*jp2_image->comps[0].dy);
parameters->cp_disto_alloc=1;
}
static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image)
{
const char
*option,
*property;
int
jp2_status;
MagickBooleanType
status;
opj_codec_t
*jp2_codec;
OPJ_COLOR_SPACE
jp2_colorspace;
opj_cparameters_t
parameters;
opj_image_cmptparm_t
jp2_info[5];
opj_image_t
*jp2_image;
opj_stream_t
*jp2_stream;
register ssize_t
i;
ssize_t
y;
unsigned int
channels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
/*
Initialize JPEG 2000 encoder parameters.
*/
opj_set_default_encoder_parameters(¶meters);
for (i=1; i < 6; i++)
if (((size_t) (1 << (i+2)) > image->columns) &&
((size_t) (1 << (i+2)) > image->rows))
break;
parameters.numresolution=i;
option=GetImageOption(image_info,"jp2:number-resolutions");
if (option != (const char *) NULL)
parameters.numresolution=StringToInteger(option);
parameters.tcp_numlayers=1;
parameters.tcp_rates[0]=0; /* lossless */
parameters.cp_disto_alloc=1;
if ((image_info->quality != 0) && (image_info->quality != 100))
{
parameters.tcp_distoratio[0]=(double) image_info->quality;
parameters.cp_fixed_quality=OPJ_TRUE;
}
if (image_info->extract != (char *) NULL)
{
RectangleInfo
geometry;
int
flags;
/*
Set tile size.
*/
flags=ParseAbsoluteGeometry(image_info->extract,&geometry);
parameters.cp_tdx=(int) geometry.width;
parameters.cp_tdy=(int) geometry.width;
if ((flags & HeightValue) != 0)
parameters.cp_tdy=(int) geometry.height;
if ((flags & XValue) != 0)
parameters.cp_tx0=geometry.x;
if ((flags & YValue) != 0)
parameters.cp_ty0=geometry.y;
parameters.tile_size_on=OPJ_TRUE;
}
option=GetImageOption(image_info,"jp2:quality");
if (option != (const char *) NULL)
{
register const char
*p;
/*
Set quality PSNR.
*/
p=option;
for (i=0; sscanf(p,"%f",¶meters.tcp_distoratio[i]) == 1; i++)
{
if (i >= 100)
break;
while ((*p != '\0') && (*p != ','))
p++;
if (*p == '\0')
break;
p++;
}
parameters.tcp_numlayers=i+1;
parameters.cp_fixed_quality=OPJ_TRUE;
}
option=GetImageOption(image_info,"jp2:progression-order");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"LRCP") == 0)
parameters.prog_order=OPJ_LRCP;
if (LocaleCompare(option,"RLCP") == 0)
parameters.prog_order=OPJ_RLCP;
if (LocaleCompare(option,"RPCL") == 0)
parameters.prog_order=OPJ_RPCL;
if (LocaleCompare(option,"PCRL") == 0)
parameters.prog_order=OPJ_PCRL;
if (LocaleCompare(option,"CPRL") == 0)
parameters.prog_order=OPJ_CPRL;
}
option=GetImageOption(image_info,"jp2:rate");
if (option != (const char *) NULL)
{
register const char
*p;
/*
Set compression rate.
*/
p=option;
for (i=0; sscanf(p,"%f",¶meters.tcp_rates[i]) == 1; i++)
{
if (i > 100)
break;
while ((*p != '\0') && (*p != ','))
p++;
if (*p == '\0')
break;
p++;
}
parameters.tcp_numlayers=i+1;
parameters.cp_disto_alloc=OPJ_TRUE;
}
if (image_info->sampling_factor != (const char *) NULL)
(void) sscanf(image_info->sampling_factor,"%d,%d",
¶meters.subsampling_dx,¶meters.subsampling_dy);
property=GetImageProperty(image,"comment");
if (property != (const char *) NULL)
parameters.cp_comment=ConstantString(property);
channels=3;
jp2_colorspace=OPJ_CLRSPC_SRGB;
if (image->colorspace == YUVColorspace)
{
jp2_colorspace=OPJ_CLRSPC_SYCC;
parameters.subsampling_dx=2;
}
else
{
if (IsGrayColorspace(image->colorspace) != MagickFalse)
{
channels=1;
jp2_colorspace=OPJ_CLRSPC_GRAY;
}
else
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->matte != MagickFalse)
channels++;
}
parameters.tcp_mct=channels == 3 ? 1 : 0;
ResetMagickMemory(jp2_info,0,sizeof(jp2_info));
for (i=0; i < (ssize_t) channels; i++)
{
jp2_info[i].prec=(unsigned int) image->depth;
jp2_info[i].bpp=(unsigned int) image->depth;
if ((image->depth == 1) &&
((LocaleCompare(image_info->magick,"JPT") == 0) ||
(LocaleCompare(image_info->magick,"JP2") == 0)))
{
jp2_info[i].prec++; /* OpenJPEG returns exception for depth @ 1 */
jp2_info[i].bpp++;
}
jp2_info[i].sgnd=0;
jp2_info[i].dx=parameters.subsampling_dx;
jp2_info[i].dy=parameters.subsampling_dy;
jp2_info[i].w=(unsigned int) image->columns;
jp2_info[i].h=(unsigned int) image->rows;
}
jp2_image=opj_image_create(channels,jp2_info,jp2_colorspace);
if (jp2_image == (opj_image_t *) NULL)
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
jp2_image->x0=parameters.image_offset_x0;
jp2_image->y0=parameters.image_offset_y0;
jp2_image->x1=(unsigned int) (2*parameters.image_offset_x0+(image->columns-1)*
parameters.subsampling_dx+1);
jp2_image->y1=(unsigned int) (2*parameters.image_offset_y0+(image->rows-1)*
parameters.subsampling_dx+1);
if ((image->depth == 12) &&
((image->columns == 2048) || (image->rows == 1080) ||
(image->columns == 4096) || (image->rows == 2160)))
CinemaProfileCompliance(jp2_image,¶meters);
if (channels == 4)
jp2_image->comps[3].alpha=1;
else
if ((channels == 2) && (jp2_colorspace == OPJ_CLRSPC_GRAY))
jp2_image->comps[1].alpha=1;
/*
Convert to JP2 pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*p;
ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) channels; i++)
{
double
scale;
register int
*q;
scale=(double) ((1UL << jp2_image->comps[i].prec)-1)/QuantumRange;
q=jp2_image->comps[i].data+(y/jp2_image->comps[i].dy*
image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx);
switch (i)
{
case 0:
{
if (jp2_colorspace == OPJ_CLRSPC_GRAY)
{
*q=(int) (scale*GetPixelLuma(image,p));
break;
}
*q=(int) (scale*p->red);
break;
}
case 1:
{
if (jp2_colorspace == OPJ_CLRSPC_GRAY)
{
*q=(int) (scale*(QuantumRange-p->opacity));
break;
}
*q=(int) (scale*p->green);
break;
}
case 2:
{
*q=(int) (scale*p->blue);
break;
}
case 3:
{
*q=(int) (scale*(QuantumRange-p->opacity));
break;
}
}
}
p++;
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (LocaleCompare(image_info->magick,"JPT") == 0)
jp2_codec=opj_create_compress(OPJ_CODEC_JPT);
else
if (LocaleCompare(image_info->magick,"J2K") == 0)
jp2_codec=opj_create_compress(OPJ_CODEC_J2K);
else
jp2_codec=opj_create_compress(OPJ_CODEC_JP2);
opj_set_warning_handler(jp2_codec,JP2WarningHandler,&image->exception);
opj_set_error_handler(jp2_codec,JP2ErrorHandler,&image->exception);
opj_setup_encoder(jp2_codec,¶meters,jp2_image);
jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_FALSE);
opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
opj_stream_set_user_data(jp2_stream,image,NULL);
if (jp2_stream == (opj_stream_t *) NULL)
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
jp2_status=opj_start_compress(jp2_codec,jp2_image,jp2_stream);
if (jp2_status == 0)
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
if ((opj_encode(jp2_codec,jp2_stream) == 0) ||
(opj_end_compress(jp2_codec,jp2_stream) == 0))
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
}
/*
Free resources.
*/
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
(void) CloseBlob(image);
return(MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2738_0 |
crossvul-cpp_data_good_3174_1 | /*
* llc_sap.c - driver routines for SAP component.
*
* Copyright (c) 1997 by Procom Technology, Inc.
* 2001-2003 by Arnaldo Carvalho de Melo <acme@conectiva.com.br>
*
* This program can be redistributed or modified under the terms of the
* GNU General Public License as published by the Free Software Foundation.
* This program is distributed without any warranty or implied warranty
* of merchantability or fitness for a particular purpose.
*
* See the GNU General Public License for more details.
*/
#include <net/llc.h>
#include <net/llc_if.h>
#include <net/llc_conn.h>
#include <net/llc_pdu.h>
#include <net/llc_sap.h>
#include <net/llc_s_ac.h>
#include <net/llc_s_ev.h>
#include <net/llc_s_st.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <linux/llc.h>
#include <linux/slab.h>
static int llc_mac_header_len(unsigned short devtype)
{
switch (devtype) {
case ARPHRD_ETHER:
case ARPHRD_LOOPBACK:
return sizeof(struct ethhdr);
}
return 0;
}
/**
* llc_alloc_frame - allocates sk_buff for frame
* @dev: network device this skb will be sent over
* @type: pdu type to allocate
* @data_size: data size to allocate
*
* Allocates an sk_buff for frame and initializes sk_buff fields.
* Returns allocated skb or %NULL when out of memory.
*/
struct sk_buff *llc_alloc_frame(struct sock *sk, struct net_device *dev,
u8 type, u32 data_size)
{
int hlen = type == LLC_PDU_TYPE_U ? 3 : 4;
struct sk_buff *skb;
hlen += llc_mac_header_len(dev->type);
skb = alloc_skb(hlen + data_size, GFP_ATOMIC);
if (skb) {
skb_reset_mac_header(skb);
skb_reserve(skb, hlen);
skb_reset_network_header(skb);
skb_reset_transport_header(skb);
skb->protocol = htons(ETH_P_802_2);
skb->dev = dev;
if (sk != NULL)
skb_set_owner_w(skb, sk);
}
return skb;
}
void llc_save_primitive(struct sock *sk, struct sk_buff *skb, u8 prim)
{
struct sockaddr_llc *addr;
/* save primitive for use by the user. */
addr = llc_ui_skb_cb(skb);
memset(addr, 0, sizeof(*addr));
addr->sllc_family = sk->sk_family;
addr->sllc_arphrd = skb->dev->type;
addr->sllc_test = prim == LLC_TEST_PRIM;
addr->sllc_xid = prim == LLC_XID_PRIM;
addr->sllc_ua = prim == LLC_DATAUNIT_PRIM;
llc_pdu_decode_sa(skb, addr->sllc_mac);
llc_pdu_decode_ssap(skb, &addr->sllc_sap);
}
/**
* llc_sap_rtn_pdu - Informs upper layer on rx of an UI, XID or TEST pdu.
* @sap: pointer to SAP
* @skb: received pdu
*/
void llc_sap_rtn_pdu(struct llc_sap *sap, struct sk_buff *skb)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
switch (LLC_U_PDU_RSP(pdu)) {
case LLC_1_PDU_CMD_TEST:
ev->prim = LLC_TEST_PRIM; break;
case LLC_1_PDU_CMD_XID:
ev->prim = LLC_XID_PRIM; break;
case LLC_1_PDU_CMD_UI:
ev->prim = LLC_DATAUNIT_PRIM; break;
}
ev->ind_cfm_flag = LLC_IND;
}
/**
* llc_find_sap_trans - finds transition for event
* @sap: pointer to SAP
* @skb: happened event
*
* This function finds transition that matches with happened event.
* Returns the pointer to found transition on success or %NULL for
* failure.
*/
static struct llc_sap_state_trans *llc_find_sap_trans(struct llc_sap *sap,
struct sk_buff *skb)
{
int i = 0;
struct llc_sap_state_trans *rc = NULL;
struct llc_sap_state_trans **next_trans;
struct llc_sap_state *curr_state = &llc_sap_state_table[sap->state - 1];
/*
* Search thru events for this state until list exhausted or until
* its obvious the event is not valid for the current state
*/
for (next_trans = curr_state->transitions; next_trans[i]->ev; i++)
if (!next_trans[i]->ev(sap, skb)) {
rc = next_trans[i]; /* got event match; return it */
break;
}
return rc;
}
/**
* llc_exec_sap_trans_actions - execute actions related to event
* @sap: pointer to SAP
* @trans: pointer to transition that it's actions must be performed
* @skb: happened event.
*
* This function executes actions that is related to happened event.
* Returns 0 for success and 1 for failure of at least one action.
*/
static int llc_exec_sap_trans_actions(struct llc_sap *sap,
struct llc_sap_state_trans *trans,
struct sk_buff *skb)
{
int rc = 0;
const llc_sap_action_t *next_action = trans->ev_actions;
for (; next_action && *next_action; next_action++)
if ((*next_action)(sap, skb))
rc = 1;
return rc;
}
/**
* llc_sap_next_state - finds transition, execs actions & change SAP state
* @sap: pointer to SAP
* @skb: happened event
*
* This function finds transition that matches with happened event, then
* executes related actions and finally changes state of SAP. It returns
* 0 on success and 1 for failure.
*/
static int llc_sap_next_state(struct llc_sap *sap, struct sk_buff *skb)
{
int rc = 1;
struct llc_sap_state_trans *trans;
if (sap->state > LLC_NR_SAP_STATES)
goto out;
trans = llc_find_sap_trans(sap, skb);
if (!trans)
goto out;
/*
* Got the state to which we next transition; perform the actions
* associated with this transition before actually transitioning to the
* next state
*/
rc = llc_exec_sap_trans_actions(sap, trans, skb);
if (rc)
goto out;
/*
* Transition SAP to next state if all actions execute successfully
*/
sap->state = trans->next_state;
out:
return rc;
}
/**
* llc_sap_state_process - sends event to SAP state machine
* @sap: sap to use
* @skb: pointer to occurred event
*
* After executing actions of the event, upper layer will be indicated
* if needed(on receiving an UI frame). sk can be null for the
* datalink_proto case.
*/
static void llc_sap_state_process(struct llc_sap *sap, struct sk_buff *skb)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
/*
* We have to hold the skb, because llc_sap_next_state
* will kfree it in the sending path and we need to
* look at the skb->cb, where we encode llc_sap_state_ev.
*/
skb_get(skb);
ev->ind_cfm_flag = 0;
llc_sap_next_state(sap, skb);
if (ev->ind_cfm_flag == LLC_IND) {
if (skb->sk->sk_state == TCP_LISTEN)
kfree_skb(skb);
else {
llc_save_primitive(skb->sk, skb, ev->prim);
/* queue skb to the user. */
if (sock_queue_rcv_skb(skb->sk, skb))
kfree_skb(skb);
}
}
kfree_skb(skb);
}
/**
* llc_build_and_send_test_pkt - TEST interface for upper layers.
* @sap: sap to use
* @skb: packet to send
* @dmac: destination mac address
* @dsap: destination sap
*
* This function is called when upper layer wants to send a TEST pdu.
* Returns 0 for success, 1 otherwise.
*/
void llc_build_and_send_test_pkt(struct llc_sap *sap,
struct sk_buff *skb, u8 *dmac, u8 dsap)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
ev->saddr.lsap = sap->laddr.lsap;
ev->daddr.lsap = dsap;
memcpy(ev->saddr.mac, skb->dev->dev_addr, IFHWADDRLEN);
memcpy(ev->daddr.mac, dmac, IFHWADDRLEN);
ev->type = LLC_SAP_EV_TYPE_PRIM;
ev->prim = LLC_TEST_PRIM;
ev->prim_type = LLC_PRIM_TYPE_REQ;
llc_sap_state_process(sap, skb);
}
/**
* llc_build_and_send_xid_pkt - XID interface for upper layers
* @sap: sap to use
* @skb: packet to send
* @dmac: destination mac address
* @dsap: destination sap
*
* This function is called when upper layer wants to send a XID pdu.
* Returns 0 for success, 1 otherwise.
*/
void llc_build_and_send_xid_pkt(struct llc_sap *sap, struct sk_buff *skb,
u8 *dmac, u8 dsap)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
ev->saddr.lsap = sap->laddr.lsap;
ev->daddr.lsap = dsap;
memcpy(ev->saddr.mac, skb->dev->dev_addr, IFHWADDRLEN);
memcpy(ev->daddr.mac, dmac, IFHWADDRLEN);
ev->type = LLC_SAP_EV_TYPE_PRIM;
ev->prim = LLC_XID_PRIM;
ev->prim_type = LLC_PRIM_TYPE_REQ;
llc_sap_state_process(sap, skb);
}
/**
* llc_sap_rcv - sends received pdus to the sap state machine
* @sap: current sap component structure.
* @skb: received frame.
*
* Sends received pdus to the sap state machine.
*/
static void llc_sap_rcv(struct llc_sap *sap, struct sk_buff *skb,
struct sock *sk)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
ev->type = LLC_SAP_EV_TYPE_PDU;
ev->reason = 0;
skb_orphan(skb);
sock_hold(sk);
skb->sk = sk;
skb->destructor = sock_efree;
llc_sap_state_process(sap, skb);
}
static inline bool llc_dgram_match(const struct llc_sap *sap,
const struct llc_addr *laddr,
const struct sock *sk)
{
struct llc_sock *llc = llc_sk(sk);
return sk->sk_type == SOCK_DGRAM &&
llc->laddr.lsap == laddr->lsap &&
ether_addr_equal(llc->laddr.mac, laddr->mac);
}
/**
* llc_lookup_dgram - Finds dgram socket for the local sap/mac
* @sap: SAP
* @laddr: address of local LLC (MAC + SAP)
*
* Search socket list of the SAP and finds connection using the local
* mac, and local sap. Returns pointer for socket found, %NULL otherwise.
*/
static struct sock *llc_lookup_dgram(struct llc_sap *sap,
const struct llc_addr *laddr)
{
struct sock *rc;
struct hlist_nulls_node *node;
int slot = llc_sk_laddr_hashfn(sap, laddr);
struct hlist_nulls_head *laddr_hb = &sap->sk_laddr_hash[slot];
rcu_read_lock_bh();
again:
sk_nulls_for_each_rcu(rc, node, laddr_hb) {
if (llc_dgram_match(sap, laddr, rc)) {
/* Extra checks required by SLAB_DESTROY_BY_RCU */
if (unlikely(!atomic_inc_not_zero(&rc->sk_refcnt)))
goto again;
if (unlikely(llc_sk(rc)->sap != sap ||
!llc_dgram_match(sap, laddr, rc))) {
sock_put(rc);
continue;
}
goto found;
}
}
rc = NULL;
/*
* if the nulls value we got at the end of this lookup is
* not the expected one, we must restart lookup.
* We probably met an item that was moved to another chain.
*/
if (unlikely(get_nulls_value(node) != slot))
goto again;
found:
rcu_read_unlock_bh();
return rc;
}
static inline bool llc_mcast_match(const struct llc_sap *sap,
const struct llc_addr *laddr,
const struct sk_buff *skb,
const struct sock *sk)
{
struct llc_sock *llc = llc_sk(sk);
return sk->sk_type == SOCK_DGRAM &&
llc->laddr.lsap == laddr->lsap &&
llc->dev == skb->dev;
}
static void llc_do_mcast(struct llc_sap *sap, struct sk_buff *skb,
struct sock **stack, int count)
{
struct sk_buff *skb1;
int i;
for (i = 0; i < count; i++) {
skb1 = skb_clone(skb, GFP_ATOMIC);
if (!skb1) {
sock_put(stack[i]);
continue;
}
llc_sap_rcv(sap, skb1, stack[i]);
sock_put(stack[i]);
}
}
/**
* llc_sap_mcast - Deliver multicast PDU's to all matching datagram sockets.
* @sap: SAP
* @laddr: address of local LLC (MAC + SAP)
*
* Search socket list of the SAP and finds connections with same sap.
* Deliver clone to each.
*/
static void llc_sap_mcast(struct llc_sap *sap,
const struct llc_addr *laddr,
struct sk_buff *skb)
{
int i = 0, count = 256 / sizeof(struct sock *);
struct sock *sk, *stack[count];
struct llc_sock *llc;
struct hlist_head *dev_hb = llc_sk_dev_hash(sap, skb->dev->ifindex);
spin_lock_bh(&sap->sk_lock);
hlist_for_each_entry(llc, dev_hb, dev_hash_node) {
sk = &llc->sk;
if (!llc_mcast_match(sap, laddr, skb, sk))
continue;
sock_hold(sk);
if (i < count)
stack[i++] = sk;
else {
llc_do_mcast(sap, skb, stack, i);
i = 0;
}
}
spin_unlock_bh(&sap->sk_lock);
llc_do_mcast(sap, skb, stack, i);
}
void llc_sap_handler(struct llc_sap *sap, struct sk_buff *skb)
{
struct llc_addr laddr;
llc_pdu_decode_da(skb, laddr.mac);
llc_pdu_decode_dsap(skb, &laddr.lsap);
if (is_multicast_ether_addr(laddr.mac)) {
llc_sap_mcast(sap, &laddr, skb);
kfree_skb(skb);
} else {
struct sock *sk = llc_lookup_dgram(sap, &laddr);
if (sk) {
llc_sap_rcv(sap, skb, sk);
sock_put(sk);
} else
kfree_skb(skb);
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3174_1 |
crossvul-cpp_data_bad_3070_4 | /*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE.
*/
#include <stdio.h>
#include "ssl_locl.h"
#include <openssl/comp.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/rand.h>
/* seed1 through seed5 are concatenated */
static int tls1_PRF(SSL *s,
const void *seed1, int seed1_len,
const void *seed2, int seed2_len,
const void *seed3, int seed3_len,
const void *seed4, int seed4_len,
const void *seed5, int seed5_len,
const unsigned char *sec, int slen,
unsigned char *out, int olen)
{
const EVP_MD *md = ssl_prf_md(s);
EVP_PKEY_CTX *pctx = NULL;
int ret = 0;
size_t outlen = olen;
if (md == NULL) {
/* Should never happen */
SSLerr(SSL_F_TLS1_PRF, ERR_R_INTERNAL_ERROR);
return 0;
}
pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1_PRF, NULL);
if (pctx == NULL || EVP_PKEY_derive_init(pctx) <= 0
|| EVP_PKEY_CTX_set_tls1_prf_md(pctx, md) <= 0
|| EVP_PKEY_CTX_set1_tls1_prf_secret(pctx, sec, slen) <= 0)
goto err;
if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed1, seed1_len) <= 0)
goto err;
if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed2, seed2_len) <= 0)
goto err;
if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed3, seed3_len) <= 0)
goto err;
if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed4, seed4_len) <= 0)
goto err;
if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed5, seed5_len) <= 0)
goto err;
if (EVP_PKEY_derive(pctx, out, &outlen) <= 0)
goto err;
ret = 1;
err:
EVP_PKEY_CTX_free(pctx);
return ret;
}
static int tls1_generate_key_block(SSL *s, unsigned char *km, int num)
{
int ret;
ret = tls1_PRF(s,
TLS_MD_KEY_EXPANSION_CONST,
TLS_MD_KEY_EXPANSION_CONST_SIZE, s->s3->server_random,
SSL3_RANDOM_SIZE, s->s3->client_random, SSL3_RANDOM_SIZE,
NULL, 0, NULL, 0, s->session->master_key,
s->session->master_key_length, km, num);
return ret;
}
int tls1_change_cipher_state(SSL *s, int which)
{
unsigned char *p, *mac_secret;
unsigned char tmp1[EVP_MAX_KEY_LENGTH];
unsigned char tmp2[EVP_MAX_KEY_LENGTH];
unsigned char iv1[EVP_MAX_IV_LENGTH * 2];
unsigned char iv2[EVP_MAX_IV_LENGTH * 2];
unsigned char *ms, *key, *iv;
EVP_CIPHER_CTX *dd;
const EVP_CIPHER *c;
#ifndef OPENSSL_NO_COMP
const SSL_COMP *comp;
#endif
const EVP_MD *m;
int mac_type;
int *mac_secret_size;
EVP_MD_CTX *mac_ctx;
EVP_PKEY *mac_key;
int n, i, j, k, cl;
int reuse_dd = 0;
c = s->s3->tmp.new_sym_enc;
m = s->s3->tmp.new_hash;
mac_type = s->s3->tmp.new_mac_pkey_type;
#ifndef OPENSSL_NO_COMP
comp = s->s3->tmp.new_compression;
#endif
if (which & SSL3_CC_READ) {
if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
else
s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
if (s->enc_read_ctx != NULL)
reuse_dd = 1;
else if ((s->enc_read_ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
else
/*
* make sure it's initialised in case we exit later with an error
*/
EVP_CIPHER_CTX_reset(s->enc_read_ctx);
dd = s->enc_read_ctx;
mac_ctx = ssl_replace_hash(&s->read_hash, NULL);
if (mac_ctx == NULL)
goto err;
#ifndef OPENSSL_NO_COMP
COMP_CTX_free(s->expand);
s->expand = NULL;
if (comp != NULL) {
s->expand = COMP_CTX_new(comp->method);
if (s->expand == NULL) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,
SSL_R_COMPRESSION_LIBRARY_ERROR);
goto err2;
}
}
#endif
/*
* this is done by dtls1_reset_seq_numbers for DTLS
*/
if (!SSL_IS_DTLS(s))
RECORD_LAYER_reset_read_sequence(&s->rlayer);
mac_secret = &(s->s3->read_mac_secret[0]);
mac_secret_size = &(s->s3->read_mac_secret_size);
} else {
if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM;
else
s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM;
if (s->enc_write_ctx != NULL && !SSL_IS_DTLS(s))
reuse_dd = 1;
else if ((s->enc_write_ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
dd = s->enc_write_ctx;
if (SSL_IS_DTLS(s)) {
mac_ctx = EVP_MD_CTX_new();
if (mac_ctx == NULL)
goto err;
s->write_hash = mac_ctx;
} else {
mac_ctx = ssl_replace_hash(&s->write_hash, NULL);
if (mac_ctx == NULL)
goto err;
}
#ifndef OPENSSL_NO_COMP
COMP_CTX_free(s->compress);
s->compress = NULL;
if (comp != NULL) {
s->compress = COMP_CTX_new(comp->method);
if (s->compress == NULL) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,
SSL_R_COMPRESSION_LIBRARY_ERROR);
goto err2;
}
}
#endif
/*
* this is done by dtls1_reset_seq_numbers for DTLS
*/
if (!SSL_IS_DTLS(s))
RECORD_LAYER_reset_write_sequence(&s->rlayer);
mac_secret = &(s->s3->write_mac_secret[0]);
mac_secret_size = &(s->s3->write_mac_secret_size);
}
if (reuse_dd)
EVP_CIPHER_CTX_reset(dd);
p = s->s3->tmp.key_block;
i = *mac_secret_size = s->s3->tmp.new_mac_secret_size;
cl = EVP_CIPHER_key_length(c);
j = cl;
/* Was j=(exp)?5:EVP_CIPHER_key_length(c); */
/* If GCM/CCM mode only part of IV comes from PRF */
if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
k = EVP_GCM_TLS_FIXED_IV_LEN;
else if (EVP_CIPHER_mode(c) == EVP_CIPH_CCM_MODE)
k = EVP_CCM_TLS_FIXED_IV_LEN;
else
k = EVP_CIPHER_iv_length(c);
if ((which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
(which == SSL3_CHANGE_CIPHER_SERVER_READ)) {
ms = &(p[0]);
n = i + i;
key = &(p[n]);
n += j + j;
iv = &(p[n]);
n += k + k;
} else {
n = i;
ms = &(p[n]);
n += i + j;
key = &(p[n]);
n += j + k;
iv = &(p[n]);
n += k;
}
if (n > s->s3->tmp.key_block_length) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
memcpy(mac_secret, ms, i);
if (!(EVP_CIPHER_flags(c) & EVP_CIPH_FLAG_AEAD_CIPHER)) {
mac_key = EVP_PKEY_new_mac_key(mac_type, NULL,
mac_secret, *mac_secret_size);
if (mac_key == NULL
|| EVP_DigestSignInit(mac_ctx, NULL, m, NULL, mac_key) <= 0) {
EVP_PKEY_free(mac_key);
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
EVP_PKEY_free(mac_key);
}
#ifdef SSL_DEBUG
printf("which = %04X\nmac key=", which);
{
int z;
for (z = 0; z < i; z++)
printf("%02X%c", ms[z], ((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE) {
if (!EVP_CipherInit_ex(dd, c, NULL, key, NULL, (which & SSL3_CC_WRITE))
|| !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_GCM_SET_IV_FIXED, k, iv)) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
} else if (EVP_CIPHER_mode(c) == EVP_CIPH_CCM_MODE) {
int taglen;
if (s->s3->tmp.
new_cipher->algorithm_enc & (SSL_AES128CCM8 | SSL_AES256CCM8))
taglen = 8;
else
taglen = 16;
if (!EVP_CipherInit_ex(dd, c, NULL, NULL, NULL, (which & SSL3_CC_WRITE))
|| !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_IVLEN, 12, NULL)
|| !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_TAG, taglen, NULL)
|| !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_CCM_SET_IV_FIXED, k, iv)
|| !EVP_CipherInit_ex(dd, NULL, NULL, key, NULL, -1)) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
} else {
if (!EVP_CipherInit_ex(dd, c, NULL, key, iv, (which & SSL3_CC_WRITE))) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
}
/* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
if ((EVP_CIPHER_flags(c) & EVP_CIPH_FLAG_AEAD_CIPHER) && *mac_secret_size
&& !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_MAC_KEY,
*mac_secret_size, mac_secret)) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
#ifdef OPENSSL_SSL_TRACE_CRYPTO
if (s->msg_callback) {
int wh = which & SSL3_CC_WRITE ? TLS1_RT_CRYPTO_WRITE : 0;
if (*mac_secret_size)
s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_MAC,
mac_secret, *mac_secret_size,
s, s->msg_callback_arg);
if (c->key_len)
s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_KEY,
key, c->key_len, s, s->msg_callback_arg);
if (k) {
if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
wh |= TLS1_RT_CRYPTO_FIXED_IV;
else
wh |= TLS1_RT_CRYPTO_IV;
s->msg_callback(2, s->version, wh, iv, k, s, s->msg_callback_arg);
}
}
#endif
#ifdef SSL_DEBUG
printf("which = %04X\nkey=", which);
{
int z;
for (z = 0; z < EVP_CIPHER_key_length(c); z++)
printf("%02X%c", key[z], ((z + 1) % 16) ? ' ' : '\n');
}
printf("\niv=");
{
int z;
for (z = 0; z < k; z++)
printf("%02X%c", iv[z], ((z + 1) % 16) ? ' ' : '\n');
}
printf("\n");
#endif
OPENSSL_cleanse(tmp1, sizeof(tmp1));
OPENSSL_cleanse(tmp2, sizeof(tmp1));
OPENSSL_cleanse(iv1, sizeof(iv1));
OPENSSL_cleanse(iv2, sizeof(iv2));
return (1);
err:
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
err2:
OPENSSL_cleanse(tmp1, sizeof(tmp1));
OPENSSL_cleanse(tmp2, sizeof(tmp1));
OPENSSL_cleanse(iv1, sizeof(iv1));
OPENSSL_cleanse(iv2, sizeof(iv2));
return (0);
}
int tls1_setup_key_block(SSL *s)
{
unsigned char *p;
const EVP_CIPHER *c;
const EVP_MD *hash;
int num;
SSL_COMP *comp;
int mac_type = NID_undef, mac_secret_size = 0;
int ret = 0;
if (s->s3->tmp.key_block_length != 0)
return (1);
if (!ssl_cipher_get_evp
(s->session, &c, &hash, &mac_type, &mac_secret_size, &comp,
SSL_USE_ETM(s))) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
return (0);
}
s->s3->tmp.new_sym_enc = c;
s->s3->tmp.new_hash = hash;
s->s3->tmp.new_mac_pkey_type = mac_type;
s->s3->tmp.new_mac_secret_size = mac_secret_size;
num = EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c);
num *= 2;
ssl3_cleanup_key_block(s);
if ((p = OPENSSL_malloc(num)) == NULL) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
goto err;
}
s->s3->tmp.key_block_length = num;
s->s3->tmp.key_block = p;
#ifdef SSL_DEBUG
printf("client random\n");
{
int z;
for (z = 0; z < SSL3_RANDOM_SIZE; z++)
printf("%02X%c", s->s3->client_random[z],
((z + 1) % 16) ? ' ' : '\n');
}
printf("server random\n");
{
int z;
for (z = 0; z < SSL3_RANDOM_SIZE; z++)
printf("%02X%c", s->s3->server_random[z],
((z + 1) % 16) ? ' ' : '\n');
}
printf("master key\n");
{
int z;
for (z = 0; z < s->session->master_key_length; z++)
printf("%02X%c", s->session->master_key[z],
((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (!tls1_generate_key_block(s, p, num))
goto err;
#ifdef SSL_DEBUG
printf("\nkey block\n");
{
int z;
for (z = 0; z < num; z++)
printf("%02X%c", p[z], ((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
&& s->method->version <= TLS1_VERSION) {
/*
* enable vulnerability countermeasure for CBC ciphers with known-IV
* problem (http://www.openssl.org/~bodo/tls-cbc.txt)
*/
s->s3->need_empty_fragments = 1;
if (s->session->cipher != NULL) {
if (s->session->cipher->algorithm_enc == SSL_eNULL)
s->s3->need_empty_fragments = 0;
#ifndef OPENSSL_NO_RC4
if (s->session->cipher->algorithm_enc == SSL_RC4)
s->s3->need_empty_fragments = 0;
#endif
}
}
ret = 1;
err:
return (ret);
}
int tls1_final_finish_mac(SSL *s, const char *str, int slen, unsigned char *out)
{
int hashlen;
unsigned char hash[EVP_MAX_MD_SIZE];
if (!ssl3_digest_cached_records(s, 0))
return 0;
hashlen = ssl_handshake_hash(s, hash, sizeof(hash));
if (hashlen == 0)
return 0;
if (!tls1_PRF(s, str, slen, hash, hashlen, NULL, 0, NULL, 0, NULL, 0,
s->session->master_key, s->session->master_key_length,
out, TLS1_FINISH_MAC_LENGTH))
return 0;
OPENSSL_cleanse(hash, hashlen);
return TLS1_FINISH_MAC_LENGTH;
}
int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
int len)
{
if (s->session->flags & SSL_SESS_FLAG_EXTMS) {
unsigned char hash[EVP_MAX_MD_SIZE * 2];
int hashlen;
/*
* Digest cached records keeping record buffer (if present): this wont
* affect client auth because we're freezing the buffer at the same
* point (after client key exchange and before certificate verify)
*/
if (!ssl3_digest_cached_records(s, 1))
return -1;
hashlen = ssl_handshake_hash(s, hash, sizeof(hash));
#ifdef SSL_DEBUG
fprintf(stderr, "Handshake hashes:\n");
BIO_dump_fp(stderr, (char *)hash, hashlen);
#endif
tls1_PRF(s,
TLS_MD_EXTENDED_MASTER_SECRET_CONST,
TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE,
hash, hashlen,
NULL, 0,
NULL, 0,
NULL, 0, p, len, s->session->master_key,
SSL3_MASTER_SECRET_SIZE);
OPENSSL_cleanse(hash, hashlen);
} else {
tls1_PRF(s,
TLS_MD_MASTER_SECRET_CONST,
TLS_MD_MASTER_SECRET_CONST_SIZE,
s->s3->client_random, SSL3_RANDOM_SIZE,
NULL, 0,
s->s3->server_random, SSL3_RANDOM_SIZE,
NULL, 0, p, len, s->session->master_key,
SSL3_MASTER_SECRET_SIZE);
}
#ifdef SSL_DEBUG
fprintf(stderr, "Premaster Secret:\n");
BIO_dump_fp(stderr, (char *)p, len);
fprintf(stderr, "Client Random:\n");
BIO_dump_fp(stderr, (char *)s->s3->client_random, SSL3_RANDOM_SIZE);
fprintf(stderr, "Server Random:\n");
BIO_dump_fp(stderr, (char *)s->s3->server_random, SSL3_RANDOM_SIZE);
fprintf(stderr, "Master Secret:\n");
BIO_dump_fp(stderr, (char *)s->session->master_key,
SSL3_MASTER_SECRET_SIZE);
#endif
#ifdef OPENSSL_SSL_TRACE_CRYPTO
if (s->msg_callback) {
s->msg_callback(2, s->version, TLS1_RT_CRYPTO_PREMASTER,
p, len, s, s->msg_callback_arg);
s->msg_callback(2, s->version, TLS1_RT_CRYPTO_CLIENT_RANDOM,
s->s3->client_random, SSL3_RANDOM_SIZE,
s, s->msg_callback_arg);
s->msg_callback(2, s->version, TLS1_RT_CRYPTO_SERVER_RANDOM,
s->s3->server_random, SSL3_RANDOM_SIZE,
s, s->msg_callback_arg);
s->msg_callback(2, s->version, TLS1_RT_CRYPTO_MASTER,
s->session->master_key,
SSL3_MASTER_SECRET_SIZE, s, s->msg_callback_arg);
}
#endif
return (SSL3_MASTER_SECRET_SIZE);
}
int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
const char *label, size_t llen,
const unsigned char *context,
size_t contextlen, int use_context)
{
unsigned char *val = NULL;
size_t vallen = 0, currentvalpos;
int rv;
/*
* construct PRF arguments we construct the PRF argument ourself rather
* than passing separate values into the TLS PRF to ensure that the
* concatenation of values does not create a prohibited label.
*/
vallen = llen + SSL3_RANDOM_SIZE * 2;
if (use_context) {
vallen += 2 + contextlen;
}
val = OPENSSL_malloc(vallen);
if (val == NULL)
goto err2;
currentvalpos = 0;
memcpy(val + currentvalpos, (unsigned char *)label, llen);
currentvalpos += llen;
memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
currentvalpos += SSL3_RANDOM_SIZE;
memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
currentvalpos += SSL3_RANDOM_SIZE;
if (use_context) {
val[currentvalpos] = (contextlen >> 8) & 0xff;
currentvalpos++;
val[currentvalpos] = contextlen & 0xff;
currentvalpos++;
if ((contextlen > 0) || (context != NULL)) {
memcpy(val + currentvalpos, context, contextlen);
}
}
/*
* disallow prohibited labels note that SSL3_RANDOM_SIZE > max(prohibited
* label len) = 15, so size of val > max(prohibited label len) = 15 and
* the comparisons won't have buffer overflow
*/
if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0)
goto err1;
if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
TLS_MD_SERVER_FINISH_CONST_SIZE) == 0)
goto err1;
if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
TLS_MD_MASTER_SECRET_CONST_SIZE) == 0)
goto err1;
if (memcmp(val, TLS_MD_EXTENDED_MASTER_SECRET_CONST,
TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE) == 0)
goto err1;
if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0)
goto err1;
rv = tls1_PRF(s,
val, vallen,
NULL, 0,
NULL, 0,
NULL, 0,
NULL, 0,
s->session->master_key, s->session->master_key_length,
out, olen);
goto ret;
err1:
SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
rv = 0;
goto ret;
err2:
SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, ERR_R_MALLOC_FAILURE);
rv = 0;
ret:
OPENSSL_clear_free(val, vallen);
return (rv);
}
int tls1_alert_code(int code)
{
switch (code) {
case SSL_AD_CLOSE_NOTIFY:
return (SSL3_AD_CLOSE_NOTIFY);
case SSL_AD_UNEXPECTED_MESSAGE:
return (SSL3_AD_UNEXPECTED_MESSAGE);
case SSL_AD_BAD_RECORD_MAC:
return (SSL3_AD_BAD_RECORD_MAC);
case SSL_AD_DECRYPTION_FAILED:
return (TLS1_AD_DECRYPTION_FAILED);
case SSL_AD_RECORD_OVERFLOW:
return (TLS1_AD_RECORD_OVERFLOW);
case SSL_AD_DECOMPRESSION_FAILURE:
return (SSL3_AD_DECOMPRESSION_FAILURE);
case SSL_AD_HANDSHAKE_FAILURE:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_NO_CERTIFICATE:
return (-1);
case SSL_AD_BAD_CERTIFICATE:
return (SSL3_AD_BAD_CERTIFICATE);
case SSL_AD_UNSUPPORTED_CERTIFICATE:
return (SSL3_AD_UNSUPPORTED_CERTIFICATE);
case SSL_AD_CERTIFICATE_REVOKED:
return (SSL3_AD_CERTIFICATE_REVOKED);
case SSL_AD_CERTIFICATE_EXPIRED:
return (SSL3_AD_CERTIFICATE_EXPIRED);
case SSL_AD_CERTIFICATE_UNKNOWN:
return (SSL3_AD_CERTIFICATE_UNKNOWN);
case SSL_AD_ILLEGAL_PARAMETER:
return (SSL3_AD_ILLEGAL_PARAMETER);
case SSL_AD_UNKNOWN_CA:
return (TLS1_AD_UNKNOWN_CA);
case SSL_AD_ACCESS_DENIED:
return (TLS1_AD_ACCESS_DENIED);
case SSL_AD_DECODE_ERROR:
return (TLS1_AD_DECODE_ERROR);
case SSL_AD_DECRYPT_ERROR:
return (TLS1_AD_DECRYPT_ERROR);
case SSL_AD_EXPORT_RESTRICTION:
return (TLS1_AD_EXPORT_RESTRICTION);
case SSL_AD_PROTOCOL_VERSION:
return (TLS1_AD_PROTOCOL_VERSION);
case SSL_AD_INSUFFICIENT_SECURITY:
return (TLS1_AD_INSUFFICIENT_SECURITY);
case SSL_AD_INTERNAL_ERROR:
return (TLS1_AD_INTERNAL_ERROR);
case SSL_AD_USER_CANCELLED:
return (TLS1_AD_USER_CANCELLED);
case SSL_AD_NO_RENEGOTIATION:
return (TLS1_AD_NO_RENEGOTIATION);
case SSL_AD_UNSUPPORTED_EXTENSION:
return (TLS1_AD_UNSUPPORTED_EXTENSION);
case SSL_AD_CERTIFICATE_UNOBTAINABLE:
return (TLS1_AD_CERTIFICATE_UNOBTAINABLE);
case SSL_AD_UNRECOGNIZED_NAME:
return (TLS1_AD_UNRECOGNIZED_NAME);
case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
return (TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
return (TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
case SSL_AD_UNKNOWN_PSK_IDENTITY:
return (TLS1_AD_UNKNOWN_PSK_IDENTITY);
case SSL_AD_INAPPROPRIATE_FALLBACK:
return (TLS1_AD_INAPPROPRIATE_FALLBACK);
case SSL_AD_NO_APPLICATION_PROTOCOL:
return (TLS1_AD_NO_APPLICATION_PROTOCOL);
default:
return (-1);
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3070_4 |
crossvul-cpp_data_bad_2739_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% JJJ PPPP 222 %
% J P P 2 2 %
% J PPPP 22 %
% J J P 2 %
% JJ P 22222 %
% %
% %
% Read/Write JPEG-2000 Image Format %
% %
% Cristy %
% Nathan Brown %
% June 2001 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/semaphore.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/module.h"
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
#include <openjpeg.h>
#endif
/*
Forward declarations.
*/
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
static MagickBooleanType
WriteJP2Image(const ImageInfo *,Image *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s J 2 K %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsJ2K() returns MagickTrue if the image format type, identified by the
% magick string, is J2K.
%
% The format of the IsJ2K method is:
%
% MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\xff\x4f\xff\x51",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s J P 2 %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsJP2() returns MagickTrue if the image format type, identified by the
% magick string, is JP2.
%
% The format of the IsJP2 method is:
%
% MagickBooleanType IsJP2(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsJP2(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\x0d\x0a\x87\x0a",4) == 0)
return(MagickTrue);
if (length < 12)
return(MagickFalse);
if (memcmp(magick,"\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a",12) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d J P 2 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadJP2Image() reads a JPEG 2000 Image file (JP2) or JPEG 2000
% codestream (JPC) image file and returns it. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image or set of images.
%
% JP2 support is originally written by Nathan Brown, nathanbrown@letu.edu.
%
% The format of the ReadJP2Image method is:
%
% Image *ReadJP2Image(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
static void JP2ErrorHandler(const char *message,void *client_data)
{
ExceptionInfo
*exception;
exception=(ExceptionInfo *) client_data;
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
message,"`%s'","OpenJP2");
}
static OPJ_SIZE_T JP2ReadHandler(void *buffer,OPJ_SIZE_T length,void *context)
{
Image
*image;
ssize_t
count;
image=(Image *) context;
count=ReadBlob(image,(ssize_t) length,(unsigned char *) buffer);
if (count == 0)
return((OPJ_SIZE_T) -1);
return((OPJ_SIZE_T) count);
}
static OPJ_BOOL JP2SeekHandler(OPJ_OFF_T offset,void *context)
{
Image
*image;
image=(Image *) context;
return(SeekBlob(image,offset,SEEK_SET) < 0 ? OPJ_FALSE : OPJ_TRUE);
}
static OPJ_OFF_T JP2SkipHandler(OPJ_OFF_T offset,void *context)
{
Image
*image;
image=(Image *) context;
return(SeekBlob(image,offset,SEEK_CUR) < 0 ? -1 : offset);
}
static void JP2WarningHandler(const char *message,void *client_data)
{
ExceptionInfo
*exception;
exception=(ExceptionInfo *) client_data;
(void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
message,"`%s'","OpenJP2");
}
static OPJ_SIZE_T JP2WriteHandler(void *buffer,OPJ_SIZE_T length,void *context)
{
Image
*image;
ssize_t
count;
image=(Image *) context;
count=WriteBlob(image,(ssize_t) length,(unsigned char *) buffer);
return((OPJ_SIZE_T) count);
}
static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception)
{
const char
*option;
Image
*image;
int
jp2_status;
MagickBooleanType
status;
opj_codec_t
*jp2_codec;
opj_codestream_index_t
*codestream_index = (opj_codestream_index_t *) NULL;
opj_dparameters_t
parameters;
opj_image_t
*jp2_image;
opj_stream_t
*jp2_stream;
register ssize_t
i;
ssize_t
y;
unsigned char
sans[4];
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize JP2 codec.
*/
if (ReadBlob(image,4,sans) != 4)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) SeekBlob(image,SEEK_SET,0);
if (LocaleCompare(image_info->magick,"JPT") == 0)
jp2_codec=opj_create_decompress(OPJ_CODEC_JPT);
else
if (IsJ2K(sans,4) != MagickFalse)
jp2_codec=opj_create_decompress(OPJ_CODEC_J2K);
else
jp2_codec=opj_create_decompress(OPJ_CODEC_JP2);
opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
opj_set_default_decoder_parameters(¶meters);
option=GetImageOption(image_info,"jp2:reduce-factor");
if (option != (const char *) NULL)
parameters.cp_reduce=StringToInteger(option);
option=GetImageOption(image_info,"jp2:quality-layers");
if (option == (const char *) NULL)
option=GetImageOption(image_info,"jp2:layer-number");
if (option != (const char *) NULL)
parameters.cp_layer=StringToInteger(option);
if (opj_setup_decoder(jp2_codec,¶meters) == 0)
{
opj_destroy_codec(jp2_codec);
ThrowReaderException(DelegateError,"UnableToManageJP2Stream");
}
jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE);
opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
opj_stream_set_user_data(jp2_stream,image,NULL);
opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image));
if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
jp2_status=1;
if ((image->columns != 0) && (image->rows != 0))
{
/*
Extract an area from the image.
*/
jp2_status=opj_set_decode_area(jp2_codec,jp2_image,
(OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y,
(OPJ_INT32) image->extract_info.x+(ssize_t) image->columns,
(OPJ_INT32) image->extract_info.y+(ssize_t) image->rows);
if (jp2_status == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
}
if ((image_info->number_scenes != 0) && (image_info->scene != 0))
jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image,
(unsigned int) image_info->scene-1);
else
if (image->ping == MagickFalse)
{
jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image);
if (jp2_status != 0)
jp2_status=opj_end_decompress(jp2_codec,jp2_stream);
}
if (jp2_status == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
opj_stream_destroy(jp2_stream);
for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
{
if ((jp2_image->comps[i].dx == 0) || (jp2_image->comps[i].dy == 0))
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported")
}
}
/*
Convert JP2 image.
*/
image->columns=(size_t) jp2_image->comps[0].w;
image->rows=(size_t) jp2_image->comps[0].h;
image->depth=jp2_image->comps[0].prec;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->compression=JPEG2000Compression;
if (jp2_image->color_space == 2)
{
SetImageColorspace(image,GRAYColorspace);
if (jp2_image->numcomps > 1)
image->matte=MagickTrue;
}
else
if (jp2_image->color_space == 3)
SetImageColorspace(image,Rec601YCbCrColorspace);
if (jp2_image->numcomps > 3)
image->matte=MagickTrue;
if (jp2_image->icc_profile_buf != (unsigned char *) NULL)
{
StringInfo
*profile;
profile=BlobToStringInfo(jp2_image->icc_profile_buf,
jp2_image->icc_profile_len);
if (profile != (StringInfo *) NULL)
SetImageProfile(image,"icc",profile);
}
if (image->ping != MagickFalse)
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
opj_destroy_cstr_index(&codestream_index);
return(GetFirstImageInList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
{
double
pixel,
scale;
scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1);
pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy*
image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+
(jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0));
switch (i)
{
case 0:
{
q->red=ClampToQuantum(pixel);
q->green=q->red;
q->blue=q->red;
q->opacity=OpaqueOpacity;
break;
}
case 1:
{
if (jp2_image->numcomps == 2)
{
q->opacity=ClampToQuantum(QuantumRange-pixel);
break;
}
q->green=ClampToQuantum(pixel);
break;
}
case 2:
{
q->blue=ClampToQuantum(pixel);
break;
}
case 3:
{
q->opacity=ClampToQuantum(QuantumRange-pixel);
break;
}
}
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
/*
Free resources.
*/
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
opj_destroy_cstr_index(&codestream_index);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r J P 2 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterJP2Image() adds attributes for the JP2 image format to the list of
% supported formats. The attributes include the image format tag, a method
% method to read and/or write the format, whether the format supports the
% saving of more than one frame to the same file or blob, whether the format
% supports native in-memory I/O, and a brief description of the format.
%
% The format of the RegisterJP2Image method is:
%
% size_t RegisterJP2Image(void)
%
*/
ModuleExport size_t RegisterJP2Image(void)
{
char
version[MaxTextExtent];
MagickInfo
*entry;
*version='\0';
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
(void) FormatLocaleString(version,MaxTextExtent,"%s",opj_version());
#endif
entry=SetMagickInfo("JP2");
entry->description=ConstantString("JPEG-2000 File Format Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJP2;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("J2C");
entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJ2K;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("J2K");
entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJ2K;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JPM");
entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJP2;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JPT");
entry->description=ConstantString("JPEG-2000 File Format Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJP2;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JPC");
entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJP2;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r J P 2 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterJP2Image() removes format registrations made by the JP2 module
% from the list of supported formats.
%
% The format of the UnregisterJP2Image method is:
%
% UnregisterJP2Image(void)
%
*/
ModuleExport void UnregisterJP2Image(void)
{
(void) UnregisterMagickInfo("JPC");
(void) UnregisterMagickInfo("JPT");
(void) UnregisterMagickInfo("JPM");
(void) UnregisterMagickInfo("JP2");
(void) UnregisterMagickInfo("J2K");
}
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e J P 2 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteJP2Image() writes an image in the JPEG 2000 image format.
%
% JP2 support originally written by Nathan Brown, nathanbrown@letu.edu
%
% The format of the WriteJP2Image method is:
%
% MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static void CinemaProfileCompliance(const opj_image_t *jp2_image,
opj_cparameters_t *parameters)
{
/*
Digital Cinema 4K profile compliant codestream.
*/
parameters->tile_size_on=OPJ_FALSE;
parameters->cp_tdx=1;
parameters->cp_tdy=1;
parameters->tp_flag='C';
parameters->tp_on=1;
parameters->cp_tx0=0;
parameters->cp_ty0=0;
parameters->image_offset_x0=0;
parameters->image_offset_y0=0;
parameters->cblockw_init=32;
parameters->cblockh_init=32;
parameters->csty|=0x01;
parameters->prog_order=OPJ_CPRL;
parameters->roi_compno=(-1);
parameters->subsampling_dx=1;
parameters->subsampling_dy=1;
parameters->irreversible=1;
if ((jp2_image->comps[0].w == 2048) || (jp2_image->comps[0].h == 1080))
{
/*
Digital Cinema 2K.
*/
parameters->cp_cinema=OPJ_CINEMA2K_24;
parameters->cp_rsiz=OPJ_CINEMA2K;
parameters->max_comp_size=1041666;
if (parameters->numresolution > 6)
parameters->numresolution=6;
}
if ((jp2_image->comps[0].w == 4096) || (jp2_image->comps[0].h == 2160))
{
/*
Digital Cinema 4K.
*/
parameters->cp_cinema=OPJ_CINEMA4K_24;
parameters->cp_rsiz=OPJ_CINEMA4K;
parameters->max_comp_size=1041666;
if (parameters->numresolution < 1)
parameters->numresolution=1;
if (parameters->numresolution > 7)
parameters->numresolution=7;
parameters->numpocs=2;
parameters->POC[0].tile=1;
parameters->POC[0].resno0=0;
parameters->POC[0].compno0=0;
parameters->POC[0].layno1=1;
parameters->POC[0].resno1=parameters->numresolution-1;
parameters->POC[0].compno1=3;
parameters->POC[0].prg1=OPJ_CPRL;
parameters->POC[1].tile=1;
parameters->POC[1].resno0=parameters->numresolution-1;
parameters->POC[1].compno0=0;
parameters->POC[1].layno1=1;
parameters->POC[1].resno1=parameters->numresolution;
parameters->POC[1].compno1=3;
parameters->POC[1].prg1=OPJ_CPRL;
}
parameters->tcp_numlayers=1;
parameters->tcp_rates[0]=((float) (jp2_image->numcomps*jp2_image->comps[0].w*
jp2_image->comps[0].h*jp2_image->comps[0].prec))/(parameters->max_comp_size*
8*jp2_image->comps[0].dx*jp2_image->comps[0].dy);
parameters->cp_disto_alloc=1;
}
static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image)
{
const char
*option,
*property;
int
jp2_status;
MagickBooleanType
status;
opj_codec_t
*jp2_codec;
OPJ_COLOR_SPACE
jp2_colorspace;
opj_cparameters_t
parameters;
opj_image_cmptparm_t
jp2_info[5];
opj_image_t
*jp2_image;
opj_stream_t
*jp2_stream;
register ssize_t
i;
ssize_t
y;
unsigned int
channels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
/*
Initialize JPEG 2000 encoder parameters.
*/
opj_set_default_encoder_parameters(¶meters);
for (i=1; i < 6; i++)
if (((size_t) (1 << (i+2)) > image->columns) &&
((size_t) (1 << (i+2)) > image->rows))
break;
parameters.numresolution=i;
option=GetImageOption(image_info,"jp2:number-resolutions");
if (option != (const char *) NULL)
parameters.numresolution=StringToInteger(option);
parameters.tcp_numlayers=1;
parameters.tcp_rates[0]=0; /* lossless */
parameters.cp_disto_alloc=1;
if ((image_info->quality != 0) && (image_info->quality != 100))
{
parameters.tcp_distoratio[0]=(double) image_info->quality;
parameters.cp_fixed_quality=OPJ_TRUE;
}
if (image_info->extract != (char *) NULL)
{
RectangleInfo
geometry;
int
flags;
/*
Set tile size.
*/
flags=ParseAbsoluteGeometry(image_info->extract,&geometry);
parameters.cp_tdx=(int) geometry.width;
parameters.cp_tdy=(int) geometry.width;
if ((flags & HeightValue) != 0)
parameters.cp_tdy=(int) geometry.height;
if ((flags & XValue) != 0)
parameters.cp_tx0=geometry.x;
if ((flags & YValue) != 0)
parameters.cp_ty0=geometry.y;
parameters.tile_size_on=OPJ_TRUE;
}
option=GetImageOption(image_info,"jp2:quality");
if (option != (const char *) NULL)
{
register const char
*p;
/*
Set quality PSNR.
*/
p=option;
for (i=0; sscanf(p,"%f",¶meters.tcp_distoratio[i]) == 1; i++)
{
if (i >= 100)
break;
while ((*p != '\0') && (*p != ','))
p++;
if (*p == '\0')
break;
p++;
}
parameters.tcp_numlayers=i+1;
parameters.cp_fixed_quality=OPJ_TRUE;
}
option=GetImageOption(image_info,"jp2:progression-order");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"LRCP") == 0)
parameters.prog_order=OPJ_LRCP;
if (LocaleCompare(option,"RLCP") == 0)
parameters.prog_order=OPJ_RLCP;
if (LocaleCompare(option,"RPCL") == 0)
parameters.prog_order=OPJ_RPCL;
if (LocaleCompare(option,"PCRL") == 0)
parameters.prog_order=OPJ_PCRL;
if (LocaleCompare(option,"CPRL") == 0)
parameters.prog_order=OPJ_CPRL;
}
option=GetImageOption(image_info,"jp2:rate");
if (option != (const char *) NULL)
{
register const char
*p;
/*
Set compression rate.
*/
p=option;
for (i=0; sscanf(p,"%f",¶meters.tcp_rates[i]) == 1; i++)
{
if (i > 100)
break;
while ((*p != '\0') && (*p != ','))
p++;
if (*p == '\0')
break;
p++;
}
parameters.tcp_numlayers=i+1;
parameters.cp_disto_alloc=OPJ_TRUE;
}
if (image_info->sampling_factor != (const char *) NULL)
(void) sscanf(image_info->sampling_factor,"%d,%d",
¶meters.subsampling_dx,¶meters.subsampling_dy);
property=GetImageProperty(image,"comment");
if (property != (const char *) NULL)
parameters.cp_comment=ConstantString(property);
channels=3;
jp2_colorspace=OPJ_CLRSPC_SRGB;
if (image->colorspace == YUVColorspace)
{
jp2_colorspace=OPJ_CLRSPC_SYCC;
parameters.subsampling_dx=2;
}
else
{
if (IsGrayColorspace(image->colorspace) != MagickFalse)
{
channels=1;
jp2_colorspace=OPJ_CLRSPC_GRAY;
}
else
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->matte != MagickFalse)
channels++;
}
parameters.tcp_mct=channels == 3 ? 1 : 0;
ResetMagickMemory(jp2_info,0,sizeof(jp2_info));
for (i=0; i < (ssize_t) channels; i++)
{
jp2_info[i].prec=(unsigned int) image->depth;
jp2_info[i].bpp=(unsigned int) image->depth;
if ((image->depth == 1) &&
((LocaleCompare(image_info->magick,"JPT") == 0) ||
(LocaleCompare(image_info->magick,"JP2") == 0)))
{
jp2_info[i].prec++; /* OpenJPEG returns exception for depth @ 1 */
jp2_info[i].bpp++;
}
jp2_info[i].sgnd=0;
jp2_info[i].dx=parameters.subsampling_dx;
jp2_info[i].dy=parameters.subsampling_dy;
jp2_info[i].w=(unsigned int) image->columns;
jp2_info[i].h=(unsigned int) image->rows;
}
jp2_image=opj_image_create(channels,jp2_info,jp2_colorspace);
if (jp2_image == (opj_image_t *) NULL)
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
jp2_image->x0=parameters.image_offset_x0;
jp2_image->y0=parameters.image_offset_y0;
jp2_image->x1=(unsigned int) (2*parameters.image_offset_x0+(image->columns-1)*
parameters.subsampling_dx+1);
jp2_image->y1=(unsigned int) (2*parameters.image_offset_y0+(image->rows-1)*
parameters.subsampling_dx+1);
if ((image->depth == 12) &&
((image->columns == 2048) || (image->rows == 1080) ||
(image->columns == 4096) || (image->rows == 2160)))
CinemaProfileCompliance(jp2_image,¶meters);
if (channels == 4)
jp2_image->comps[3].alpha=1;
else
if ((channels == 2) && (jp2_colorspace == OPJ_CLRSPC_GRAY))
jp2_image->comps[1].alpha=1;
/*
Convert to JP2 pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*p;
ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) channels; i++)
{
double
scale;
register int
*q;
scale=(double) ((1UL << jp2_image->comps[i].prec)-1)/QuantumRange;
q=jp2_image->comps[i].data+(y/jp2_image->comps[i].dy*
image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx);
switch (i)
{
case 0:
{
if (jp2_colorspace == OPJ_CLRSPC_GRAY)
{
*q=(int) (scale*GetPixelLuma(image,p));
break;
}
*q=(int) (scale*p->red);
break;
}
case 1:
{
if (jp2_colorspace == OPJ_CLRSPC_GRAY)
{
*q=(int) (scale*(QuantumRange-p->opacity));
break;
}
*q=(int) (scale*p->green);
break;
}
case 2:
{
*q=(int) (scale*p->blue);
break;
}
case 3:
{
*q=(int) (scale*(QuantumRange-p->opacity));
break;
}
}
}
p++;
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (LocaleCompare(image_info->magick,"JPT") == 0)
jp2_codec=opj_create_compress(OPJ_CODEC_JPT);
else
if (LocaleCompare(image_info->magick,"J2K") == 0)
jp2_codec=opj_create_compress(OPJ_CODEC_J2K);
else
jp2_codec=opj_create_compress(OPJ_CODEC_JP2);
opj_set_warning_handler(jp2_codec,JP2WarningHandler,&image->exception);
opj_set_error_handler(jp2_codec,JP2ErrorHandler,&image->exception);
opj_setup_encoder(jp2_codec,¶meters,jp2_image);
jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_FALSE);
opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
opj_stream_set_user_data(jp2_stream,image,NULL);
if (jp2_stream == (opj_stream_t *) NULL)
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
jp2_status=opj_start_compress(jp2_codec,jp2_image,jp2_stream);
if (jp2_status == 0)
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
if ((opj_encode(jp2_codec,jp2_stream) == 0) ||
(opj_end_compress(jp2_codec,jp2_stream) == 0))
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
}
/*
Free resources.
*/
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
(void) CloseBlob(image);
return(MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2739_0 |
crossvul-cpp_data_good_1658_2 | /* ntp_config.c
*
* This file contains the ntpd configuration code.
*
* Written By: Sachin Kamboj
* University of Delaware
* Newark, DE 19711
* Some parts borrowed from the older ntp_config.c
* Copyright (c) 2006
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#ifdef HAVE_NETINFO
# include <netinfo/ni.h>
#endif
#include <stdio.h>
#include <ctype.h>
#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
#include <signal.h>
#ifndef SIGCHLD
# define SIGCHLD SIGCLD
#endif
#ifdef HAVE_SYS_WAIT_H
# include <sys/wait.h>
#endif
#include "ntp.h"
#include "ntpd.h"
#include "ntp_io.h"
#include "ntp_unixtime.h"
#include "ntp_refclock.h"
#include "ntp_filegen.h"
#include "ntp_stdlib.h"
#include "lib_strbuf.h"
#include "ntp_assert.h"
#include "ntpd-opts.h"
#include "ntp_random.h"
#include "ntp_workimpl.h"
#include <isc/net.h>
#include <isc/result.h>
/*
* [Bug 467]: Some linux headers collide with CONFIG_PHONE and CONFIG_KEYS
* so #include these later.
*/
#include "ntp_config.h"
#include "ntp_cmdargs.h"
#include "ntp_scanner.h"
#include "ntp_parser.h"
/* list of servers from command line for config_peers() */
int cmdline_server_count;
char ** cmdline_servers;
/*
* "logconfig" building blocks
*/
struct masks {
const char * name;
unsigned long mask;
};
static struct masks logcfg_class[] = {
{ "clock", NLOG_OCLOCK },
{ "peer", NLOG_OPEER },
{ "sync", NLOG_OSYNC },
{ "sys", NLOG_OSYS },
{ NULL, 0 }
};
static struct masks logcfg_item[] = {
{ "info", NLOG_INFO },
{ "allinfo", NLOG_SYSINFO|NLOG_PEERINFO|NLOG_CLOCKINFO|NLOG_SYNCINFO },
{ "events", NLOG_EVENT },
{ "allevents", NLOG_SYSEVENT|NLOG_PEEREVENT|NLOG_CLOCKEVENT|NLOG_SYNCEVENT },
{ "status", NLOG_STATUS },
{ "allstatus", NLOG_SYSSTATUS|NLOG_PEERSTATUS|NLOG_CLOCKSTATUS|NLOG_SYNCSTATUS },
{ "statistics", NLOG_STATIST },
{ "allstatistics", NLOG_SYSSTATIST|NLOG_PEERSTATIST|NLOG_CLOCKSTATIST|NLOG_SYNCSTATIST },
{ "allclock", (NLOG_INFO|NLOG_STATIST|NLOG_EVENT|NLOG_STATUS)<<NLOG_OCLOCK },
{ "allpeer", (NLOG_INFO|NLOG_STATIST|NLOG_EVENT|NLOG_STATUS)<<NLOG_OPEER },
{ "allsys", (NLOG_INFO|NLOG_STATIST|NLOG_EVENT|NLOG_STATUS)<<NLOG_OSYS },
{ "allsync", (NLOG_INFO|NLOG_STATIST|NLOG_EVENT|NLOG_STATUS)<<NLOG_OSYNC },
{ "all", NLOG_SYSMASK|NLOG_PEERMASK|NLOG_CLOCKMASK|NLOG_SYNCMASK },
{ NULL, 0 }
};
typedef struct peer_resolved_ctx_tag {
int flags;
int host_mode; /* T_* token identifier */
u_short family;
keyid_t keyid;
u_char hmode; /* MODE_* */
u_char version;
u_char minpoll;
u_char maxpoll;
u_char ttl;
const char * group;
} peer_resolved_ctx;
/* Limits */
#define MAXPHONE 10 /* maximum number of phone strings */
#define MAXPPS 20 /* maximum length of PPS device string */
/*
* Miscellaneous macros
*/
#define ISEOL(c) ((c) == '#' || (c) == '\n' || (c) == '\0')
#define ISSPACE(c) ((c) == ' ' || (c) == '\t')
/*
* Definitions of things either imported from or exported to outside
*/
extern int yydebug; /* ntp_parser.c (.y) */
int curr_include_level; /* The current include level */
struct FILE_INFO *fp[MAXINCLUDELEVEL+1];
config_tree cfgt; /* Parser output stored here */
struct config_tree_tag *cfg_tree_history; /* History of configs */
char *sys_phone[MAXPHONE] = {NULL}; /* ACTS phone numbers */
char default_keysdir[] = NTP_KEYSDIR;
char *keysdir = default_keysdir; /* crypto keys directory */
char * saveconfigdir;
#if defined(HAVE_SCHED_SETSCHEDULER)
int config_priority_override = 0;
int config_priority;
#endif
const char *config_file;
char default_ntp_signd_socket[] =
#ifdef NTP_SIGND_PATH
NTP_SIGND_PATH;
#else
"";
#endif
char *ntp_signd_socket = default_ntp_signd_socket;
#ifdef HAVE_NETINFO
struct netinfo_config_state *config_netinfo = NULL;
int check_netinfo = 1;
#endif /* HAVE_NETINFO */
#ifdef SYS_WINNT
char *alt_config_file;
LPTSTR temp;
char config_file_storage[MAX_PATH];
char alt_config_file_storage[MAX_PATH];
#endif /* SYS_WINNT */
#ifdef HAVE_NETINFO
/*
* NetInfo configuration state
*/
struct netinfo_config_state {
void *domain; /* domain with config */
ni_id config_dir; /* ID config dir */
int prop_index; /* current property */
int val_index; /* current value */
char **val_list; /* value list */
};
#endif
struct REMOTE_CONFIG_INFO remote_config; /* Remote configuration buffer and
pointer info */
int input_from_file = 1; /* A boolean flag, which when set, indicates that
the input is to be taken from the configuration
file, instead of the remote-configuration buffer
*/
int old_config_style = 1; /* A boolean flag, which when set,
* indicates that the old configuration
* format with a newline at the end of
* every command is being used
*/
int cryptosw; /* crypto command called */
extern int sys_maxclock;
extern char *stats_drift_file; /* name of the driftfile */
extern char *leapseconds_file_name; /*name of the leapseconds file */
#ifdef HAVE_IPTOS_SUPPORT
extern unsigned int qos; /* QoS setting */
#endif /* HAVE_IPTOS_SUPPORT */
#ifdef BC_LIST_FRAMEWORK_NOT_YET_USED
/*
* backwards compatibility flags
*/
bc_entry bc_list[] = {
{ T_Bc_bugXXXX, 1 } /* default enabled */
};
/*
* declare an int pointer for each flag for quick testing without
* walking bc_list. If the pointer is consumed by libntp rather
* than ntpd, declare it in a libntp source file pointing to storage
* initialized with the appropriate value for other libntp clients, and
* redirect it to point into bc_list during ntpd startup.
*/
int *p_bcXXXX_enabled = &bc_list[0].enabled;
#endif
/* FUNCTION PROTOTYPES */
static void init_syntax_tree(config_tree *);
static void apply_enable_disable(attr_val_fifo *q, int enable);
#ifdef FREE_CFG_T
static void free_auth_node(config_tree *);
static void free_config_other_modes(config_tree *);
static void free_config_auth(config_tree *);
static void free_config_tos(config_tree *);
static void free_config_monitor(config_tree *);
static void free_config_access(config_tree *);
static void free_config_tinker(config_tree *);
static void free_config_system_opts(config_tree *);
static void free_config_logconfig(config_tree *);
static void free_config_phone(config_tree *);
static void free_config_qos(config_tree *);
static void free_config_setvar(config_tree *);
static void free_config_ttl(config_tree *);
static void free_config_trap(config_tree *);
static void free_config_fudge(config_tree *);
static void free_config_vars(config_tree *);
static void free_config_peers(config_tree *);
static void free_config_unpeers(config_tree *);
static void free_config_nic_rules(config_tree *);
#ifdef SIM
static void free_config_sim(config_tree *);
#endif
static void destroy_address_fifo(address_fifo *);
#define FREE_ADDRESS_FIFO(pf) \
do { \
destroy_address_fifo(pf); \
(pf) = NULL; \
} while (0)
void free_all_config_trees(void); /* atexit() */
static void free_config_tree(config_tree *ptree);
#endif /* FREE_CFG_T */
static void destroy_restrict_node(restrict_node *my_node);
static int is_sane_resolved_address(sockaddr_u *peeraddr, int hmode);
static void save_and_apply_config_tree(void);
static void destroy_int_fifo(int_fifo *);
#define FREE_INT_FIFO(pf) \
do { \
destroy_int_fifo(pf); \
(pf) = NULL; \
} while (0)
static void destroy_string_fifo(string_fifo *);
#define FREE_STRING_FIFO(pf) \
do { \
destroy_string_fifo(pf); \
(pf) = NULL; \
} while (0)
static void destroy_attr_val_fifo(attr_val_fifo *);
#define FREE_ATTR_VAL_FIFO(pf) \
do { \
destroy_attr_val_fifo(pf); \
(pf) = NULL; \
} while (0)
static void destroy_filegen_fifo(filegen_fifo *);
#define FREE_FILEGEN_FIFO(pf) \
do { \
destroy_filegen_fifo(pf); \
(pf) = NULL; \
} while (0)
static void destroy_restrict_fifo(restrict_fifo *);
#define FREE_RESTRICT_FIFO(pf) \
do { \
destroy_restrict_fifo(pf); \
(pf) = NULL; \
} while (0)
static void destroy_setvar_fifo(setvar_fifo *);
#define FREE_SETVAR_FIFO(pf) \
do { \
destroy_setvar_fifo(pf); \
(pf) = NULL; \
} while (0)
static void destroy_addr_opts_fifo(addr_opts_fifo *);
#define FREE_ADDR_OPTS_FIFO(pf) \
do { \
destroy_addr_opts_fifo(pf); \
(pf) = NULL; \
} while (0)
static void config_tos(config_tree *);
static void config_monitor(config_tree *);
static void config_tinker(config_tree *);
static void config_system_opts(config_tree *);
static void config_logconfig(config_tree *);
static void config_vars(config_tree *);
#ifdef SIM
static sockaddr_u *get_next_address(address_node *addr);
static void config_sim(config_tree *);
static void config_ntpdsim(config_tree *);
#else /* !SIM follows */
static void config_ntpd(config_tree *);
static void config_other_modes(config_tree *);
static void config_auth(config_tree *);
static void config_access(config_tree *);
static void config_phone(config_tree *);
static void config_qos(config_tree *);
static void config_setvar(config_tree *);
static void config_ttl(config_tree *);
static void config_trap(config_tree *);
static void config_fudge(config_tree *);
static void config_peers(config_tree *);
static void config_unpeers(config_tree *);
static void config_nic_rules(config_tree *);
static u_char get_correct_host_mode(int token);
static int peerflag_bits(peer_node *);
#endif /* !SIM */
#ifdef WORKER
void peer_name_resolved(int, int, void *, const char *, const char *,
const struct addrinfo *,
const struct addrinfo *);
void unpeer_name_resolved(int, int, void *, const char *, const char *,
const struct addrinfo *,
const struct addrinfo *);
void trap_name_resolved(int, int, void *, const char *, const char *,
const struct addrinfo *,
const struct addrinfo *);
#endif
enum gnn_type {
t_UNK, /* Unknown */
t_REF, /* Refclock */
t_MSK /* Network Mask */
};
void ntpd_set_tod_using(const char *);
static char * normal_dtoa(double);
static unsigned long get_pfxmatch(char **s, struct masks *m);
static unsigned long get_match(char *s, struct masks *m);
static unsigned long get_logmask(char *s);
#ifndef SIM
static int getnetnum(const char *num, sockaddr_u *addr, int complain,
enum gnn_type a_type);
#endif
/* FUNCTIONS FOR INITIALIZATION
* ----------------------------
*/
#ifdef FREE_CFG_T
static void
free_auth_node(
config_tree *ptree
)
{
if (ptree->auth.keys) {
free(ptree->auth.keys);
ptree->auth.keys = NULL;
}
if (ptree->auth.keysdir) {
free(ptree->auth.keysdir);
ptree->auth.keysdir = NULL;
}
if (ptree->auth.ntp_signd_socket) {
free(ptree->auth.ntp_signd_socket);
ptree->auth.ntp_signd_socket = NULL;
}
}
#endif /* DEBUG */
static void
init_syntax_tree(
config_tree *ptree
)
{
memset(ptree, 0, sizeof(*ptree));
}
#ifdef FREE_CFG_T
void
free_all_config_trees(void)
{
config_tree *ptree;
config_tree *pnext;
ptree = cfg_tree_history;
while (ptree != NULL) {
pnext = ptree->link;
free_config_tree(ptree);
ptree = pnext;
}
}
static void
free_config_tree(
config_tree *ptree
)
{
#if defined(_MSC_VER) && defined (_DEBUG)
_CrtCheckMemory();
#endif
if (ptree->source.value.s != NULL)
free(ptree->source.value.s);
free_config_other_modes(ptree);
free_config_auth(ptree);
free_config_tos(ptree);
free_config_monitor(ptree);
free_config_access(ptree);
free_config_tinker(ptree);
free_config_system_opts(ptree);
free_config_logconfig(ptree);
free_config_phone(ptree);
free_config_qos(ptree);
free_config_setvar(ptree);
free_config_ttl(ptree);
free_config_trap(ptree);
free_config_fudge(ptree);
free_config_vars(ptree);
free_config_peers(ptree);
free_config_unpeers(ptree);
free_config_nic_rules(ptree);
#ifdef SIM
free_config_sim(ptree);
#endif
free_auth_node(ptree);
free(ptree);
#if defined(_MSC_VER) && defined (_DEBUG)
_CrtCheckMemory();
#endif
}
#endif /* FREE_CFG_T */
#ifdef SAVECONFIG
/* Dump all trees */
int
dump_all_config_trees(
FILE *df,
int comment
)
{
config_tree * cfg_ptr;
int return_value;
return_value = 0;
for (cfg_ptr = cfg_tree_history;
cfg_ptr != NULL;
cfg_ptr = cfg_ptr->link)
return_value |= dump_config_tree(cfg_ptr, df, comment);
return return_value;
}
/* The config dumper */
int
dump_config_tree(
config_tree *ptree,
FILE *df,
int comment
)
{
peer_node *peern;
unpeer_node *unpeern;
attr_val *atrv;
address_node *addr;
address_node *peer_addr;
address_node *fudge_addr;
filegen_node *fgen_node;
restrict_node *rest_node;
addr_opts_node *addr_opts;
setvar_node *setv_node;
nic_rule_node *rule_node;
int_node *i_n;
int_node *flags;
string_node *str_node;
const char *s;
char *s1;
char *s2;
char timestamp[80];
int enable;
DPRINTF(1, ("dump_config_tree(%p)\n", ptree));
if (comment) {
if (!strftime(timestamp, sizeof(timestamp),
"%Y-%m-%d %H:%M:%S",
localtime(&ptree->timestamp)))
timestamp[0] = '\0';
fprintf(df, "# %s %s %s\n",
timestamp,
(CONF_SOURCE_NTPQ == ptree->source.attr)
? "ntpq remote config from"
: "startup configuration file",
ptree->source.value.s);
}
/* For options I didn't find documentation I'll just output its name and the cor. value */
atrv = HEAD_PFIFO(ptree->vars);
for ( ; atrv != NULL; atrv = atrv->link) {
switch (atrv->type) {
#ifdef DEBUG
default:
fprintf(df, "\n# dump error:\n"
"# unknown vars type %d (%s) for %s\n",
atrv->type, token_name(atrv->type),
token_name(atrv->attr));
break;
#endif
case T_Double:
fprintf(df, "%s %s\n", keyword(atrv->attr),
normal_dtoa(atrv->value.d));
break;
case T_Integer:
fprintf(df, "%s %d\n", keyword(atrv->attr),
atrv->value.i);
break;
case T_String:
fprintf(df, "%s \"%s\"", keyword(atrv->attr),
atrv->value.s);
if (T_Driftfile == atrv->attr &&
atrv->link != NULL &&
T_WanderThreshold == atrv->link->attr) {
atrv = atrv->link;
fprintf(df, " %s\n",
normal_dtoa(atrv->value.d));
} else {
fprintf(df, "\n");
}
break;
}
}
atrv = HEAD_PFIFO(ptree->logconfig);
if (atrv != NULL) {
fprintf(df, "logconfig");
for ( ; atrv != NULL; atrv = atrv->link)
fprintf(df, " %c%s", atrv->attr, atrv->value.s);
fprintf(df, "\n");
}
if (ptree->stats_dir)
fprintf(df, "statsdir \"%s\"\n", ptree->stats_dir);
i_n = HEAD_PFIFO(ptree->stats_list);
if (i_n != NULL) {
fprintf(df, "statistics");
for ( ; i_n != NULL; i_n = i_n->link)
fprintf(df, " %s", keyword(i_n->i));
fprintf(df, "\n");
}
fgen_node = HEAD_PFIFO(ptree->filegen_opts);
for ( ; fgen_node != NULL; fgen_node = fgen_node->link) {
atrv = HEAD_PFIFO(fgen_node->options);
if (atrv != NULL) {
fprintf(df, "filegen %s",
keyword(fgen_node->filegen_token));
for ( ; atrv != NULL; atrv = atrv->link) {
switch (atrv->attr) {
#ifdef DEBUG
default:
fprintf(df, "\n# dump error:\n"
"# unknown filegen option token %s\n"
"filegen %s",
token_name(atrv->attr),
keyword(fgen_node->filegen_token));
break;
#endif
case T_File:
fprintf(df, " file %s",
atrv->value.s);
break;
case T_Type:
fprintf(df, " type %s",
keyword(atrv->value.i));
break;
case T_Flag:
fprintf(df, " %s",
keyword(atrv->value.i));
break;
}
}
fprintf(df, "\n");
}
}
atrv = HEAD_PFIFO(ptree->auth.crypto_cmd_list);
if (atrv != NULL) {
fprintf(df, "crypto");
for ( ; atrv != NULL; atrv = atrv->link) {
fprintf(df, " %s %s", keyword(atrv->attr),
atrv->value.s);
}
fprintf(df, "\n");
}
if (ptree->auth.revoke != 0)
fprintf(df, "revoke %d\n", ptree->auth.revoke);
if (ptree->auth.keysdir != NULL)
fprintf(df, "keysdir \"%s\"\n", ptree->auth.keysdir);
if (ptree->auth.keys != NULL)
fprintf(df, "keys \"%s\"\n", ptree->auth.keys);
atrv = HEAD_PFIFO(ptree->auth.trusted_key_list);
if (atrv != NULL) {
fprintf(df, "trustedkey");
for ( ; atrv != NULL; atrv = atrv->link) {
if (T_Integer == atrv->type)
fprintf(df, " %d", atrv->value.i);
else if (T_Intrange == atrv->type)
fprintf(df, " (%d ... %d)",
atrv->value.r.first,
atrv->value.r.last);
#ifdef DEBUG
else
fprintf(df, "\n# dump error:\n"
"# unknown trustedkey attr type %d\n"
"trustedkey", atrv->type);
#endif
}
fprintf(df, "\n");
}
if (ptree->auth.control_key)
fprintf(df, "controlkey %d\n", ptree->auth.control_key);
if (ptree->auth.request_key)
fprintf(df, "requestkey %d\n", ptree->auth.request_key);
/* dump enable list, then disable list */
for (enable = 1; enable >= 0; enable--) {
atrv = (enable)
? HEAD_PFIFO(ptree->enable_opts)
: HEAD_PFIFO(ptree->disable_opts);
if (atrv != NULL) {
fprintf(df, (enable)
? "enable"
: "disable");
for ( ; atrv != NULL; atrv = atrv->link)
fprintf(df, " %s",
keyword(atrv->value.i));
fprintf(df, "\n");
}
}
atrv = HEAD_PFIFO(ptree->orphan_cmds);
if (atrv != NULL) {
fprintf(df, "tos");
for ( ; atrv != NULL; atrv = atrv->link) {
switch (atrv->type) {
#ifdef DEBUG
default:
fprintf(df, "\n# dump error:\n"
"# unknown tos attr type %d %s\n"
"tos", atrv->type,
token_name(atrv->type));
break;
#endif
case T_Double:
fprintf(df, " %s %s",
keyword(atrv->attr),
normal_dtoa(atrv->value.d));
break;
}
}
fprintf(df, "\n");
}
atrv = HEAD_PFIFO(ptree->tinker);
if (atrv != NULL) {
fprintf(df, "tinker");
for ( ; atrv != NULL; atrv = atrv->link) {
NTP_INSIST(T_Double == atrv->type);
fprintf(df, " %s %s", keyword(atrv->attr),
normal_dtoa(atrv->value.d));
}
fprintf(df, "\n");
}
if (ptree->broadcastclient)
fprintf(df, "broadcastclient\n");
peern = HEAD_PFIFO(ptree->peers);
for ( ; peern != NULL; peern = peern->link) {
addr = peern->addr;
fprintf(df, "%s", keyword(peern->host_mode));
switch (addr->type) {
#ifdef DEBUG
default:
fprintf(df, "# dump error:\n"
"# unknown peer family %d for:\n"
"%s", addr->type,
keyword(peern->host_mode));
break;
#endif
case AF_UNSPEC:
break;
case AF_INET:
fprintf(df, " -4");
break;
case AF_INET6:
fprintf(df, " -6");
break;
}
fprintf(df, " %s", addr->address);
if (peern->minpoll != 0)
fprintf(df, " minpoll %u", peern->minpoll);
if (peern->maxpoll != 0)
fprintf(df, " maxpoll %u", peern->maxpoll);
if (peern->ttl != 0) {
if (strlen(addr->address) > 8
&& !memcmp(addr->address, "127.127.", 8))
fprintf(df, " mode %u", peern->ttl);
else
fprintf(df, " ttl %u", peern->ttl);
}
if (peern->peerversion != NTP_VERSION)
fprintf(df, " version %u", peern->peerversion);
if (peern->peerkey != 0)
fprintf(df, " key %u", peern->peerkey);
if (peern->group != NULL)
fprintf(df, " ident \"%s\"", peern->group);
atrv = HEAD_PFIFO(peern->peerflags);
for ( ; atrv != NULL; atrv = atrv->link) {
NTP_INSIST(T_Flag == atrv->attr);
NTP_INSIST(T_Integer == atrv->type);
fprintf(df, " %s", keyword(atrv->value.i));
}
fprintf(df, "\n");
addr_opts = HEAD_PFIFO(ptree->fudge);
for ( ; addr_opts != NULL; addr_opts = addr_opts->link) {
peer_addr = peern->addr;
fudge_addr = addr_opts->addr;
s1 = peer_addr->address;
s2 = fudge_addr->address;
if (strcmp(s1, s2))
continue;
fprintf(df, "fudge %s", s1);
for (atrv = HEAD_PFIFO(addr_opts->options);
atrv != NULL;
atrv = atrv->link) {
switch (atrv->type) {
#ifdef DEBUG
default:
fprintf(df, "\n# dump error:\n"
"# unknown fudge atrv->type %d\n"
"fudge %s", atrv->type,
s1);
break;
#endif
case T_Double:
fprintf(df, " %s %s",
keyword(atrv->attr),
normal_dtoa(atrv->value.d));
break;
case T_Integer:
fprintf(df, " %s %d",
keyword(atrv->attr),
atrv->value.i);
break;
case T_String:
fprintf(df, " %s %s",
keyword(atrv->attr),
atrv->value.s);
break;
}
}
fprintf(df, "\n");
}
}
addr = HEAD_PFIFO(ptree->manycastserver);
if (addr != NULL) {
fprintf(df, "manycastserver");
for ( ; addr != NULL; addr = addr->link)
fprintf(df, " %s", addr->address);
fprintf(df, "\n");
}
addr = HEAD_PFIFO(ptree->multicastclient);
if (addr != NULL) {
fprintf(df, "multicastclient");
for ( ; addr != NULL; addr = addr->link)
fprintf(df, " %s", addr->address);
fprintf(df, "\n");
}
for (unpeern = HEAD_PFIFO(ptree->unpeers);
unpeern != NULL;
unpeern = unpeern->link)
fprintf(df, "unpeer %s\n", unpeern->addr->address);
atrv = HEAD_PFIFO(ptree->mru_opts);
if (atrv != NULL) {
fprintf(df, "mru");
for ( ; atrv != NULL; atrv = atrv->link)
fprintf(df, " %s %d", keyword(atrv->attr),
atrv->value.i);
fprintf(df, "\n");
}
atrv = HEAD_PFIFO(ptree->discard_opts);
if (atrv != NULL) {
fprintf(df, "discard");
for ( ; atrv != NULL; atrv = atrv->link)
fprintf(df, " %s %d", keyword(atrv->attr),
atrv->value.i);
fprintf(df, "\n");
}
for (rest_node = HEAD_PFIFO(ptree->restrict_opts);
rest_node != NULL;
rest_node = rest_node->link) {
if (NULL == rest_node->addr) {
s = "default";
flags = HEAD_PFIFO(rest_node->flags);
for ( ; flags != NULL; flags = flags->link)
if (T_Source == flags->i) {
s = "source";
break;
}
} else {
s = rest_node->addr->address;
}
fprintf(df, "restrict %s", s);
if (rest_node->mask != NULL)
fprintf(df, " mask %s",
rest_node->mask->address);
flags = HEAD_PFIFO(rest_node->flags);
for ( ; flags != NULL; flags = flags->link)
if (T_Source != flags->i)
fprintf(df, " %s", keyword(flags->i));
fprintf(df, "\n");
}
rule_node = HEAD_PFIFO(ptree->nic_rules);
for ( ; rule_node != NULL; rule_node = rule_node->link) {
fprintf(df, "interface %s %s\n",
keyword(rule_node->action),
(rule_node->match_class)
? keyword(rule_node->match_class)
: rule_node->if_name);
}
str_node = HEAD_PFIFO(ptree->phone);
if (str_node != NULL) {
fprintf(df, "phone");
for ( ; str_node != NULL; str_node = str_node->link)
fprintf(df, " \"%s\"", str_node->s);
fprintf(df, "\n");
}
atrv = HEAD_PFIFO(ptree->qos);
if (atrv != NULL) {
fprintf(df, "qos");
for (; atrv != NULL; atrv = atrv->link)
fprintf(df, " %s", atrv->value.s);
fprintf(df, "\n");
}
setv_node = HEAD_PFIFO(ptree->setvar);
for ( ; setv_node != NULL; setv_node = setv_node->link) {
s1 = quote_if_needed(setv_node->var);
s2 = quote_if_needed(setv_node->val);
fprintf(df, "setvar %s = %s", s1, s2);
free(s1);
free(s2);
if (setv_node->isdefault)
fprintf(df, " default");
fprintf(df, "\n");
}
i_n = HEAD_PFIFO(ptree->ttl);
if (i_n != NULL) {
fprintf(df, "ttl");
for( ; i_n != NULL; i_n = i_n->link)
fprintf(df, " %d", i_n->i);
fprintf(df, "\n");
}
addr_opts = HEAD_PFIFO(ptree->trap);
for ( ; addr_opts != NULL; addr_opts = addr_opts->link) {
addr = addr_opts->addr;
fprintf(df, "trap %s", addr->address);
atrv = HEAD_PFIFO(addr_opts->options);
for ( ; atrv != NULL; atrv = atrv->link) {
switch (atrv->attr) {
#ifdef DEBUG
default:
fprintf(df, "\n# dump error:\n"
"# unknown trap token %d\n"
"trap %s", atrv->attr,
addr->address);
break;
#endif
case T_Port:
fprintf(df, " port %d", atrv->value.i);
break;
case T_Interface:
fprintf(df, " interface %s",
atrv->value.s);
break;
}
}
fprintf(df, "\n");
}
return 0;
}
#endif /* SAVECONFIG */
/* generic fifo routines for structs linked by 1st member */
void *
append_gen_fifo(
void *fifo,
void *entry
)
{
gen_fifo *pf;
gen_node *pe;
pf = fifo;
pe = entry;
if (NULL == pf)
pf = emalloc_zero(sizeof(*pf));
if (pe != NULL)
LINK_FIFO(*pf, pe, link);
return pf;
}
void *
concat_gen_fifos(
void *first,
void *second
)
{
gen_fifo *pf1;
gen_fifo *pf2;
pf1 = first;
pf2 = second;
if (NULL == pf1)
return pf2;
else if (NULL == pf2)
return pf1;
CONCAT_FIFO(*pf1, *pf2, link);
free(pf2);
return pf1;
}
/* FUNCTIONS FOR CREATING NODES ON THE SYNTAX TREE
* -----------------------------------------------
*/
attr_val *
create_attr_dval(
int attr,
double value
)
{
attr_val *my_val;
my_val = emalloc_zero(sizeof(*my_val));
my_val->attr = attr;
my_val->value.d = value;
my_val->type = T_Double;
return my_val;
}
attr_val *
create_attr_ival(
int attr,
int value
)
{
attr_val *my_val;
my_val = emalloc_zero(sizeof(*my_val));
my_val->attr = attr;
my_val->value.i = value;
my_val->type = T_Integer;
return my_val;
}
attr_val *
create_attr_rangeval(
int attr,
int first,
int last
)
{
attr_val *my_val;
my_val = emalloc_zero(sizeof(*my_val));
my_val->attr = attr;
my_val->value.r.first = first;
my_val->value.r.last = last;
my_val->type = T_Intrange;
return my_val;
}
attr_val *
create_attr_sval(
int attr,
char *s
)
{
attr_val *my_val;
my_val = emalloc_zero(sizeof(*my_val));
my_val->attr = attr;
if (NULL == s) /* free() hates NULL */
s = estrdup("");
my_val->value.s = s;
my_val->type = T_String;
return my_val;
}
int_node *
create_int_node(
int val
)
{
int_node *i_n;
i_n = emalloc_zero(sizeof(*i_n));
i_n->i = val;
return i_n;
}
string_node *
create_string_node(
char *str
)
{
string_node *sn;
sn = emalloc_zero(sizeof(*sn));
sn->s = str;
return sn;
}
address_node *
create_address_node(
char * addr,
int type
)
{
address_node *my_node;
NTP_REQUIRE(NULL != addr);
NTP_REQUIRE(AF_INET == type ||
AF_INET6 == type || AF_UNSPEC == type);
my_node = emalloc_zero(sizeof(*my_node));
my_node->address = addr;
my_node->type = (u_short)type;
return my_node;
}
void
destroy_address_node(
address_node *my_node
)
{
if (NULL == my_node)
return;
NTP_REQUIRE(NULL != my_node->address);
free(my_node->address);
free(my_node);
}
peer_node *
create_peer_node(
int hmode,
address_node * addr,
attr_val_fifo * options
)
{
peer_node *my_node;
attr_val *option;
int freenode;
int errflag = 0;
my_node = emalloc_zero(sizeof(*my_node));
/* Initialize node values to default */
my_node->peerversion = NTP_VERSION;
/* Now set the node to the read values */
my_node->host_mode = hmode;
my_node->addr = addr;
/*
* the options FIFO mixes items that will be saved in the
* peer_node as explicit members, such as minpoll, and
* those that are moved intact to the peer_node's peerflags
* FIFO. The options FIFO is consumed and reclaimed here.
*/
while (options != NULL) {
UNLINK_FIFO(option, *options, link);
if (NULL == option) {
free(options);
break;
}
freenode = 1;
/* Check the kind of option being set */
switch (option->attr) {
case T_Flag:
APPEND_G_FIFO(my_node->peerflags, option);
freenode = 0;
break;
case T_Minpoll:
if (option->value.i < NTP_MINPOLL ||
option->value.i > UCHAR_MAX) {
msyslog(LOG_INFO,
"minpoll: provided value (%d) is out of range [%d-%d])",
option->value.i, NTP_MINPOLL,
UCHAR_MAX);
my_node->minpoll = NTP_MINPOLL;
} else {
my_node->minpoll =
(u_char)option->value.u;
}
break;
case T_Maxpoll:
if (option->value.i < 0 ||
option->value.i > NTP_MAXPOLL) {
msyslog(LOG_INFO,
"maxpoll: provided value (%d) is out of range [0-%d])",
option->value.i, NTP_MAXPOLL);
my_node->maxpoll = NTP_MAXPOLL;
} else {
my_node->maxpoll =
(u_char)option->value.u;
}
break;
case T_Ttl:
if (option->value.u >= MAX_TTL) {
msyslog(LOG_ERR, "ttl: invalid argument");
errflag = 1;
} else {
my_node->ttl = (u_char)option->value.u;
}
break;
case T_Mode:
if (option->value.u >= UCHAR_MAX) {
msyslog(LOG_ERR, "mode: invalid argument");
errflag = 1;
} else {
my_node->ttl = (u_char)option->value.u;
}
break;
case T_Key:
if (option->value.u >= KEYID_T_MAX) {
msyslog(LOG_ERR, "key: invalid argument");
errflag = 1;
} else {
my_node->peerkey =
(keyid_t)option->value.u;
}
break;
case T_Version:
if (option->value.u >= UCHAR_MAX) {
msyslog(LOG_ERR, "version: invalid argument");
errflag = 1;
} else {
my_node->peerversion =
(u_char)option->value.u;
}
break;
case T_Ident:
my_node->group = option->value.s;
break;
default:
msyslog(LOG_ERR,
"Unknown peer/server option token %s",
token_name(option->attr));
errflag = 1;
}
if (freenode)
free(option);
}
/* Check if errors were reported. If yes, ignore the node */
if (errflag) {
free(my_node);
my_node = NULL;
}
return my_node;
}
unpeer_node *
create_unpeer_node(
address_node *addr
)
{
unpeer_node * my_node;
u_int u;
char * pch;
my_node = emalloc_zero(sizeof(*my_node));
/*
* From the parser's perspective an association ID fits into
* its generic T_String definition of a name/address "address".
* We treat all valid 16-bit numbers as association IDs.
*/
pch = addr->address;
while (*pch && isdigit(*pch))
pch++;
if (!*pch
&& 1 == sscanf(addr->address, "%u", &u)
&& u <= ASSOCID_MAX) {
my_node->assocID = (associd_t)u;
destroy_address_node(addr);
my_node->addr = NULL;
} else {
my_node->assocID = 0;
my_node->addr = addr;
}
return my_node;
}
filegen_node *
create_filegen_node(
int filegen_token,
attr_val_fifo * options
)
{
filegen_node *my_node;
my_node = emalloc_zero(sizeof(*my_node));
my_node->filegen_token = filegen_token;
my_node->options = options;
return my_node;
}
restrict_node *
create_restrict_node(
address_node * addr,
address_node * mask,
int_fifo * flags,
int line_no
)
{
restrict_node *my_node;
my_node = emalloc_zero(sizeof(*my_node));
my_node->addr = addr;
my_node->mask = mask;
my_node->flags = flags;
my_node->line_no = line_no;
return my_node;
}
static void
destroy_restrict_node(
restrict_node *my_node
)
{
/* With great care, free all the memory occupied by
* the restrict node
*/
destroy_address_node(my_node->addr);
destroy_address_node(my_node->mask);
destroy_int_fifo(my_node->flags);
free(my_node);
}
static void
destroy_int_fifo(
int_fifo * fifo
)
{
int_node * i_n;
if (fifo != NULL) {
do {
UNLINK_FIFO(i_n, *fifo, link);
if (i_n != NULL)
free(i_n);
} while (i_n != NULL);
free(fifo);
}
}
static void
destroy_string_fifo(
string_fifo * fifo
)
{
string_node * sn;
if (fifo != NULL) {
do {
UNLINK_FIFO(sn, *fifo, link);
if (sn != NULL) {
if (sn->s != NULL)
free(sn->s);
free(sn);
}
} while (sn != NULL);
free(fifo);
}
}
static void
destroy_attr_val_fifo(
attr_val_fifo * av_fifo
)
{
attr_val * av;
if (av_fifo != NULL) {
do {
UNLINK_FIFO(av, *av_fifo, link);
if (av != NULL) {
if (T_String == av->type)
free(av->value.s);
free(av);
}
} while (av != NULL);
free(av_fifo);
}
}
static void
destroy_filegen_fifo(
filegen_fifo * fifo
)
{
filegen_node * fg;
if (fifo != NULL) {
do {
UNLINK_FIFO(fg, *fifo, link);
if (fg != NULL) {
destroy_attr_val_fifo(fg->options);
free(fg);
}
} while (fg != NULL);
free(fifo);
}
}
static void
destroy_restrict_fifo(
restrict_fifo * fifo
)
{
restrict_node * rn;
if (fifo != NULL) {
do {
UNLINK_FIFO(rn, *fifo, link);
if (rn != NULL)
destroy_restrict_node(rn);
} while (rn != NULL);
free(fifo);
}
}
static void
destroy_setvar_fifo(
setvar_fifo * fifo
)
{
setvar_node * sv;
if (fifo != NULL) {
do {
UNLINK_FIFO(sv, *fifo, link);
if (sv != NULL) {
free(sv->var);
free(sv->val);
free(sv);
}
} while (sv != NULL);
free(fifo);
}
}
static void
destroy_addr_opts_fifo(
addr_opts_fifo * fifo
)
{
addr_opts_node * aon;
if (fifo != NULL) {
do {
UNLINK_FIFO(aon, *fifo, link);
if (aon != NULL) {
destroy_address_node(aon->addr);
destroy_attr_val_fifo(aon->options);
free(aon);
}
} while (aon != NULL);
free(fifo);
}
}
setvar_node *
create_setvar_node(
char * var,
char * val,
int isdefault
)
{
setvar_node * my_node;
char * pch;
/* do not allow = in the variable name */
pch = strchr(var, '=');
if (NULL != pch)
*pch = '\0';
/* Now store the string into a setvar_node */
my_node = emalloc_zero(sizeof(*my_node));
my_node->var = var;
my_node->val = val;
my_node->isdefault = isdefault;
return my_node;
}
nic_rule_node *
create_nic_rule_node(
int match_class,
char *if_name, /* interface name or numeric address */
int action
)
{
nic_rule_node *my_node;
NTP_REQUIRE(match_class != 0 || if_name != NULL);
my_node = emalloc_zero(sizeof(*my_node));
my_node->match_class = match_class;
my_node->if_name = if_name;
my_node->action = action;
return my_node;
}
addr_opts_node *
create_addr_opts_node(
address_node * addr,
attr_val_fifo * options
)
{
addr_opts_node *my_node;
my_node = emalloc_zero(sizeof(*my_node));
my_node->addr = addr;
my_node->options = options;
return my_node;
}
script_info *
create_sim_script_info(
double duration,
attr_val_fifo * script_queue
)
{
#ifndef SIM
return NULL;
#else /* SIM follows */
script_info *my_info;
attr_val *my_attr_val;
my_info = emalloc_zero(sizeof(*my_info));
/* Initialize Script Info with default values*/
my_info->duration = duration;
my_info->prop_delay = NET_DLY;
my_info->proc_delay = PROC_DLY;
/* Traverse the script_queue and fill out non-default values */
for (my_attr_val = HEAD_PFIFO(script_queue);
my_attr_val != NULL;
my_attr_val = my_attr_val->link) {
/* Set the desired value */
switch (my_attr_val->attr) {
case T_Freq_Offset:
my_info->freq_offset = my_attr_val->value.d;
break;
case T_Wander:
my_info->wander = my_attr_val->value.d;
break;
case T_Jitter:
my_info->jitter = my_attr_val->value.d;
break;
case T_Prop_Delay:
my_info->prop_delay = my_attr_val->value.d;
break;
case T_Proc_Delay:
my_info->proc_delay = my_attr_val->value.d;
break;
default:
msyslog(LOG_ERR, "Unknown script token %d",
my_attr_val->attr);
}
}
return my_info;
#endif /* SIM */
}
#ifdef SIM
static sockaddr_u *
get_next_address(
address_node *addr
)
{
const char addr_prefix[] = "192.168.0.";
static int curr_addr_num = 1;
#define ADDR_LENGTH 16 + 1 /* room for 192.168.1.255 */
char addr_string[ADDR_LENGTH];
sockaddr_u *final_addr;
struct addrinfo *ptr;
int gai_error;
final_addr = emalloc(sizeof(*final_addr));
if (addr->type == T_String) {
snprintf(addr_string, sizeof(addr_string), "%s%d",
addr_prefix, curr_addr_num++);
printf("Selecting ip address %s for hostname %s\n",
addr_string, addr->address);
gai_error = getaddrinfo(addr_string, "ntp", NULL, &ptr);
} else {
gai_error = getaddrinfo(addr->address, "ntp", NULL, &ptr);
}
if (gai_error) {
fprintf(stderr, "ERROR!! Could not get a new address\n");
exit(1);
}
memcpy(final_addr, ptr->ai_addr, ptr->ai_addrlen);
fprintf(stderr, "Successful in setting ip address of simulated server to: %s\n",
stoa(final_addr));
freeaddrinfo(ptr);
return final_addr;
}
#endif /* SIM */
server_info *
create_sim_server(
address_node * addr,
double server_offset,
script_info_fifo * script
)
{
#ifndef SIM
return NULL;
#else /* SIM follows */
server_info *my_info;
my_info = emalloc_zero(sizeof(*my_info));
my_info->server_time = server_offset;
my_info->addr = get_next_address(addr);
my_info->script = script;
UNLINK_FIFO(my_info->curr_script, *my_info->script, link);
return my_info;
#endif /* SIM */
}
sim_node *
create_sim_node(
attr_val_fifo * init_opts,
server_info_fifo * servers
)
{
sim_node *my_node;
my_node = emalloc(sizeof(*my_node));
my_node->init_opts = init_opts;
my_node->servers = servers;
return my_node;
}
/* FUNCTIONS FOR PERFORMING THE CONFIGURATION
* ------------------------------------------
*/
#ifndef SIM
static void
config_other_modes(
config_tree * ptree
)
{
sockaddr_u addr_sock;
address_node * addr_node;
if (ptree->broadcastclient)
proto_config(PROTO_BROADCLIENT, ptree->broadcastclient,
0., NULL);
addr_node = HEAD_PFIFO(ptree->manycastserver);
while (addr_node != NULL) {
ZERO_SOCK(&addr_sock);
AF(&addr_sock) = addr_node->type;
if (1 == getnetnum(addr_node->address, &addr_sock, 1,
t_UNK)) {
proto_config(PROTO_MULTICAST_ADD,
0, 0., &addr_sock);
sys_manycastserver = 1;
}
addr_node = addr_node->link;
}
/* Configure the multicast clients */
addr_node = HEAD_PFIFO(ptree->multicastclient);
if (addr_node != NULL) {
do {
ZERO_SOCK(&addr_sock);
AF(&addr_sock) = addr_node->type;
if (1 == getnetnum(addr_node->address,
&addr_sock, 1, t_UNK)) {
proto_config(PROTO_MULTICAST_ADD, 0, 0.,
&addr_sock);
}
addr_node = addr_node->link;
} while (addr_node != NULL);
proto_config(PROTO_MULTICAST_ADD, 1, 0., NULL);
}
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
destroy_address_fifo(
address_fifo * pfifo
)
{
address_node * addr_node;
if (pfifo != NULL) {
do {
UNLINK_FIFO(addr_node, *pfifo, link);
if (addr_node != NULL)
destroy_address_node(addr_node);
} while (addr_node != NULL);
free(pfifo);
}
}
static void
free_config_other_modes(
config_tree *ptree
)
{
FREE_ADDRESS_FIFO(ptree->manycastserver);
FREE_ADDRESS_FIFO(ptree->multicastclient);
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_auth(
config_tree *ptree
)
{
attr_val * my_val;
int first;
int last;
int i;
#ifdef AUTOKEY
int item;
#endif
/* Crypto Command */
#ifdef AUTOKEY
item = -1; /* quiet warning */
my_val = HEAD_PFIFO(ptree->auth.crypto_cmd_list);
for (; my_val != NULL; my_val = my_val->link) {
switch (my_val->attr) {
default:
NTP_INSIST(0);
break;
case T_Host:
item = CRYPTO_CONF_PRIV;
break;
case T_Ident:
item = CRYPTO_CONF_IDENT;
break;
case T_Pw:
item = CRYPTO_CONF_PW;
break;
case T_Randfile:
item = CRYPTO_CONF_RAND;
break;
case T_Digest:
item = CRYPTO_CONF_NID;
break;
}
crypto_config(item, my_val->value.s);
}
#endif /* AUTOKEY */
/* Keysdir Command */
if (ptree->auth.keysdir) {
if (keysdir != default_keysdir)
free(keysdir);
keysdir = estrdup(ptree->auth.keysdir);
}
/* ntp_signd_socket Command */
if (ptree->auth.ntp_signd_socket) {
if (ntp_signd_socket != default_ntp_signd_socket)
free(ntp_signd_socket);
ntp_signd_socket = estrdup(ptree->auth.ntp_signd_socket);
}
#ifdef AUTOKEY
if (ptree->auth.cryptosw && !cryptosw) {
crypto_setup();
cryptosw = 1;
}
#endif /* AUTOKEY */
/* Keys Command */
if (ptree->auth.keys)
getauthkeys(ptree->auth.keys);
/* Control Key Command */
if (ptree->auth.control_key)
ctl_auth_keyid = (keyid_t)ptree->auth.control_key;
/* Requested Key Command */
if (ptree->auth.request_key) {
DPRINTF(4, ("set info_auth_keyid to %08lx\n",
(u_long) ptree->auth.request_key));
info_auth_keyid = (keyid_t)ptree->auth.request_key;
}
/* Trusted Key Command */
my_val = HEAD_PFIFO(ptree->auth.trusted_key_list);
for (; my_val != NULL; my_val = my_val->link) {
if (T_Integer == my_val->type)
authtrust(my_val->value.i, 1);
else if (T_Intrange == my_val->type) {
first = my_val->value.r.first;
last = my_val->value.r.last;
if (first > last || first < 1 || last > 65534)
msyslog(LOG_NOTICE,
"Ignoring invalid trustedkey range %d ... %d, min 1 max 65534.",
first, last);
else
for (i = first; i <= last; i++)
authtrust((keyid_t)i, 1);
}
}
#ifdef AUTOKEY
/* crypto revoke command */
if (ptree->auth.revoke)
sys_revoke = 1 << ptree->auth.revoke;
#endif /* AUTOKEY */
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_auth(
config_tree *ptree
)
{
destroy_attr_val_fifo(ptree->auth.crypto_cmd_list);
ptree->auth.crypto_cmd_list = NULL;
destroy_attr_val_fifo(ptree->auth.trusted_key_list);
ptree->auth.trusted_key_list = NULL;
}
#endif /* FREE_CFG_T */
static void
config_tos(
config_tree *ptree
)
{
attr_val *tos;
int item;
item = -1; /* quiet warning */
tos = HEAD_PFIFO(ptree->orphan_cmds);
for (; tos != NULL; tos = tos->link) {
switch(tos->attr) {
default:
NTP_INSIST(0);
break;
case T_Ceiling:
item = PROTO_CEILING;
break;
case T_Floor:
item = PROTO_FLOOR;
break;
case T_Cohort:
item = PROTO_COHORT;
break;
case T_Orphan:
item = PROTO_ORPHAN;
break;
case T_Orphanwait:
item = PROTO_ORPHWAIT;
break;
case T_Mindist:
item = PROTO_MINDISP;
break;
case T_Maxdist:
item = PROTO_MAXDIST;
break;
case T_Minclock:
item = PROTO_MINCLOCK;
break;
case T_Maxclock:
item = PROTO_MAXCLOCK;
break;
case T_Minsane:
item = PROTO_MINSANE;
break;
case T_Beacon:
item = PROTO_BEACON;
break;
}
proto_config(item, 0, tos->value.d, NULL);
}
}
#ifdef FREE_CFG_T
static void
free_config_tos(
config_tree *ptree
)
{
FREE_ATTR_VAL_FIFO(ptree->orphan_cmds);
}
#endif /* FREE_CFG_T */
static void
config_monitor(
config_tree *ptree
)
{
int_node *pfilegen_token;
const char *filegen_string;
const char *filegen_file;
FILEGEN *filegen;
filegen_node *my_node;
attr_val *my_opts;
int filegen_type;
int filegen_flag;
/* Set the statistics directory */
if (ptree->stats_dir)
stats_config(STATS_STATSDIR, ptree->stats_dir);
/* NOTE:
* Calling filegen_get is brain dead. Doing a string
* comparison to find the relavant filegen structure is
* expensive.
*
* Through the parser, we already know which filegen is
* being specified. Hence, we should either store a
* pointer to the specified structure in the syntax tree
* or an index into a filegen array.
*
* Need to change the filegen code to reflect the above.
*/
/* Turn on the specified statistics */
pfilegen_token = HEAD_PFIFO(ptree->stats_list);
for (; pfilegen_token != NULL; pfilegen_token = pfilegen_token->link) {
filegen_string = keyword(pfilegen_token->i);
filegen = filegen_get(filegen_string);
if (NULL == filegen) {
msyslog(LOG_ERR,
"stats %s unrecognized",
filegen_string);
continue;
}
DPRINTF(4, ("enabling filegen for %s statistics '%s%s'\n",
filegen_string, filegen->prefix,
filegen->basename));
filegen->flag |= FGEN_FLAG_ENABLED;
}
/* Configure the statistics with the options */
my_node = HEAD_PFIFO(ptree->filegen_opts);
for (; my_node != NULL; my_node = my_node->link) {
filegen_file = keyword(my_node->filegen_token);
filegen = filegen_get(filegen_file);
if (NULL == filegen) {
msyslog(LOG_ERR,
"filegen category '%s' unrecognized",
filegen_file);
continue;
}
/* Initialize the filegen variables to their pre-configuration states */
filegen_flag = filegen->flag;
filegen_type = filegen->type;
/* "filegen ... enabled" is the default (when filegen is used) */
filegen_flag |= FGEN_FLAG_ENABLED;
my_opts = HEAD_PFIFO(my_node->options);
for (; my_opts != NULL; my_opts = my_opts->link) {
switch (my_opts->attr) {
case T_File:
filegen_file = my_opts->value.s;
break;
case T_Type:
switch (my_opts->value.i) {
default:
NTP_INSIST(0);
break;
case T_None:
filegen_type = FILEGEN_NONE;
break;
case T_Pid:
filegen_type = FILEGEN_PID;
break;
case T_Day:
filegen_type = FILEGEN_DAY;
break;
case T_Week:
filegen_type = FILEGEN_WEEK;
break;
case T_Month:
filegen_type = FILEGEN_MONTH;
break;
case T_Year:
filegen_type = FILEGEN_YEAR;
break;
case T_Age:
filegen_type = FILEGEN_AGE;
break;
}
break;
case T_Flag:
switch (my_opts->value.i) {
case T_Link:
filegen_flag |= FGEN_FLAG_LINK;
break;
case T_Nolink:
filegen_flag &= ~FGEN_FLAG_LINK;
break;
case T_Enable:
filegen_flag |= FGEN_FLAG_ENABLED;
break;
case T_Disable:
filegen_flag &= ~FGEN_FLAG_ENABLED;
break;
default:
msyslog(LOG_ERR,
"Unknown filegen flag token %d",
my_opts->value.i);
exit(1);
}
break;
default:
msyslog(LOG_ERR,
"Unknown filegen option token %d",
my_opts->attr);
exit(1);
}
}
filegen_config(filegen, filegen_file, filegen_type,
filegen_flag);
}
}
#ifdef FREE_CFG_T
static void
free_config_monitor(
config_tree *ptree
)
{
if (ptree->stats_dir) {
free(ptree->stats_dir);
ptree->stats_dir = NULL;
}
FREE_INT_FIFO(ptree->stats_list);
FREE_FILEGEN_FIFO(ptree->filegen_opts);
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_access(
config_tree *ptree
)
{
static int warned_signd;
attr_val * my_opt;
restrict_node * my_node;
int_node * curr_flag;
sockaddr_u addr;
sockaddr_u mask;
struct addrinfo hints;
struct addrinfo * ai_list;
struct addrinfo * pai;
int rc;
int restrict_default;
u_short flags;
u_short mflags;
int range_err;
const char * signd_warning =
#ifdef HAVE_NTP_SIGND
"MS-SNTP signd operations currently block ntpd degrading service to all clients.";
#else
"mssntp restrict bit ignored, this ntpd was configured without --enable-ntp-signd.";
#endif
/* Configure the mru options */
my_opt = HEAD_PFIFO(ptree->mru_opts);
for (; my_opt != NULL; my_opt = my_opt->link) {
range_err = FALSE;
switch (my_opt->attr) {
case T_Incalloc:
if (0 <= my_opt->value.i)
mru_incalloc = my_opt->value.u;
else
range_err = TRUE;
break;
case T_Incmem:
if (0 <= my_opt->value.i)
mru_incalloc = (my_opt->value.u * 1024)
/ sizeof(mon_entry);
else
range_err = TRUE;
break;
case T_Initalloc:
if (0 <= my_opt->value.i)
mru_initalloc = my_opt->value.u;
else
range_err = TRUE;
break;
case T_Initmem:
if (0 <= my_opt->value.i)
mru_initalloc = (my_opt->value.u * 1024)
/ sizeof(mon_entry);
else
range_err = TRUE;
break;
case T_Mindepth:
if (0 <= my_opt->value.i)
mru_mindepth = my_opt->value.u;
else
range_err = TRUE;
break;
case T_Maxage:
mru_maxage = my_opt->value.i;
break;
case T_Maxdepth:
if (0 <= my_opt->value.i)
mru_maxdepth = my_opt->value.u;
else
mru_maxdepth = UINT_MAX;
break;
case T_Maxmem:
if (0 <= my_opt->value.i)
mru_maxdepth = my_opt->value.u * 1024 /
sizeof(mon_entry);
else
mru_maxdepth = UINT_MAX;
break;
default:
msyslog(LOG_ERR,
"Unknown mru option %s (%d)",
keyword(my_opt->attr), my_opt->attr);
exit(1);
}
if (range_err)
msyslog(LOG_ERR,
"mru %s %d out of range, ignored.",
keyword(my_opt->attr), my_opt->value.i);
}
/* Configure the discard options */
my_opt = HEAD_PFIFO(ptree->discard_opts);
for (; my_opt != NULL; my_opt = my_opt->link) {
switch (my_opt->attr) {
case T_Average:
if (0 <= my_opt->value.i &&
my_opt->value.i <= UCHAR_MAX)
ntp_minpoll = (u_char)my_opt->value.u;
else
msyslog(LOG_ERR,
"discard average %d out of range, ignored.",
my_opt->value.i);
break;
case T_Minimum:
ntp_minpkt = my_opt->value.i;
break;
case T_Monitor:
mon_age = my_opt->value.i;
break;
default:
msyslog(LOG_ERR,
"Unknown discard option %s (%d)",
keyword(my_opt->attr), my_opt->attr);
exit(1);
}
}
/* Configure the restrict options */
my_node = HEAD_PFIFO(ptree->restrict_opts);
for (; my_node != NULL; my_node = my_node->link) {
/* Parse the flags */
flags = 0;
mflags = 0;
curr_flag = HEAD_PFIFO(my_node->flags);
for (; curr_flag != NULL; curr_flag = curr_flag->link) {
switch (curr_flag->i) {
default:
NTP_INSIST(0);
break;
case T_Ntpport:
mflags |= RESM_NTPONLY;
break;
case T_Source:
mflags |= RESM_SOURCE;
break;
case T_Flake:
flags |= RES_FLAKE;
break;
case T_Ignore:
flags |= RES_IGNORE;
break;
case T_Kod:
flags |= RES_KOD;
break;
case T_Mssntp:
flags |= RES_MSSNTP;
break;
case T_Limited:
flags |= RES_LIMITED;
break;
case T_Lowpriotrap:
flags |= RES_LPTRAP;
break;
case T_Nomodify:
flags |= RES_NOMODIFY;
break;
case T_Nopeer:
flags |= RES_NOPEER;
break;
case T_Noquery:
flags |= RES_NOQUERY;
break;
case T_Noserve:
flags |= RES_DONTSERVE;
break;
case T_Notrap:
flags |= RES_NOTRAP;
break;
case T_Notrust:
flags |= RES_DONTTRUST;
break;
case T_Version:
flags |= RES_VERSION;
break;
}
}
if ((RES_MSSNTP & flags) && !warned_signd) {
warned_signd = 1;
fprintf(stderr, "%s\n", signd_warning);
msyslog(LOG_WARNING, signd_warning);
}
ZERO_SOCK(&addr);
ai_list = NULL;
pai = NULL;
restrict_default = 0;
if (NULL == my_node->addr) {
ZERO_SOCK(&mask);
if (!(RESM_SOURCE & mflags)) {
/*
* The user specified a default rule
* without a -4 / -6 qualifier, add to
* both lists
*/
restrict_default = 1;
} else {
/* apply "restrict source ..." */
DPRINTF(1, ("restrict source template mflags %x flags %x\n",
mflags, flags));
hack_restrict(RESTRICT_FLAGS, NULL,
NULL, mflags, flags, 0);
continue;
}
} else {
/* Resolve the specified address */
AF(&addr) = (u_short)my_node->addr->type;
if (getnetnum(my_node->addr->address,
&addr, 1, t_UNK) != 1) {
/*
* Attempt a blocking lookup. This
* is in violation of the nonblocking
* design of ntpd's mainline code. The
* alternative of running without the
* restriction until the name resolved
* seems worse.
* Ideally some scheme could be used for
* restrict directives in the startup
* ntp.conf to delay starting up the
* protocol machinery until after all
* restrict hosts have been resolved.
*/
ai_list = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_protocol = IPPROTO_UDP;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_family = my_node->addr->type;
rc = getaddrinfo(my_node->addr->address,
"ntp", &hints,
&ai_list);
if (rc) {
msyslog(LOG_ERR,
"restrict: ignoring line %d, address/host '%s' unusable.",
my_node->line_no,
my_node->addr->address);
continue;
}
NTP_INSIST(ai_list != NULL);
pai = ai_list;
NTP_INSIST(pai->ai_addr != NULL);
NTP_INSIST(sizeof(addr) >=
pai->ai_addrlen);
memcpy(&addr, pai->ai_addr,
pai->ai_addrlen);
NTP_INSIST(AF_INET == AF(&addr) ||
AF_INET6 == AF(&addr));
}
SET_HOSTMASK(&mask, AF(&addr));
/* Resolve the mask */
if (my_node->mask) {
ZERO_SOCK(&mask);
AF(&mask) = my_node->mask->type;
if (getnetnum(my_node->mask->address,
&mask, 1, t_MSK) != 1) {
msyslog(LOG_ERR,
"restrict: ignoring line %d, mask '%s' unusable.",
my_node->line_no,
my_node->mask->address);
continue;
}
}
}
/* Set the flags */
if (restrict_default) {
AF(&addr) = AF_INET;
AF(&mask) = AF_INET;
hack_restrict(RESTRICT_FLAGS, &addr,
&mask, mflags, flags, 0);
AF(&addr) = AF_INET6;
AF(&mask) = AF_INET6;
}
do {
hack_restrict(RESTRICT_FLAGS, &addr,
&mask, mflags, flags, 0);
if (pai != NULL &&
NULL != (pai = pai->ai_next)) {
NTP_INSIST(pai->ai_addr != NULL);
NTP_INSIST(sizeof(addr) >=
pai->ai_addrlen);
ZERO_SOCK(&addr);
memcpy(&addr, pai->ai_addr,
pai->ai_addrlen);
NTP_INSIST(AF_INET == AF(&addr) ||
AF_INET6 == AF(&addr));
SET_HOSTMASK(&mask, AF(&addr));
}
} while (pai != NULL);
if (ai_list != NULL)
freeaddrinfo(ai_list);
}
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_access(
config_tree *ptree
)
{
FREE_ATTR_VAL_FIFO(ptree->mru_opts);
FREE_ATTR_VAL_FIFO(ptree->discard_opts);
FREE_RESTRICT_FIFO(ptree->restrict_opts);
}
#endif /* FREE_CFG_T */
static void
config_tinker(
config_tree *ptree
)
{
attr_val * tinker;
int item;
item = -1; /* quiet warning */
tinker = HEAD_PFIFO(ptree->tinker);
for (; tinker != NULL; tinker = tinker->link) {
switch (tinker->attr) {
default:
NTP_INSIST(0);
break;
case T_Allan:
item = LOOP_ALLAN;
break;
case T_Dispersion:
item = LOOP_PHI;
break;
case T_Freq:
item = LOOP_FREQ;
break;
case T_Huffpuff:
item = LOOP_HUFFPUFF;
break;
case T_Panic:
item = LOOP_PANIC;
break;
case T_Step:
item = LOOP_MAX;
break;
case T_Stepout:
item = LOOP_MINSTEP;
break;
}
loop_config(item, tinker->value.d);
}
}
#ifdef FREE_CFG_T
static void
free_config_tinker(
config_tree *ptree
)
{
FREE_ATTR_VAL_FIFO(ptree->tinker);
}
#endif /* FREE_CFG_T */
/*
* config_nic_rules - apply interface listen/ignore/drop items
*/
#ifndef SIM
void
config_nic_rules(
config_tree *ptree
)
{
nic_rule_node * curr_node;
sockaddr_u addr;
nic_rule_match match_type;
nic_rule_action action;
char * if_name;
char * pchSlash;
int prefixlen;
int addrbits;
curr_node = HEAD_PFIFO(ptree->nic_rules);
if (curr_node != NULL
&& (HAVE_OPT( NOVIRTUALIPS ) || HAVE_OPT( INTERFACE ))) {
msyslog(LOG_ERR,
"interface/nic rules are not allowed with --interface (-I) or --novirtualips (-L)%s",
(input_from_file) ? ", exiting" : "");
if (input_from_file)
exit(1);
else
return;
}
for (; curr_node != NULL; curr_node = curr_node->link) {
prefixlen = -1;
if_name = curr_node->if_name;
if (if_name != NULL)
if_name = estrdup(if_name);
switch (curr_node->match_class) {
default:
/*
* this assignment quiets a gcc "may be used
* uninitialized" warning and is here for no
* other reason.
*/
match_type = MATCH_ALL;
NTP_INSIST(0);
break;
case 0:
/*
* 0 is out of range for valid token T_...
* and in a nic_rules_node indicates the
* interface descriptor is either a name or
* address, stored in if_name in either case.
*/
NTP_INSIST(if_name != NULL);
pchSlash = strchr(if_name, '/');
if (pchSlash != NULL)
*pchSlash = '\0';
if (is_ip_address(if_name, AF_UNSPEC, &addr)) {
match_type = MATCH_IFADDR;
if (pchSlash != NULL) {
sscanf(pchSlash + 1, "%d",
&prefixlen);
addrbits = 8 *
SIZEOF_INADDR(AF(&addr));
prefixlen = max(-1, prefixlen);
prefixlen = min(prefixlen,
addrbits);
}
} else {
match_type = MATCH_IFNAME;
if (pchSlash != NULL)
*pchSlash = '/';
}
break;
case T_All:
match_type = MATCH_ALL;
break;
case T_Ipv4:
match_type = MATCH_IPV4;
break;
case T_Ipv6:
match_type = MATCH_IPV6;
break;
case T_Wildcard:
match_type = MATCH_WILDCARD;
break;
}
switch (curr_node->action) {
default:
/*
* this assignment quiets a gcc "may be used
* uninitialized" warning and is here for no
* other reason.
*/
action = ACTION_LISTEN;
NTP_INSIST(0);
break;
case T_Listen:
action = ACTION_LISTEN;
break;
case T_Ignore:
action = ACTION_IGNORE;
break;
case T_Drop:
action = ACTION_DROP;
break;
}
add_nic_rule(match_type, if_name, prefixlen,
action);
timer_interfacetimeout(current_time + 2);
if (if_name != NULL)
free(if_name);
}
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_nic_rules(
config_tree *ptree
)
{
nic_rule_node *curr_node;
if (ptree->nic_rules != NULL) {
while (1) {
UNLINK_FIFO(curr_node, *ptree->nic_rules, link);
if (NULL == curr_node)
break;
if (curr_node->if_name != NULL)
free(curr_node->if_name);
free(curr_node);
}
free(ptree->nic_rules);
ptree->nic_rules = NULL;
}
}
#endif /* FREE_CFG_T */
static void
apply_enable_disable(
attr_val_fifo * fifo,
int enable
)
{
attr_val *curr_flag;
int option;
#ifdef BC_LIST_FRAMEWORK_NOT_YET_USED
bc_entry *pentry;
#endif
for (curr_flag = HEAD_PFIFO(fifo);
curr_flag != NULL;
curr_flag = curr_flag->link) {
option = curr_flag->value.i;
switch (option) {
default:
msyslog(LOG_ERR,
"can not apply enable/disable token %d, unknown",
option);
break;
case T_Auth:
proto_config(PROTO_AUTHENTICATE, enable, 0., NULL);
break;
case T_Bclient:
proto_config(PROTO_BROADCLIENT, enable, 0., NULL);
break;
case T_Calibrate:
proto_config(PROTO_CAL, enable, 0., NULL);
break;
case T_Kernel:
proto_config(PROTO_KERNEL, enable, 0., NULL);
break;
case T_Monitor:
proto_config(PROTO_MONITOR, enable, 0., NULL);
break;
case T_Ntp:
proto_config(PROTO_NTP, enable, 0., NULL);
break;
case T_Stats:
proto_config(PROTO_FILEGEN, enable, 0., NULL);
break;
#ifdef BC_LIST_FRAMEWORK_NOT_YET_USED
case T_Bc_bugXXXX:
pentry = bc_list;
while (pentry->token) {
if (pentry->token == option)
break;
pentry++;
}
if (!pentry->token) {
msyslog(LOG_ERR,
"compat token %d not in bc_list[]",
option);
continue;
}
pentry->enabled = enable;
break;
#endif
}
}
}
static void
config_system_opts(
config_tree *ptree
)
{
apply_enable_disable(ptree->enable_opts, 1);
apply_enable_disable(ptree->disable_opts, 0);
}
#ifdef FREE_CFG_T
static void
free_config_system_opts(
config_tree *ptree
)
{
FREE_ATTR_VAL_FIFO(ptree->enable_opts);
FREE_ATTR_VAL_FIFO(ptree->disable_opts);
}
#endif /* FREE_CFG_T */
static void
config_logconfig(
config_tree *ptree
)
{
attr_val * my_lc;
my_lc = HEAD_PFIFO(ptree->logconfig);
for (; my_lc != NULL; my_lc = my_lc->link) {
switch (my_lc->attr) {
case '+':
ntp_syslogmask |= get_logmask(my_lc->value.s);
break;
case '-':
ntp_syslogmask &= ~get_logmask(my_lc->value.s);
break;
case '=':
ntp_syslogmask = get_logmask(my_lc->value.s);
break;
}
}
}
#ifdef FREE_CFG_T
static void
free_config_logconfig(
config_tree *ptree
)
{
FREE_ATTR_VAL_FIFO(ptree->logconfig);
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_phone(
config_tree *ptree
)
{
int i;
string_node * sn;
i = 0;
sn = HEAD_PFIFO(ptree->phone);
for (; sn != NULL; sn = sn->link) {
/* need to leave array entry for NULL terminator */
if (i < COUNTOF(sys_phone) - 1) {
sys_phone[i++] = estrdup(sn->s);
sys_phone[i] = NULL;
} else {
msyslog(LOG_INFO,
"phone: Number of phone entries exceeds %lu. Ignoring phone %s...",
(u_long)(COUNTOF(sys_phone) - 1), sn->s);
}
}
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_phone(
config_tree *ptree
)
{
FREE_STRING_FIFO(ptree->phone);
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_qos(
config_tree *ptree
)
{
attr_val * my_qc;
char * s;
#ifdef HAVE_IPTOS_SUPPORT
unsigned int qtos = 0;
#endif
my_qc = HEAD_PFIFO(ptree->qos);
for (; my_qc != NULL; my_qc = my_qc->link) {
s = my_qc->value.s;
#ifdef HAVE_IPTOS_SUPPORT
if (!strcmp(s, "lowdelay"))
qtos = CONF_QOS_LOWDELAY;
else if (!strcmp(s, "throughput"))
qtos = CONF_QOS_THROUGHPUT;
else if (!strcmp(s, "reliability"))
qtos = CONF_QOS_RELIABILITY;
else if (!strcmp(s, "mincost"))
qtos = CONF_QOS_MINCOST;
#ifdef IPTOS_PREC_INTERNETCONTROL
else if (!strcmp(s, "routine") || !strcmp(s, "cs0"))
qtos = CONF_QOS_CS0;
else if (!strcmp(s, "priority") || !strcmp(s, "cs1"))
qtos = CONF_QOS_CS1;
else if (!strcmp(s, "immediate") || !strcmp(s, "cs2"))
qtos = CONF_QOS_CS2;
else if (!strcmp(s, "flash") || !strcmp(s, "cs3"))
qtos = CONF_QOS_CS3; /* overlapping prefix on keyword */
if (!strcmp(s, "flashoverride") || !strcmp(s, "cs4"))
qtos = CONF_QOS_CS4;
else if (!strcmp(s, "critical") || !strcmp(s, "cs5"))
qtos = CONF_QOS_CS5;
else if(!strcmp(s, "internetcontrol") || !strcmp(s, "cs6"))
qtos = CONF_QOS_CS6;
else if (!strcmp(s, "netcontrol") || !strcmp(s, "cs7"))
qtos = CONF_QOS_CS7;
#endif /* IPTOS_PREC_INTERNETCONTROL */
if (qtos == 0)
msyslog(LOG_ERR, "parse error, qos %s not accepted\n", s);
else
qos = qtos;
#endif /* HAVE IPTOS_SUPPORT */
/*
* value is set, but not being effective. Need code to
* change the current connections to notice. Might
* also consider logging a message about the action.
* XXX msyslog(LOG_INFO, "QoS %s requested by config\n", s);
*/
}
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_qos(
config_tree *ptree
)
{
FREE_ATTR_VAL_FIFO(ptree->qos);
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_setvar(
config_tree *ptree
)
{
setvar_node *my_node;
size_t varlen, vallen, octets;
char * str;
str = NULL;
my_node = HEAD_PFIFO(ptree->setvar);
for (; my_node != NULL; my_node = my_node->link) {
varlen = strlen(my_node->var);
vallen = strlen(my_node->val);
octets = varlen + vallen + 1 + 1;
str = erealloc(str, octets);
snprintf(str, octets, "%s=%s", my_node->var,
my_node->val);
set_sys_var(str, octets, (my_node->isdefault)
? DEF
: 0);
}
if (str != NULL)
free(str);
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_setvar(
config_tree *ptree
)
{
FREE_SETVAR_FIFO(ptree->setvar);
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_ttl(
config_tree *ptree
)
{
int i = 0;
int_node *curr_ttl;
curr_ttl = HEAD_PFIFO(ptree->ttl);
for (; curr_ttl != NULL; curr_ttl = curr_ttl->link) {
if (i < COUNTOF(sys_ttl))
sys_ttl[i++] = (u_char)curr_ttl->i;
else
msyslog(LOG_INFO,
"ttl: Number of TTL entries exceeds %lu. Ignoring TTL %d...",
(u_long)COUNTOF(sys_ttl), curr_ttl->i);
}
sys_ttlmax = i - 1;
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_ttl(
config_tree *ptree
)
{
FREE_INT_FIFO(ptree->ttl);
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_trap(
config_tree *ptree
)
{
addr_opts_node *curr_trap;
attr_val *curr_opt;
sockaddr_u addr_sock;
sockaddr_u peeraddr;
struct interface *localaddr;
struct addrinfo hints;
char port_text[8];
settrap_parms *pstp;
u_short port;
int err_flag;
int rc;
/* silence warning about addr_sock potentially uninitialized */
AF(&addr_sock) = AF_UNSPEC;
curr_trap = HEAD_PFIFO(ptree->trap);
for (; curr_trap != NULL; curr_trap = curr_trap->link) {
err_flag = 0;
port = 0;
localaddr = NULL;
curr_opt = HEAD_PFIFO(curr_trap->options);
for (; curr_opt != NULL; curr_opt = curr_opt->link) {
if (T_Port == curr_opt->attr) {
if (curr_opt->value.i < 1
|| curr_opt->value.i > USHRT_MAX) {
msyslog(LOG_ERR,
"invalid port number "
"%d, trap ignored",
curr_opt->value.i);
err_flag = 1;
}
port = (u_short)curr_opt->value.i;
}
else if (T_Interface == curr_opt->attr) {
/* Resolve the interface address */
ZERO_SOCK(&addr_sock);
if (getnetnum(curr_opt->value.s,
&addr_sock, 1, t_UNK) != 1) {
err_flag = 1;
break;
}
localaddr = findinterface(&addr_sock);
if (NULL == localaddr) {
msyslog(LOG_ERR,
"can't find interface with address %s",
stoa(&addr_sock));
err_flag = 1;
}
}
}
/* Now process the trap for the specified interface
* and port number
*/
if (!err_flag) {
if (!port)
port = TRAPPORT;
ZERO_SOCK(&peeraddr);
rc = getnetnum(curr_trap->addr->address,
&peeraddr, 1, t_UNK);
if (1 != rc) {
#ifndef WORKER
msyslog(LOG_ERR,
"trap: unable to use IP address %s.",
curr_trap->addr->address);
#else /* WORKER follows */
/*
* save context and hand it off
* for name resolution.
*/
memset(&hints, 0, sizeof(hints));
hints.ai_protocol = IPPROTO_UDP;
hints.ai_socktype = SOCK_DGRAM;
snprintf(port_text, sizeof(port_text),
"%u", port);
hints.ai_flags = Z_AI_NUMERICSERV;
pstp = emalloc_zero(sizeof(*pstp));
if (localaddr != NULL) {
hints.ai_family = localaddr->family;
pstp->ifaddr_nonnull = 1;
memcpy(&pstp->ifaddr,
&localaddr->sin,
sizeof(pstp->ifaddr));
}
rc = getaddrinfo_sometime(
curr_trap->addr->address,
port_text, &hints,
INITIAL_DNS_RETRY,
&trap_name_resolved,
pstp);
if (!rc)
msyslog(LOG_ERR,
"config_trap: getaddrinfo_sometime(%s,%s): %m",
curr_trap->addr->address,
port_text);
#endif /* WORKER */
continue;
}
/* port is at same location for v4 and v6 */
SET_PORT(&peeraddr, port);
if (NULL == localaddr)
localaddr = ANY_INTERFACE_CHOOSE(&peeraddr);
else
AF(&peeraddr) = AF(&addr_sock);
if (!ctlsettrap(&peeraddr, localaddr, 0,
NTP_VERSION))
msyslog(LOG_ERR,
"set trap %s -> %s failed.",
latoa(localaddr),
stoa(&peeraddr));
}
}
}
/*
* trap_name_resolved()
*
* Callback invoked when config_trap()'s DNS lookup completes.
*/
# ifdef WORKER
void
trap_name_resolved(
int rescode,
int gai_errno,
void * context,
const char * name,
const char * service,
const struct addrinfo * hints,
const struct addrinfo * res
)
{
settrap_parms *pstp;
struct interface *localaddr;
sockaddr_u peeraddr;
pstp = context;
if (rescode) {
msyslog(LOG_ERR,
"giving up resolving trap host %s: %s (%d)",
name, gai_strerror(rescode), rescode);
free(pstp);
return;
}
NTP_INSIST(sizeof(peeraddr) >= res->ai_addrlen);
memset(&peeraddr, 0, sizeof(peeraddr));
memcpy(&peeraddr, res->ai_addr, res->ai_addrlen);
localaddr = NULL;
if (pstp->ifaddr_nonnull)
localaddr = findinterface(&pstp->ifaddr);
if (NULL == localaddr)
localaddr = ANY_INTERFACE_CHOOSE(&peeraddr);
if (!ctlsettrap(&peeraddr, localaddr, 0, NTP_VERSION))
msyslog(LOG_ERR, "set trap %s -> %s failed.",
latoa(localaddr), stoa(&peeraddr));
free(pstp);
}
# endif /* WORKER */
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_trap(
config_tree *ptree
)
{
FREE_ADDR_OPTS_FIFO(ptree->trap);
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_fudge(
config_tree *ptree
)
{
addr_opts_node *curr_fudge;
attr_val *curr_opt;
sockaddr_u addr_sock;
address_node *addr_node;
struct refclockstat clock_stat;
int err_flag;
curr_fudge = HEAD_PFIFO(ptree->fudge);
for (; curr_fudge != NULL; curr_fudge = curr_fudge->link) {
err_flag = 0;
/* Get the reference clock address and
* ensure that it is sane
*/
addr_node = curr_fudge->addr;
ZERO_SOCK(&addr_sock);
if (getnetnum(addr_node->address, &addr_sock, 1, t_REF)
!= 1) {
err_flag = 1;
msyslog(LOG_ERR,
"unrecognized fudge reference clock address %s, line ignored",
stoa(&addr_sock));
}
if (!ISREFCLOCKADR(&addr_sock)) {
err_flag = 1;
msyslog(LOG_ERR,
"inappropriate address %s for the fudge command, line ignored",
stoa(&addr_sock));
}
/* Parse all the options to the fudge command */
memset(&clock_stat, 0, sizeof(clock_stat));
curr_opt = HEAD_PFIFO(curr_fudge->options);
for (; curr_opt != NULL; curr_opt = curr_opt->link) {
switch (curr_opt->attr) {
case T_Time1:
clock_stat.haveflags |= CLK_HAVETIME1;
clock_stat.fudgetime1 = curr_opt->value.d;
break;
case T_Time2:
clock_stat.haveflags |= CLK_HAVETIME2;
clock_stat.fudgetime2 = curr_opt->value.d;
break;
case T_Stratum:
clock_stat.haveflags |= CLK_HAVEVAL1;
clock_stat.fudgeval1 = curr_opt->value.i;
break;
case T_Refid:
clock_stat.haveflags |= CLK_HAVEVAL2;
clock_stat.fudgeval2 = 0;
memcpy(&clock_stat.fudgeval2,
curr_opt->value.s,
min(strlen(curr_opt->value.s), 4));
break;
case T_Flag1:
clock_stat.haveflags |= CLK_HAVEFLAG1;
if (curr_opt->value.i)
clock_stat.flags |= CLK_FLAG1;
else
clock_stat.flags &= ~CLK_FLAG1;
break;
case T_Flag2:
clock_stat.haveflags |= CLK_HAVEFLAG2;
if (curr_opt->value.i)
clock_stat.flags |= CLK_FLAG2;
else
clock_stat.flags &= ~CLK_FLAG2;
break;
case T_Flag3:
clock_stat.haveflags |= CLK_HAVEFLAG3;
if (curr_opt->value.i)
clock_stat.flags |= CLK_FLAG3;
else
clock_stat.flags &= ~CLK_FLAG3;
break;
case T_Flag4:
clock_stat.haveflags |= CLK_HAVEFLAG4;
if (curr_opt->value.i)
clock_stat.flags |= CLK_FLAG4;
else
clock_stat.flags &= ~CLK_FLAG4;
break;
default:
msyslog(LOG_ERR,
"Unexpected fudge flag %s (%d) for %s\n",
token_name(curr_opt->attr),
curr_opt->attr, stoa(&addr_sock));
exit(curr_opt->attr ? curr_opt->attr : 1);
}
}
# ifdef REFCLOCK
if (!err_flag)
refclock_control(&addr_sock, &clock_stat, NULL);
# endif
}
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_fudge(
config_tree *ptree
)
{
FREE_ADDR_OPTS_FIFO(ptree->fudge);
}
#endif /* FREE_CFG_T */
static void
config_vars(
config_tree *ptree
)
{
attr_val *curr_var;
int len;
curr_var = HEAD_PFIFO(ptree->vars);
for (; curr_var != NULL; curr_var = curr_var->link) {
/* Determine which variable to set and set it */
switch (curr_var->attr) {
case T_Broadcastdelay:
proto_config(PROTO_BROADDELAY, 0, curr_var->value.d, NULL);
break;
case T_Tick:
proto_config(PROTO_ADJ, 0, curr_var->value.d, NULL);
break;
case T_Driftfile:
if ('\0' == curr_var->value.s[0]) {
stats_drift_file = 0;
msyslog(LOG_INFO, "config: driftfile disabled\n");
} else
stats_config(STATS_FREQ_FILE, curr_var->value.s);
break;
case T_Ident:
sys_ident = curr_var->value.s;
break;
case T_WanderThreshold: /* FALLTHROUGH */
case T_Nonvolatile:
wander_threshold = curr_var->value.d;
break;
case T_Leapfile:
stats_config(STATS_LEAP_FILE, curr_var->value.s);
break;
case T_Pidfile:
stats_config(STATS_PID_FILE, curr_var->value.s);
break;
case T_Logfile:
if (-1 == change_logfile(curr_var->value.s, 0))
msyslog(LOG_ERR,
"Cannot open logfile %s: %m",
curr_var->value.s);
break;
case T_Saveconfigdir:
if (saveconfigdir != NULL)
free(saveconfigdir);
len = strlen(curr_var->value.s);
if (0 == len) {
saveconfigdir = NULL;
} else if (DIR_SEP != curr_var->value.s[len - 1]
#ifdef SYS_WINNT /* slash is also a dir. sep. on Windows */
&& '/' != curr_var->value.s[len - 1]
#endif
) {
len++;
saveconfigdir = emalloc(len + 1);
snprintf(saveconfigdir, len + 1,
"%s%c",
curr_var->value.s,
DIR_SEP);
} else {
saveconfigdir = estrdup(
curr_var->value.s);
}
break;
case T_Automax:
#ifdef AUTOKEY
sys_automax = curr_var->value.i;
#endif
break;
default:
msyslog(LOG_ERR,
"config_vars(): unexpected token %d",
curr_var->attr);
}
}
}
#ifdef FREE_CFG_T
static void
free_config_vars(
config_tree *ptree
)
{
FREE_ATTR_VAL_FIFO(ptree->vars);
}
#endif /* FREE_CFG_T */
/* Define a function to check if a resolved address is sane.
* If yes, return 1, else return 0;
*/
static int
is_sane_resolved_address(
sockaddr_u * peeraddr,
int hmode
)
{
if (!ISREFCLOCKADR(peeraddr) && ISBADADR(peeraddr)) {
msyslog(LOG_ERR,
"attempt to configure invalid address %s",
stoa(peeraddr));
return 0;
}
/*
* Shouldn't be able to specify multicast
* address for server/peer!
* and unicast address for manycastclient!
*/
if ((T_Server == hmode || T_Peer == hmode || T_Pool == hmode)
&& IS_MCAST(peeraddr)) {
msyslog(LOG_ERR,
"attempt to configure invalid address %s",
stoa(peeraddr));
return 0;
}
if (T_Manycastclient == hmode && !IS_MCAST(peeraddr)) {
msyslog(LOG_ERR,
"attempt to configure invalid address %s",
stoa(peeraddr));
return 0;
}
if (IS_IPV6(peeraddr) && !ipv6_works)
return 0;
/* Ok, all tests succeeded, now we can return 1 */
return 1;
}
#ifndef SIM
static u_char
get_correct_host_mode(
int token
)
{
switch (token) {
case T_Server:
case T_Pool:
case T_Manycastclient:
return MODE_CLIENT;
case T_Peer:
return MODE_ACTIVE;
case T_Broadcast:
return MODE_BROADCAST;
default:
return 0;
}
}
/*
* peerflag_bits() get config_peers() peerflags value from a
* peer_node's queue of flag attr_val entries.
*/
static int
peerflag_bits(
peer_node *pn
)
{
int peerflags;
attr_val *option;
/* translate peerflags options to bits */
peerflags = 0;
option = HEAD_PFIFO(pn->peerflags);
for (; option != NULL; option = option->link) {
switch (option->value.i) {
default:
NTP_INSIST(0);
break;
case T_Autokey:
peerflags |= FLAG_SKEY;
break;
case T_Burst:
peerflags |= FLAG_BURST;
break;
case T_Iburst:
peerflags |= FLAG_IBURST;
break;
case T_Noselect:
peerflags |= FLAG_NOSELECT;
break;
case T_Preempt:
peerflags |= FLAG_PREEMPT;
break;
case T_Prefer:
peerflags |= FLAG_PREFER;
break;
case T_True:
peerflags |= FLAG_TRUE;
break;
case T_Xleave:
peerflags |= FLAG_XLEAVE;
break;
}
}
return peerflags;
}
static void
config_peers(
config_tree *ptree
)
{
sockaddr_u peeraddr;
struct addrinfo hints;
peer_node * curr_peer;
peer_resolved_ctx * ctx;
u_char hmode;
/* add servers named on the command line with iburst implied */
for (;
cmdline_server_count > 0;
cmdline_server_count--, cmdline_servers++) {
ZERO_SOCK(&peeraddr);
/*
* If we have a numeric address, we can safely
* proceed in the mainline with it. Otherwise, hand
* the hostname off to the blocking child.
*/
if (is_ip_address(*cmdline_servers, AF_UNSPEC,
&peeraddr)) {
SET_PORT(&peeraddr, NTP_PORT);
if (is_sane_resolved_address(&peeraddr,
T_Server))
peer_config(
&peeraddr,
NULL,
NULL,
MODE_CLIENT,
NTP_VERSION,
0,
0,
FLAG_IBURST,
0,
0,
NULL);
} else {
/* we have a hostname to resolve */
# ifdef WORKER
ctx = emalloc_zero(sizeof(*ctx));
ctx->family = AF_UNSPEC;
ctx->host_mode = T_Server;
ctx->hmode = MODE_CLIENT;
ctx->version = NTP_VERSION;
ctx->flags = FLAG_IBURST;
memset(&hints, 0, sizeof(hints));
hints.ai_family = (u_short)ctx->family;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
getaddrinfo_sometime(*cmdline_servers,
"ntp", &hints,
INITIAL_DNS_RETRY,
&peer_name_resolved,
(void *)ctx);
# else /* !WORKER follows */
msyslog(LOG_ERR,
"hostname %s can not be used, please use IP address instead.\n",
curr_peer->addr->address);
# endif
}
}
/* add associations from the configuration file */
curr_peer = HEAD_PFIFO(ptree->peers);
for (; curr_peer != NULL; curr_peer = curr_peer->link) {
ZERO_SOCK(&peeraddr);
/* Find the correct host-mode */
hmode = get_correct_host_mode(curr_peer->host_mode);
NTP_INSIST(hmode != 0);
if (T_Pool == curr_peer->host_mode) {
AF(&peeraddr) = curr_peer->addr->type;
peer_config(
&peeraddr,
curr_peer->addr->address,
NULL,
hmode,
curr_peer->peerversion,
curr_peer->minpoll,
curr_peer->maxpoll,
peerflag_bits(curr_peer),
curr_peer->ttl,
curr_peer->peerkey,
curr_peer->group);
/*
* If we have a numeric address, we can safely
* proceed in the mainline with it. Otherwise, hand
* the hostname off to the blocking child.
*/
} else if (is_ip_address(curr_peer->addr->address,
curr_peer->addr->type, &peeraddr)) {
SET_PORT(&peeraddr, NTP_PORT);
if (is_sane_resolved_address(&peeraddr,
curr_peer->host_mode))
peer_config(
&peeraddr,
NULL,
NULL,
hmode,
curr_peer->peerversion,
curr_peer->minpoll,
curr_peer->maxpoll,
peerflag_bits(curr_peer),
curr_peer->ttl,
curr_peer->peerkey,
curr_peer->group);
} else {
/* we have a hostname to resolve */
# ifdef WORKER
ctx = emalloc_zero(sizeof(*ctx));
ctx->family = curr_peer->addr->type;
ctx->host_mode = curr_peer->host_mode;
ctx->hmode = hmode;
ctx->version = curr_peer->peerversion;
ctx->minpoll = curr_peer->minpoll;
ctx->maxpoll = curr_peer->maxpoll;
ctx->flags = peerflag_bits(curr_peer);
ctx->ttl = curr_peer->ttl;
ctx->keyid = curr_peer->peerkey;
ctx->group = curr_peer->group;
memset(&hints, 0, sizeof(hints));
hints.ai_family = ctx->family;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
getaddrinfo_sometime(curr_peer->addr->address,
"ntp", &hints,
INITIAL_DNS_RETRY,
&peer_name_resolved, ctx);
# else /* !WORKER follows */
msyslog(LOG_ERR,
"hostname %s can not be used, please use IP address instead.\n",
curr_peer->addr->address);
# endif
}
}
}
#endif /* !SIM */
/*
* peer_name_resolved()
*
* Callback invoked when config_peers()'s DNS lookup completes.
*/
#ifdef WORKER
void
peer_name_resolved(
int rescode,
int gai_errno,
void * context,
const char * name,
const char * service,
const struct addrinfo * hints,
const struct addrinfo * res
)
{
sockaddr_u peeraddr;
peer_resolved_ctx * ctx;
u_short af;
const char * fam_spec;
ctx = context;
DPRINTF(1, ("peer_name_resolved(%s) rescode %d\n", name, rescode));
if (rescode) {
#ifndef IGNORE_DNS_ERRORS
free(ctx);
msyslog(LOG_ERR,
"giving up resolving host %s: %s (%d)",
name, gai_strerror(rescode), rescode);
#else /* IGNORE_DNS_ERRORS follows */
getaddrinfo_sometime(name, service, hints,
INITIAL_DNS_RETRY,
&peer_name_resolved, context);
#endif
return;
}
/* Loop to configure a single association */
for (; res != NULL; res = res->ai_next) {
memcpy(&peeraddr, res->ai_addr, res->ai_addrlen);
if (is_sane_resolved_address(&peeraddr,
ctx->host_mode)) {
NLOG(NLOG_SYSINFO) {
af = ctx->family;
fam_spec = (AF_INET6 == af)
? "(AAAA) "
: (AF_INET == af)
? "(A) "
: "";
msyslog(LOG_INFO, "DNS %s %s-> %s",
name, fam_spec,
stoa(&peeraddr));
}
peer_config(
&peeraddr,
NULL,
NULL,
ctx->hmode,
ctx->version,
ctx->minpoll,
ctx->maxpoll,
ctx->flags,
ctx->ttl,
ctx->keyid,
ctx->group);
break;
}
}
free(ctx);
}
#endif /* WORKER */
#ifdef FREE_CFG_T
static void
free_config_peers(
config_tree *ptree
)
{
peer_node *curr_peer;
if (ptree->peers != NULL) {
while (1) {
UNLINK_FIFO(curr_peer, *ptree->peers, link);
if (NULL == curr_peer)
break;
destroy_address_node(curr_peer->addr);
destroy_attr_val_fifo(curr_peer->peerflags);
free(curr_peer);
}
free(ptree->peers);
ptree->peers = NULL;
}
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_unpeers(
config_tree *ptree
)
{
sockaddr_u peeraddr;
struct addrinfo hints;
unpeer_node * curr_unpeer;
struct peer * p;
const char * name;
int rc;
curr_unpeer = HEAD_PFIFO(ptree->unpeers);
for (; curr_unpeer != NULL; curr_unpeer = curr_unpeer->link) {
/*
* Either AssocID will be zero, and we unpeer by name/
* address addr, or it is nonzero and addr NULL.
*/
if (curr_unpeer->assocID) {
p = findpeerbyassoc(curr_unpeer->assocID);
if (p != NULL) {
msyslog(LOG_NOTICE, "unpeered %s",
stoa(&p->srcadr));
peer_clear(p, "GONE");
unpeer(p);
}
continue;
}
memset(&peeraddr, 0, sizeof(peeraddr));
AF(&peeraddr) = curr_unpeer->addr->type;
name = curr_unpeer->addr->address;
rc = getnetnum(name, &peeraddr, 0, t_UNK);
/* Do we have a numeric address? */
if (rc > 0) {
DPRINTF(1, ("unpeer: searching for %s\n",
stoa(&peeraddr)));
p = findexistingpeer(&peeraddr, NULL, NULL, -1);
if (p != NULL) {
msyslog(LOG_NOTICE, "unpeered %s",
stoa(&peeraddr));
peer_clear(p, "GONE");
unpeer(p);
}
continue;
}
/*
* It's not a numeric IP address, it's a hostname.
* Check for associations with a matching hostname.
*/
for (p = peer_list; p != NULL; p = p->p_link)
if (p->hostname != NULL)
if (!strcasecmp(p->hostname, name))
break;
if (p != NULL) {
msyslog(LOG_NOTICE, "unpeered %s", name);
peer_clear(p, "GONE");
unpeer(p);
}
/* Resolve the hostname to address(es). */
# ifdef WORKER
memset(&hints, 0, sizeof(hints));
hints.ai_family = curr_unpeer->addr->type;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
getaddrinfo_sometime(name, "ntp", &hints,
INITIAL_DNS_RETRY,
&unpeer_name_resolved, NULL);
# else /* !WORKER follows */
msyslog(LOG_ERR,
"hostname %s can not be used, please use IP address instead.\n",
name);
# endif
}
}
#endif /* !SIM */
/*
* unpeer_name_resolved()
*
* Callback invoked when config_unpeers()'s DNS lookup completes.
*/
#ifdef WORKER
void
unpeer_name_resolved(
int rescode,
int gai_errno,
void * context,
const char * name,
const char * service,
const struct addrinfo * hints,
const struct addrinfo * res
)
{
sockaddr_u peeraddr;
struct peer * peer;
u_short af;
const char * fam_spec;
DPRINTF(1, ("unpeer_name_resolved(%s) rescode %d\n", name, rescode));
if (rescode) {
msyslog(LOG_ERR, "giving up resolving unpeer %s: %s (%d)",
name, gai_strerror(rescode), rescode);
return;
}
/*
* Loop through the addresses found
*/
for (; res != NULL; res = res->ai_next) {
NTP_INSIST(res->ai_addrlen <= sizeof(peeraddr));
memcpy(&peeraddr, res->ai_addr, res->ai_addrlen);
DPRINTF(1, ("unpeer: searching for peer %s\n",
stoa(&peeraddr)));
peer = findexistingpeer(&peeraddr, NULL, NULL, -1);
if (peer != NULL) {
af = AF(&peeraddr);
fam_spec = (AF_INET6 == af)
? "(AAAA) "
: (AF_INET == af)
? "(A) "
: "";
msyslog(LOG_NOTICE, "unpeered %s %s-> %s", name,
fam_spec, stoa(&peeraddr));
peer_clear(peer, "GONE");
unpeer(peer);
}
}
}
#endif /* WORKER */
#ifdef FREE_CFG_T
static void
free_config_unpeers(
config_tree *ptree
)
{
unpeer_node *curr_unpeer;
if (ptree->unpeers != NULL) {
while (1) {
UNLINK_FIFO(curr_unpeer, *ptree->unpeers, link);
if (NULL == curr_unpeer)
break;
destroy_address_node(curr_unpeer->addr);
free(curr_unpeer);
}
free(ptree->unpeers);
}
}
#endif /* FREE_CFG_T */
#ifdef SIM
static void
config_sim(
config_tree *ptree
)
{
int i;
server_info *serv_info;
attr_val *init_stmt;
sim_node *sim_n;
/* Check if a simulate block was found in the configuration code.
* If not, return an error and exit
*/
sim_n = HEAD_PFIFO(ptree->sim_details);
if (NULL == sim_n) {
fprintf(stderr, "ERROR!! I couldn't find a \"simulate\" block for configuring the simulator.\n");
fprintf(stderr, "\tCheck your configuration file.\n");
exit(1);
}
/* Process the initialization statements
* -------------------------------------
*/
init_stmt = HEAD_PFIFO(sim_n->init_opts);
for (; init_stmt != NULL; init_stmt = init_stmt->link) {
switch(init_stmt->attr) {
case T_Beep_Delay:
simulation.beep_delay = init_stmt->value.d;
break;
case T_Sim_Duration:
simulation.end_time = init_stmt->value.d;
break;
default:
fprintf(stderr,
"Unknown simulator init token %d\n",
init_stmt->attr);
exit(1);
}
}
/* Process the server list
* -----------------------
*/
simulation.num_of_servers = 0;
serv_info = HEAD_PFIFO(sim_n->servers);
for (; serv_info != NULL; serv_info = serv_info->link)
simulation.num_of_servers++;
simulation.servers = emalloc(simulation.num_of_servers *
sizeof(simulation.servers[0]));
i = 0;
serv_info = HEAD_PFIFO(sim_n->servers);
for (; serv_info != NULL; serv_info = serv_info->link) {
if (NULL == serv_info) {
fprintf(stderr, "Simulator server list is corrupt\n");
exit(1);
} else {
simulation.servers[i] = *serv_info;
simulation.servers[i].link = NULL;
i++;
}
}
printf("Creating server associations\n");
create_server_associations();
fprintf(stderr,"\tServer associations successfully created!!\n");
}
#ifdef FREE_CFG_T
static void
free_config_sim(
config_tree *ptree
)
{
sim_node *sim_n;
server_info *serv_n;
script_info *script_n;
if (NULL == ptree->sim_details)
return;
sim_n = HEAD_PFIFO(ptree->sim_details);
free(ptree->sim_details);
ptree->sim_details = NULL;
if (NULL == sim_n)
return;
FREE_ATTR_VAL_FIFO(sim_n->init_opts);
while (1) {
UNLINK_FIFO(serv_n, *sim_n->servers, link);
if (NULL == serv_n)
break;
script_n = serv_n->curr_script;
while (script_n != NULL) {
free(script_n);
if (serv_n->script != NULL)
UNLINK_FIFO(script_n, *serv_n->script,
link);
else
break;
}
if (serv_n->script != NULL)
free(serv_n->script);
free(serv_n);
}
free(sim_n);
}
#endif /* FREE_CFG_T */
#endif /* SIM */
/* Define two different config functions. One for the daemon and the other for
* the simulator. The simulator ignores a lot of the standard ntpd configuration
* options
*/
#ifndef SIM
static void
config_ntpd(
config_tree *ptree
)
{
config_nic_rules(ptree);
io_open_sockets();
config_monitor(ptree);
config_auth(ptree);
config_tos(ptree);
config_access(ptree);
config_tinker(ptree);
config_system_opts(ptree);
config_logconfig(ptree);
config_phone(ptree);
config_setvar(ptree);
config_ttl(ptree);
config_trap(ptree);
config_vars(ptree);
config_other_modes(ptree);
config_peers(ptree);
config_unpeers(ptree);
config_fudge(ptree);
config_qos(ptree);
#ifdef TEST_BLOCKING_WORKER
{
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
getaddrinfo_sometime("www.cnn.com", "ntp", &hints,
INITIAL_DNS_RETRY,
gai_test_callback, (void *)1);
hints.ai_family = AF_INET6;
getaddrinfo_sometime("ipv6.google.com", "ntp", &hints,
INITIAL_DNS_RETRY,
gai_test_callback, (void *)0x600);
}
#endif
}
#endif /* !SIM */
#ifdef SIM
static void
config_ntpdsim(
config_tree *ptree
)
{
printf("Configuring Simulator...\n");
printf("Some ntpd-specific commands in the configuration file will be ignored.\n");
config_tos(ptree);
config_monitor(ptree);
config_tinker(ptree);
config_system_opts(ptree);
config_logconfig(ptree);
config_vars(ptree);
config_sim(ptree);
}
#endif /* SIM */
/*
* config_remotely() - implements ntpd side of ntpq :config
*/
void
config_remotely(
sockaddr_u * remote_addr
)
{
struct FILE_INFO remote_cuckoo;
char origin[128];
snprintf(origin, sizeof(origin), "remote config from %s",
stoa(remote_addr));
memset(&remote_cuckoo, 0, sizeof(remote_cuckoo));
remote_cuckoo.fname = origin;
remote_cuckoo.line_no = 1;
remote_cuckoo.col_no = 1;
ip_file = &remote_cuckoo;
input_from_file = 0;
init_syntax_tree(&cfgt);
yyparse();
cfgt.source.attr = CONF_SOURCE_NTPQ;
cfgt.timestamp = time(NULL);
cfgt.source.value.s = estrdup(stoa(remote_addr));
DPRINTF(1, ("Finished Parsing!!\n"));
save_and_apply_config_tree();
input_from_file = 1;
}
/*
* getconfig() - process startup configuration file e.g /etc/ntp.conf
*/
void
getconfig(
int argc,
char ** argv
)
{
char line[MAXLINE];
#ifdef DEBUG
atexit(free_all_config_trees);
#endif
#ifndef SYS_WINNT
config_file = CONFIG_FILE;
#else
temp = CONFIG_FILE;
if (!ExpandEnvironmentStrings((LPCTSTR)temp, (LPTSTR)config_file_storage, (DWORD)sizeof(config_file_storage))) {
msyslog(LOG_ERR, "ExpandEnvironmentStrings CONFIG_FILE failed: %m\n");
exit(1);
}
config_file = config_file_storage;
temp = ALT_CONFIG_FILE;
if (!ExpandEnvironmentStrings((LPCTSTR)temp, (LPTSTR)alt_config_file_storage, (DWORD)sizeof(alt_config_file_storage))) {
msyslog(LOG_ERR, "ExpandEnvironmentStrings ALT_CONFIG_FILE failed: %m\n");
exit(1);
}
alt_config_file = alt_config_file_storage;
#endif /* SYS_WINNT */
/*
* install a non default variable with this daemon version
*/
snprintf(line, sizeof(line), "daemon_version=\"%s\"", Version);
set_sys_var(line, strlen(line)+1, RO);
/*
* Set up for the first time step to install a variable showing
* which syscall is being used to step.
*/
set_tod_using = &ntpd_set_tod_using;
/*
* On Windows, the variable has already been set, on the rest,
* initialize it to "UNKNOWN".
*/
#ifndef SYS_WINNT
strncpy(line, "settimeofday=\"UNKNOWN\"", sizeof(line));
set_sys_var(line, strlen(line) + 1, RO);
#endif
getCmdOpts(argc, argv);
init_syntax_tree(&cfgt);
curr_include_level = 0;
if (
(fp[curr_include_level] = F_OPEN(FindConfig(config_file), "r")) == NULL
#ifdef HAVE_NETINFO
/* If there is no config_file, try NetInfo. */
&& check_netinfo && !(config_netinfo = get_netinfo_config())
#endif /* HAVE_NETINFO */
) {
msyslog(LOG_INFO, "getconfig: Couldn't open <%s>", FindConfig(config_file));
#ifndef SYS_WINNT
io_open_sockets();
return;
#else
/* Under WinNT try alternate_config_file name, first NTP.CONF, then NTP.INI */
if ((fp[curr_include_level] = F_OPEN(FindConfig(alt_config_file), "r")) == NULL) {
/*
* Broadcast clients can sometimes run without
* a configuration file.
*/
msyslog(LOG_INFO, "getconfig: Couldn't open <%s>", FindConfig(alt_config_file));
io_open_sockets();
return;
}
cfgt.source.value.s = estrdup(alt_config_file);
#endif /* SYS_WINNT */
} else
cfgt.source.value.s = estrdup(config_file);
/*** BULK OF THE PARSER ***/
#ifdef DEBUG
yydebug = !!(debug >= 5);
#endif
ip_file = fp[curr_include_level];
yyparse();
DPRINTF(1, ("Finished Parsing!!\n"));
cfgt.source.attr = CONF_SOURCE_FILE;
cfgt.timestamp = time(NULL);
save_and_apply_config_tree();
while (curr_include_level != -1)
FCLOSE(fp[curr_include_level--]);
#ifdef HAVE_NETINFO
if (config_netinfo)
free_netinfo_config(config_netinfo);
#endif /* HAVE_NETINFO */
}
void
save_and_apply_config_tree(void)
{
config_tree *ptree;
#ifndef SAVECONFIG
config_tree *punlinked;
#endif
/*
* Keep all the configuration trees applied since startup in
* a list that can be used to dump the configuration back to
* a text file.
*/
ptree = emalloc(sizeof(*ptree));
memcpy(ptree, &cfgt, sizeof(*ptree));
memset(&cfgt, 0, sizeof(cfgt));
LINK_TAIL_SLIST(cfg_tree_history, ptree, link, config_tree);
#ifdef SAVECONFIG
if (HAVE_OPT( SAVECONFIGQUIT )) {
FILE *dumpfile;
int err;
int dumpfailed;
dumpfile = fopen(OPT_ARG( SAVECONFIGQUIT ), "w");
if (NULL == dumpfile) {
err = errno;
fprintf(stderr,
"can not create save file %s, error %d %s\n",
OPT_ARG( SAVECONFIGQUIT ), err,
strerror(err));
exit(err);
}
dumpfailed = dump_all_config_trees(dumpfile, 0);
if (dumpfailed)
fprintf(stderr,
"--saveconfigquit %s error %d\n",
OPT_ARG( SAVECONFIGQUIT ),
dumpfailed);
else
fprintf(stderr,
"configuration saved to %s\n",
OPT_ARG( SAVECONFIGQUIT ));
exit(dumpfailed);
}
#endif /* SAVECONFIG */
/* The actual configuration done depends on whether we are configuring the
* simulator or the daemon. Perform a check and call the appropriate
* function as needed.
*/
#ifndef SIM
config_ntpd(ptree);
#else
config_ntpdsim(ptree);
#endif
/*
* With configure --disable-saveconfig, there's no use keeping
* the config tree around after application, so free it.
*/
#ifndef SAVECONFIG
UNLINK_SLIST(punlinked, cfg_tree_history, ptree, link,
config_tree);
NTP_INSIST(punlinked == ptree);
free_config_tree(ptree);
#endif
}
void
ntpd_set_tod_using(
const char *which
)
{
char line[128];
snprintf(line, sizeof(line), "settimeofday=\"%s\"", which);
set_sys_var(line, strlen(line) + 1, RO);
}
static char *
normal_dtoa(
double d
)
{
char * buf;
char * pch_e;
char * pch_nz;
LIB_GETBUF(buf);
snprintf(buf, LIB_BUFLENGTH, "%g", d);
/* use lowercase 'e', strip any leading zeroes in exponent */
pch_e = strchr(buf, 'e');
if (NULL == pch_e) {
pch_e = strchr(buf, 'E');
if (NULL == pch_e)
return buf;
*pch_e = 'e';
}
pch_e++;
if ('-' == *pch_e)
pch_e++;
pch_nz = pch_e;
while ('0' == *pch_nz)
pch_nz++;
if (pch_nz == pch_e)
return buf;
strncpy(pch_e, pch_nz, LIB_BUFLENGTH - (pch_e - buf));
return buf;
}
/* FUNCTIONS COPIED FROM THE OLDER ntp_config.c
* --------------------------------------------
*/
/*
* get_pfxmatch - find value for prefixmatch
* and update char * accordingly
*/
static unsigned long
get_pfxmatch(
char ** s,
struct masks *m
)
{
while (m->name) {
if (strncmp(*s, m->name, strlen(m->name)) == 0) {
*s += strlen(m->name);
return m->mask;
} else {
m++;
}
}
return 0;
}
/*
* get_match - find logmask value
*/
static unsigned long
get_match(
char *s,
struct masks *m
)
{
while (m->name) {
if (strcmp(s, m->name) == 0)
return m->mask;
else
m++;
}
return 0;
}
/*
* get_logmask - build bitmask for ntp_syslogmask
*/
static unsigned long
get_logmask(
char *s
)
{
char *t;
unsigned long offset;
unsigned long mask;
t = s;
offset = get_pfxmatch(&t, logcfg_class);
mask = get_match(t, logcfg_item);
if (mask)
return mask << offset;
else
msyslog(LOG_ERR, "logconfig: illegal argument %s - ignored", s);
return 0;
}
#ifdef HAVE_NETINFO
/*
* get_netinfo_config - find the nearest NetInfo domain with an ntp
* configuration and initialize the configuration state.
*/
static struct netinfo_config_state *
get_netinfo_config(void)
{
ni_status status;
void *domain;
ni_id config_dir;
struct netinfo_config_state *config;
if (ni_open(NULL, ".", &domain) != NI_OK) return NULL;
while ((status = ni_pathsearch(domain, &config_dir, NETINFO_CONFIG_DIR)) == NI_NODIR) {
void *next_domain;
if (ni_open(domain, "..", &next_domain) != NI_OK) {
ni_free(next_domain);
break;
}
ni_free(domain);
domain = next_domain;
}
if (status != NI_OK) {
ni_free(domain);
return NULL;
}
config = emalloc(sizeof(*config));
config->domain = domain;
config->config_dir = config_dir;
config->prop_index = 0;
config->val_index = 0;
config->val_list = NULL;
return config;
}
/*
* free_netinfo_config - release NetInfo configuration state
*/
static void
free_netinfo_config(
struct netinfo_config_state *config
)
{
ni_free(config->domain);
free(config);
}
/*
* gettokens_netinfo - return tokens from NetInfo
*/
static int
gettokens_netinfo (
struct netinfo_config_state *config,
char **tokenlist,
int *ntokens
)
{
int prop_index = config->prop_index;
int val_index = config->val_index;
char **val_list = config->val_list;
/*
* Iterate through each keyword and look for a property that matches it.
*/
again:
if (!val_list) {
for (; prop_index < COUNTOF(keywords); prop_index++)
{
ni_namelist namelist;
struct keyword current_prop = keywords[prop_index];
ni_index index;
/*
* For each value associated in the property, we're going to return
* a separate line. We squirrel away the values in the config state
* so the next time through, we don't need to do this lookup.
*/
NI_INIT(&namelist);
if (NI_OK == ni_lookupprop(config->domain,
&config->config_dir, current_prop.text,
&namelist)) {
/* Found the property, but it has no values */
if (namelist.ni_namelist_len == 0) continue;
config->val_list =
emalloc(sizeof(char*) *
(namelist.ni_namelist_len + 1));
val_list = config->val_list;
for (index = 0;
index < namelist.ni_namelist_len;
index++) {
char *value;
value = namelist.ni_namelist_val[index];
val_list[index] = estrdup(value);
}
val_list[index] = NULL;
break;
}
ni_namelist_free(&namelist);
}
config->prop_index = prop_index;
}
/* No list; we're done here. */
if (!val_list)
return CONFIG_UNKNOWN;
/*
* We have a list of values for the current property.
* Iterate through them and return each in order.
*/
if (val_list[val_index]) {
int ntok = 1;
int quoted = 0;
char *tokens = val_list[val_index];
msyslog(LOG_INFO, "%s %s", keywords[prop_index].text, val_list[val_index]);
(const char*)tokenlist[0] = keywords[prop_index].text;
for (ntok = 1; ntok < MAXTOKENS; ntok++) {
tokenlist[ntok] = tokens;
while (!ISEOL(*tokens) && (!ISSPACE(*tokens) || quoted))
quoted ^= (*tokens++ == '"');
if (ISEOL(*tokens)) {
*tokens = '\0';
break;
} else { /* must be space */
*tokens++ = '\0';
while (ISSPACE(*tokens))
tokens++;
if (ISEOL(*tokens))
break;
}
}
if (ntok == MAXTOKENS) {
/* HMS: chomp it to lose the EOL? */
msyslog(LOG_ERR,
"gettokens_netinfo: too many tokens. Ignoring: %s",
tokens);
} else {
*ntokens = ntok + 1;
}
config->val_index++; /* HMS: Should this be in the 'else'? */
return keywords[prop_index].keytype;
}
/* We're done with the current property. */
prop_index = ++config->prop_index;
/* Free val_list and reset counters. */
for (val_index = 0; val_list[val_index]; val_index++)
free(val_list[val_index]);
free(val_list);
val_list = config->val_list = NULL;
val_index = config->val_index = 0;
goto again;
}
#endif /* HAVE_NETINFO */
/*
* getnetnum - return a net number (this is crude, but careful)
*
* returns 1 for success, and mysteriously, 0 for most failures, and
* -1 if the address found is IPv6 and we believe IPv6 isn't working.
*/
#ifndef SIM
static int
getnetnum(
const char *num,
sockaddr_u *addr,
int complain,
enum gnn_type a_type /* ignored */
)
{
NTP_REQUIRE(AF_UNSPEC == AF(addr) ||
AF_INET == AF(addr) ||
AF_INET6 == AF(addr));
if (!is_ip_address(num, AF(addr), addr))
return 0;
if (IS_IPV6(addr) && !ipv6_works)
return -1;
# ifdef ISC_PLATFORM_HAVESALEN
addr->sa.sa_len = SIZEOF_SOCKADDR(AF(addr));
# endif
SET_PORT(addr, NTP_PORT);
DPRINTF(2, ("getnetnum given %s, got %s\n", num, stoa(addr)));
return 1;
}
#endif /* !SIM */
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_1658_2 |
crossvul-cpp_data_good_4790_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% M M AAA TTTTT L AAA BBBB %
% MM MM A A T L A A B B %
% M M M AAAAA T L AAAAA BBBB %
% M M A A T L A A B B %
% M M A A T LLLLL A A BBBB %
% %
% %
% Read MATLAB Image Format %
% %
% Software Design %
% Jaroslav Fojtik %
% 2001-2008 %
% %
% %
% Permission is hereby granted, free of charge, to any person obtaining a %
% copy of this software and associated documentation files ("ImageMagick"), %
% to deal in ImageMagick without restriction, including without limitation %
% the rights to use, copy, modify, merge, publish, distribute, sublicense, %
% and/or sell copies of ImageMagick, and to permit persons to whom the %
% ImageMagick is furnished to do so, subject to the following conditions: %
% %
% The above copyright notice and this permission notice shall be included in %
% all copies or substantial portions of ImageMagick. %
% %
% The software is provided "as is", without warranty of any kind, express or %
% implied, including but not limited to the warranties of merchantability, %
% fitness for a particular purpose and noninfringement. In no event shall %
% ImageMagick Studio be liable for any claim, damages or other liability, %
% whether in an action of contract, tort or otherwise, arising from, out of %
% or in connection with ImageMagick or the use or other dealings in %
% ImageMagick. %
% %
% Except as contained in this notice, the name of the ImageMagick Studio %
% shall not be used in advertising or otherwise to promote the sale, use or %
% other dealings in ImageMagick without prior written authorization from the %
% ImageMagick Studio. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace-private.h"
#include "magick/distort.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#include "magick/transform.h"
#include "magick/utility-private.h"
#if defined(MAGICKCORE_ZLIB_DELEGATE)
#include "zlib.h"
#endif
/*
Forward declaration.
*/
static MagickBooleanType
WriteMATImage(const ImageInfo *,Image *);
/* Auto coloring method, sorry this creates some artefact inside data
MinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black
MinReal+j*0 = white MaxReal+j*0 = black
MinReal+j*MinComplex = blue MaxReal+j*MinComplex = black
*/
typedef struct
{
char identific[124];
unsigned short Version;
char EndianIndicator[2];
unsigned long DataType;
unsigned long ObjectSize;
unsigned long unknown1;
unsigned long unknown2;
unsigned short unknown5;
unsigned char StructureFlag;
unsigned char StructureClass;
unsigned long unknown3;
unsigned long unknown4;
unsigned long DimFlag;
unsigned long SizeX;
unsigned long SizeY;
unsigned short Flag1;
unsigned short NameFlag;
}
MATHeader;
static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
static const char *OsDesc=
#if defined(MAGICKCORE_WINDOWS_SUPPORT)
"PCWIN";
#else
#ifdef __APPLE__
"MAC";
#else
"LNX86";
#endif
#endif
typedef enum
{
miINT8 = 1, /* 8 bit signed */
miUINT8, /* 8 bit unsigned */
miINT16, /* 16 bit signed */
miUINT16, /* 16 bit unsigned */
miINT32, /* 32 bit signed */
miUINT32, /* 32 bit unsigned */
miSINGLE, /* IEEE 754 single precision float */
miRESERVE1,
miDOUBLE, /* IEEE 754 double precision float */
miRESERVE2,
miRESERVE3,
miINT64, /* 64 bit signed */
miUINT64, /* 64 bit unsigned */
miMATRIX, /* MATLAB array */
miCOMPRESSED, /* Compressed Data */
miUTF8, /* Unicode UTF-8 Encoded Character Data */
miUTF16, /* Unicode UTF-16 Encoded Character Data */
miUTF32 /* Unicode UTF-32 Encoded Character Data */
} mat5_data_type;
typedef enum
{
mxCELL_CLASS=1, /* cell array */
mxSTRUCT_CLASS, /* structure */
mxOBJECT_CLASS, /* object */
mxCHAR_CLASS, /* character array */
mxSPARSE_CLASS, /* sparse array */
mxDOUBLE_CLASS, /* double precision array */
mxSINGLE_CLASS, /* single precision floating point */
mxINT8_CLASS, /* 8 bit signed integer */
mxUINT8_CLASS, /* 8 bit unsigned integer */
mxINT16_CLASS, /* 16 bit signed integer */
mxUINT16_CLASS, /* 16 bit unsigned integer */
mxINT32_CLASS, /* 32 bit signed integer */
mxUINT32_CLASS, /* 32 bit unsigned integer */
mxINT64_CLASS, /* 64 bit signed integer */
mxUINT64_CLASS, /* 64 bit unsigned integer */
mxFUNCTION_CLASS /* Function handle */
} arrayclasstype;
#define FLAG_COMPLEX 0x8
#define FLAG_GLOBAL 0x4
#define FLAG_LOGICAL 0x2
static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum};
static void InsertComplexDoubleRow(double *p, int y, Image * image, double MinVal,
double MaxVal)
{
ExceptionInfo
*exception;
double f;
int x;
register PixelPacket *q;
if (MinVal == 0)
MinVal = -1;
if (MaxVal == 0)
MaxVal = 1;
exception=(&image->exception);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
return;
for (x = 0; x < (ssize_t) image->columns; x++)
{
if (*p > 0)
{
f = (*p / MaxVal) * (QuantumRange - GetPixelRed(q));
if (f + GetPixelRed(q) > QuantumRange)
SetPixelRed(q,QuantumRange);
else
SetPixelRed(q,GetPixelRed(q)+(int) f);
if ((int) f / 2.0 > GetPixelGreen(q))
{
SetPixelGreen(q,0);
SetPixelBlue(q,0);
}
else
{
SetPixelBlue(q,GetPixelBlue(q)-(int) (f/2.0));
SetPixelGreen(q,GetPixelBlue(q));
}
}
if (*p < 0)
{
f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(q));
if (f + GetPixelBlue(q) > QuantumRange)
SetPixelBlue(q,QuantumRange);
else
SetPixelBlue(q,GetPixelBlue(q)+(int) f);
if ((int) f / 2.0 > q->green)
{
SetPixelRed(q,0);
SetPixelGreen(q,0);
}
else
{
SetPixelRed(q,GetPixelRed(q)-(int) (f/2.0));
SetPixelGreen(q,GetPixelRed(q));
}
}
p++;
q++;
}
if (!SyncAuthenticPixels(image,exception))
return;
return;
}
static void InsertComplexFloatRow(float *p, int y, Image * image, double MinVal,
double MaxVal)
{
ExceptionInfo
*exception;
double f;
int x;
register PixelPacket *q;
if (MinVal == 0)
MinVal = -1;
if (MaxVal == 0)
MaxVal = 1;
exception=(&image->exception);
q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);
if (q == (PixelPacket *) NULL)
return;
for (x = 0; x < (ssize_t) image->columns; x++)
{
if (*p > 0)
{
f = (*p / MaxVal) * (QuantumRange - GetPixelRed(q));
if (f + GetPixelRed(q) > QuantumRange)
SetPixelRed(q,QuantumRange);
else
SetPixelRed(q,GetPixelRed(q)+(int) f);
if ((int) f / 2.0 > GetPixelGreen(q))
{
SetPixelGreen(q,0);
SetPixelBlue(q,0);
}
else
{
SetPixelBlue(q,GetPixelBlue(q)-(int) (f/2.0));
SetPixelGreen(q,GetPixelBlue(q));
}
}
if (*p < 0)
{
f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(q));
if (f + GetPixelBlue(q) > QuantumRange)
SetPixelBlue(q,QuantumRange);
else
SetPixelBlue(q,GetPixelBlue(q)+(int) f);
if ((int) f / 2.0 > q->green)
{
SetPixelGreen(q,0);
SetPixelRed(q,0);
}
else
{
SetPixelRed(q,GetPixelRed(q)-(int) (f/2.0));
SetPixelGreen(q,GetPixelRed(q));
}
}
p++;
q++;
}
if (!SyncAuthenticPixels(image,exception))
return;
return;
}
/************** READERS ******************/
/* This function reads one block of floats*/
static void ReadBlobFloatsLSB(Image * image, size_t len, float *data)
{
while (len >= 4)
{
*data++ = ReadBlobFloat(image);
len -= sizeof(float);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
static void ReadBlobFloatsMSB(Image * image, size_t len, float *data)
{
while (len >= 4)
{
*data++ = ReadBlobFloat(image);
len -= sizeof(float);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
/* This function reads one block of doubles*/
static void ReadBlobDoublesLSB(Image * image, size_t len, double *data)
{
while (len >= 8)
{
*data++ = ReadBlobDouble(image);
len -= sizeof(double);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
static void ReadBlobDoublesMSB(Image * image, size_t len, double *data)
{
while (len >= 8)
{
*data++ = ReadBlobDouble(image);
len -= sizeof(double);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
/* Calculate minimum and maximum from a given block of data */
static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max)
{
MagickOffsetType filepos;
int i, x;
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
double *dblrow;
float *fltrow;
if (endian_indicator == LSBEndian)
{
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
}
else /* MI */
{
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
}
filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */
for (i = 0; i < SizeY; i++)
{
if (CellType==miDOUBLE)
{
ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff);
dblrow = (double *)BImgBuff;
if (i == 0)
{
*Min = *Max = *dblrow;
}
for (x = 0; x < SizeX; x++)
{
if (*Min > *dblrow)
*Min = *dblrow;
if (*Max < *dblrow)
*Max = *dblrow;
dblrow++;
}
}
if (CellType==miSINGLE)
{
ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff);
fltrow = (float *)BImgBuff;
if (i == 0)
{
*Min = *Max = *fltrow;
}
for (x = 0; x < (ssize_t) SizeX; x++)
{
if (*Min > *fltrow)
*Min = *fltrow;
if (*Max < *fltrow)
*Max = *fltrow;
fltrow++;
}
}
}
(void) SeekBlob(image, filepos, SEEK_SET);
}
static void FixSignedValues(PixelPacket *q, int y)
{
while(y-->0)
{
/* Please note that negative values will overflow
Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255>
<-1;-128> + 127+1 = <0; 127> */
SetPixelRed(q,GetPixelRed(q)+QuantumRange/2+1);
SetPixelGreen(q,GetPixelGreen(q)+QuantumRange/2+1);
SetPixelBlue(q,GetPixelBlue(q)+QuantumRange/2+1);
q++;
}
}
/** Fix whole row of logical/binary data. It means pack it. */
static void FixLogical(unsigned char *Buff,int ldblk)
{
unsigned char mask=128;
unsigned char *BuffL = Buff;
unsigned char val = 0;
while(ldblk-->0)
{
if(*Buff++ != 0)
val |= mask;
mask >>= 1;
if(mask==0)
{
*BuffL++ = val;
val = 0;
mask = 128;
}
}
*BuffL = val;
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
static voidpf AcquireZIPMemory(voidpf context,unsigned int items,
unsigned int size)
{
(void) context;
return((voidpf) AcquireQuantumMemory(items,size));
}
static void RelinquishZIPMemory(voidpf context,voidpf memory)
{
(void) context;
memory=RelinquishMagickMemory(memory);
}
#endif
#if defined(MAGICKCORE_ZLIB_DELEGATE)
/** This procedure decompreses an image block for a new MATLAB format. */
static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception)
{
Image *image2;
void *CacheBlock, *DecompressBlock;
z_stream zip_info;
FILE *mat_file;
size_t magick_size;
size_t extent;
int file;
int status;
int zip_status;
if(clone_info==NULL) return NULL;
if(clone_info->file) /* Close file opened from previous transaction. */
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
CacheBlock = AcquireQuantumMemory((size_t)((Size<16384)?Size:16384),sizeof(unsigned char *));
if(CacheBlock==NULL) return NULL;
DecompressBlock = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *));
if(DecompressBlock==NULL)
{
RelinquishMagickMemory(CacheBlock);
return NULL;
}
mat_file=0;
file = AcquireUniqueFileResource(clone_info->filename);
if (file != -1)
mat_file = fdopen(file,"w");
if(!mat_file)
{
RelinquishMagickMemory(CacheBlock);
RelinquishMagickMemory(DecompressBlock);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Cannot create file stream for decompressed image");
return NULL;
}
zip_info.zalloc=AcquireZIPMemory;
zip_info.zfree=RelinquishZIPMemory;
zip_info.opaque = (voidpf) NULL;
zip_status = inflateInit(&zip_info);
if (zip_status != Z_OK)
{
RelinquishMagickMemory(CacheBlock);
RelinquishMagickMemory(DecompressBlock);
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"UnableToUncompressImage","`%s'",clone_info->filename);
(void) fclose(mat_file);
RelinquishUniqueFileResource(clone_info->filename);
return NULL;
}
/* zip_info.next_out = 8*4;*/
zip_info.avail_in = 0;
zip_info.total_out = 0;
while(Size>0 && !EOFBlob(orig))
{
magick_size = ReadBlob(orig, (Size<16384)?Size:16384, (unsigned char *) CacheBlock);
zip_info.next_in = (Bytef *) CacheBlock;
zip_info.avail_in = (uInt) magick_size;
while(zip_info.avail_in>0)
{
zip_info.avail_out = 4096;
zip_info.next_out = (Bytef *) DecompressBlock;
zip_status = inflate(&zip_info,Z_NO_FLUSH);
if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END))
break;
extent=fwrite(DecompressBlock, 4096-zip_info.avail_out, 1, mat_file);
(void) extent;
if(zip_status == Z_STREAM_END) goto DblBreak;
}
if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END))
break;
Size -= magick_size;
}
DblBreak:
inflateEnd(&zip_info);
(void)fclose(mat_file);
RelinquishMagickMemory(CacheBlock);
RelinquishMagickMemory(DecompressBlock);
if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile;
if( (image2 = AcquireImage(clone_info))==NULL ) goto EraseFile;
status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
DeleteImageFromList(&image2);
EraseFile:
fclose(clone_info->file);
clone_info->file = NULL;
UnlinkFile:
RelinquishUniqueFileResource(clone_info->filename);
return NULL;
}
return image2;
}
#endif
static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
typedef struct {
unsigned char Type[4];
unsigned int nRows;
unsigned int nCols;
unsigned int imagf;
unsigned int nameLen;
} MAT4_HDR;
long
ldblk;
EndianType
endian;
Image
*rotate_image;
MagickBooleanType
status;
MAT4_HDR
HDR;
QuantumInfo
*quantum_info;
QuantumFormatType
format_type;
register ssize_t
i;
ssize_t
y;
unsigned char
*pixels;
unsigned int
depth;
(void) SeekBlob(image,0,SEEK_SET);
ldblk=ReadBlobLSBLong(image);
if ((ldblk > 9999) || (ldblk < 0))
return((Image *) NULL);
HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */
HDR.Type[2]=ldblk % 10; ldblk /= 10; /* P digit */
HDR.Type[1]=ldblk % 10; ldblk /= 10; /* O digit */
HDR.Type[0]=ldblk; /* M digit */
if (HDR.Type[3] != 0) return((Image *) NULL); /* Data format */
if (HDR.Type[2] != 0) return((Image *) NULL); /* Always 0 */
if (HDR.Type[0] == 0)
{
HDR.nRows=ReadBlobLSBLong(image);
HDR.nCols=ReadBlobLSBLong(image);
HDR.imagf=ReadBlobLSBLong(image);
HDR.nameLen=ReadBlobLSBLong(image);
endian=LSBEndian;
}
else
{
HDR.nRows=ReadBlobMSBLong(image);
HDR.nCols=ReadBlobMSBLong(image);
HDR.imagf=ReadBlobMSBLong(image);
HDR.nameLen=ReadBlobMSBLong(image);
endian=MSBEndian;
}
if (HDR.nameLen > 0xFFFF)
return((Image *) NULL);
for (i=0; i < (ssize_t) HDR.nameLen; i++)
{
int
byte;
/*
Skip matrix name.
*/
byte=ReadBlobByte(image);
if (byte == EOF)
return((Image *) NULL);
}
image->columns=(size_t) HDR.nRows;
image->rows=(size_t) HDR.nCols;
SetImageColorspace(image,GRAYColorspace);
if (image_info->ping != MagickFalse)
{
Swap(image->columns,image->rows);
return(image);
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
return((Image *) NULL);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
return((Image *) NULL);
switch(HDR.Type[1])
{
case 0:
format_type=FloatingPointQuantumFormat;
depth=64;
break;
case 1:
format_type=FloatingPointQuantumFormat;
depth=32;
break;
case 2:
format_type=UnsignedQuantumFormat;
depth=16;
break;
case 3:
format_type=SignedQuantumFormat;
depth=16;
case 4:
format_type=UnsignedQuantumFormat;
depth=8;
break;
default:
format_type=UnsignedQuantumFormat;
depth=8;
break;
}
image->depth=depth;
if (HDR.Type[0] != 0)
SetQuantumEndian(image,quantum_info,MSBEndian);
status=SetQuantumFormat(image,quantum_info,format_type);
status=SetQuantumDepth(image,quantum_info,depth);
status=SetQuantumEndian(image,quantum_info,endian);
SetQuantumScale(quantum_info,1.0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
ssize_t
count;
register PixelPacket
*magick_restrict q;
count=ReadBlob(image,depth/8*image->columns,(unsigned char *) pixels);
if (count == -1)
break;
q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3))
FixSignedValues(q,image->columns);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (HDR.imagf == 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
/*
Read complex pixels.
*/
status=ReadBlob(image,depth/8*image->columns,(unsigned char *) pixels);
if (status == -1)
break;
if (HDR.Type[1] == 0)
InsertComplexDoubleRow((double *) pixels,y,image,0,0);
else
InsertComplexFloatRow((float *) pixels,y,image,0,0);
}
quantum_info=DestroyQuantumInfo(quantum_info);
rotate_image=RotateImage(image,90.0,exception);
if (rotate_image != (Image *) NULL)
{
image=DestroyImage(image);
image=rotate_image;
}
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d M A T L A B i m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadMATImage() reads an MAT X image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadMATImage method is:
%
% Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: Method ReadMATImage returns a pointer to the image after
% reading. A null image is returned if there is a memory shortage or if
% the image cannot be read.
%
% o image_info: Specifies a pointer to a ImageInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
PixelPacket *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
size_t Unknown6;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
image = AcquireImage(image_info);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=CloneImageInfo(image_info);
if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
{
image2=ReadMATImageV4(image_info,image,exception);
if (image2 == NULL)
goto MATLAB_KO;
image=image2;
goto END_OF_READING;
}
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
Unknown6 = ReadBlobXXXLong(image2);
(void) Unknown6;
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
if (Frames == 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
SetImageColorspace(image,GRAYColorspace);
image->type=GrayscaleType;
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
quantum_info=DestroyQuantumInfo(quantum_info);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if(image2!=NULL)
if(image2!=image) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) unlink(clone_info->filename);
}
}
}
}
RelinquishMagickMemory(BImgBuff);
END_OF_READING:
clone_info=DestroyImageInfo(clone_info);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r M A T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method RegisterMATImage adds attributes for the MAT image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterMATImage method is:
%
% size_t RegisterMATImage(void)
%
*/
ModuleExport size_t RegisterMATImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("MAT");
entry->decoder=(DecodeImageHandler *) ReadMATImage;
entry->encoder=(EncodeImageHandler *) WriteMATImage;
entry->blob_support=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=AcquireString("MATLAB level 5 image format");
entry->module=AcquireString("MAT");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r M A T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method UnregisterMATImage removes format registrations made by the
% MAT module from the list of supported formats.
%
% The format of the UnregisterMATImage method is:
%
% UnregisterMATImage(void)
%
*/
ModuleExport void UnregisterMATImage(void)
{
(void) UnregisterMagickInfo("MAT");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M A T L A B I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Function WriteMATImage writes an Matlab matrix to a file.
%
% The format of the WriteMATImage method is:
%
% unsigned int WriteMATImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o status: Function WriteMATImage return True if the image is written.
% False is returned is there is a memory shortage or if the image file
% fails to write.
%
% o image_info: Specifies a pointer to a ImageInfo structure.
%
% o image: A pointer to an Image structure.
%
*/
static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image)
{
ExceptionInfo
*exception;
ssize_t y;
unsigned z;
const PixelPacket *p;
unsigned int status;
int logging;
size_t DataSize;
char padding;
char MATLAB_HDR[0x80];
time_t current_time;
struct tm local_time;
unsigned char *pixels;
int is_gray;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT");
(void) logging;
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(MagickFalse);
image->depth=8;
current_time=time((time_t *) NULL);
#if defined(MAGICKCORE_HAVE_LOCALTIME_R)
(void) localtime_r(¤t_time,&local_time);
#else
(void) memcpy(&local_time,localtime(¤t_time),sizeof(local_time));
#endif
(void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124));
FormatLocaleString(MATLAB_HDR,sizeof(MATLAB_HDR),
"MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d",
OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon],
local_time.tm_mday,local_time.tm_hour,local_time.tm_min,
local_time.tm_sec,local_time.tm_year+1900);
MATLAB_HDR[0x7C]=0;
MATLAB_HDR[0x7D]=1;
MATLAB_HDR[0x7E]='I';
MATLAB_HDR[0x7F]='M';
(void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR);
scene=0;
do
{
(void) TransformImageColorspace(image,sRGBColorspace);
is_gray = SetImageGray(image,&image->exception);
z = is_gray ? 0 : 3;
/*
Store MAT header.
*/
DataSize = image->rows /*Y*/ * image->columns /*X*/;
if(!is_gray) DataSize *= 3 /*Z*/;
padding=((unsigned char)(DataSize-1) & 0x7) ^ 0x7;
(void) WriteBlobLSBLong(image, miMATRIX);
(void) WriteBlobLSBLong(image, (unsigned int) DataSize+padding+(is_gray ? 48 : 56));
(void) WriteBlobLSBLong(image, 0x6); /* 0x88 */
(void) WriteBlobLSBLong(image, 0x8); /* 0x8C */
(void) WriteBlobLSBLong(image, 0x6); /* 0x90 */
(void) WriteBlobLSBLong(image, 0);
(void) WriteBlobLSBLong(image, 0x5); /* 0x98 */
(void) WriteBlobLSBLong(image, is_gray ? 0x8 : 0xC); /* 0x9C - DimFlag */
(void) WriteBlobLSBLong(image, (unsigned int) image->rows); /* x: 0xA0 */
(void) WriteBlobLSBLong(image, (unsigned int) image->columns); /* y: 0xA4 */
if(!is_gray)
{
(void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */
(void) WriteBlobLSBLong(image, 0);
}
(void) WriteBlobLSBShort(image, 1); /* 0xB0 */
(void) WriteBlobLSBShort(image, 1); /* 0xB2 */
(void) WriteBlobLSBLong(image, 'M'); /* 0xB4 */
(void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */
(void) WriteBlobLSBLong(image, (unsigned int) DataSize); /* 0xBC */
/*
Store image data.
*/
exception=(&image->exception);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
do
{
for (y=0; y < (ssize_t)image->columns; y++)
{
p=GetVirtualPixels(image,y,0,1,image->rows,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
z2qtype[z],pixels,exception);
(void) WriteBlob(image,image->rows,pixels);
}
if (!SyncAuthenticPixels(image,exception))
break;
} while(z-- >= 2);
while(padding-->0) (void) WriteBlobByte(image,0);
quantum_info=DestroyQuantumInfo(quantum_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_4790_0 |
crossvul-cpp_data_bad_2627_0 | /*
* Copyright (c) 1994-2008 Carnegie Mellon University. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The name "Carnegie Mellon University" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For permission or any legal
* details, please contact
* Carnegie Mellon University
* Center for Technology Transfer and Enterprise Creation
* 4615 Forbes Avenue
* Suite 302
* Pittsburgh, PA 15213
* (412) 268-7393, fax: (412) 268-7395
* innovation@andrew.cmu.edu
*
* 4. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Computing Services
* at Carnegie Mellon University (http://www.cmu.edu/computing/)."
*
* CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <config.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <syslog.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <stdbool.h>
#include <errno.h>
#include <sasl/sasl.h>
#ifdef HAVE_SSL
#include <openssl/hmac.h>
#include <openssl/rand.h>
#endif /* HAVE_SSL */
#include "acl.h"
#include "annotate.h"
#include "append.h"
#include "auth.h"
#ifdef USE_AUTOCREATE
#include "autocreate.h"
#endif // USE_AUTOCREATE
#include "assert.h"
#include "backend.h"
#include "bsearch.h"
#include "bufarray.h"
#include "charset.h"
#include "dlist.h"
#include "exitcodes.h"
#include "idle.h"
#include "global.h"
#include "times.h"
#include "proxy.h"
#include "imap_proxy.h"
#include "imapd.h"
#include "imapurl.h"
#include "imparse.h"
#include "index.h"
#include "mailbox.h"
#include "message.h"
#include "mboxevent.h"
#include "mboxkey.h"
#include "mboxlist.h"
#include "mboxname.h"
#include "mbdump.h"
#include "mupdate-client.h"
#include "partlist.h"
#include "proc.h"
#include "quota.h"
#include "seen.h"
#include "statuscache.h"
#include "sync_log.h"
#include "sync_support.h"
#include "telemetry.h"
#include "tls.h"
#include "user.h"
#include "userdeny.h"
#include "util.h"
#include "version.h"
#include "xmalloc.h"
#include "xstrlcat.h"
#include "xstrlcpy.h"
#include "ptrarray.h"
#include "xstats.h"
/* generated headers are not necessarily in current directory */
#include "imap/imap_err.h"
#include "imap/pushstats.h" /* SNMP interface */
#include "iostat.h"
extern int optind;
extern char *optarg;
/* global state */
const int config_need_data = CONFIG_NEED_PARTITION_DATA;
static int imaps = 0;
static sasl_ssf_t extprops_ssf = 0;
static int nosaslpasswdcheck = 0;
static int apns_enabled = 0;
/* PROXY STUFF */
/* we want a list of our outgoing connections here and which one we're
currently piping */
static const int ultraparanoid = 1; /* should we kick after every operation? */
unsigned int proxy_cmdcnt;
static int referral_kick = 0; /* kick after next command recieved, for
referrals that are likely to change the
mailbox list */
/* global conversations database holder to avoid re-opening during
* status command or list responses */
struct conversations_state *global_conversations = NULL;
/* all subscription commands go to the backend server containing the
user's inbox */
struct backend *backend_inbox = NULL;
/* the current server most commands go to */
struct backend *backend_current = NULL;
/* our cached connections */
struct backend **backend_cached = NULL;
/* cached connection to mupdate master (for multiple XFER and MUPDATEPUSH) */
static mupdate_handle *mupdate_h = NULL;
/* are we doing virtdomains with multiple IPs? */
static int disable_referrals;
/* has the client issued an RLIST, RLSUB, or LIST (REMOTE)? */
static int supports_referrals;
/* end PROXY STUFF */
/* per-user/session state */
static int imapd_timeout;
struct protstream *imapd_out = NULL;
struct protstream *imapd_in = NULL;
static struct protgroup *protin = NULL;
static const char *imapd_clienthost = "[local]";
static int imapd_logfd = -1;
char *imapd_userid = NULL, *proxy_userid = NULL;
static char *imapd_magicplus = NULL;
struct auth_state *imapd_authstate = 0;
static int imapd_userisadmin = 0;
static int imapd_userisproxyadmin = 0;
static sasl_conn_t *imapd_saslconn; /* the sasl connection context */
static int imapd_starttls_done = 0; /* have we done a successful starttls? */
static int imapd_tls_required = 0; /* is tls required? */
static void *imapd_tls_comp = NULL; /* TLS compression method, if any */
static int imapd_compress_done = 0; /* have we done a successful compress? */
static const char *plaintextloginalert = NULL;
static int ignorequota = 0;
#define QUIRK_SEARCHFUZZY (1<<0)
static struct id_data {
struct attvaluelist *params;
int did_id;
int quirks;
} imapd_id;
#ifdef HAVE_SSL
/* our tls connection, if any */
static SSL *tls_conn = NULL;
#endif /* HAVE_SSL */
/* stage(s) for APPEND */
struct appendstage {
struct stagemsg *stage;
FILE *f;
strarray_t flags;
time_t internaldate;
int binary;
struct entryattlist *annotations;
};
static ptrarray_t stages = PTRARRAY_INITIALIZER;
/* the sasl proxy policy context */
static struct proxy_context imapd_proxyctx = {
1, 1, &imapd_authstate, &imapd_userisadmin, &imapd_userisproxyadmin
};
/* current sub-user state */
static struct index_state *imapd_index;
/* current namespace */
struct namespace imapd_namespace;
/* track if we're idling */
static int idling = 0;
const struct mbox_name_attribute mbox_name_attributes[] = {
/* from RFC 3501 */
{ MBOX_ATTRIBUTE_NOINFERIORS, "\\Noinferiors" },
{ MBOX_ATTRIBUTE_NOSELECT, "\\Noselect" },
{ MBOX_ATTRIBUTE_MARKED, "\\Marked" },
{ MBOX_ATTRIBUTE_UNMARKED, "\\Unmarked" },
/* from RFC 5258 */
{ MBOX_ATTRIBUTE_NONEXISTENT, "\\NonExistent" },
{ MBOX_ATTRIBUTE_SUBSCRIBED, "\\Subscribed" },
{ MBOX_ATTRIBUTE_REMOTE, "\\Remote" },
{ MBOX_ATTRIBUTE_HASCHILDREN, "\\HasChildren" },
{ MBOX_ATTRIBUTE_HASNOCHILDREN, "\\HasNoChildren" },
{ 0, NULL }
};
/*
* These bitmasks define how List selection options can be combined:
* list_select_mod_opts may only be used if at least one list_select_base_opt
* is also present.
* For example, (RECURSIVEMATCH) and (RECURSIVEMATCH REMOTE) are invalid, but
* (RECURSIVEMATCH SUBSCRIBED) is ok.
*/
static const int list_select_base_opts = LIST_SEL_SUBSCRIBED;
static const int list_select_mod_opts = LIST_SEL_RECURSIVEMATCH;
/* structure that list_data passes its callbacks */
struct list_rock {
struct listargs *listargs;
strarray_t *subs;
char *last_name;
mbentry_t *last_mbentry;
uint32_t last_attributes;
int last_category;
hash_table server_table; /* for proxying */
};
/* Information about one mailbox name that LIST returns */
struct list_entry {
const char *name;
uint32_t attributes; /* bitmap of MBOX_ATTRIBUTE_* */
};
/* structure that list_data_recursivematch passes its callbacks */
struct list_rock_recursivematch {
struct listargs *listargs;
struct hash_table table; /* maps mailbox names to attributes (uint32_t *) */
int count; /* # of entries in table */
struct list_entry *array;
};
/* CAPABILITIES are defined here, not including TLS/SASL ones,
and those that are configurable */
enum {
CAPA_PREAUTH = 0x1,
CAPA_POSTAUTH = 0x2
};
struct capa_struct {
const char *str;
int mask;
};
static struct capa_struct base_capabilities[] = {
/* pre-auth capabilities */
{ "IMAP4rev1", 3 },
{ "LITERAL+", 3 },
{ "ID", 3 },
{ "ENABLE", 3 },
/* post-auth capabilities */
{ "ACL", 2 },
{ "RIGHTS=kxten", 2 },
{ "QUOTA", 2 },
{ "MAILBOX-REFERRALS", 2 },
{ "NAMESPACE", 2 },
{ "UIDPLUS", 2 },
{ "NO_ATOMIC_RENAME", 2 },
{ "UNSELECT", 2 },
{ "CHILDREN", 2 },
{ "MULTIAPPEND", 2 },
{ "BINARY", 2 },
{ "CATENATE", 2 },
{ "CONDSTORE", 2 },
{ "ESEARCH", 2 },
{ "SEARCH=FUZZY", 2 }, /* RFC 6203 */
{ "SORT", 2 },
{ "SORT=MODSEQ", 2 },
{ "SORT=DISPLAY", 2 },
{ "SORT=UID", 2 }, /* not standard */
{ "THREAD=ORDEREDSUBJECT", 2 },
{ "THREAD=REFERENCES", 2 },
{ "THREAD=REFS", 2 }, /* draft-ietf-morg-inthread */
{ "ANNOTATEMORE", 2 },
{ "ANNOTATE-EXPERIMENT-1", 2 },
{ "METADATA", 2 },
{ "LIST-EXTENDED", 2 },
{ "LIST-STATUS", 2 },
{ "LIST-MYRIGHTS", 2 }, /* not standard */
{ "LIST-METADATA", 2 }, /* not standard */
{ "WITHIN", 2 },
{ "QRESYNC", 2 },
{ "SCAN", 2 },
{ "XLIST", 2 }, /* not standard */
{ "XMOVE", 2 }, /* not standard */
{ "MOVE", 2 },
{ "SPECIAL-USE", 2 },
{ "CREATE-SPECIAL-USE", 2 },
{ "DIGEST=SHA1", 2 }, /* not standard */
{ "X-REPLICATION", 2 }, /* not standard */
#ifdef HAVE_SSL
{ "URLAUTH", 2 },
{ "URLAUTH=BINARY", 2 },
#endif
/* keep this to mark the end of the list */
{ 0, 0 }
};
static void motd_file(void);
void shut_down(int code);
void fatal(const char *s, int code);
static void cmdloop(void);
static void cmd_login(char *tag, char *user);
static void cmd_authenticate(char *tag, char *authtype, char *resp);
static void cmd_noop(char *tag, char *cmd);
static void capa_response(int flags);
static void cmd_capability(char *tag);
static void cmd_append(char *tag, char *name, const char *cur_name);
static void cmd_select(char *tag, char *cmd, char *name);
static void cmd_close(char *tag, char *cmd);
static int parse_fetch_args(const char *tag, const char *cmd,
int allow_vanished,
struct fetchargs *fa);
static void cmd_fetch(char *tag, char *sequence, int usinguid);
static void cmd_store(char *tag, char *sequence, int usinguid);
static void cmd_search(char *tag, int usinguid);
static void cmd_sort(char *tag, int usinguid);
static void cmd_thread(char *tag, int usinguid);
static void cmd_copy(char *tag, char *sequence, char *name, int usinguid, int ismove);
static void cmd_expunge(char *tag, char *sequence);
static void cmd_create(char *tag, char *name, struct dlist *extargs, int localonly);
static void cmd_delete(char *tag, char *name, int localonly, int force);
static void cmd_dump(char *tag, char *name, int uid_start);
static void cmd_undump(char *tag, char *name);
static void cmd_xfer(const char *tag, const char *name,
const char *toserver, const char *topart);
static void cmd_rename(char *tag, char *oldname, char *newname, char *partition);
static void cmd_reconstruct(const char *tag, const char *name, int recursive);
static void getlistargs(char *tag, struct listargs *listargs);
static void cmd_list(char *tag, struct listargs *listargs);
static void cmd_changesub(char *tag, char *namespace, char *name, int add);
static void cmd_getacl(const char *tag, const char *name);
static void cmd_listrights(char *tag, char *name, char *identifier);
static void cmd_myrights(const char *tag, const char *name);
static void cmd_setacl(char *tag, const char *name,
const char *identifier, const char *rights);
static void cmd_getquota(const char *tag, const char *name);
static void cmd_getquotaroot(const char *tag, const char *name);
static void cmd_setquota(const char *tag, const char *quotaroot);
static void cmd_status(char *tag, char *name);
static void cmd_namespace(char* tag);
static void cmd_mupdatepush(char *tag, char *name);
static void cmd_id(char* tag);
static void cmd_idle(char* tag);
static void cmd_starttls(char *tag, int imaps);
static void cmd_xconvsort(char *tag, int updates);
static void cmd_xconvmultisort(char *tag);
static void cmd_xconvmeta(const char *tag);
static void cmd_xconvfetch(const char *tag);
static int do_xconvfetch(struct dlist *cidlist,
modseq_t ifchangedsince,
struct fetchargs *fetchargs);
static void cmd_xsnippets(char *tag);
static void cmd_xstats(char *tag, int c);
static void cmd_xapplepushservice(const char *tag,
struct applepushserviceargs *applepushserviceargs);
static void cmd_xbackup(const char *tag, const char *mailbox,
const char *channel);
#ifdef HAVE_SSL
static void cmd_urlfetch(char *tag);
static void cmd_genurlauth(char *tag);
static void cmd_resetkey(char *tag, char *mailbox, char *mechanism);
#endif
#ifdef HAVE_ZLIB
static void cmd_compress(char *tag, char *alg);
#endif
static void cmd_getannotation(const char* tag, char *mboxpat);
static void cmd_getmetadata(const char* tag);
static void cmd_setannotation(const char* tag, char *mboxpat);
static void cmd_setmetadata(const char* tag, char *mboxpat);
static void cmd_xrunannotator(const char *tag, const char *sequence,
int usinguid);
static void cmd_xwarmup(const char *tag);
static void cmd_enable(char* tag);
static void cmd_syncget(const char *tag, struct dlist *kl);
static void cmd_syncapply(const char *tag, struct dlist *kl,
struct sync_reserve_list *reserve_list);
static void cmd_syncrestart(const char *tag, struct sync_reserve_list **reserve_listp,
int realloc);
static void cmd_syncrestore(const char *tag, struct dlist *kin,
struct sync_reserve_list *reserve_list);
static void cmd_xkillmy(const char *tag, const char *cmdname);
static void cmd_xforever(const char *tag);
static void cmd_xmeid(const char *tag, const char *id);
static int parsecreateargs(struct dlist **extargs);
static int parse_annotate_fetch_data(const char *tag,
int permessage_flag,
strarray_t *entries,
strarray_t *attribs);
static int parse_metadata_string_or_list(const char *tag,
strarray_t *sa,
int *is_list);
static int parse_annotate_store_data(const char *tag,
int permessage_flag,
struct entryattlist **entryatts);
static int parse_metadata_store_data(const char *tag,
struct entryattlist **entryatts);
static int getlistselopts(char *tag, struct listargs *args);
static int getlistretopts(char *tag, struct listargs *args);
static int get_snippetargs(struct snippetargs **sap);
static void free_snippetargs(struct snippetargs **sap);
static int getsortcriteria(char *tag, struct sortcrit **sortcrit);
static int getdatetime(time_t *date);
static int parse_windowargs(const char *tag, struct windowargs **, int);
static void free_windowargs(struct windowargs *wa);
static void appendfieldlist(struct fieldlist **l, char *section,
strarray_t *fields, char *trail,
void *d, size_t size);
static void freefieldlist(struct fieldlist *l);
void freestrlist(struct strlist *l);
static int set_haschildren(const mbentry_t *entry, void *rock);
static char *canonical_list_pattern(const char *reference,
const char *pattern);
static void canonical_list_patterns(const char *reference,
strarray_t *patterns);
static int list_cb(struct findall_data *data, void *rock);
static int subscribed_cb(struct findall_data *data, void *rock);
static void list_data(struct listargs *listargs);
static int list_data_remote(struct backend *be, char *tag,
struct listargs *listargs, strarray_t *subs);
static void clear_id();
extern int saslserver(sasl_conn_t *conn, const char *mech,
const char *init_resp, const char *resp_prefix,
const char *continuation, const char *empty_resp,
struct protstream *pin, struct protstream *pout,
int *sasl_result, char **success_data);
/* Enable the resetting of a sasl_conn_t */
static int reset_saslconn(sasl_conn_t **conn);
static struct
{
char *ipremoteport;
char *iplocalport;
sasl_ssf_t ssf;
char *authid;
} saslprops = {NULL,NULL,0,NULL};
static int imapd_canon_user(sasl_conn_t *conn, void *context,
const char *user, unsigned ulen,
unsigned flags, const char *user_realm,
char *out, unsigned out_max, unsigned *out_ulen)
{
char userbuf[MAX_MAILBOX_BUFFER], *p;
size_t n;
int r;
if (!ulen) ulen = strlen(user);
if (config_getswitch(IMAPOPT_IMAPMAGICPLUS)) {
/* make a working copy of the auth[z]id */
if (ulen >= MAX_MAILBOX_BUFFER) {
sasl_seterror(conn, 0, "buffer overflow while canonicalizing");
return SASL_BUFOVER;
}
memcpy(userbuf, user, ulen);
userbuf[ulen] = '\0';
user = userbuf;
/* See if we're using the magic plus */
if ((p = strchr(userbuf, '+'))) {
n = config_virtdomains ? strcspn(p, "@") : strlen(p);
if (flags & SASL_CU_AUTHZID) {
/* make a copy of the magic plus */
if (imapd_magicplus) free(imapd_magicplus);
imapd_magicplus = xstrndup(p, n);
}
/* strip the magic plus from the auth[z]id */
memmove(p, p+n, strlen(p+n)+1);
ulen -= n;
}
}
r = mysasl_canon_user(conn, context, user, ulen, flags, user_realm,
out, out_max, out_ulen);
if (!r && imapd_magicplus && flags == SASL_CU_AUTHZID) {
/* If we're only doing the authzid, put back the magic plus
in case its used in the challenge/response calculation */
n = strlen(imapd_magicplus);
if (*out_ulen + n > out_max) {
sasl_seterror(conn, 0, "buffer overflow while canonicalizing");
r = SASL_BUFOVER;
}
else {
p = (config_virtdomains && (p = strchr(out, '@'))) ?
p : out + *out_ulen;
memmove(p+n, p, strlen(p)+1);
memcpy(p, imapd_magicplus, n);
*out_ulen += n;
}
}
return r;
}
static int imapd_proxy_policy(sasl_conn_t *conn,
void *context,
const char *requested_user, unsigned rlen,
const char *auth_identity, unsigned alen,
const char *def_realm,
unsigned urlen,
struct propctx *propctx)
{
char userbuf[MAX_MAILBOX_BUFFER];
if (config_getswitch(IMAPOPT_IMAPMAGICPLUS)) {
size_t n;
char *p;
/* make a working copy of the authzid */
if (!rlen) rlen = strlen(requested_user);
if (rlen >= MAX_MAILBOX_BUFFER) {
sasl_seterror(conn, 0, "buffer overflow while proxying");
return SASL_BUFOVER;
}
memcpy(userbuf, requested_user, rlen);
userbuf[rlen] = '\0';
requested_user = userbuf;
/* See if we're using the magic plus */
if ((p = strchr(userbuf, '+'))) {
n = config_virtdomains ? strcspn(p, "@") : strlen(p);
/* strip the magic plus from the authzid */
memmove(p, p+n, strlen(p+n)+1);
rlen -= n;
}
}
return mysasl_proxy_policy(conn, context, requested_user, rlen,
auth_identity, alen, def_realm, urlen, propctx);
}
static int imapd_sasl_log(void *context __attribute__((unused)),
int level, const char *message)
{
int syslog_level = LOG_INFO;
switch (level) {
case SASL_LOG_ERR:
case SASL_LOG_FAIL:
syslog_level = LOG_ERR;
break;
case SASL_LOG_WARN:
syslog_level = LOG_WARNING;
break;
case SASL_LOG_DEBUG:
case SASL_LOG_TRACE:
case SASL_LOG_PASS:
syslog_level = LOG_DEBUG;
break;
}
syslog(syslog_level, "SASL %s", message);
return SASL_OK;
}
static const struct sasl_callback mysasl_cb[] = {
{ SASL_CB_GETOPT, (mysasl_cb_ft *) &mysasl_config, NULL },
{ SASL_CB_PROXY_POLICY, (mysasl_cb_ft *) &imapd_proxy_policy, (void*) &imapd_proxyctx },
{ SASL_CB_CANON_USER, (mysasl_cb_ft *) &imapd_canon_user, (void*) &disable_referrals },
{ SASL_CB_LOG, (mysasl_cb_ft *) &imapd_sasl_log, NULL },
{ SASL_CB_LIST_END, NULL, NULL }
};
/* imapd_refer() issues a referral to the client. */
static void imapd_refer(const char *tag,
const char *server,
const char *mailbox)
{
struct imapurl imapurl;
char url[MAX_MAILBOX_PATH+1];
memset(&imapurl, 0, sizeof(struct imapurl));
imapurl.server = server;
imapurl.mailbox = mailbox;
imapurl.auth = !strcmp(imapd_userid, "anonymous") ? "anonymous" : "*";
imapurl_toURL(url, &imapurl);
prot_printf(imapd_out, "%s NO [REFERRAL %s] Remote mailbox.\r\n",
tag, url);
free(imapurl.freeme);
}
/* wrapper for mboxlist_lookup that will force a referral if we are remote
* returns IMAP_SERVER_UNAVAILABLE if we don't have a place to send the client
* (that'd be a bug).
* returns IMAP_MAILBOX_MOVED if we referred the client */
/* ext_name is the external name of the mailbox */
/* you can avoid referring the client by setting tag or ext_name to NULL. */
static int mlookup(const char *tag, const char *ext_name,
const char *name, mbentry_t **mbentryptr)
{
int r;
mbentry_t *mbentry = NULL;
r = mboxlist_lookup(name, &mbentry, NULL);
if ((r == IMAP_MAILBOX_NONEXISTENT || (!r && (mbentry->mbtype & MBTYPE_RESERVE))) &&
config_mupdate_server) {
/* It is not currently active, make sure we have the most recent
* copy of the database */
kick_mupdate();
mboxlist_entry_free(&mbentry);
r = mboxlist_lookup(name, &mbentry, NULL);
}
if (r) goto done;
if (mbentry->mbtype & MBTYPE_RESERVE) {
r = IMAP_MAILBOX_RESERVED;
}
else if (mbentry->mbtype & MBTYPE_DELETED) {
r = IMAP_MAILBOX_NONEXISTENT;
}
else if (mbentry->mbtype & MBTYPE_MOVING) {
/* do we have rights on the mailbox? */
if (!imapd_userisadmin &&
(!mbentry->acl || !(cyrus_acl_myrights(imapd_authstate, mbentry->acl) & ACL_LOOKUP))) {
r = IMAP_MAILBOX_NONEXISTENT;
} else if (tag && ext_name && mbentry->server) {
imapd_refer(tag, mbentry->server, ext_name);
r = IMAP_MAILBOX_MOVED;
} else if (config_mupdate_server) {
r = IMAP_SERVER_UNAVAILABLE;
} else {
r = IMAP_MAILBOX_NOTSUPPORTED;
}
}
done:
if (r) mboxlist_entry_free(&mbentry);
else if (mbentryptr) *mbentryptr = mbentry;
else mboxlist_entry_free(&mbentry); /* we don't actually want it! */
return r;
}
static void imapd_reset(void)
{
int i;
int bytes_in = 0;
int bytes_out = 0;
proc_cleanup();
/* close backend connections */
i = 0;
while (backend_cached && backend_cached[i]) {
proxy_downserver(backend_cached[i]);
if (backend_cached[i]->last_result.s) {
free(backend_cached[i]->last_result.s);
}
free(backend_cached[i]);
i++;
}
if (backend_cached) free(backend_cached);
backend_cached = NULL;
backend_inbox = backend_current = NULL;
if (mupdate_h) mupdate_disconnect(&mupdate_h);
mupdate_h = NULL;
proxy_cmdcnt = 0;
disable_referrals = 0;
supports_referrals = 0;
if (imapd_index) index_close(&imapd_index);
if (imapd_in) {
/* Flush the incoming buffer */
prot_NONBLOCK(imapd_in);
prot_fill(imapd_in);
bytes_in = prot_bytes_in(imapd_in);
prot_free(imapd_in);
}
if (imapd_out) {
/* Flush the outgoing buffer */
prot_flush(imapd_out);
bytes_out = prot_bytes_out(imapd_out);
prot_free(imapd_out);
}
if (config_auditlog)
syslog(LOG_NOTICE, "auditlog: traffic sessionid=<%s> bytes_in=<%d> bytes_out=<%d>",
session_id(), bytes_in, bytes_out);
imapd_in = imapd_out = NULL;
if (protin) protgroup_reset(protin);
#ifdef HAVE_SSL
if (tls_conn) {
if (tls_reset_servertls(&tls_conn) == -1) {
fatal("tls_reset() failed", EC_TEMPFAIL);
}
tls_conn = NULL;
}
#endif
cyrus_reset_stdio();
imapd_clienthost = "[local]";
if (imapd_logfd != -1) {
close(imapd_logfd);
imapd_logfd = -1;
}
if (imapd_userid != NULL) {
free(imapd_userid);
imapd_userid = NULL;
}
if (proxy_userid != NULL) {
free(proxy_userid);
proxy_userid = NULL;
}
if (imapd_magicplus != NULL) {
free(imapd_magicplus);
imapd_magicplus = NULL;
}
if (imapd_authstate) {
auth_freestate(imapd_authstate);
imapd_authstate = NULL;
}
imapd_userisadmin = 0;
imapd_userisproxyadmin = 0;
client_capa = 0;
if (imapd_saslconn) {
sasl_dispose(&imapd_saslconn);
free(imapd_saslconn);
imapd_saslconn = NULL;
}
imapd_compress_done = 0;
imapd_tls_comp = NULL;
imapd_starttls_done = 0;
plaintextloginalert = NULL;
if(saslprops.iplocalport) {
free(saslprops.iplocalport);
saslprops.iplocalport = NULL;
}
if(saslprops.ipremoteport) {
free(saslprops.ipremoteport);
saslprops.ipremoteport = NULL;
}
if(saslprops.authid) {
free(saslprops.authid);
saslprops.authid = NULL;
}
saslprops.ssf = 0;
clear_id();
}
/*
* run once when process is forked;
* MUST NOT exit directly; must return with non-zero error code
*/
int service_init(int argc, char **argv, char **envp)
{
int opt, events;
if (geteuid() == 0) fatal("must run as the Cyrus user", EC_USAGE);
setproctitle_init(argc, argv, envp);
/* set signal handlers */
signals_set_shutdown(&shut_down);
signal(SIGPIPE, SIG_IGN);
/* load the SASL plugins */
global_sasl_init(1, 1, mysasl_cb);
/* open the mboxlist, we'll need it for real work */
mboxlist_init(0);
mboxlist_open(NULL);
/* open the quota db, we'll need it for real work */
quotadb_init(0);
quotadb_open(NULL);
/* open the user deny db */
denydb_init(0);
denydb_open(0);
/* setup for sending IMAP IDLE notifications */
idle_init();
/* setup for mailbox event notifications */
events = mboxevent_init();
apns_enabled =
(events & EVENT_APPLEPUSHSERVICE) && config_getstring(IMAPOPT_APS_TOPIC);
search_attr_init();
/* create connection to the SNMP listener, if available. */
snmp_connect(); /* ignore return code */
snmp_set_str(SERVER_NAME_VERSION,cyrus_version());
while ((opt = getopt(argc, argv, "Np:sq")) != EOF) {
switch (opt) {
case 's': /* imaps (do starttls right away) */
imaps = 1;
if (!tls_enabled()) {
syslog(LOG_ERR, "imaps: required OpenSSL options not present");
fatal("imaps: required OpenSSL options not present",
EC_CONFIG);
}
break;
case 'p': /* external protection */
extprops_ssf = atoi(optarg);
break;
case 'N': /* bypass SASL password check. Not recommended unless
* you know what you're doing! */
nosaslpasswdcheck = 1;
break;
case 'q': /* don't enforce quotas */
ignorequota = 1;
break;
default:
break;
}
}
/* Initialize the annotatemore extention */
if (config_mupdate_server)
annotate_init(annotate_fetch_proxy, annotate_store_proxy);
else
annotate_init(NULL, NULL);
annotatemore_open();
if (config_getswitch(IMAPOPT_STATUSCACHE)) {
statuscache_open();
}
/* Create a protgroup for input from the client and selected backend */
protin = protgroup_new(2);
return 0;
}
/*
* run for each accepted connection
*/
#ifdef ID_SAVE_CMDLINE
int service_main(int argc, char **argv, char **envp __attribute__((unused)))
#else
int service_main(int argc __attribute__((unused)),
char **argv __attribute__((unused)),
char **envp __attribute__((unused)))
#endif
{
sasl_security_properties_t *secprops = NULL;
const char *localip, *remoteip;
struct mboxevent *mboxevent = NULL;
struct io_count *io_count_start = NULL;
struct io_count *io_count_stop = NULL;
if (config_iolog) {
io_count_start = xmalloc (sizeof (struct io_count));
io_count_stop = xmalloc (sizeof (struct io_count));
read_io_count(io_count_start);
}
session_new_id();
signals_poll();
#ifdef ID_SAVE_CMDLINE
/* get command line args for use in ID before getopt mangles them */
id_getcmdline(argc, argv);
#endif
sync_log_init();
imapd_in = prot_new(0, 0);
imapd_out = prot_new(1, 1);
protgroup_insert(protin, imapd_in);
/* Find out name of client host */
imapd_clienthost = get_clienthost(0, &localip, &remoteip);
/* create the SASL connection */
if (sasl_server_new("imap", config_servername,
NULL, NULL, NULL, NULL, 0,
&imapd_saslconn) != SASL_OK) {
fatal("SASL failed initializing: sasl_server_new()", EC_TEMPFAIL);
}
secprops = mysasl_secprops(0);
if (sasl_setprop(imapd_saslconn, SASL_SEC_PROPS, secprops) != SASL_OK)
fatal("Failed to set SASL property", EC_TEMPFAIL);
if (sasl_setprop(imapd_saslconn, SASL_SSF_EXTERNAL, &extprops_ssf) != SASL_OK)
fatal("Failed to set SASL property", EC_TEMPFAIL);
if (localip && remoteip) {
sasl_setprop(imapd_saslconn, SASL_IPREMOTEPORT, remoteip);
saslprops.ipremoteport = xstrdup(remoteip);
sasl_setprop(imapd_saslconn, SASL_IPLOCALPORT, localip);
saslprops.iplocalport = xstrdup(localip);
}
imapd_tls_required = config_getswitch(IMAPOPT_TLS_REQUIRED);
proc_register(config_ident, imapd_clienthost, NULL, NULL, NULL);
/* Set inactivity timer */
imapd_timeout = config_getint(IMAPOPT_TIMEOUT);
if (imapd_timeout < 30) imapd_timeout = 30;
imapd_timeout *= 60;
prot_settimeout(imapd_in, imapd_timeout);
prot_setflushonread(imapd_in, imapd_out);
/* we were connected on imaps port so we should do
TLS negotiation immediately */
if (imaps == 1) cmd_starttls(NULL, 1);
snmp_increment(TOTAL_CONNECTIONS, 1);
snmp_increment(ACTIVE_CONNECTIONS, 1);
/* Setup a default namespace until replaced after authentication. */
mboxname_init_namespace(&imapd_namespace, /*isadmin*/1);
mboxevent_setnamespace(&imapd_namespace);
cmdloop();
/* LOGOUT executed */
prot_flush(imapd_out);
snmp_increment(ACTIVE_CONNECTIONS, -1);
/* send a Logout event notification */
if ((mboxevent = mboxevent_new(EVENT_LOGOUT))) {
mboxevent_set_access(mboxevent, saslprops.iplocalport,
saslprops.ipremoteport, imapd_userid, NULL, 1);
mboxevent_notify(&mboxevent);
mboxevent_free(&mboxevent);
}
/* cleanup */
imapd_reset();
if (config_iolog) {
read_io_count(io_count_stop);
syslog(LOG_INFO,
"IMAP session stats : I/O read : %d bytes : I/O write : %d bytes",
io_count_stop->io_read_count - io_count_start->io_read_count,
io_count_stop->io_write_count - io_count_start->io_write_count);
free (io_count_start);
free (io_count_stop);
}
return 0;
}
/* Called by service API to shut down the service */
void service_abort(int error)
{
shut_down(error);
}
/*
* Try to find a motd file; if found spit out message as an [ALERT]
*/
static void motd_file(void)
{
char *filename = NULL;
int fd = -1;
struct protstream *motd_in = NULL;
char buf[MAX_MAILBOX_PATH+1];
char *p;
filename = strconcat(config_dir, "/msg/motd", (char *)NULL);
fd = open(filename, O_RDONLY, 0);
if (fd < 0)
goto out;
motd_in = prot_new(fd, 0);
prot_fgets(buf, sizeof(buf), motd_in);
if ((p = strchr(buf, '\r'))!=NULL) *p = 0;
if ((p = strchr(buf, '\n'))!=NULL) *p = 0;
for (p = buf; *p == '['; p++); /* can't have [ be first char, sigh */
prot_printf(imapd_out, "* OK [ALERT] %s\r\n", p);
out:
if (motd_in)
prot_free(motd_in);
if (fd >= 0)
close(fd);
free(filename);
}
/*
* Cleanly shut down and exit
*/
void shut_down(int code) __attribute__((noreturn));
void shut_down(int code)
{
int i;
int bytes_in = 0;
int bytes_out = 0;
in_shutdown = 1;
proc_cleanup();
i = 0;
while (backend_cached && backend_cached[i]) {
proxy_downserver(backend_cached[i]);
if (backend_cached[i]->last_result.s) {
free(backend_cached[i]->last_result.s);
}
free(backend_cached[i]);
i++;
}
if (backend_cached) free(backend_cached);
if (mupdate_h) mupdate_disconnect(&mupdate_h);
if (idling)
idle_stop(index_mboxname(imapd_index));
if (imapd_index) index_close(&imapd_index);
sync_log_done();
seen_done();
mboxkey_done();
mboxlist_close();
mboxlist_done();
quotadb_close();
quotadb_done();
denydb_close();
denydb_done();
annotatemore_close();
annotate_done();
idle_done();
if (config_getswitch(IMAPOPT_STATUSCACHE)) {
statuscache_close();
statuscache_done();
}
partlist_local_done();
if (imapd_in) {
/* Flush the incoming buffer */
prot_NONBLOCK(imapd_in);
prot_fill(imapd_in);
bytes_in = prot_bytes_in(imapd_in);
prot_free(imapd_in);
}
if (imapd_out) {
/* Flush the outgoing buffer */
prot_flush(imapd_out);
bytes_out = prot_bytes_out(imapd_out);
prot_free(imapd_out);
/* one less active connection */
snmp_increment(ACTIVE_CONNECTIONS, -1);
}
if (config_auditlog)
syslog(LOG_NOTICE, "auditlog: traffic sessionid=<%s> bytes_in=<%d> bytes_out=<%d>",
session_id(), bytes_in, bytes_out);
if (protin) protgroup_free(protin);
#ifdef HAVE_SSL
tls_shutdown_serverengine();
#endif
cyrus_done();
exit(code);
}
EXPORTED void fatal(const char *s, int code)
{
static int recurse_code = 0;
if (recurse_code) {
/* We were called recursively. Just give up */
proc_cleanup();
snmp_increment(ACTIVE_CONNECTIONS, -1);
exit(recurse_code);
}
recurse_code = code;
if (imapd_out) {
prot_printf(imapd_out, "* BYE Fatal error: %s\r\n", s);
prot_flush(imapd_out);
}
if (stages.count) {
/* Cleanup the stage(s) */
struct appendstage *curstage;
while ((curstage = ptrarray_pop(&stages))) {
if (curstage->f != NULL) fclose(curstage->f);
append_removestage(curstage->stage);
strarray_fini(&curstage->flags);
freeentryatts(curstage->annotations);
free(curstage);
}
ptrarray_fini(&stages);
}
syslog(LOG_ERR, "Fatal error: %s", s);
shut_down(code);
}
/*
* Check the currently selected mailbox for updates.
*
* 'be' is the backend (if any) that we just proxied a command to.
*/
static void imapd_check(struct backend *be, int usinguid)
{
if (backend_current && backend_current != be) {
/* remote mailbox */
char mytag[128];
proxy_gentag(mytag, sizeof(mytag));
prot_printf(backend_current->out, "%s Noop\r\n", mytag);
pipe_until_tag(backend_current, mytag, 0);
}
else {
/* local mailbox */
index_check(imapd_index, usinguid, 0);
}
}
/*
* Top-level command loop parsing
*/
static void cmdloop(void)
{
int c;
int usinguid, havepartition, havenamespace, recursive;
static struct buf tag, cmd, arg1, arg2, arg3;
char *p, shut[MAX_MAILBOX_PATH+1], cmdname[100];
const char *err;
const char * commandmintimer;
double commandmintimerd = 0.0;
struct sync_reserve_list *reserve_list =
sync_reserve_list_create(SYNC_MESSAGE_LIST_HASH_SIZE);
struct applepushserviceargs applepushserviceargs;
prot_printf(imapd_out, "* OK [CAPABILITY ");
capa_response(CAPA_PREAUTH);
prot_printf(imapd_out, "]");
if (config_serverinfo) prot_printf(imapd_out, " %s", config_servername);
if (config_serverinfo == IMAP_ENUM_SERVERINFO_ON) {
prot_printf(imapd_out, " Cyrus IMAP %s", cyrus_version());
}
prot_printf(imapd_out, " server ready\r\n");
/* clear cancelled flag if present before the next command */
cmd_cancelled();
motd_file();
/* Get command timer logging paramater. This string
* is a time in seconds. Any command that takes >=
* this time to execute is logged */
commandmintimer = config_getstring(IMAPOPT_COMMANDMINTIMER);
cmdtime_settimer(commandmintimer ? 1 : 0);
if (commandmintimer) {
commandmintimerd = atof(commandmintimer);
}
for (;;) {
/* Release any held index */
index_release(imapd_index);
/* Flush any buffered output */
prot_flush(imapd_out);
if (backend_current) prot_flush(backend_current->out);
/* command no longer running */
proc_register(config_ident, imapd_clienthost, imapd_userid, index_mboxname(imapd_index), NULL);
/* Check for shutdown file */
if ( !imapd_userisadmin && imapd_userid &&
(shutdown_file(shut, sizeof(shut)) ||
userdeny(imapd_userid, config_ident, shut, sizeof(shut)))) {
for (p = shut; *p == '['; p++); /* can't have [ be first char */
prot_printf(imapd_out, "* BYE [ALERT] %s\r\n", p);
telemetry_rusage(imapd_userid);
shut_down(0);
}
signals_poll();
if (!proxy_check_input(protin, imapd_in, imapd_out,
backend_current ? backend_current->in : NULL,
NULL, 0)) {
/* No input from client */
continue;
}
/* Parse tag */
c = getword(imapd_in, &tag);
if (c == EOF) {
if ((err = prot_error(imapd_in))!=NULL
&& strcmp(err, PROT_EOF_STRING)) {
syslog(LOG_WARNING, "%s, closing connection", err);
prot_printf(imapd_out, "* BYE %s\r\n", err);
}
goto done;
}
if (c != ' ' || !imparse_isatom(tag.s) || (tag.s[0] == '*' && !tag.s[1])) {
prot_printf(imapd_out, "* BAD Invalid tag\r\n");
eatline(imapd_in, c);
continue;
}
/* Parse command name */
c = getword(imapd_in, &cmd);
if (!cmd.s[0]) {
prot_printf(imapd_out, "%s BAD Null command\r\n", tag.s);
eatline(imapd_in, c);
continue;
}
lcase(cmd.s);
xstrncpy(cmdname, cmd.s, 99);
cmd.s[0] = toupper((unsigned char) cmd.s[0]);
if (config_getswitch(IMAPOPT_CHATTY))
syslog(LOG_NOTICE, "command: %s %s", tag.s, cmd.s);
proc_register(config_ident, imapd_clienthost, imapd_userid, index_mboxname(imapd_index), cmd.s);
/* if we need to force a kick, do so */
if (referral_kick) {
kick_mupdate();
referral_kick = 0;
}
if (plaintextloginalert) {
prot_printf(imapd_out, "* OK [ALERT] %s\r\n",
plaintextloginalert);
plaintextloginalert = NULL;
}
/* Only Authenticate/Enable/Login/Logout/Noop/Capability/Id/Starttls
allowed when not logged in */
if (!imapd_userid && !strchr("AELNCIS", cmd.s[0])) goto nologin;
/* Start command timer */
cmdtime_starttimer();
/* note that about half the commands (the common ones that don't
hit the mailboxes file) now close the mailboxes file just in
case it was open. */
switch (cmd.s[0]) {
case 'A':
if (!strcmp(cmd.s, "Authenticate")) {
int haveinitresp = 0;
if (c != ' ') goto missingargs;
c = getword(imapd_in, &arg1);
if (!imparse_isatom(arg1.s)) {
prot_printf(imapd_out, "%s BAD Invalid authenticate mechanism\r\n", tag.s);
eatline(imapd_in, c);
continue;
}
if (c == ' ') {
haveinitresp = 1;
c = getword(imapd_in, &arg2);
if (c == EOF) goto missingargs;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
if (imapd_userid) {
prot_printf(imapd_out, "%s BAD Already authenticated\r\n", tag.s);
continue;
}
cmd_authenticate(tag.s, arg1.s, haveinitresp ? arg2.s : NULL);
snmp_increment(AUTHENTICATE_COUNT, 1);
}
else if (!imapd_userid) goto nologin;
else if (!strcmp(cmd.s, "Append")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_append(tag.s, arg1.s, NULL);
snmp_increment(APPEND_COUNT, 1);
}
else goto badcmd;
break;
case 'C':
if (!strcmp(cmd.s, "Capability")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_capability(tag.s);
snmp_increment(CAPABILITY_COUNT, 1);
}
else if (!imapd_userid) goto nologin;
#ifdef HAVE_ZLIB
else if (!strcmp(cmd.s, "Compress")) {
if (c != ' ') goto missingargs;
c = getword(imapd_in, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_compress(tag.s, arg1.s);
snmp_increment(COMPRESS_COUNT, 1);
}
#endif /* HAVE_ZLIB */
else if (!strcmp(cmd.s, "Check")) {
if (!imapd_index && !backend_current) goto nomailbox;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_noop(tag.s, cmd.s);
snmp_increment(CHECK_COUNT, 1);
}
else if (!strcmp(cmd.s, "Copy")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
copy:
c = getword(imapd_in, &arg1);
if (c == '\r') goto missingargs;
if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_copy(tag.s, arg1.s, arg2.s, usinguid, /*ismove*/0);
snmp_increment(COPY_COUNT, 1);
}
else if (!strcmp(cmd.s, "Create")) {
struct dlist *extargs = NULL;
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == ' ') {
c = parsecreateargs(&extargs);
if (c == EOF) goto badpartition;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_create(tag.s, arg1.s, extargs, 0);
dlist_free(&extargs);
snmp_increment(CREATE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Close")) {
if (!imapd_index && !backend_current) goto nomailbox;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_close(tag.s, cmd.s);
snmp_increment(CLOSE_COUNT, 1);
}
else goto badcmd;
break;
case 'D':
if (!strcmp(cmd.s, "Delete")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_delete(tag.s, arg1.s, 0, 0);
snmp_increment(DELETE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Deleteacl")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_setacl(tag.s, arg1.s, arg2.s, NULL);
snmp_increment(DELETEACL_COUNT, 1);
}
else if (!strcmp(cmd.s, "Dump")) {
int uid_start = 0;
if(c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if(c == ' ') {
c = getastring(imapd_in, imapd_out, &arg2);
if(!imparse_isnumber(arg2.s)) goto extraargs;
uid_start = atoi(arg2.s);
}
if(c == '\r') c = prot_getc(imapd_in);
if(c != '\n') goto extraargs;
cmd_dump(tag.s, arg1.s, uid_start);
/* snmp_increment(DUMP_COUNT, 1);*/
}
else goto badcmd;
break;
case 'E':
if (!imapd_userid) goto nologin;
else if (!strcmp(cmd.s, "Enable")) {
if (c != ' ') goto missingargs;
cmd_enable(tag.s);
}
else if (!strcmp(cmd.s, "Expunge")) {
if (!imapd_index && !backend_current) goto nomailbox;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_expunge(tag.s, 0);
snmp_increment(EXPUNGE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Examine")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
prot_ungetc(c, imapd_in);
cmd_select(tag.s, cmd.s, arg1.s);
snmp_increment(EXAMINE_COUNT, 1);
}
else goto badcmd;
break;
case 'F':
if (!strcmp(cmd.s, "Fetch")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
fetch:
c = getword(imapd_in, &arg1);
if (c == '\r') goto missingargs;
if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence;
cmd_fetch(tag.s, arg1.s, usinguid);
snmp_increment(FETCH_COUNT, 1);
}
else goto badcmd;
break;
case 'G':
if (!strcmp(cmd.s, "Getacl")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_getacl(tag.s, arg1.s);
snmp_increment(GETACL_COUNT, 1);
}
else if (!strcmp(cmd.s, "Getannotation")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_getannotation(tag.s, arg1.s);
snmp_increment(GETANNOTATION_COUNT, 1);
}
else if (!strcmp(cmd.s, "Getmetadata")) {
if (c != ' ') goto missingargs;
cmd_getmetadata(tag.s);
snmp_increment(GETANNOTATION_COUNT, 1);
}
else if (!strcmp(cmd.s, "Getquota")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_getquota(tag.s, arg1.s);
snmp_increment(GETQUOTA_COUNT, 1);
}
else if (!strcmp(cmd.s, "Getquotaroot")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_getquotaroot(tag.s, arg1.s);
snmp_increment(GETQUOTAROOT_COUNT, 1);
}
#ifdef HAVE_SSL
else if (!strcmp(cmd.s, "Genurlauth")) {
if (c != ' ') goto missingargs;
cmd_genurlauth(tag.s);
/* snmp_increment(GENURLAUTH_COUNT, 1);*/
}
#endif
else goto badcmd;
break;
case 'I':
if (!strcmp(cmd.s, "Id")) {
if (c != ' ') goto missingargs;
cmd_id(tag.s);
snmp_increment(ID_COUNT, 1);
}
else if (!imapd_userid) goto nologin;
else if (!strcmp(cmd.s, "Idle") && idle_enabled()) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_idle(tag.s);
snmp_increment(IDLE_COUNT, 1);
}
else goto badcmd;
break;
case 'L':
if (!strcmp(cmd.s, "Login")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if(c != ' ') goto missingargs;
cmd_login(tag.s, arg1.s);
snmp_increment(LOGIN_COUNT, 1);
}
else if (!strcmp(cmd.s, "Logout")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
snmp_increment(LOGOUT_COUNT, 1);
/* force any responses from our selected backend */
if (backend_current) imapd_check(NULL, 0);
prot_printf(imapd_out, "* BYE %s\r\n",
error_message(IMAP_BYE_LOGOUT));
prot_printf(imapd_out, "%s OK %s\r\n", tag.s,
error_message(IMAP_OK_COMPLETED));
if (imapd_userid && *imapd_userid) {
telemetry_rusage(imapd_userid);
}
goto done;
}
else if (!imapd_userid) goto nologin;
else if (!strcmp(cmd.s, "List")) {
struct listargs listargs;
if (c != ' ') goto missingargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.ret = LIST_RET_CHILDREN;
getlistargs(tag.s, &listargs);
if (listargs.pat.count) cmd_list(tag.s, &listargs);
snmp_increment(LIST_COUNT, 1);
}
else if (!strcmp(cmd.s, "Lsub")) {
struct listargs listargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.cmd = LIST_CMD_LSUB;
listargs.sel = LIST_SEL_SUBSCRIBED;
if (!strcasecmpsafe(imapd_magicplus, "+dav"))
listargs.sel |= LIST_SEL_DAV;
listargs.ref = arg1.s;
strarray_append(&listargs.pat, arg2.s);
cmd_list(tag.s, &listargs);
snmp_increment(LSUB_COUNT, 1);
}
else if (!strcmp(cmd.s, "Listrights")) {
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_listrights(tag.s, arg1.s, arg2.s);
snmp_increment(LISTRIGHTS_COUNT, 1);
}
else if (!strcmp(cmd.s, "Localappend")) {
/* create a local-only mailbox */
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c != ' ') goto missingargs;
cmd_append(tag.s, arg1.s, *arg2.s ? arg2.s : NULL);
snmp_increment(APPEND_COUNT, 1);
}
else if (!strcmp(cmd.s, "Localcreate")) {
/* create a local-only mailbox */
struct dlist *extargs = NULL;
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == ' ') {
c = parsecreateargs(&extargs);
if (c == EOF) goto badpartition;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_create(tag.s, arg1.s, extargs, 1);
dlist_free(&extargs);
/* xxxx snmp_increment(CREATE_COUNT, 1); */
}
else if (!strcmp(cmd.s, "Localdelete")) {
/* delete a mailbox locally only */
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_delete(tag.s, arg1.s, 1, 1);
/* xxxx snmp_increment(DELETE_COUNT, 1); */
}
else goto badcmd;
break;
case 'M':
if (!strcmp(cmd.s, "Myrights")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_myrights(tag.s, arg1.s);
/* xxxx snmp_increment(MYRIGHTS_COUNT, 1); */
}
else if (!strcmp(cmd.s, "Mupdatepush")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if(c == EOF) goto missingargs;
if(c == '\r') c = prot_getc(imapd_in);
if(c != '\n') goto extraargs;
cmd_mupdatepush(tag.s, arg1.s);
/* xxxx snmp_increment(MUPDATEPUSH_COUNT, 1); */
}
else if (!strcmp(cmd.s, "Move")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
move:
c = getword(imapd_in, &arg1);
if (c == '\r') goto missingargs;
if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_copy(tag.s, arg1.s, arg2.s, usinguid, /*ismove*/1);
snmp_increment(COPY_COUNT, 1);
} else goto badcmd;
break;
case 'N':
if (!strcmp(cmd.s, "Noop")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_noop(tag.s, cmd.s);
/* xxxx snmp_increment(NOOP_COUNT, 1); */
}
else if (!imapd_userid) goto nologin;
else if (!strcmp(cmd.s, "Namespace")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_namespace(tag.s);
/* xxxx snmp_increment(NAMESPACE_COUNT, 1); */
}
else goto badcmd;
break;
case 'R':
if (!strcmp(cmd.s, "Rename")) {
havepartition = 0;
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == EOF) goto missingargs;
if (c == ' ') {
havepartition = 1;
c = getword(imapd_in, &arg3);
if (!imparse_isatom(arg3.s)) goto badpartition;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_rename(tag.s, arg1.s, arg2.s, havepartition ? arg3.s : 0);
/* xxxx snmp_increment(RENAME_COUNT, 1); */
} else if(!strcmp(cmd.s, "Reconstruct")) {
recursive = 0;
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if(c == ' ') {
/* Optional RECURSEIVE argument */
c = getword(imapd_in, &arg2);
if(!imparse_isatom(arg2.s))
goto extraargs;
else if(!strcasecmp(arg2.s, "RECURSIVE"))
recursive = 1;
else
goto extraargs;
}
if(c == '\r') c = prot_getc(imapd_in);
if(c != '\n') goto extraargs;
cmd_reconstruct(tag.s, arg1.s, recursive);
/* snmp_increment(RECONSTRUCT_COUNT, 1); */
}
else if (!strcmp(cmd.s, "Rlist")) {
struct listargs listargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.sel = LIST_SEL_REMOTE;
listargs.ret = LIST_RET_CHILDREN;
listargs.ref = arg1.s;
strarray_append(&listargs.pat, arg2.s);
cmd_list(tag.s, &listargs);
/* snmp_increment(LIST_COUNT, 1); */
}
else if (!strcmp(cmd.s, "Rlsub")) {
struct listargs listargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.cmd = LIST_CMD_LSUB;
listargs.sel = LIST_SEL_REMOTE | LIST_SEL_SUBSCRIBED;
listargs.ref = arg1.s;
strarray_append(&listargs.pat, arg2.s);
cmd_list(tag.s, &listargs);
/* snmp_increment(LSUB_COUNT, 1); */
}
#ifdef HAVE_SSL
else if (!strcmp(cmd.s, "Resetkey")) {
int have_mbox = 0, have_mech = 0;
if (c == ' ') {
have_mbox = 1;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == ' ') {
have_mech = 1;
c = getword(imapd_in, &arg2);
}
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_resetkey(tag.s, have_mbox ? arg1.s : 0,
have_mech ? arg2.s : 0);
/* snmp_increment(RESETKEY_COUNT, 1);*/
}
#endif
else goto badcmd;
break;
case 'S':
if (!strcmp(cmd.s, "Starttls")) {
if (!tls_enabled()) {
/* we don't support starttls */
goto badcmd;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
/* XXX discard any input pipelined after STARTTLS */
prot_flush(imapd_in);
/* if we've already done SASL fail */
if (imapd_userid != NULL) {
prot_printf(imapd_out,
"%s BAD Can't Starttls after authentication\r\n", tag.s);
continue;
}
/* if we've already done COMPRESS fail */
if (imapd_compress_done == 1) {
prot_printf(imapd_out,
"%s BAD Can't Starttls after Compress\r\n", tag.s);
continue;
}
/* check if already did a successful tls */
if (imapd_starttls_done == 1) {
prot_printf(imapd_out,
"%s BAD Already did a successful Starttls\r\n",
tag.s);
continue;
}
cmd_starttls(tag.s, 0);
snmp_increment(STARTTLS_COUNT, 1);
continue;
}
if (!imapd_userid) {
goto nologin;
} else if (!strcmp(cmd.s, "Store")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
store:
c = getword(imapd_in, &arg1);
if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence;
cmd_store(tag.s, arg1.s, usinguid);
snmp_increment(STORE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Select")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
prot_ungetc(c, imapd_in);
cmd_select(tag.s, cmd.s, arg1.s);
snmp_increment(SELECT_COUNT, 1);
}
else if (!strcmp(cmd.s, "Search")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
search:
cmd_search(tag.s, usinguid);
snmp_increment(SEARCH_COUNT, 1);
}
else if (!strcmp(cmd.s, "Subscribe")) {
if (c != ' ') goto missingargs;
havenamespace = 0;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == ' ') {
havenamespace = 1;
c = getastring(imapd_in, imapd_out, &arg2);
}
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
if (havenamespace) {
cmd_changesub(tag.s, arg1.s, arg2.s, 1);
}
else {
cmd_changesub(tag.s, (char *)0, arg1.s, 1);
}
snmp_increment(SUBSCRIBE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Setacl")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg3);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_setacl(tag.s, arg1.s, arg2.s, arg3.s);
snmp_increment(SETACL_COUNT, 1);
}
else if (!strcmp(cmd.s, "Setannotation")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_setannotation(tag.s, arg1.s);
snmp_increment(SETANNOTATION_COUNT, 1);
}
else if (!strcmp(cmd.s, "Setmetadata")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_setmetadata(tag.s, arg1.s);
snmp_increment(SETANNOTATION_COUNT, 1);
}
else if (!strcmp(cmd.s, "Setquota")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_setquota(tag.s, arg1.s);
snmp_increment(SETQUOTA_COUNT, 1);
}
else if (!strcmp(cmd.s, "Sort")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
sort:
cmd_sort(tag.s, usinguid);
snmp_increment(SORT_COUNT, 1);
}
else if (!strcmp(cmd.s, "Status")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_status(tag.s, arg1.s);
snmp_increment(STATUS_COUNT, 1);
}
else if (!strcmp(cmd.s, "Scan")) {
struct listargs listargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg3);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.ref = arg1.s;
strarray_append(&listargs.pat, arg2.s);
listargs.scan = arg3.s;
cmd_list(tag.s, &listargs);
snmp_increment(SCAN_COUNT, 1);
}
else if (!strcmp(cmd.s, "Syncapply")) {
struct dlist *kl = sync_parseline(imapd_in);
if (kl) {
cmd_syncapply(tag.s, kl, reserve_list);
dlist_free(&kl);
}
else goto extraargs;
}
else if (!strcmp(cmd.s, "Syncget")) {
struct dlist *kl = sync_parseline(imapd_in);
if (kl) {
cmd_syncget(tag.s, kl);
dlist_free(&kl);
}
else goto extraargs;
}
else if (!strcmp(cmd.s, "Syncrestart")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
/* just clear the GUID cache */
cmd_syncrestart(tag.s, &reserve_list, 1);
}
else if (!strcmp(cmd.s, "Syncrestore")) {
struct dlist *kl = sync_parseline(imapd_in);
if (kl) {
cmd_syncrestore(tag.s, kl, reserve_list);
dlist_free(&kl);
}
else goto extraargs;
}
else goto badcmd;
break;
case 'T':
if (!strcmp(cmd.s, "Thread")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
thread:
cmd_thread(tag.s, usinguid);
snmp_increment(THREAD_COUNT, 1);
}
else goto badcmd;
break;
case 'U':
if (!strcmp(cmd.s, "Uid")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 1;
if (c != ' ') goto missingargs;
c = getword(imapd_in, &arg1);
if (c != ' ') goto missingargs;
lcase(arg1.s);
xstrncpy(cmdname, arg1.s, 99);
if (!strcmp(arg1.s, "fetch")) {
goto fetch;
}
else if (!strcmp(arg1.s, "store")) {
goto store;
}
else if (!strcmp(arg1.s, "search")) {
goto search;
}
else if (!strcmp(arg1.s, "sort")) {
goto sort;
}
else if (!strcmp(arg1.s, "thread")) {
goto thread;
}
else if (!strcmp(arg1.s, "copy")) {
goto copy;
}
else if (!strcmp(arg1.s, "move")) {
goto move;
}
else if (!strcmp(arg1.s, "xmove")) {
goto move;
}
else if (!strcmp(arg1.s, "expunge")) {
c = getword(imapd_in, &arg1);
if (!imparse_issequence(arg1.s)) goto badsequence;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_expunge(tag.s, arg1.s);
snmp_increment(EXPUNGE_COUNT, 1);
}
else if (!strcmp(arg1.s, "xrunannotator")) {
goto xrunannotator;
}
else {
prot_printf(imapd_out, "%s BAD Unrecognized UID subcommand\r\n", tag.s);
eatline(imapd_in, c);
}
}
else if (!strcmp(cmd.s, "Unsubscribe")) {
if (c != ' ') goto missingargs;
havenamespace = 0;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == ' ') {
havenamespace = 1;
c = getastring(imapd_in, imapd_out, &arg2);
}
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
if (havenamespace) {
cmd_changesub(tag.s, arg1.s, arg2.s, 0);
}
else {
cmd_changesub(tag.s, (char *)0, arg1.s, 0);
}
snmp_increment(UNSUBSCRIBE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Unselect")) {
if (!imapd_index && !backend_current) goto nomailbox;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_close(tag.s, cmd.s);
snmp_increment(UNSELECT_COUNT, 1);
}
else if (!strcmp(cmd.s, "Undump")) {
if(c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
/* we want to get a list at this point */
if(c != ' ') goto missingargs;
cmd_undump(tag.s, arg1.s);
/* snmp_increment(UNDUMP_COUNT, 1);*/
}
#ifdef HAVE_SSL
else if (!strcmp(cmd.s, "Urlfetch")) {
if (c != ' ') goto missingargs;
cmd_urlfetch(tag.s);
/* snmp_increment(URLFETCH_COUNT, 1);*/
}
#endif
else goto badcmd;
break;
case 'X':
if (!strcmp(cmd.s, "Xbackup")) {
int havechannel = 0;
if (!config_getswitch(IMAPOPT_XBACKUP_ENABLED))
goto badcmd;
/* user */
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
/* channel */
if (c == ' ') {
havechannel = 1;
c = getword(imapd_in, &arg2);
if (c == EOF) goto missingargs;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_xbackup(tag.s, arg1.s, havechannel ? arg2.s : NULL);
// snmp_increment(XBACKUP_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xconvfetch")) {
cmd_xconvfetch(tag.s);
// snmp_increment(XCONVFETCH_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xconvmultisort")) {
if (c != ' ') goto missingargs;
if (!imapd_index && !backend_current) goto nomailbox;
cmd_xconvmultisort(tag.s);
// snmp_increment(XCONVMULTISORT_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xconvsort")) {
if (c != ' ') goto missingargs;
if (!imapd_index && !backend_current) goto nomailbox;
cmd_xconvsort(tag.s, 0);
// snmp_increment(XCONVSORT_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xconvupdates")) {
if (c != ' ') goto missingargs;
if (!imapd_index && !backend_current) goto nomailbox;
cmd_xconvsort(tag.s, 1);
// snmp_increment(XCONVUPDATES_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xfer")) {
int havepartition = 0;
/* Mailbox */
if(c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
/* Dest Server */
if(c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if(c == ' ') {
/* Dest Partition */
c = getastring(imapd_in, imapd_out, &arg3);
if (!imparse_isatom(arg3.s)) goto badpartition;
havepartition = 1;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_xfer(tag.s, arg1.s, arg2.s,
(havepartition ? arg3.s : NULL));
/* snmp_increment(XFER_COUNT, 1);*/
}
else if (!strcmp(cmd.s, "Xconvmeta")) {
cmd_xconvmeta(tag.s);
}
else if (!strcmp(cmd.s, "Xlist")) {
struct listargs listargs;
if (c != ' ') goto missingargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.cmd = LIST_CMD_XLIST;
listargs.ret = LIST_RET_CHILDREN | LIST_RET_SPECIALUSE;
getlistargs(tag.s, &listargs);
if (listargs.pat.count) cmd_list(tag.s, &listargs);
snmp_increment(LIST_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xmove")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
goto move;
}
else if (!strcmp(cmd.s, "Xrunannotator")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
xrunannotator:
c = getword(imapd_in, &arg1);
if (!arg1.len || !imparse_issequence(arg1.s)) goto badsequence;
cmd_xrunannotator(tag.s, arg1.s, usinguid);
// snmp_increment(XRUNANNOTATOR_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xsnippets")) {
if (c != ' ') goto missingargs;
if (!imapd_index && !backend_current) goto nomailbox;
cmd_xsnippets(tag.s);
// snmp_increment(XSNIPPETS_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xstats")) {
cmd_xstats(tag.s, c);
}
else if (!strcmp(cmd.s, "Xwarmup")) {
/* XWARMUP doesn't need a mailbox to be selected */
if (c != ' ') goto missingargs;
cmd_xwarmup(tag.s);
// snmp_increment(XWARMUP_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xkillmy")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_xkillmy(tag.s, arg1.s);
}
else if (!strcmp(cmd.s, "Xforever")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_xforever(tag.s);
}
else if (!strcmp(cmd.s, "Xmeid")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_xmeid(tag.s, arg1.s);
}
else if (apns_enabled && !strcmp(cmd.s, "Xapplepushservice")) {
if (c != ' ') goto missingargs;
memset(&applepushserviceargs, 0, sizeof(struct applepushserviceargs));
do {
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto aps_missingargs;
if (!strcmp(arg1.s, "mailboxes")) {
c = prot_getc(imapd_in);
if (c != '(')
goto aps_missingargs;
c = prot_getc(imapd_in);
if (c != ')') {
prot_ungetc(c, imapd_in);
do {
c = getastring(imapd_in, imapd_out, &arg2);
if (c == EOF) break;
strarray_push(&applepushserviceargs.mailboxes, arg2.s);
} while (c == ' ');
}
if (c != ')')
goto aps_missingargs;
c = prot_getc(imapd_in);
}
else {
c = getastring(imapd_in, imapd_out, &arg2);
// regular key/value
if (!strcmp(arg1.s, "aps-version")) {
if (!imparse_isnumber(arg2.s)) goto aps_extraargs;
applepushserviceargs.aps_version = atoi(arg2.s);
}
else if (!strcmp(arg1.s, "aps-account-id"))
buf_copy(&applepushserviceargs.aps_account_id, &arg2);
else if (!strcmp(arg1.s, "aps-device-token"))
buf_copy(&applepushserviceargs.aps_device_token, &arg2);
else if (!strcmp(arg1.s, "aps-subtopic"))
buf_copy(&applepushserviceargs.aps_subtopic, &arg2);
else
goto aps_extraargs;
}
} while (c == ' ');
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto aps_extraargs;
cmd_xapplepushservice(tag.s, &applepushserviceargs);
}
else goto badcmd;
break;
default:
badcmd:
prot_printf(imapd_out, "%s BAD Unrecognized command\r\n", tag.s);
eatline(imapd_in, c);
}
/* End command timer - don't log "idle" commands */
if (commandmintimer && strcmp("idle", cmdname)) {
double cmdtime, nettime;
const char *mboxname = index_mboxname(imapd_index);
if (!mboxname) mboxname = "<none>";
cmdtime_endtimer(&cmdtime, &nettime);
if (cmdtime >= commandmintimerd) {
syslog(LOG_NOTICE, "cmdtimer: '%s' '%s' '%s' '%f' '%f' '%f'",
imapd_userid ? imapd_userid : "<none>", cmdname, mboxname,
cmdtime, nettime, cmdtime + nettime);
}
}
continue;
nologin:
prot_printf(imapd_out, "%s BAD Please login first\r\n", tag.s);
eatline(imapd_in, c);
continue;
nomailbox:
prot_printf(imapd_out,
"%s BAD Please select a mailbox first\r\n", tag.s);
eatline(imapd_in, c);
continue;
aps_missingargs:
buf_free(&applepushserviceargs.aps_account_id);
buf_free(&applepushserviceargs.aps_device_token);
buf_free(&applepushserviceargs.aps_subtopic);
strarray_fini(&applepushserviceargs.mailboxes);
missingargs:
prot_printf(imapd_out,
"%s BAD Missing required argument to %s\r\n", tag.s, cmd.s);
eatline(imapd_in, c);
continue;
aps_extraargs:
buf_free(&applepushserviceargs.aps_account_id);
buf_free(&applepushserviceargs.aps_device_token);
buf_free(&applepushserviceargs.aps_subtopic);
strarray_fini(&applepushserviceargs.mailboxes);
extraargs:
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to %s\r\n", tag.s, cmd.s);
eatline(imapd_in, c);
continue;
badsequence:
prot_printf(imapd_out,
"%s BAD Invalid sequence in %s\r\n", tag.s, cmd.s);
eatline(imapd_in, c);
continue;
badpartition:
prot_printf(imapd_out,
"%s BAD Invalid partition name in %s\r\n", tag.s, cmd.s);
eatline(imapd_in, c);
continue;
}
done:
cmd_syncrestart(NULL, &reserve_list, 0);
}
#ifdef USE_AUTOCREATE
/*
* Autocreate Inbox and subfolders upon login
*/
static void autocreate_inbox(void)
{
if (imapd_userisadmin) return;
if (imapd_userisproxyadmin) return;
if (config_getint(IMAPOPT_AUTOCREATE_QUOTA) >= 0) {
char *inboxname = mboxname_user_mbox(imapd_userid, NULL);
int r = mboxlist_lookup(inboxname, NULL, NULL);
free(inboxname);
if (r != IMAP_MAILBOX_NONEXISTENT) return;
autocreate_user(&imapd_namespace, imapd_userid);
}
}
#endif // USE_AUTOCREATE
static void authentication_success(void)
{
int r;
struct mboxevent *mboxevent;
/* authstate already created by mysasl_proxy_policy() */
imapd_userisadmin = global_authisa(imapd_authstate, IMAPOPT_ADMINS);
/* Create telemetry log */
imapd_logfd = telemetry_log(imapd_userid, imapd_in, imapd_out, 0);
/* Set namespace */
r = mboxname_init_namespace(&imapd_namespace,
imapd_userisadmin || imapd_userisproxyadmin);
mboxevent_setnamespace(&imapd_namespace);
if (r) {
syslog(LOG_ERR, "%s", error_message(r));
fatal(error_message(r), EC_CONFIG);
}
/* Make a copy of the external userid for use in proxying */
proxy_userid = xstrdup(imapd_userid);
/* send a Login event notification */
if ((mboxevent = mboxevent_new(EVENT_LOGIN))) {
mboxevent_set_access(mboxevent, saslprops.iplocalport,
saslprops.ipremoteport, imapd_userid, NULL, 1);
mboxevent_notify(&mboxevent);
mboxevent_free(&mboxevent);
}
#ifdef USE_AUTOCREATE
autocreate_inbox();
#endif // USE_AUTOCREATE
}
static int checklimits(const char *tag)
{
struct proc_limits limits;
limits.procname = "imapd";
limits.clienthost = imapd_clienthost;
limits.userid = imapd_userid;
if (proc_checklimits(&limits)) {
const char *sep = "";
prot_printf(imapd_out, "%s NO Too many open connections (", tag);
if (limits.maxhost) {
prot_printf(imapd_out, "%s%d of %d from %s", sep,
limits.host, limits.maxhost, imapd_clienthost);
sep = ", ";
}
if (limits.maxuser) {
prot_printf(imapd_out, "%s%d of %d for %s", sep,
limits.user, limits.maxuser, imapd_userid);
}
prot_printf(imapd_out, ")\r\n");
free(imapd_userid);
imapd_userid = NULL;
auth_freestate(imapd_authstate);
imapd_authstate = NULL;
return 1;
}
return 0;
}
/*
* Perform a LOGIN command
*/
static void cmd_login(char *tag, char *user)
{
char userbuf[MAX_MAILBOX_BUFFER];
char replybuf[MAX_MAILBOX_BUFFER];
unsigned userlen;
const char *canon_user = userbuf;
const void *val;
int c;
struct buf passwdbuf;
char *passwd;
const char *reply = NULL;
int r;
int failedloginpause;
if (imapd_userid) {
eatline(imapd_in, ' ');
prot_printf(imapd_out, "%s BAD Already logged in\r\n", tag);
return;
}
r = imapd_canon_user(imapd_saslconn, NULL, user, 0,
SASL_CU_AUTHID | SASL_CU_AUTHZID, NULL,
userbuf, sizeof(userbuf), &userlen);
if (r) {
eatline(imapd_in, ' ');
syslog(LOG_NOTICE, "badlogin: %s plaintext %s invalid user",
imapd_clienthost, beautify_string(user));
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(IMAP_INVALID_USER));
return;
}
/* possibly disallow login */
if (imapd_tls_required ||
(!imapd_starttls_done && (extprops_ssf < 2) &&
!config_getswitch(IMAPOPT_ALLOWPLAINTEXT) &&
!is_userid_anonymous(canon_user))) {
eatline(imapd_in, ' ');
prot_printf(imapd_out, "%s NO Login only available under a layer\r\n",
tag);
return;
}
memset(&passwdbuf,0,sizeof(struct buf));
c = getastring(imapd_in, imapd_out, &passwdbuf);
if(c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
buf_free(&passwdbuf);
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to LOGIN\r\n",
tag);
eatline(imapd_in, c);
return;
}
passwd = passwdbuf.s;
if (is_userid_anonymous(canon_user)) {
if (config_getswitch(IMAPOPT_ALLOWANONYMOUSLOGIN)) {
passwd = beautify_string(passwd);
if (strlen(passwd) > 500) passwd[500] = '\0';
syslog(LOG_NOTICE, "login: %s anonymous %s",
imapd_clienthost, passwd);
reply = "Anonymous access granted";
imapd_userid = xstrdup("anonymous");
}
else {
syslog(LOG_NOTICE, "badlogin: %s anonymous login refused",
imapd_clienthost);
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(IMAP_ANONYMOUS_NOT_PERMITTED));
buf_free(&passwdbuf);
return;
}
}
else if ( nosaslpasswdcheck ) {
snprintf(replybuf, sizeof(replybuf),
"User logged in SESSIONID=<%s>", session_id());
reply = replybuf;
imapd_userid = xstrdup(canon_user);
imapd_authstate = auth_newstate(canon_user);
syslog(LOG_NOTICE, "login: %s %s%s nopassword%s %s", imapd_clienthost,
imapd_userid, imapd_magicplus ? imapd_magicplus : "",
imapd_starttls_done ? "+TLS" : "", reply);
}
else if ((r = sasl_checkpass(imapd_saslconn,
canon_user,
strlen(canon_user),
passwd,
strlen(passwd))) != SASL_OK) {
syslog(LOG_NOTICE, "badlogin: %s plaintext %s %s",
imapd_clienthost, canon_user, sasl_errdetail(imapd_saslconn));
failedloginpause = config_getint(IMAPOPT_FAILEDLOGINPAUSE);
if (failedloginpause != 0) {
sleep(failedloginpause);
}
/* Don't allow user probing */
if (r == SASL_NOUSER) r = SASL_BADAUTH;
if ((reply = sasl_errstring(r, NULL, NULL)) != NULL) {
prot_printf(imapd_out, "%s NO Login failed: %s\r\n", tag, reply);
} else {
prot_printf(imapd_out, "%s NO Login failed: %d\r\n", tag, r);
}
snmp_increment_args(AUTHENTICATION_NO, 1,
VARIABLE_AUTH, 0 /* hash_simple("LOGIN") */,
VARIABLE_LISTEND);
buf_free(&passwdbuf);
return;
}
else {
r = sasl_getprop(imapd_saslconn, SASL_USERNAME, &val);
if(r != SASL_OK) {
if ((reply = sasl_errstring(r, NULL, NULL)) != NULL) {
prot_printf(imapd_out, "%s NO Login failed: %s\r\n",
tag, reply);
} else {
prot_printf(imapd_out, "%s NO Login failed: %d\r\n", tag, r);
}
snmp_increment_args(AUTHENTICATION_NO, 1,
VARIABLE_AUTH, 0 /* hash_simple("LOGIN") */,
VARIABLE_LISTEND);
buf_free(&passwdbuf);
return;
}
snprintf(replybuf, sizeof(replybuf),
"User logged in SESSIONID=<%s>", session_id());
reply = replybuf;
imapd_userid = xstrdup((const char *) val);
snmp_increment_args(AUTHENTICATION_YES, 1,
VARIABLE_AUTH, 0 /*hash_simple("LOGIN") */,
VARIABLE_LISTEND);
syslog(LOG_NOTICE, "login: %s %s%s plaintext%s %s", imapd_clienthost,
imapd_userid, imapd_magicplus ? imapd_magicplus : "",
imapd_starttls_done ? "+TLS" : "",
reply ? reply : "");
/* Apply penalty only if not under layer */
if (!imapd_starttls_done) {
int plaintextloginpause = config_getint(IMAPOPT_PLAINTEXTLOGINPAUSE);
if (plaintextloginpause) {
sleep(plaintextloginpause);
}
/* Fetch plaintext login nag message */
plaintextloginalert = config_getstring(IMAPOPT_PLAINTEXTLOGINALERT);
}
}
buf_free(&passwdbuf);
if (checklimits(tag)) return;
prot_printf(imapd_out, "%s OK [CAPABILITY ", tag);
capa_response(CAPA_PREAUTH|CAPA_POSTAUTH);
prot_printf(imapd_out, "] %s\r\n", reply);
authentication_success();
}
/*
* Perform an AUTHENTICATE command
*/
static void cmd_authenticate(char *tag, char *authtype, char *resp)
{
int sasl_result;
const void *val;
const char *ssfmsg = NULL;
char replybuf[MAX_MAILBOX_BUFFER];
const char *reply = NULL;
const char *canon_user;
int r;
int failedloginpause;
if (imapd_tls_required) {
prot_printf(imapd_out,
"%s NO Authenticate only available under a layer\r\n", tag);
return;
}
r = saslserver(imapd_saslconn, authtype, resp, "", "+ ", "",
imapd_in, imapd_out, &sasl_result, NULL);
if (r) {
const char *errorstring = NULL;
switch (r) {
case IMAP_SASL_CANCEL:
prot_printf(imapd_out,
"%s BAD Client canceled authentication\r\n", tag);
break;
case IMAP_SASL_PROTERR:
errorstring = prot_error(imapd_in);
prot_printf(imapd_out,
"%s NO Error reading client response: %s\r\n",
tag, errorstring ? errorstring : "");
break;
default:
/* failed authentication */
syslog(LOG_NOTICE, "badlogin: %s %s [%s]",
imapd_clienthost, authtype, sasl_errdetail(imapd_saslconn));
snmp_increment_args(AUTHENTICATION_NO, 1,
VARIABLE_AUTH, 0, /* hash_simple(authtype) */
VARIABLE_LISTEND);
failedloginpause = config_getint(IMAPOPT_FAILEDLOGINPAUSE);
if (failedloginpause != 0) {
sleep(failedloginpause);
}
/* Don't allow user probing */
if (sasl_result == SASL_NOUSER) sasl_result = SASL_BADAUTH;
errorstring = sasl_errstring(sasl_result, NULL, NULL);
if (errorstring) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, errorstring);
} else {
prot_printf(imapd_out, "%s NO Error authenticating\r\n", tag);
}
}
reset_saslconn(&imapd_saslconn);
return;
}
/* successful authentication */
/* get the userid from SASL --- already canonicalized from
* mysasl_proxy_policy()
*/
sasl_result = sasl_getprop(imapd_saslconn, SASL_USERNAME, &val);
if (sasl_result != SASL_OK) {
prot_printf(imapd_out, "%s NO weird SASL error %d SASL_USERNAME\r\n",
tag, sasl_result);
syslog(LOG_ERR, "weird SASL error %d getting SASL_USERNAME",
sasl_result);
reset_saslconn(&imapd_saslconn);
return;
}
canon_user = (const char *) val;
/* If we're proxying, the authzid may contain a magic plus,
so re-canonify it */
if (config_getswitch(IMAPOPT_IMAPMAGICPLUS) && strchr(canon_user, '+')) {
char userbuf[MAX_MAILBOX_BUFFER];
unsigned userlen;
sasl_result = imapd_canon_user(imapd_saslconn, NULL, canon_user, 0,
SASL_CU_AUTHID | SASL_CU_AUTHZID,
NULL, userbuf, sizeof(userbuf), &userlen);
if (sasl_result != SASL_OK) {
prot_printf(imapd_out,
"%s NO SASL canonification error %d\r\n",
tag, sasl_result);
reset_saslconn(&imapd_saslconn);
return;
}
imapd_userid = xstrdup(userbuf);
} else {
imapd_userid = xstrdup(canon_user);
}
snprintf(replybuf, sizeof(replybuf),
"User logged in SESSIONID=<%s>", session_id());
reply = replybuf;
syslog(LOG_NOTICE, "login: %s %s%s %s%s %s", imapd_clienthost,
imapd_userid, imapd_magicplus ? imapd_magicplus : "",
authtype, imapd_starttls_done ? "+TLS" : "", reply);
sasl_getprop(imapd_saslconn, SASL_SSF, &val);
saslprops.ssf = *((sasl_ssf_t *) val);
/* really, we should be doing a sasl_getprop on SASL_SSF_EXTERNAL,
but the current libsasl doesn't allow that. */
if (imapd_starttls_done) {
switch(saslprops.ssf) {
case 0: ssfmsg = "tls protection"; break;
case 1: ssfmsg = "tls plus integrity protection"; break;
default: ssfmsg = "tls plus privacy protection"; break;
}
} else {
switch(saslprops.ssf) {
case 0: ssfmsg = "no protection"; break;
case 1: ssfmsg = "integrity protection"; break;
default: ssfmsg = "privacy protection"; break;
}
}
snmp_increment_args(AUTHENTICATION_YES, 1,
VARIABLE_AUTH, 0, /* hash_simple(authtype) */
VARIABLE_LISTEND);
if (checklimits(tag)) {
reset_saslconn(&imapd_saslconn);
return;
}
if (!saslprops.ssf) {
prot_printf(imapd_out, "%s OK [CAPABILITY ", tag);
capa_response(CAPA_PREAUTH|CAPA_POSTAUTH);
prot_printf(imapd_out, "] Success (%s) SESSIONID=<%s>\r\n",
ssfmsg, session_id());
} else {
prot_printf(imapd_out, "%s OK Success (%s) SESSIONID=<%s>\r\n",
tag, ssfmsg, session_id());
}
prot_setsasl(imapd_in, imapd_saslconn);
prot_setsasl(imapd_out, imapd_saslconn);
authentication_success();
}
/*
* Perform a NOOP command
*/
static void cmd_noop(char *tag, char *cmd)
{
if (backend_current) {
/* remote mailbox */
prot_printf(backend_current->out, "%s %s\r\n", tag, cmd);
pipe_including_tag(backend_current, tag, 0);
return;
}
index_check(imapd_index, 1, 0);
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
static void clear_id() {
if (imapd_id.params) {
freeattvalues(imapd_id.params);
}
memset(&imapd_id, 0, sizeof(struct id_data));
}
/*
* Parse and perform an ID command.
*
* the command has been parsed up to the parameter list.
*
* we only allow one ID in non-authenticated state from a given client.
* we only allow MAXIDFAILED consecutive failed IDs from a given client.
* we only record MAXIDLOG ID responses from a given client.
*/
static void cmd_id(char *tag)
{
int c = EOF, npair = 0;
static struct buf arg, field;
/* check if we've already had an ID in non-authenticated state */
if (!imapd_userid && imapd_id.did_id) {
prot_printf(imapd_out, "%s OK NIL\r\n", tag);
eatline(imapd_in, c);
return;
}
clear_id();
/* ok, accept parameter list */
c = getword(imapd_in, &arg);
/* check for "NIL" or start of parameter list */
if (strcasecmp(arg.s, "NIL") && c != '(') {
prot_printf(imapd_out, "%s BAD Invalid parameter list in Id\r\n", tag);
eatline(imapd_in, c);
return;
}
/* parse parameter list */
if (c == '(') {
for (;;) {
if (c == ')') {
/* end of string/value pairs */
break;
}
/* get field name */
c = getstring(imapd_in, imapd_out, &field);
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Invalid/missing field name in Id\r\n",
tag);
eatline(imapd_in, c);
return;
}
/* get field value */
c = getnstring(imapd_in, imapd_out, &arg);
if (c != ' ' && c != ')') {
prot_printf(imapd_out,
"%s BAD Invalid/missing value in Id\r\n",
tag);
eatline(imapd_in, c);
return;
}
/* ok, we're anal, but we'll still process the ID command */
if (strlen(field.s) > MAXIDFIELDLEN) {
prot_printf(imapd_out,
"%s BAD field longer than %u octets in Id\r\n",
tag, MAXIDFIELDLEN);
eatline(imapd_in, c);
return;
}
if (arg.len > MAXIDVALUELEN) {
prot_printf(imapd_out,
"%s BAD value longer than %u octets in Id\r\n",
tag, MAXIDVALUELEN);
eatline(imapd_in, c);
return;
}
if (++npair > MAXIDPAIRS) {
prot_printf(imapd_out,
"%s BAD too many (%u) field-value pairs in ID\r\n",
tag, MAXIDPAIRS);
eatline(imapd_in, c);
return;
}
if (!strcmp(field.s, "os") && !strcmp(arg.s, "iOS")) {
imapd_id.quirks |= QUIRK_SEARCHFUZZY;
}
/* ok, we're happy enough */
appendattvalue(&imapd_id.params, field.s, &arg);
}
if (c != ')') {
/* erp! */
prot_printf(imapd_out, "%s BAD trailing junk\r\n", tag);
eatline(imapd_in, c);
return;
}
c = prot_getc(imapd_in);
}
/* check for CRLF */
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out, "%s BAD Unexpected extra arguments to Id\r\n", tag);
eatline(imapd_in, c);
return;
}
/* log the client's ID string.
eventually this should be a callback or something. */
if (npair) {
struct buf logbuf = BUF_INITIALIZER;
struct attvaluelist *pptr;
for (pptr = imapd_id.params; pptr; pptr = pptr->next) {
const char *val = buf_cstring(&pptr->value);
/* should we check for and format literals here ??? */
buf_printf(&logbuf, " \"%s\" ", pptr->attrib);
if (!val || !strcmp(val, "NIL"))
buf_printf(&logbuf, "NIL");
else
buf_printf(&logbuf, "\"%s\"", val);
}
syslog(LOG_INFO, "client id sessionid=<%s>:%s", session_id(), buf_cstring(&logbuf));
buf_free(&logbuf);
}
/* spit out our ID string.
eventually this might be configurable. */
if (config_getswitch(IMAPOPT_IMAPIDRESPONSE) &&
(imapd_authstate || (config_serverinfo == IMAP_ENUM_SERVERINFO_ON))) {
id_response(imapd_out);
prot_printf(imapd_out, ")\r\n");
}
else
prot_printf(imapd_out, "* ID NIL\r\n");
imapd_check(NULL, 0);
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
imapd_id.did_id = 1;
}
static bool deadline_exceeded(const struct timespec *d)
{
struct timespec now;
if (d->tv_sec <= 0) {
/* No deadline configured */
return false;
}
errno = 0;
if (clock_gettime(CLOCK_MONOTONIC, &now) == -1) {
syslog(LOG_ERR, "clock_gettime (%d %m): error reading clock", errno);
return false;
}
return now.tv_sec > d->tv_sec ||
(now.tv_sec == d->tv_sec && now.tv_nsec > d->tv_nsec);
}
/*
* Perform an IDLE command
*/
static void cmd_idle(char *tag)
{
int c = EOF;
int flags;
static struct buf arg;
static int idle_period = -1;
static time_t idle_timeout = -1;
struct timespec deadline = { 0, 0 };
if (idle_timeout == -1) {
idle_timeout = config_getint(IMAPOPT_IMAPIDLETIMEOUT);
if (idle_timeout <= 0) {
idle_timeout = config_getint(IMAPOPT_TIMEOUT);
}
idle_timeout *= 60; /* unit is minutes */
}
if (idle_timeout > 0) {
errno = 0;
if (clock_gettime(CLOCK_MONOTONIC, &deadline) == -1) {
syslog(LOG_ERR, "clock_gettime (%d %m): error reading clock",
errno);
} else {
deadline.tv_sec += idle_timeout;
}
}
if (!backend_current) { /* Local mailbox */
/* Tell client we are idling and waiting for end of command */
prot_printf(imapd_out, "+ idling\r\n");
prot_flush(imapd_out);
/* Start doing mailbox updates */
index_check(imapd_index, 1, 0);
idle_start(index_mboxname(imapd_index));
/* use this flag so if getc causes a shutdown due to
* connection abort we tell idled about it */
idling = 1;
index_release(imapd_index);
while ((flags = idle_wait(imapd_in->fd))) {
if (deadline_exceeded(&deadline)) {
syslog(LOG_DEBUG, "timeout for user '%s' while idling",
imapd_userid);
shut_down(0);
break;
}
if (flags & IDLE_INPUT) {
/* Get continuation data */
c = getword(imapd_in, &arg);
break;
}
/* Send unsolicited untagged responses to the client */
if (flags & IDLE_MAILBOX)
index_check(imapd_index, 1, 0);
if (flags & IDLE_ALERT) {
char shut[MAX_MAILBOX_PATH+1];
if (! imapd_userisadmin &&
(shutdown_file(shut, sizeof(shut)) ||
(imapd_userid &&
userdeny(imapd_userid, config_ident, shut, sizeof(shut))))) {
char *p;
for (p = shut; *p == '['; p++); /* can't have [ be first char */
prot_printf(imapd_out, "* BYE [ALERT] %s\r\n", p);
shut_down(0);
}
}
index_release(imapd_index);
prot_flush(imapd_out);
}
/* Stop updates and do any necessary cleanup */
idling = 0;
idle_stop(index_mboxname(imapd_index));
}
else { /* Remote mailbox */
int done = 0;
enum { shutdown_skip, shutdown_bye, shutdown_silent } shutdown = shutdown_skip;
char buf[2048];
/* get polling period */
if (idle_period == -1) {
idle_period = config_getint(IMAPOPT_IMAPIDLEPOLL);
}
if (CAPA(backend_current, CAPA_IDLE)) {
/* Start IDLE on backend */
prot_printf(backend_current->out, "%s IDLE\r\n", tag);
if (!prot_fgets(buf, sizeof(buf), backend_current->in)) {
/* If we received nothing from the backend, fail */
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(IMAP_SERVER_UNAVAILABLE));
return;
}
if (buf[0] != '+') {
/* If we received anything but a continuation response,
spit out what we received and quit */
prot_write(imapd_out, buf, strlen(buf));
return;
}
}
/* Tell client we are idling and waiting for end of command */
prot_printf(imapd_out, "+ idling\r\n");
prot_flush(imapd_out);
/* Pipe updates to client while waiting for end of command */
while (!done) {
if (deadline_exceeded(&deadline)) {
syslog(LOG_DEBUG,
"timeout for user '%s' while idling on remote mailbox",
imapd_userid);
shutdown = shutdown_silent;
goto done;
}
/* Flush any buffered output */
prot_flush(imapd_out);
/* Check for shutdown file */
if (!imapd_userisadmin &&
(shutdown_file(buf, sizeof(buf)) ||
(imapd_userid &&
userdeny(imapd_userid, config_ident, buf, sizeof(buf))))) {
done = 1;
shutdown = shutdown_bye;
goto done;
}
done = proxy_check_input(protin, imapd_in, imapd_out,
backend_current->in, NULL, idle_period);
/* If not running IDLE on backend, poll the mailbox for updates */
if (!CAPA(backend_current, CAPA_IDLE)) {
imapd_check(NULL, 0);
}
}
/* Get continuation data */
c = getword(imapd_in, &arg);
done:
if (CAPA(backend_current, CAPA_IDLE)) {
/* Either the client timed out, or ended the command.
In either case we're done, so terminate IDLE on backend */
prot_printf(backend_current->out, "Done\r\n");
pipe_until_tag(backend_current, tag, 0);
}
switch (shutdown) {
case shutdown_bye:
;
char *p;
for (p = buf; *p == '['; p++); /* can't have [ be first char */
prot_printf(imapd_out, "* BYE [ALERT] %s\r\n", p);
/* fallthrough */
case shutdown_silent:
shut_down(0);
break;
case shutdown_skip:
default:
break;
}
}
imapd_check(NULL, 1);
if (c != EOF) {
if (!strcasecmp(arg.s, "Done") &&
(c = (c == '\r') ? prot_getc(imapd_in) : c) == '\n') {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
else {
prot_printf(imapd_out,
"%s BAD Invalid Idle continuation\r\n", tag);
eatline(imapd_in, c);
}
}
}
static void capa_response(int flags)
{
const char *sasllist; /* the list of SASL mechanisms */
int mechcount;
int need_space = 0;
int i;
int lminus = config_getswitch(IMAPOPT_LITERALMINUS);
for (i = 0; base_capabilities[i].str; i++) {
const char *capa = base_capabilities[i].str;
/* Filter capabilities if requested */
if (capa_is_disabled(capa))
continue;
/* Don't show "MAILBOX-REFERRALS" if disabled by config */
if (config_getswitch(IMAPOPT_PROXYD_DISABLE_MAILBOX_REFERRALS) &&
!strcmp(capa, "MAILBOX-REFERRALS"))
continue;
/* Don't show if they're not shown at this level of login */
if (!(base_capabilities[i].mask & flags))
continue;
/* cheap and nasty version of LITERAL- support - just say so */
if (lminus && !strcmp(capa, "LITERAL+"))
capa = "LITERAL-";
/* print the capability */
if (need_space) prot_putc(' ', imapd_out);
else need_space = 1;
prot_printf(imapd_out, "%s", base_capabilities[i].str);
}
if (config_mupdate_server) {
prot_printf(imapd_out, " MUPDATE=mupdate://%s/", config_mupdate_server);
}
if (apns_enabled) {
prot_printf(imapd_out, " XAPPLEPUSHSERVICE");
}
if (tls_enabled() && !imapd_starttls_done && !imapd_authstate) {
prot_printf(imapd_out, " STARTTLS");
}
if (imapd_tls_required || imapd_authstate ||
(!imapd_starttls_done && (extprops_ssf < 2) &&
!config_getswitch(IMAPOPT_ALLOWPLAINTEXT))) {
prot_printf(imapd_out, " LOGINDISABLED");
}
/* add the SASL mechs */
if (!imapd_tls_required && (!imapd_authstate || saslprops.ssf) &&
sasl_listmech(imapd_saslconn, NULL,
"AUTH=", " AUTH=",
!imapd_authstate ? " SASL-IR" : "", &sasllist,
NULL, &mechcount) == SASL_OK && mechcount > 0) {
prot_printf(imapd_out, " %s", sasllist);
} else {
/* else don't show anything */
}
if (!(flags & CAPA_POSTAUTH)) return;
if (config_getswitch(IMAPOPT_CONVERSATIONS))
prot_printf(imapd_out, " XCONVERSATIONS");
#ifdef HAVE_ZLIB
if (!imapd_compress_done && !imapd_tls_comp) {
prot_printf(imapd_out, " COMPRESS=DEFLATE");
}
#endif // HAVE_ZLIB
for (i = 0 ; i < QUOTA_NUMRESOURCES ; i++)
prot_printf(imapd_out, " X-QUOTA=%s", quota_names[i]);
if (idle_enabled()) {
prot_printf(imapd_out, " IDLE");
}
}
/*
* Perform a CAPABILITY command
*/
static void cmd_capability(char *tag)
{
imapd_check(NULL, 0);
prot_printf(imapd_out, "* CAPABILITY ");
capa_response(CAPA_PREAUTH|CAPA_POSTAUTH);
prot_printf(imapd_out, "\r\n%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
/*
* Parse and perform an APPEND command.
* The command has been parsed up to and including
* the mailbox name.
*/
static int isokflag(char *s, int *isseen)
{
if (s[0] == '\\') {
lcase(s);
if (!strcmp(s, "\\seen")) {
*isseen = 1;
return 1;
}
if (!strcmp(s, "\\answered")) return 1;
if (!strcmp(s, "\\flagged")) return 1;
if (!strcmp(s, "\\draft")) return 1;
if (!strcmp(s, "\\deleted")) return 1;
/* uh oh, system flag i don't recognize */
return 0;
} else {
/* valid user flag? */
return imparse_isatom(s);
}
}
static int getliteralsize(const char *p, int c,
unsigned *size, int *binary, const char **parseerr)
{
int isnowait = 0;
uint32_t num;
/* Check for literal8 */
if (*p == '~') {
p++;
*binary = 1;
}
/* check for start of literal */
if (*p != '{') {
*parseerr = "Missing required argument to Append command";
return IMAP_PROTOCOL_ERROR;
}
/* Read size from literal */
if (parseuint32(p+1, &p, &num)) {
*parseerr = "Literal size not a number";
return IMAP_PROTOCOL_ERROR;
}
if (*p == '+') {
isnowait++;
p++;
}
if (c == '\r') {
c = prot_getc(imapd_in);
}
if (*p != '}' || p[1] || c != '\n') {
*parseerr = "Invalid literal in Append command";
return IMAP_PROTOCOL_ERROR;
}
if (!isnowait) {
/* Tell client to send the message */
prot_printf(imapd_out, "+ go ahead\r\n");
prot_flush(imapd_out);
}
*size = num;
return 0;
}
static int catenate_text(FILE *f, unsigned *totalsize, int *binary,
const char **parseerr)
{
int c;
static struct buf arg;
unsigned size = 0;
char buf[4096+1];
unsigned n;
int r;
c = getword(imapd_in, &arg);
/* Read size from literal */
r = getliteralsize(arg.s, c, &size, binary, parseerr);
if (r) return r;
if (*totalsize > UINT_MAX - size) r = IMAP_MESSAGE_TOO_LARGE;
/* Catenate message part to stage */
while (size) {
n = prot_read(imapd_in, buf, size > 4096 ? 4096 : size);
if (!n) {
syslog(LOG_ERR,
"DISCONNECT: client disconnected during upload of literal");
return IMAP_IOERROR;
}
buf[n] = '\0';
if (!*binary && (n != strlen(buf))) r = IMAP_MESSAGE_CONTAINSNULL;
size -= n;
if (r) continue;
/* XXX do we want to try and validate the message like
we do in message_copy_strict()? */
if (f) fwrite(buf, n, 1, f);
}
*totalsize += size;
return r;
}
static int catenate_url(const char *s, const char *cur_name, FILE *f,
unsigned *totalsize, const char **parseerr)
{
struct imapurl url;
struct index_state *state;
uint32_t msgno;
int r = 0, doclose = 0;
unsigned long size = 0;
r = imapurl_fromURL(&url, s);
if (r) {
*parseerr = "Improperly specified URL";
r = IMAP_BADURL;
} else if (url.server) {
*parseerr = "Only relative URLs are supported";
r = IMAP_BADURL;
#if 0
} else if (url.server && strcmp(url.server, config_servername)) {
*parseerr = "Cannot catenate messages from another server";
r = IMAP_BADURL;
#endif
} else if (!url.mailbox && !imapd_index && !cur_name) {
*parseerr = "No mailbox is selected or specified";
r = IMAP_BADURL;
} else if (url.mailbox || (url.mailbox = cur_name)) {
mbentry_t *mbentry = NULL;
/* lookup the location of the mailbox */
char *intname = mboxname_from_external(url.mailbox, &imapd_namespace, imapd_userid);
r = mlookup(NULL, NULL, intname, &mbentry);
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
struct backend *be;
be = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (be) {
r = proxy_catenate_url(be, &url, f, &size, parseerr);
if (*totalsize > UINT_MAX - size)
r = IMAP_MESSAGE_TOO_LARGE;
else
*totalsize += size;
}
else
r = IMAP_SERVER_UNAVAILABLE;
free(url.freeme);
mboxlist_entry_free(&mbentry);
free(intname);
return r;
}
mboxlist_entry_free(&mbentry);
/* local mailbox */
if (!r) {
struct index_init init;
memset(&init, 0, sizeof(init));
init.userid = imapd_userid;
init.authstate = imapd_authstate;
init.out = imapd_out;
r = index_open(intname, &init, &state);
if (init.vanishedlist) seqset_free(init.vanishedlist);
}
if (!r) doclose = 1;
if (!r && !(state->myrights & ACL_READ))
r = (imapd_userisadmin || (state->myrights & ACL_LOOKUP)) ?
IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT;
if (r) {
*parseerr = error_message(r);
r = IMAP_BADURL;
}
free(intname);
} else {
state = imapd_index;
}
if (r) {
/* nothing to do, handled up top */
} else if (url.uidvalidity &&
(state->mailbox->i.uidvalidity != url.uidvalidity)) {
*parseerr = "Uidvalidity of mailbox has changed";
r = IMAP_BADURL;
} else if (!url.uid || !(msgno = index_finduid(state, url.uid)) ||
(index_getuid(state, msgno) != url.uid)) {
*parseerr = "No such message in mailbox";
r = IMAP_BADURL;
} else {
/* Catenate message part to stage */
struct protstream *s = prot_new(fileno(f), 1);
r = index_urlfetch(state, msgno, 0, url.section,
url.start_octet, url.octet_count, s, &size);
if (r == IMAP_BADURL)
*parseerr = "No such message part";
else if (!r) {
if (*totalsize > UINT_MAX - size)
r = IMAP_MESSAGE_TOO_LARGE;
else
*totalsize += size;
}
prot_flush(s);
prot_free(s);
/* XXX do we want to try and validate the message like
we do in message_copy_strict()? */
}
free(url.freeme);
if (doclose) index_close(&state);
return r;
}
static int append_catenate(FILE *f, const char *cur_name, unsigned *totalsize,
int *binary, const char **parseerr, const char **url)
{
int c, r = 0;
static struct buf arg;
do {
c = getword(imapd_in, &arg);
if (c != ' ') {
*parseerr = "Missing message part data in Append command";
return IMAP_PROTOCOL_ERROR;
}
if (!strcasecmp(arg.s, "TEXT")) {
int r1 = catenate_text(f, totalsize, binary, parseerr);
if (r1) return r1;
/* if we see a SP, we're trying to catenate more than one part */
/* Parse newline terminating command */
c = prot_getc(imapd_in);
}
else if (!strcasecmp(arg.s, "URL")) {
c = getastring(imapd_in, imapd_out, &arg);
if (c != ' ' && c != ')') {
*parseerr = "Missing URL in Append command";
return IMAP_PROTOCOL_ERROR;
}
if (!r) {
r = catenate_url(arg.s, cur_name, f, totalsize, parseerr);
if (r) {
*url = arg.s;
return r;
}
}
}
else {
*parseerr = "Invalid message part type in Append command";
return IMAP_PROTOCOL_ERROR;
}
fflush(f);
} while (c == ' ');
if (c != ')') {
*parseerr = "Missing space or ) after catenate list in Append command";
return IMAP_PROTOCOL_ERROR;
}
if (ferror(f) || fsync(fileno(f))) {
syslog(LOG_ERR, "IOERROR: writing message: %m");
return IMAP_IOERROR;
}
return r;
}
/* If an APPEND is proxied from another server,
* 'cur_name' is the name of the currently selected mailbox (if any)
* in case we have to resolve relative URLs
*/
static void cmd_append(char *tag, char *name, const char *cur_name)
{
int c;
static struct buf arg;
time_t now = time(NULL);
quota_t qdiffs[QUOTA_NUMRESOURCES] = QUOTA_DIFFS_INITIALIZER;
unsigned size;
int sync_seen = 0;
int r;
int i;
struct appendstate appendstate;
unsigned long uidvalidity = 0;
long doappenduid = 0;
const char *parseerr = NULL, *url = NULL;
struct appendstage *curstage;
mbentry_t *mbentry = NULL;
/* See if we can append */
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(tag, name, intname, &mbentry);
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
struct backend *s = NULL;
if (supports_referrals) {
imapd_refer(tag, mbentry->server, name);
/* Eat the argument */
eatline(imapd_in, prot_getc(imapd_in));
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!s) r = IMAP_SERVER_UNAVAILABLE;
mboxlist_entry_free(&mbentry);
imapd_check(s, 0);
if (!r) {
int is_active = 1;
s->context = (void*) &is_active;
if (imapd_index) {
const char *mboxname = index_mboxname(imapd_index);
prot_printf(s->out, "%s Localappend {" SIZE_T_FMT "+}\r\n%s"
" {" SIZE_T_FMT "+}\r\n%s ",
tag, strlen(name), name,
strlen(mboxname), mboxname);
} else {
prot_printf(s->out, "%s Localappend {" SIZE_T_FMT "+}\r\n%s"
" \"\" ", tag, strlen(name), name);
}
if (!(r = pipe_command(s, 16384))) {
pipe_including_tag(s, tag, 0);
}
s->context = NULL;
} else {
eatline(imapd_in, prot_getc(imapd_in));
}
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag,
prot_error(imapd_in) ? prot_error(imapd_in) :
error_message(r));
}
free(intname);
return;
}
mboxlist_entry_free(&mbentry);
/* local mailbox */
if (!r) {
qdiffs[QUOTA_MESSAGE] = 1;
r = append_check(intname, imapd_authstate, ACL_INSERT, ignorequota ? NULL : qdiffs);
}
if (r) {
eatline(imapd_in, ' ');
prot_printf(imapd_out, "%s NO %s%s\r\n",
tag,
(r == IMAP_MAILBOX_NONEXISTENT &&
mboxlist_createmailboxcheck(intname, 0, 0,
imapd_userisadmin,
imapd_userid, imapd_authstate,
NULL, NULL, 0) == 0)
? "[TRYCREATE] " : "", error_message(r));
free(intname);
return;
}
c = ' '; /* just parsed a space */
/* we loop, to support MULTIAPPEND */
while (!r && c == ' ') {
curstage = xzmalloc(sizeof(*curstage));
ptrarray_push(&stages, curstage);
/* now parsing "append-opts" in the ABNF */
/* Parse flags */
c = getword(imapd_in, &arg);
if (c == '(' && !arg.s[0]) {
strarray_init(&curstage->flags);
do {
c = getword(imapd_in, &arg);
if (!curstage->flags.count && !arg.s[0] && c == ')') break; /* empty list */
if (!isokflag(arg.s, &sync_seen)) {
parseerr = "Invalid flag in Append command";
r = IMAP_PROTOCOL_ERROR;
goto done;
}
strarray_append(&curstage->flags, arg.s);
} while (c == ' ');
if (c != ')') {
parseerr =
"Missing space or ) after flag name in Append command";
r = IMAP_PROTOCOL_ERROR;
goto done;
}
c = prot_getc(imapd_in);
if (c != ' ') {
parseerr = "Missing space after flag list in Append command";
r = IMAP_PROTOCOL_ERROR;
goto done;
}
c = getword(imapd_in, &arg);
}
/* Parse internaldate */
if (c == '\"' && !arg.s[0]) {
prot_ungetc(c, imapd_in);
c = getdatetime(&(curstage->internaldate));
if (c != ' ') {
parseerr = "Invalid date-time in Append command";
r = IMAP_PROTOCOL_ERROR;
goto done;
}
c = getword(imapd_in, &arg);
}
/* try to parse a sequence of "append-ext" */
for (;;) {
if (!strcasecmp(arg.s, "ANNOTATION")) {
/* RFC5257 */
if (c != ' ') {
parseerr = "Missing annotation data in Append command";
r = IMAP_PROTOCOL_ERROR;
goto done;
}
c = parse_annotate_store_data(tag,
/*permessage_flag*/1,
&curstage->annotations);
if (c == EOF) {
eatline(imapd_in, c);
goto cleanup;
}
qdiffs[QUOTA_ANNOTSTORAGE] += sizeentryatts(curstage->annotations);
c = getword(imapd_in, &arg);
}
else
break; /* not a known extension keyword */
}
/* Stage the message */
curstage->f = append_newstage(intname, now, stages.count, &(curstage->stage));
if (!curstage->f) {
r = IMAP_IOERROR;
goto done;
}
/* now parsing "append-data" in the ABNF */
if (!strcasecmp(arg.s, "CATENATE")) {
if (c != ' ' || (c = prot_getc(imapd_in) != '(')) {
parseerr = "Missing message part(s) in Append command";
r = IMAP_PROTOCOL_ERROR;
goto done;
}
/* Catenate the message part(s) to stage */
size = 0;
r = append_catenate(curstage->f, cur_name, &size,
&(curstage->binary), &parseerr, &url);
if (r) goto done;
}
else {
/* Read size from literal */
r = getliteralsize(arg.s, c, &size, &(curstage->binary), &parseerr);
if (!r && size == 0) r = IMAP_ZERO_LENGTH_LITERAL;
if (r) goto done;
/* Copy message to stage */
r = message_copy_strict(imapd_in, curstage->f, size, curstage->binary);
}
qdiffs[QUOTA_STORAGE] += size;
/* If this is a non-BINARY message, close the stage file.
* Otherwise, leave it open so we can encode the binary parts.
*
* XXX For BINARY MULTIAPPEND, we may have to close the stage files
* anyways to avoid too many open files.
*/
if (!curstage->binary) {
fclose(curstage->f);
curstage->f = NULL;
}
/* if we see a SP, we're trying to append more than one message */
/* Parse newline terminating command */
c = prot_getc(imapd_in);
}
done:
if (r) {
eatline(imapd_in, c);
} else {
/* we should be looking at the end of the line */
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
parseerr = "junk after literal";
r = IMAP_PROTOCOL_ERROR;
eatline(imapd_in, c);
}
}
/* Append from the stage(s) */
if (!r) {
qdiffs[QUOTA_MESSAGE] = stages.count;
r = append_setup(&appendstate, intname,
imapd_userid, imapd_authstate, ACL_INSERT,
ignorequota ? NULL : qdiffs, &imapd_namespace,
(imapd_userisadmin || imapd_userisproxyadmin),
EVENT_MESSAGE_APPEND);
}
if (!r) {
struct body *body;
doappenduid = (appendstate.myrights & ACL_READ);
uidvalidity = append_uidvalidity(&appendstate);
for (i = 0; !r && i < stages.count ; i++) {
curstage = stages.data[i];
body = NULL;
if (curstage->binary) {
r = message_parse_binary_file(curstage->f, &body);
fclose(curstage->f);
curstage->f = NULL;
}
if (!r) {
r = append_fromstage(&appendstate, &body, curstage->stage,
curstage->internaldate,
&curstage->flags, 0,
curstage->annotations);
}
if (body) {
/* Note: either the calls to message_parse_binary_file()
* or append_fromstage() above, may create a body. */
message_free_body(body);
free(body);
body = NULL;
}
}
if (!r) {
r = append_commit(&appendstate);
} else {
append_abort(&appendstate);
}
}
imapd_check(NULL, 1);
if (r == IMAP_PROTOCOL_ERROR && parseerr) {
prot_printf(imapd_out, "%s BAD %s\r\n", tag, parseerr);
} else if (r == IMAP_BADURL) {
prot_printf(imapd_out, "%s NO [BADURL \"%s\"] %s\r\n",
tag, url, parseerr);
} else if (r) {
prot_printf(imapd_out, "%s NO %s%s\r\n",
tag,
(r == IMAP_MAILBOX_NONEXISTENT &&
mboxlist_createmailboxcheck(intname, 0, 0,
imapd_userisadmin,
imapd_userid, imapd_authstate,
NULL, NULL, 0) == 0)
? "[TRYCREATE] " : r == IMAP_MESSAGE_TOO_LARGE
? "[TOOBIG]" : "", error_message(r));
} else if (doappenduid) {
/* is this a space seperated list or sequence list? */
prot_printf(imapd_out, "%s OK [APPENDUID %lu ", tag, uidvalidity);
if (appendstate.nummsg == 1) {
prot_printf(imapd_out, "%u", appendstate.baseuid);
} else {
prot_printf(imapd_out, "%u:%u", appendstate.baseuid,
appendstate.baseuid + appendstate.nummsg - 1);
}
prot_printf(imapd_out, "] %s\r\n", error_message(IMAP_OK_COMPLETED));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
cleanup:
/* Cleanup the stage(s) */
while ((curstage = ptrarray_pop(&stages))) {
if (curstage->f != NULL) fclose(curstage->f);
append_removestage(curstage->stage);
strarray_fini(&curstage->flags);
freeentryatts(curstage->annotations);
free(curstage);
}
free(intname);
ptrarray_fini(&stages);
}
/*
* Warn if mailbox is close to or over any quota resource.
*
* Warn if the following possibilities occur:
* - quotawarnkb not set + quotawarn hit
* - quotawarnkb set larger than mailbox + quotawarn hit
* - quotawarnkb set + hit + quotawarn hit
* - quotawarnmsg not set + quotawarn hit
* - quotawarnmsg set larger than mailbox + quotawarn hit
* - quotawarnmsg set + hit + quotawarn hit
*/
static void warn_about_quota(const char *quotaroot)
{
time_t now = time(NULL);
struct quota q;
int res;
int r;
int thresholds[QUOTA_NUMRESOURCES];
int pc_threshold = config_getint(IMAPOPT_QUOTAWARN);
int pc_usage;
struct buf msg = BUF_INITIALIZER;
static char lastqr[MAX_MAILBOX_PATH+1] = "";
static time_t nextalert = 0;
if (!quotaroot || !*quotaroot)
return; /* no quota, nothing to do */
/* rate limit checks and warnings to every 10 min */
if (!strcmp(quotaroot, lastqr) && now < nextalert)
return;
strlcpy(lastqr, quotaroot, sizeof(lastqr));
nextalert = now + 600;
quota_init(&q, quotaroot);
r = quota_read(&q, NULL, 0);
if (r)
goto out; /* failed to read */
memset(thresholds, 0, sizeof(thresholds));
thresholds[QUOTA_STORAGE] = config_getint(IMAPOPT_QUOTAWARNKB);
thresholds[QUOTA_MESSAGE] = config_getint(IMAPOPT_QUOTAWARNMSG);
thresholds[QUOTA_ANNOTSTORAGE] = config_getint(IMAPOPT_QUOTAWARNKB);
for (res = 0 ; res < QUOTA_NUMRESOURCES ; res++) {
if (q.limits[res] < 0)
continue; /* this resource is unlimited */
buf_reset(&msg);
if (thresholds[res] <= 0 ||
thresholds[res] >= q.limits[res] ||
q.useds[res] > ((quota_t) (q.limits[res] - thresholds[res])) * quota_units[res]) {
pc_usage = (int)(((double) q.useds[res] * 100.0) /
(double) ((quota_t) q.limits[res] * quota_units[res]));
if (q.useds[res] > (quota_t) q.limits[res] * quota_units[res])
buf_printf(&msg, error_message(IMAP_NO_OVERQUOTA),
quota_names[res]);
else if (pc_usage > pc_threshold)
buf_printf(&msg, error_message(IMAP_NO_CLOSEQUOTA),
pc_usage, quota_names[res]);
}
if (msg.len)
prot_printf(imapd_out, "* NO [ALERT] %s\r\n", buf_cstring(&msg));
}
buf_reset(&msg);
out:
quota_free(&q);
}
/*
* Perform a SELECT/EXAMINE/BBOARD command
*/
static void cmd_select(char *tag, char *cmd, char *name)
{
int c;
int r = 0;
int doclose = 0;
mbentry_t *mbentry = NULL;
struct backend *backend_next = NULL;
struct index_init init;
int wasopen = 0;
struct vanished_params *v = &init.vanished;
memset(&init, 0, sizeof(struct index_init));
c = prot_getc(imapd_in);
if (c == ' ') {
static struct buf arg, parm1, parm2;
c = prot_getc(imapd_in);
if (c != '(') goto badlist;
c = getword(imapd_in, &arg);
if (arg.s[0] == '\0') goto badlist;
for (;;) {
ucase(arg.s);
if (!strcmp(arg.s, "CONDSTORE")) {
client_capa |= CAPA_CONDSTORE;
}
else if ((client_capa & CAPA_QRESYNC) &&
!strcmp(arg.s, "QRESYNC")) {
char *p;
if (c != ' ') goto badqresync;
c = prot_getc(imapd_in);
if (c != '(') goto badqresync;
c = getastring(imapd_in, imapd_out, &arg);
v->uidvalidity = strtoul(arg.s, &p, 10);
if (*p || !v->uidvalidity || v->uidvalidity == ULONG_MAX) goto badqresync;
if (c != ' ') goto badqresync;
c = getmodseq(imapd_in, &v->modseq);
if (c == EOF) goto badqresync;
if (c == ' ') {
c = prot_getc(imapd_in);
if (c != '(') {
/* optional UID sequence */
prot_ungetc(c, imapd_in);
c = getword(imapd_in, &arg);
if (!imparse_issequence(arg.s)) goto badqresync;
v->sequence = arg.s;
if (c == ' ') {
c = prot_getc(imapd_in);
if (c != '(') goto badqresync;
}
}
if (c == '(') {
/* optional sequence match data */
c = getword(imapd_in, &parm1);
if (!imparse_issequence(parm1.s)) goto badqresync;
v->match_seq = parm1.s;
if (c != ' ') goto badqresync;
c = getword(imapd_in, &parm2);
if (!imparse_issequence(parm2.s)) goto badqresync;
v->match_uid = parm2.s;
if (c != ')') goto badqresync;
c = prot_getc(imapd_in);
}
}
if (c != ')') goto badqresync;
c = prot_getc(imapd_in);
}
else if (!strcmp(arg.s, "ANNOTATE")) {
/*
* RFC5257 requires us to parse this keyword, which
* indicates that the client wants unsolicited
* ANNOTATION responses in this session, but we don't
* actually have to do anything with it, so we won't.
*/
;
}
else {
prot_printf(imapd_out, "%s BAD Invalid %s modifier %s\r\n",
tag, cmd, arg.s);
eatline(imapd_in, c);
return;
}
if (c == ' ') c = getword(imapd_in, &arg);
else break;
}
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close parenthesis in %s\r\n", tag, cmd);
eatline(imapd_in, c);
return;
}
c = prot_getc(imapd_in);
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to %s\r\n", tag, cmd);
eatline(imapd_in, c);
return;
}
if (imapd_index) {
index_close(&imapd_index);
wasopen = 1;
}
if (backend_current) {
/* remove backend_current from the protgroup */
protgroup_delete(protin, backend_current->in);
wasopen = 1;
}
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(tag, name, intname, &mbentry);
if (r == IMAP_MAILBOX_MOVED) {
free(intname);
return;
}
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
char mytag[128];
if (supports_referrals) {
imapd_refer(tag, mbentry->server, name);
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
backend_next = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox,
imapd_in);
if (!backend_next) r = IMAP_SERVER_UNAVAILABLE;
if (backend_current && backend_current != backend_next) {
/* switching servers; flush old server output */
proxy_gentag(mytag, sizeof(mytag));
prot_printf(backend_current->out, "%s Unselect\r\n", mytag);
/* do not fatal() here, because we don't really care about this
* server anymore anyway */
pipe_until_tag(backend_current, mytag, 1);
}
backend_current = backend_next;
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
if (client_capa) {
/* Enable client capabilities on new backend */
proxy_gentag(mytag, sizeof(mytag));
prot_printf(backend_current->out, "%s Enable", mytag);
if (client_capa & CAPA_QRESYNC)
prot_printf(backend_current->out, " Qresync");
else if (client_capa & CAPA_CONDSTORE)
prot_printf(backend_current->out, " Condstore");
prot_printf(backend_current->out, "\r\n");
pipe_until_tag(backend_current, mytag, 0);
}
/* Send SELECT command to backend */
prot_printf(backend_current->out, "%s %s {" SIZE_T_FMT "+}\r\n%s",
tag, cmd, strlen(name), name);
if (v->uidvalidity) {
prot_printf(backend_current->out, " (QRESYNC (%lu " MODSEQ_FMT,
v->uidvalidity, v->modseq);
if (v->sequence) {
prot_printf(backend_current->out, " %s", v->sequence);
}
if (v->match_seq && v->match_uid) {
prot_printf(backend_current->out, " (%s %s)",
v->match_seq, v->match_uid);
}
prot_printf(backend_current->out, "))");
}
prot_printf(backend_current->out, "\r\n");
switch (pipe_including_tag(backend_current, tag, 0)) {
case PROXY_OK:
syslog(LOG_DEBUG, "open: user %s opened %s on %s",
imapd_userid, name, mbentry->server);
/* add backend_current to the protgroup */
protgroup_insert(protin, backend_current->in);
break;
default:
syslog(LOG_DEBUG, "open: user %s failed to open %s", imapd_userid,
name);
/* not successfully selected */
backend_current = NULL;
break;
}
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
mboxlist_entry_free(&mbentry);
/* local mailbox */
if (backend_current) {
char mytag[128];
/* switching servers; flush old server output */
proxy_gentag(mytag, sizeof(mytag));
prot_printf(backend_current->out, "%s Unselect\r\n", mytag);
/* do not fatal() here, because we don't really care about this
* server anymore anyway */
pipe_until_tag(backend_current, mytag, 1);
}
backend_current = NULL;
if (wasopen) prot_printf(imapd_out, "* OK [CLOSED] Ok\r\n");
init.userid = imapd_userid;
init.authstate = imapd_authstate;
init.out = imapd_out;
init.examine_mode = cmd[0] == 'E';
init.select = 1;
if (!strcasecmpsafe(imapd_magicplus, "+dav")) init.want_dav = 1;
r = index_open(intname, &init, &imapd_index);
if (!r) doclose = 1;
if (!r && !index_hasrights(imapd_index, ACL_READ)) {
r = (imapd_userisadmin || index_hasrights(imapd_index, ACL_LOOKUP)) ?
IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT;
}
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
if (init.vanishedlist) seqset_free(init.vanishedlist);
init.vanishedlist = NULL;
if (doclose) index_close(&imapd_index);
free(intname);
return;
}
if (index_hasrights(imapd_index, ACL_EXPUNGE))
warn_about_quota(imapd_index->mailbox->quotaroot);
index_select(imapd_index, &init);
if (init.vanishedlist) seqset_free(init.vanishedlist);
init.vanishedlist = NULL;
prot_printf(imapd_out, "%s OK [READ-%s] %s\r\n", tag,
index_hasrights(imapd_index, ACL_READ_WRITE) ?
"WRITE" : "ONLY", error_message(IMAP_OK_COMPLETED));
syslog(LOG_DEBUG, "open: user %s opened %s", imapd_userid, name);
free(intname);
return;
badlist:
prot_printf(imapd_out, "%s BAD Invalid modifier list in %s\r\n", tag, cmd);
eatline(imapd_in, c);
return;
badqresync:
prot_printf(imapd_out, "%s BAD Invalid QRESYNC parameter list in %s\r\n",
tag, cmd);
eatline(imapd_in, c);
return;
}
/*
* Perform a CLOSE/UNSELECT command
*/
static void cmd_close(char *tag, char *cmd)
{
if (backend_current) {
/* remote mailbox */
prot_printf(backend_current->out, "%s %s\r\n", tag, cmd);
/* xxx do we want this to say OK if the connection is gone?
* saying NO is clearly wrong, hense the fatal request. */
pipe_including_tag(backend_current, tag, 0);
/* remove backend_current from the protgroup */
protgroup_delete(protin, backend_current->in);
backend_current = NULL;
return;
}
/* local mailbox */
if ((cmd[0] == 'C') && index_hasrights(imapd_index, ACL_EXPUNGE)) {
index_expunge(imapd_index, NULL, 1);
/* don't tell changes here */
}
index_close(&imapd_index);
/* http://www.rfc-editor.org/errata_search.php?rfc=5162
* Errata ID: 1808 - don't send HIGHESTMODSEQ to a close
* command, because it can lose synchronisation */
prot_printf(imapd_out, "%s OK %s\r\n",
tag, error_message(IMAP_OK_COMPLETED));
}
/*
* Append to the section list.
*/
static void section_list_append(struct section **l,
const char *name,
const struct octetinfo *oi)
{
struct section **tail = l;
while (*tail) tail = &(*tail)->next;
*tail = xzmalloc(sizeof(struct section));
(*tail)->name = xstrdup(name);
(*tail)->octetinfo = *oi;
(*tail)->next = NULL;
}
static void section_list_free(struct section *l)
{
struct section *n;
while (l) {
n = l->next;
free(l->name);
free(l);
l = n;
}
}
/*
* Parse the syntax for a partial fetch:
* "<" number "." nz-number ">"
*/
#define PARSE_PARTIAL(start_octet, octet_count) \
(start_octet) = (octet_count) = 0; \
if (*p == '<' && Uisdigit(p[1])) { \
(start_octet) = p[1] - '0'; \
p += 2; \
while (Uisdigit((int) *p)) { \
(start_octet) = \
(start_octet) * 10 + *p++ - '0'; \
} \
\
if (*p == '.' && p[1] >= '1' && p[1] <= '9') { \
(octet_count) = p[1] - '0'; \
p[0] = '>'; p[1] = '\0'; /* clip off the octet count \
(its not used in the reply) */ \
p += 2; \
while (Uisdigit(*p)) { \
(octet_count) = \
(octet_count) * 10 + *p++ - '0'; \
} \
} \
else p--; \
\
if (*p != '>') { \
prot_printf(imapd_out, \
"%s BAD Invalid body partial\r\n", tag); \
eatline(imapd_in, c); \
goto freeargs; \
} \
p++; \
}
static int parse_fetch_args(const char *tag, const char *cmd,
int allow_vanished,
struct fetchargs *fa)
{
static struct buf fetchatt, fieldname;
int c;
int inlist = 0;
char *p, *section;
struct octetinfo oi;
strarray_t *newfields = strarray_new();
c = getword(imapd_in, &fetchatt);
if (c == '(' && !fetchatt.s[0]) {
inlist = 1;
c = getword(imapd_in, &fetchatt);
}
for (;;) {
ucase(fetchatt.s);
switch (fetchatt.s[0]) {
case 'A':
if (!inlist && !strcmp(fetchatt.s, "ALL")) {
fa->fetchitems |= FETCH_ALL;
}
else if (!strcmp(fetchatt.s, "ANNOTATION")) {
fa->fetchitems |= FETCH_ANNOTATION;
if (c != ' ')
goto badannotation;
c = prot_getc(imapd_in);
if (c != '(')
goto badannotation;
c = parse_annotate_fetch_data(tag,
/*permessage_flag*/1,
&fa->entries,
&fa->attribs);
if (c == EOF) {
eatline(imapd_in, c);
goto freeargs;
}
if (c != ')') {
badannotation:
prot_printf(imapd_out, "%s BAD invalid Annotation\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
c = prot_getc(imapd_in);
}
else goto badatt;
break;
case 'B':
if (!strncmp(fetchatt.s, "BINARY[", 7) ||
!strncmp(fetchatt.s, "BINARY.PEEK[", 12) ||
!strncmp(fetchatt.s, "BINARY.SIZE[", 12)) {
int binsize = 0;
p = section = fetchatt.s + 7;
if (!strncmp(p, "PEEK[", 5)) {
p = section += 5;
}
else if (!strncmp(p, "SIZE[", 5)) {
p = section += 5;
binsize = 1;
}
else {
fa->fetchitems |= FETCH_SETSEEN;
}
while (Uisdigit(*p) || *p == '.') {
if (*p == '.' && !Uisdigit(p[-1])) break;
/* Part number cannot begin with '0' */
if (*p == '0' && !Uisdigit(p[-1])) break;
p++;
}
if (*p != ']') {
prot_printf(imapd_out, "%s BAD Invalid binary section\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
p++;
if (!binsize) PARSE_PARTIAL(oi.start_octet, oi.octet_count);
if (*p) {
prot_printf(imapd_out, "%s BAD Junk after binary section\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
if (binsize)
section_list_append(&fa->sizesections, section, &oi);
else
section_list_append(&fa->binsections, section, &oi);
}
else if (!strcmp(fetchatt.s, "BODY")) {
fa->fetchitems |= FETCH_BODY;
}
else if (!strcmp(fetchatt.s, "BODYSTRUCTURE")) {
fa->fetchitems |= FETCH_BODYSTRUCTURE;
}
else if (!strncmp(fetchatt.s, "BODY[", 5) ||
!strncmp(fetchatt.s, "BODY.PEEK[", 10)) {
p = section = fetchatt.s + 5;
if (!strncmp(p, "PEEK[", 5)) {
p = section += 5;
}
else {
fa->fetchitems |= FETCH_SETSEEN;
}
while (Uisdigit(*p) || *p == '.') {
if (*p == '.' && !Uisdigit(p[-1])) break;
/* Obsolete section 0 can only occur before close brace */
if (*p == '0' && !Uisdigit(p[-1]) && p[1] != ']') break;
p++;
}
if (*p == 'H' && !strncmp(p, "HEADER.FIELDS", 13) &&
(p == section || p[-1] == '.') &&
(p[13] == '\0' || !strcmp(p+13, ".NOT"))) {
/*
* If not top-level or a HEADER.FIELDS.NOT, can't pull
* the headers out of the cache.
*/
if (p != section || p[13] != '\0') {
fa->cache_atleast = BIT32_MAX;
}
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing required argument to %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
c = prot_getc(imapd_in);
if (c != '(') {
prot_printf(imapd_out, "%s BAD Missing required open parenthesis in %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
do {
c = getastring(imapd_in, imapd_out, &fieldname);
for (p = fieldname.s; *p; p++) {
if (*p <= ' ' || *p & 0x80 || *p == ':') break;
}
if (*p || !*fieldname.s) {
prot_printf(imapd_out, "%s BAD Invalid field-name in %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
strarray_append(newfields, fieldname.s);
if (fa->cache_atleast < BIT32_MAX) {
bit32 this_ver =
mailbox_cached_header(fieldname.s);
if(this_ver > fa->cache_atleast)
fa->cache_atleast = this_ver;
}
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out, "%s BAD Missing required close parenthesis in %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
/* Grab/parse the ]<x.y> part */
c = getword(imapd_in, &fieldname);
p = fieldname.s;
if (*p++ != ']') {
prot_printf(imapd_out, "%s BAD Missing required close bracket after %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
PARSE_PARTIAL(oi.start_octet, oi.octet_count);
if (*p) {
prot_printf(imapd_out, "%s BAD Junk after body section\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
appendfieldlist(&fa->fsections,
section, newfields, fieldname.s,
&oi, sizeof(oi));
/* old 'newfields' is managed by the fieldlist now */
newfields = strarray_new();
break;
}
switch (*p) {
case 'H':
if (p != section && p[-1] != '.') break;
if (!strncmp(p, "HEADER]", 7)) p += 6;
break;
case 'M':
if (!strncmp(p-1, ".MIME]", 6)) p += 4;
break;
case 'T':
if (p != section && p[-1] != '.') break;
if (!strncmp(p, "TEXT]", 5)) p += 4;
break;
}
if (*p != ']') {
prot_printf(imapd_out, "%s BAD Invalid body section\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
p++;
PARSE_PARTIAL(oi.start_octet, oi.octet_count);
if (*p) {
prot_printf(imapd_out, "%s BAD Junk after body section\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
section_list_append(&fa->bodysections, section, &oi);
}
else goto badatt;
break;
case 'C':
if (!strcmp(fetchatt.s, "CID") &&
config_getswitch(IMAPOPT_CONVERSATIONS)) {
fa->fetchitems |= FETCH_CID;
}
else goto badatt;
break;
case 'D':
if (!strcmp(fetchatt.s, "DIGEST.SHA1")) {
fa->fetchitems |= FETCH_GUID;
}
else goto badatt;
break;
case 'E':
if (!strcmp(fetchatt.s, "ENVELOPE")) {
fa->fetchitems |= FETCH_ENVELOPE;
}
else goto badatt;
break;
case 'F':
if (!inlist && !strcmp(fetchatt.s, "FAST")) {
fa->fetchitems |= FETCH_FAST;
}
else if (!inlist && !strcmp(fetchatt.s, "FULL")) {
fa->fetchitems |= FETCH_FULL;
}
else if (!strcmp(fetchatt.s, "FLAGS")) {
fa->fetchitems |= FETCH_FLAGS;
}
else if (!strcmp(fetchatt.s, "FOLDER")) {
fa->fetchitems |= FETCH_FOLDER;
}
else goto badatt;
break;
case 'I':
if (!strcmp(fetchatt.s, "INTERNALDATE")) {
fa->fetchitems |= FETCH_INTERNALDATE;
}
else goto badatt;
break;
case 'M':
if (!strcmp(fetchatt.s, "MODSEQ")) {
fa->fetchitems |= FETCH_MODSEQ;
}
else goto badatt;
break;
case 'R':
if (!strcmp(fetchatt.s, "RFC822")) {
fa->fetchitems |= FETCH_RFC822|FETCH_SETSEEN;
}
else if (!strcmp(fetchatt.s, "RFC822.HEADER")) {
fa->fetchitems |= FETCH_HEADER;
}
else if (!strcmp(fetchatt.s, "RFC822.PEEK")) {
fa->fetchitems |= FETCH_RFC822;
}
else if (!strcmp(fetchatt.s, "RFC822.SIZE")) {
fa->fetchitems |= FETCH_SIZE;
}
else if (!strcmp(fetchatt.s, "RFC822.TEXT")) {
fa->fetchitems |= FETCH_TEXT|FETCH_SETSEEN;
}
else if (!strcmp(fetchatt.s, "RFC822.SHA1")) {
fa->fetchitems |= FETCH_SHA1;
}
else if (!strcmp(fetchatt.s, "RFC822.FILESIZE")) {
fa->fetchitems |= FETCH_FILESIZE;
}
else if (!strcmp(fetchatt.s, "RFC822.TEXT.PEEK")) {
fa->fetchitems |= FETCH_TEXT;
}
else if (!strcmp(fetchatt.s, "RFC822.HEADER.LINES") ||
!strcmp(fetchatt.s, "RFC822.HEADER.LINES.NOT")) {
if (c != ' ') {
prot_printf(imapd_out, "%s BAD Missing required argument to %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
c = prot_getc(imapd_in);
if (c != '(') {
prot_printf(imapd_out, "%s BAD Missing required open parenthesis in %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
do {
c = getastring(imapd_in, imapd_out, &fieldname);
for (p = fieldname.s; *p; p++) {
if (*p <= ' ' || *p & 0x80 || *p == ':') break;
}
if (*p || !*fieldname.s) {
prot_printf(imapd_out, "%s BAD Invalid field-name in %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
lcase(fieldname.s);;
/* 19 is magic number -- length of
* "RFC822.HEADERS.NOT" */
strarray_append(strlen(fetchatt.s) == 19 ?
&fa->headers : &fa->headers_not,
fieldname.s);
if (strlen(fetchatt.s) != 19) {
fa->cache_atleast = BIT32_MAX;
}
if (fa->cache_atleast < BIT32_MAX) {
bit32 this_ver =
mailbox_cached_header(fieldname.s);
if(this_ver > fa->cache_atleast)
fa->cache_atleast = this_ver;
}
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out, "%s BAD Missing required close parenthesis in %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
c = prot_getc(imapd_in);
}
else goto badatt;
break;
case 'U':
if (!strcmp(fetchatt.s, "UID")) {
fa->fetchitems |= FETCH_UID;
}
else if (!strcmp(fetchatt.s, "UIDVALIDITY")) {
fa->fetchitems |= FETCH_UIDVALIDITY;
}
else goto badatt;
break;
default:
badatt:
prot_printf(imapd_out, "%s BAD Invalid %s attribute %s\r\n", tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
if (inlist && c == ' ') c = getword(imapd_in, &fetchatt);
else break;
}
if (inlist && c == ')') {
inlist = 0;
c = prot_getc(imapd_in);
}
if (inlist) {
prot_printf(imapd_out, "%s BAD Missing close parenthesis in %s\r\n",
tag, cmd);
eatline(imapd_in, c);
goto freeargs;
}
if (c == ' ') {
/* Grab/parse the modifier(s) */
c = prot_getc(imapd_in);
if (c != '(') {
prot_printf(imapd_out,
"%s BAD Missing required open parenthesis in %s modifiers\r\n",
tag, cmd);
eatline(imapd_in, c);
goto freeargs;
}
do {
c = getword(imapd_in, &fetchatt);
ucase(fetchatt.s);
if (!strcmp(fetchatt.s, "CHANGEDSINCE")) {
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing required argument to %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
c = getmodseq(imapd_in, &fa->changedsince);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Invalid argument to %s %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
fa->fetchitems |= FETCH_MODSEQ;
}
else if (allow_vanished &&
!strcmp(fetchatt.s, "VANISHED")) {
fa->vanished = 1;
}
else {
prot_printf(imapd_out, "%s BAD Invalid %s modifier %s\r\n",
tag, cmd, fetchatt.s);
eatline(imapd_in, c);
goto freeargs;
}
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out, "%s BAD Missing close parenthesis in %s\r\n",
tag, cmd);
eatline(imapd_in, c);
goto freeargs;
}
c = prot_getc(imapd_in);
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out, "%s BAD Unexpected extra arguments to %s\r\n", tag, cmd);
eatline(imapd_in, c);
goto freeargs;
}
if (!fa->fetchitems && !fa->bodysections && !fa->fsections &&
!fa->binsections && !fa->sizesections &&
!fa->headers.count && !fa->headers_not.count) {
prot_printf(imapd_out, "%s BAD Missing required argument to %s\r\n", tag, cmd);
goto freeargs;
}
if (fa->vanished && !fa->changedsince) {
prot_printf(imapd_out, "%s BAD Missing required argument to %s\r\n", tag, cmd);
goto freeargs;
}
if (fa->fetchitems & FETCH_MODSEQ) {
if (!(client_capa & CAPA_CONDSTORE)) {
client_capa |= CAPA_CONDSTORE;
if (imapd_index)
prot_printf(imapd_out, "* OK [HIGHESTMODSEQ " MODSEQ_FMT "] \r\n",
index_highestmodseq(imapd_index));
}
}
if (fa->fetchitems & (FETCH_ANNOTATION|FETCH_FOLDER)) {
fa->namespace = &imapd_namespace;
fa->userid = imapd_userid;
}
if (fa->fetchitems & FETCH_ANNOTATION) {
fa->isadmin = imapd_userisadmin || imapd_userisproxyadmin;
fa->authstate = imapd_authstate;
}
strarray_free(newfields);
return 0;
freeargs:
strarray_free(newfields);
return IMAP_PROTOCOL_BAD_PARAMETERS;
}
static void fetchargs_fini (struct fetchargs *fa)
{
section_list_free(fa->binsections);
section_list_free(fa->sizesections);
section_list_free(fa->bodysections);
freefieldlist(fa->fsections);
strarray_fini(&fa->headers);
strarray_fini(&fa->headers_not);
strarray_fini(&fa->entries);
strarray_fini(&fa->attribs);
memset(fa, 0, sizeof(struct fetchargs));
}
/*
* Parse and perform a FETCH/UID FETCH command
* The command has been parsed up to and including
* the sequence
*/
static void cmd_fetch(char *tag, char *sequence, int usinguid)
{
const char *cmd = usinguid ? "UID Fetch" : "Fetch";
struct fetchargs fetchargs;
int fetchedsomething, r;
clock_t start = clock();
char mytime[100];
if (backend_current) {
/* remote mailbox */
prot_printf(backend_current->out, "%s %s %s ", tag, cmd, sequence);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
/* local mailbox */
memset(&fetchargs, 0, sizeof(struct fetchargs));
r = parse_fetch_args(tag, cmd,
(usinguid && (client_capa & CAPA_QRESYNC)),
&fetchargs);
if (r)
goto freeargs;
if (usinguid)
fetchargs.fetchitems |= FETCH_UID;
r = index_fetch(imapd_index, sequence, usinguid, &fetchargs,
&fetchedsomething);
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
if (r) {
prot_printf(imapd_out, "%s NO %s (%s sec)\r\n", tag,
error_message(r), mytime);
} else if (fetchedsomething || usinguid) {
prot_printf(imapd_out, "%s OK %s (%s sec)\r\n", tag,
error_message(IMAP_OK_COMPLETED), mytime);
} else {
/* normal FETCH, nothing came back */
prot_printf(imapd_out, "%s NO %s (%s sec)\r\n", tag,
error_message(IMAP_NO_NOSUCHMSG), mytime);
}
freeargs:
fetchargs_fini(&fetchargs);
}
static void do_one_xconvmeta(struct conversations_state *state,
conversation_id_t cid,
conversation_t *conv,
struct dlist *itemlist)
{
struct dlist *item = dlist_newpklist(NULL, "");
struct dlist *fl;
assert(conv);
assert(itemlist);
for (fl = itemlist->head; fl; fl = fl->next) {
const char *key = dlist_cstring(fl);
/* xxx - parse to a fetchitems? */
if (!strcasecmp(key, "MODSEQ"))
dlist_setnum64(item, "MODSEQ", conv->modseq);
else if (!strcasecmp(key, "EXISTS"))
dlist_setnum32(item, "EXISTS", conv->exists);
else if (!strcasecmp(key, "UNSEEN"))
dlist_setnum32(item, "UNSEEN", conv->unseen);
else if (!strcasecmp(key, "SIZE"))
dlist_setnum32(item, "SIZE", conv->size);
else if (!strcasecmp(key, "COUNT")) {
struct dlist *flist = dlist_newlist(item, "COUNT");
fl = fl->next;
if (dlist_isatomlist(fl)) {
struct dlist *tmp;
for (tmp = fl->head; tmp; tmp = tmp->next) {
const char *lookup = dlist_cstring(tmp);
int i = strarray_find_case(state->counted_flags, lookup, 0);
if (i >= 0) {
dlist_setflag(flist, "FLAG", lookup);
dlist_setnum32(flist, "COUNT", conv->counts[i]);
}
}
}
}
else if (!strcasecmp(key, "SENDERS")) {
conv_sender_t *sender;
struct dlist *slist = dlist_newlist(item, "SENDERS");
for (sender = conv->senders; sender; sender = sender->next) {
struct dlist *sli = dlist_newlist(slist, "");
dlist_setatom(sli, "NAME", sender->name);
dlist_setatom(sli, "ROUTE", sender->route);
dlist_setatom(sli, "MAILBOX", sender->mailbox);
dlist_setatom(sli, "DOMAIN", sender->domain);
}
}
/* XXX - maybe rename FOLDERCOUNTS or something? */
else if (!strcasecmp(key, "FOLDEREXISTS")) {
struct dlist *flist = dlist_newlist(item, "FOLDEREXISTS");
conv_folder_t *folder;
fl = fl->next;
if (dlist_isatomlist(fl)) {
struct dlist *tmp;
for (tmp = fl->head; tmp; tmp = tmp->next) {
const char *extname = dlist_cstring(tmp);
char *intname = mboxname_from_external(extname, &imapd_namespace, imapd_userid);
folder = conversation_find_folder(state, conv, intname);
free(intname);
dlist_setatom(flist, "MBOXNAME", extname);
/* ok if it's not there */
dlist_setnum32(flist, "EXISTS", folder ? folder->exists : 0);
}
}
}
else if (!strcasecmp(key, "FOLDERUNSEEN")) {
struct dlist *flist = dlist_newlist(item, "FOLDERUNSEEN");
conv_folder_t *folder;
fl = fl->next;
if (dlist_isatomlist(fl)) {
struct dlist *tmp;
for (tmp = fl->head; tmp; tmp = tmp->next) {
const char *extname = dlist_cstring(tmp);
char *intname = mboxname_from_external(extname, &imapd_namespace, imapd_userid);
folder = conversation_find_folder(state, conv, intname);
free(intname);
dlist_setatom(flist, "MBOXNAME", extname);
/* ok if it's not there */
dlist_setnum32(flist, "UNSEEN", folder ? folder->unseen : 0);
}
}
}
else {
dlist_setatom(item, key, NULL); /* add a NIL response */
}
}
prot_printf(imapd_out, "* XCONVMETA %s ", conversation_id_encode(cid));
dlist_print(item, 0, imapd_out);
prot_printf(imapd_out, "\r\n");
dlist_free(&item);
}
static void do_xconvmeta(const char *tag,
struct conversations_state *state,
struct dlist *cidlist,
struct dlist *itemlist)
{
conversation_id_t cid;
struct dlist *dl;
int r;
for (dl = cidlist->head; dl; dl = dl->next) {
const char *cidstr = dlist_cstring(dl);
conversation_t *conv = NULL;
if (!conversation_id_decode(&cid, cidstr) || !cid) {
prot_printf(imapd_out, "%s BAD Invalid CID %s\r\n", tag, cidstr);
return;
}
r = conversation_load(state, cid, &conv);
if (r) {
prot_printf(imapd_out, "%s BAD Failed to read %s\r\n", tag, cidstr);
conversation_free(conv);
return;
}
if (conv && conv->exists)
do_one_xconvmeta(state, cid, conv, itemlist);
conversation_free(conv);
}
prot_printf(imapd_out, "%s OK Completed\r\n", tag);
}
static int do_xbackup(const char *channel,
const ptrarray_t *list)
{
sasl_callback_t *cb = NULL;
struct backend *backend = NULL;
const char *hostname;
const char *port;
unsigned sync_flags = 0; // FIXME ??
int partial_success = 0;
int mbox_count = 0;
int i, r;
hostname = sync_get_config(channel, "sync_host");
if (!hostname) {
syslog(LOG_ERR, "XBACKUP: couldn't find hostname for channel '%s'", channel);
return IMAP_BAD_SERVER;
}
port = sync_get_config(channel, "sync_port");
if (port) csync_protocol.service = port;
cb = mysasl_callbacks(NULL,
sync_get_config(channel, "sync_authname"),
sync_get_config(channel, "sync_realm"),
sync_get_config(channel, "sync_password"));
syslog(LOG_INFO, "XBACKUP: connecting to server '%s' for channel '%s'",
hostname, channel);
backend = backend_connect(NULL, hostname, &csync_protocol, NULL, cb, NULL, -1);
if (!backend) {
syslog(LOG_ERR, "XBACKUP: failed to connect to server '%s' for channel '%s'",
hostname, channel);
return IMAP_SERVER_UNAVAILABLE;
}
free_callbacks(cb);
cb = NULL;
for (i = 0; i < list->count; i++) {
const mbname_t *mbname = ptrarray_nth(list, i);
if (!mbname) continue;
const char *userid = mbname_userid(mbname);
const char *intname = mbname_intname(mbname);
if (userid) {
syslog(LOG_INFO, "XBACKUP: replicating user %s", userid);
r = sync_do_user(userid, NULL, backend, /*channelp*/ NULL, sync_flags);
}
else {
struct sync_name_list *mboxname_list = sync_name_list_create();
syslog(LOG_INFO, "XBACKUP: replicating mailbox %s", intname);
sync_name_list_add(mboxname_list, intname);
r = sync_do_mailboxes(mboxname_list, NULL, backend,
/*channelp*/ NULL, sync_flags);
mbox_count++;
sync_name_list_free(&mboxname_list);
}
if (r) {
prot_printf(imapd_out, "* NO %s %s (%s)\r\n",
userid ? "USER" : "MAILBOX",
userid ? userid : intname,
error_message(r));
}
else {
partial_success++;
prot_printf(imapd_out, "* OK %s %s\r\n",
userid ? "USER" : "MAILBOX",
userid ? userid : intname);
}
prot_flush(imapd_out);
/* send RESTART after each user, or 1000 mailboxes */
if (!r && i < list->count - 1 && (userid || mbox_count >= 1000)) {
mbox_count = 0;
sync_send_restart(backend->out);
r = sync_parse_response("RESTART", backend->in, NULL);
if (r) goto done;
}
}
/* send a final RESTART */
sync_send_restart(backend->out);
sync_parse_response("RESTART", backend->in, NULL);
if (partial_success) r = 0;
done:
backend_disconnect(backend);
free(backend);
return r;
}
static int xbackup_addmbox(struct findall_data *data, void *rock)
{
if (!data) return 0;
ptrarray_t *list = (ptrarray_t *) rock;
if (!data->mbname) {
/* No partial matches */ /* FIXME ??? */
return 0;
}
/* Only add shared mailboxes or user INBOXes */
if (!mbname_localpart(data->mbname) ||
(!mbname_isdeleted(data->mbname) &&
!strarray_size(mbname_boxes(data->mbname)))) {
ptrarray_append(list, mbname_dup(data->mbname));
}
return 0;
}
/* Parse and perform an XBACKUP command. */
void cmd_xbackup(const char *tag,
const char *mailbox,
const char *channel)
{
ptrarray_t list = PTRARRAY_INITIALIZER;
int i, r;
/* admins only please */
if (!imapd_userisadmin && !imapd_userisproxyadmin) {
r = IMAP_PERMISSION_DENIED;
goto done;
}
if (!config_getswitch(IMAPOPT_XBACKUP_ENABLED)) {
/* shouldn't get here, but just in case */
r = IMAP_PERMISSION_DENIED;
goto done;
}
mboxlist_findall(NULL, mailbox, 1, NULL, NULL, xbackup_addmbox, &list);
if (list.count) {
r = do_xbackup(channel, &list);
for (i = 0; i < list.count; i++) {
mbname_t *mbname = ptrarray_nth(&list, i);
if (mbname)
mbname_free(&mbname);
}
ptrarray_fini(&list);
}
else {
r = IMAP_MAILBOX_NONEXISTENT;
}
done:
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
}
/*
* Parse and perform a XCONVMETA command.
*/
void cmd_xconvmeta(const char *tag)
{
int r;
int c = ' ';
struct conversations_state *state = NULL;
struct dlist *cidlist = NULL;
struct dlist *itemlist = NULL;
if (backend_current) {
/* remote mailbox */
prot_printf(backend_current->out, "%s XCONVMETA ", tag);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
if (!config_getswitch(IMAPOPT_CONVERSATIONS)) {
prot_printf(imapd_out, "%s BAD Unrecognized command\r\n", tag);
eatline(imapd_in, c);
goto done;
}
c = dlist_parse_asatomlist(&cidlist, 0, imapd_in);
if (c != ' ') {
prot_printf(imapd_out, "%s BAD Failed to parse CID list\r\n", tag);
eatline(imapd_in, c);
goto done;
}
c = dlist_parse_asatomlist(&itemlist, 0, imapd_in);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out, "%s BAD Failed to parse item list\r\n", tag);
eatline(imapd_in, c);
goto done;
}
r = conversations_open_user(imapd_userid, &state);
if (r) {
prot_printf(imapd_out, "%s BAD failed to open db: %s\r\n",
tag, error_message(r));
goto done;
}
do_xconvmeta(tag, state, cidlist, itemlist);
done:
dlist_free(&itemlist);
dlist_free(&cidlist);
conversations_commit(&state);
}
/*
* Parse and perform a XCONVFETCH command.
*/
void cmd_xconvfetch(const char *tag)
{
int c = ' ';
struct fetchargs fetchargs;
int r;
clock_t start = clock();
modseq_t ifchangedsince = 0;
char mytime[100];
struct dlist *cidlist = NULL;
struct dlist *item;
if (backend_current) {
/* remote mailbox */
prot_printf(backend_current->out, "%s XCONVFETCH ", tag);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
if (!config_getswitch(IMAPOPT_CONVERSATIONS)) {
prot_printf(imapd_out, "%s BAD Unrecognized command\r\n", tag);
eatline(imapd_in, c);
return;
}
/* local mailbox */
memset(&fetchargs, 0, sizeof(struct fetchargs));
c = dlist_parse_asatomlist(&cidlist, 0, imapd_in);
if (c != ' ')
goto syntax_error;
/* check CIDs */
for (item = cidlist->head; item; item = item->next) {
if (!dlist_ishex64(item)) {
prot_printf(imapd_out, "%s BAD Invalid CID\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
}
c = getmodseq(imapd_in, &ifchangedsince);
if (c != ' ')
goto syntax_error;
r = parse_fetch_args(tag, "Xconvfetch", 0, &fetchargs);
if (r)
goto freeargs;
fetchargs.fetchitems |= (FETCH_UIDVALIDITY|FETCH_FOLDER);
fetchargs.namespace = &imapd_namespace;
fetchargs.userid = imapd_userid;
r = do_xconvfetch(cidlist, ifchangedsince, &fetchargs);
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
if (r) {
prot_printf(imapd_out, "%s NO %s (%s sec)\r\n", tag,
error_message(r), mytime);
} else {
prot_printf(imapd_out, "%s OK Completed (%s sec)\r\n",
tag, mytime);
}
freeargs:
dlist_free(&cidlist);
fetchargs_fini(&fetchargs);
return;
syntax_error:
prot_printf(imapd_out, "%s BAD Syntax error\r\n", tag);
eatline(imapd_in, c);
dlist_free(&cidlist);
fetchargs_fini(&fetchargs);
}
static int xconvfetch_lookup(struct conversations_state *statep,
conversation_id_t cid,
modseq_t ifchangedsince,
hash_table *wanted_cids,
strarray_t *folder_list)
{
const char *key = conversation_id_encode(cid);
conversation_t *conv = NULL;
conv_folder_t *folder;
int r;
r = conversation_load(statep, cid, &conv);
if (r) return r;
if (!conv)
goto out;
if (!conv->exists)
goto out;
/* output the metadata for this conversation */
{
struct dlist *dl = dlist_newlist(NULL, "");
dlist_setatom(dl, "", "MODSEQ");
do_one_xconvmeta(statep, cid, conv, dl);
dlist_free(&dl);
}
if (ifchangedsince >= conv->modseq)
goto out;
hash_insert(key, (void *)1, wanted_cids);
for (folder = conv->folders; folder; folder = folder->next) {
/* no contents */
if (!folder->exists)
continue;
/* finally, something worth looking at */
strarray_add(folder_list, strarray_nth(statep->folder_names, folder->number));
}
out:
conversation_free(conv);
return 0;
}
static int do_xconvfetch(struct dlist *cidlist,
modseq_t ifchangedsince,
struct fetchargs *fetchargs)
{
struct conversations_state *state = NULL;
int r = 0;
struct index_state *index_state = NULL;
struct dlist *dl;
hash_table wanted_cids = HASH_TABLE_INITIALIZER;
strarray_t folder_list = STRARRAY_INITIALIZER;
struct index_init init;
int i;
r = conversations_open_user(imapd_userid, &state);
if (r) goto out;
construct_hash_table(&wanted_cids, 1024, 0);
for (dl = cidlist->head; dl; dl = dl->next) {
r = xconvfetch_lookup(state, dlist_num(dl), ifchangedsince,
&wanted_cids, &folder_list);
if (r) goto out;
}
/* unchanged, woot */
if (!folder_list.count)
goto out;
fetchargs->cidhash = &wanted_cids;
memset(&init, 0, sizeof(struct index_init));
init.userid = imapd_userid;
init.authstate = imapd_authstate;
init.out = imapd_out;
for (i = 0; i < folder_list.count; i++) {
const char *mboxname = folder_list.data[i];
r = index_open(mboxname, &init, &index_state);
if (r == IMAP_MAILBOX_NONEXISTENT)
continue;
if (r)
goto out;
index_checkflags(index_state, 0, 0);
/* make sure \Deleted messages are expunged. Will also lock the
* mailbox state and read any new information */
r = index_expunge(index_state, NULL, 1);
if (!r)
index_fetchresponses(index_state, NULL, /*usinguid*/1,
fetchargs, NULL);
index_close(&index_state);
if (r) goto out;
}
r = 0;
out:
index_close(&index_state);
conversations_commit(&state);
free_hash_table(&wanted_cids, NULL);
strarray_fini(&folder_list);
return r;
}
#undef PARSE_PARTIAL /* cleanup */
/*
* Parse and perform a STORE/UID STORE command
* The command has been parsed up to and including
* the sequence
*/
static void cmd_store(char *tag, char *sequence, int usinguid)
{
const char *cmd = usinguid ? "UID Store" : "Store";
struct storeargs storeargs;
static struct buf operation, flagname;
int len, c;
int flagsparsed = 0, inlist = 0;
char *modified = NULL;
int r;
if (backend_current) {
/* remote mailbox */
prot_printf(backend_current->out, "%s %s %s ",
tag, cmd, sequence);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
/* local mailbox */
memset(&storeargs, 0, sizeof storeargs);
storeargs.unchangedsince = ~0ULL;
storeargs.usinguid = usinguid;
strarray_init(&storeargs.flags);
c = prot_getc(imapd_in);
if (c == '(') {
/* Grab/parse the modifier(s) */
static struct buf storemod;
do {
c = getword(imapd_in, &storemod);
ucase(storemod.s);
if (!strcmp(storemod.s, "UNCHANGEDSINCE")) {
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing required argument to %s %s\r\n",
tag, cmd, storemod.s);
eatline(imapd_in, c);
return;
}
c = getmodseq(imapd_in, &storeargs.unchangedsince);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Invalid argument to %s UNCHANGEDSINCE\r\n",
tag, cmd);
eatline(imapd_in, c);
return;
}
}
else {
prot_printf(imapd_out, "%s BAD Invalid %s modifier %s\r\n",
tag, cmd, storemod.s);
eatline(imapd_in, c);
return;
}
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close paren in store modifier entry \r\n",
tag);
eatline(imapd_in, c);
return;
}
c = prot_getc(imapd_in);
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing required argument to %s\r\n",
tag, cmd);
eatline(imapd_in, c);
return;
}
}
else
prot_ungetc(c, imapd_in);
c = getword(imapd_in, &operation);
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing required argument to %s\r\n", tag, cmd);
eatline(imapd_in, c);
return;
}
lcase(operation.s);
len = strlen(operation.s);
if (len > 7 && !strcmp(operation.s+len-7, ".silent")) {
storeargs.silent = 1;
operation.s[len-7] = '\0';
}
if (!strcmp(operation.s, "+flags")) {
storeargs.operation = STORE_ADD_FLAGS;
}
else if (!strcmp(operation.s, "-flags")) {
storeargs.operation = STORE_REMOVE_FLAGS;
}
else if (!strcmp(operation.s, "flags")) {
storeargs.operation = STORE_REPLACE_FLAGS;
}
else if (!strcmp(operation.s, "annotation")) {
storeargs.operation = STORE_ANNOTATION;
/* ANNOTATION has implicit .SILENT behaviour */
storeargs.silent = 1;
c = parse_annotate_store_data(tag, /*permessage_flag*/1,
&storeargs.entryatts);
if (c == EOF) {
eatline(imapd_in, c);
goto freeflags;
}
storeargs.namespace = &imapd_namespace;
storeargs.isadmin = imapd_userisadmin;
storeargs.userid = imapd_userid;
storeargs.authstate = imapd_authstate;
goto notflagsdammit;
}
else {
prot_printf(imapd_out, "%s BAD Invalid %s attribute\r\n", tag, cmd);
eatline(imapd_in, ' ');
return;
}
for (;;) {
c = getword(imapd_in, &flagname);
if (c == '(' && !flagname.s[0] && !flagsparsed && !inlist) {
inlist = 1;
continue;
}
if (!flagname.s[0]) break;
if (flagname.s[0] == '\\') {
lcase(flagname.s);
if (!strcmp(flagname.s, "\\seen")) {
storeargs.seen = 1;
}
else if (!strcmp(flagname.s, "\\answered")) {
storeargs.system_flags |= FLAG_ANSWERED;
}
else if (!strcmp(flagname.s, "\\flagged")) {
storeargs.system_flags |= FLAG_FLAGGED;
}
else if (!strcmp(flagname.s, "\\deleted")) {
storeargs.system_flags |= FLAG_DELETED;
}
else if (!strcmp(flagname.s, "\\draft")) {
storeargs.system_flags |= FLAG_DRAFT;
}
else {
prot_printf(imapd_out, "%s BAD Invalid system flag in %s command\r\n",
tag, cmd);
eatline(imapd_in, c);
goto freeflags;
}
}
else if (!imparse_isatom(flagname.s)) {
prot_printf(imapd_out, "%s BAD Invalid flag name %s in %s command\r\n",
tag, flagname.s, cmd);
eatline(imapd_in, c);
goto freeflags;
}
else
strarray_append(&storeargs.flags, flagname.s);
flagsparsed++;
if (c != ' ') break;
}
if (!inlist && !flagsparsed) {
prot_printf(imapd_out, "%s BAD Missing required argument to %s\r\n", tag, cmd);
eatline(imapd_in, c);
return;
}
if (inlist && c == ')') {
inlist = 0;
c = prot_getc(imapd_in);
}
if (inlist) {
prot_printf(imapd_out, "%s BAD Missing close parenthesis in %s\r\n", tag, cmd);
eatline(imapd_in, c);
goto freeflags;
}
notflagsdammit:
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out, "%s BAD Unexpected extra arguments to %s\r\n", tag, cmd);
eatline(imapd_in, c);
goto freeflags;
}
if ((storeargs.unchangedsince != ULONG_MAX) &&
!(client_capa & CAPA_CONDSTORE)) {
client_capa |= CAPA_CONDSTORE;
prot_printf(imapd_out, "* OK [HIGHESTMODSEQ " MODSEQ_FMT "] \r\n",
index_highestmodseq(imapd_index));
}
r = index_store(imapd_index, sequence, &storeargs);
/* format the MODIFIED response code */
if (storeargs.modified) {
char *seqstr = seqset_cstring(storeargs.modified);
assert(seqstr);
modified = strconcat("[MODIFIED ", seqstr, "] ", (char *)NULL);
free(seqstr);
}
else {
modified = xstrdup("");
}
if (r) {
prot_printf(imapd_out, "%s NO %s%s\r\n",
tag, modified, error_message(r));
}
else {
prot_printf(imapd_out, "%s OK %s%s\r\n",
tag, modified, error_message(IMAP_OK_COMPLETED));
}
freeflags:
strarray_fini(&storeargs.flags);
freeentryatts(storeargs.entryatts);
seqset_free(storeargs.modified);
free(modified);
}
static void cmd_search(char *tag, int usinguid)
{
int c;
struct searchargs *searchargs;
clock_t start = clock();
char mytime[100];
int n;
if (backend_current) {
/* remote mailbox */
const char *cmd = usinguid ? "UID Search" : "Search";
prot_printf(backend_current->out, "%s %s ", tag, cmd);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
/* local mailbox */
searchargs = new_searchargs(tag, GETSEARCH_CHARSET_KEYWORD|GETSEARCH_RETURN,
&imapd_namespace, imapd_userid, imapd_authstate,
imapd_userisadmin || imapd_userisproxyadmin);
/* special case quirk for iPhones */
if (imapd_id.quirks & QUIRK_SEARCHFUZZY)
searchargs->fuzzy_depth++;
c = get_search_program(imapd_in, imapd_out, searchargs);
if (c == EOF) {
eatline(imapd_in, ' ');
freesearchargs(searchargs);
return;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out, "%s BAD Unexpected extra arguments to Search\r\n", tag);
eatline(imapd_in, c);
freesearchargs(searchargs);
return;
}
if (searchargs->charset == CHARSET_UNKNOWN_CHARSET) {
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(IMAP_UNRECOGNIZED_CHARSET));
}
else {
n = index_search(imapd_index, searchargs, usinguid);
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
prot_printf(imapd_out, "%s OK %s (%d msgs in %s secs)\r\n", tag,
error_message(IMAP_OK_COMPLETED), n, mytime);
}
freesearchargs(searchargs);
}
/*
* Perform a SORT/UID SORT command
*/
static void cmd_sort(char *tag, int usinguid)
{
int c;
struct sortcrit *sortcrit = NULL;
struct searchargs *searchargs = NULL;
clock_t start = clock();
char mytime[100];
int n;
if (backend_current) {
/* remote mailbox */
const char *cmd = usinguid ? "UID Sort" : "Sort";
prot_printf(backend_current->out, "%s %s ", tag, cmd);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
/* local mailbox */
c = getsortcriteria(tag, &sortcrit);
if (c == EOF) goto error;
searchargs = new_searchargs(tag, GETSEARCH_CHARSET_FIRST,
&imapd_namespace, imapd_userid, imapd_authstate,
imapd_userisadmin || imapd_userisproxyadmin);
if (imapd_id.quirks & QUIRK_SEARCHFUZZY)
searchargs->fuzzy_depth++;
c = get_search_program(imapd_in, imapd_out, searchargs);
if (c == EOF) goto error;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Sort\r\n", tag);
goto error;
}
n = index_sort(imapd_index, sortcrit, searchargs, usinguid);
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
if (CONFIG_TIMING_VERBOSE) {
char *s = sortcrit_as_string(sortcrit);
syslog(LOG_DEBUG, "SORT (%s) processing time: %d msg in %s sec",
s, n, mytime);
free(s);
}
prot_printf(imapd_out, "%s OK %s (%d msgs in %s secs)\r\n", tag,
error_message(IMAP_OK_COMPLETED), n, mytime);
freesortcrit(sortcrit);
freesearchargs(searchargs);
return;
error:
eatline(imapd_in, (c == EOF ? ' ' : c));
freesortcrit(sortcrit);
freesearchargs(searchargs);
}
/*
* Perform a XCONVSORT or XCONVUPDATES command
*/
void cmd_xconvsort(char *tag, int updates)
{
int c;
struct sortcrit *sortcrit = NULL;
struct searchargs *searchargs = NULL;
struct windowargs *windowargs = NULL;
struct index_init init;
struct index_state *oldstate = NULL;
struct conversations_state *cstate = NULL;
clock_t start = clock();
char mytime[100];
int r;
if (backend_current) {
/* remote mailbox */
const char *cmd = "Xconvsort";
prot_printf(backend_current->out, "%s %s ", tag, cmd);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
assert(imapd_index);
if (!config_getswitch(IMAPOPT_CONVERSATIONS)) {
prot_printf(imapd_out, "%s BAD Unrecognized command\r\n", tag);
eatline(imapd_in, ' ');
return;
}
c = getsortcriteria(tag, &sortcrit);
if (c == EOF) goto error;
if (c != ' ') {
prot_printf(imapd_out, "%s BAD Missing window args in XConvSort\r\n",
tag);
goto error;
}
c = parse_windowargs(tag, &windowargs, updates);
if (c != ' ')
goto error;
/* open the conversations state first - we don't care if it fails,
* because that probably just means it's already open */
conversations_open_mbox(index_mboxname(imapd_index), &cstate);
if (updates) {
/* in XCONVUPDATES, need to force a re-read from scratch into
* a new index, because we ask for deleted messages */
oldstate = imapd_index;
imapd_index = NULL;
memset(&init, 0, sizeof(struct index_init));
init.userid = imapd_userid;
init.authstate = imapd_authstate;
init.out = imapd_out;
init.want_expunged = 1;
r = index_open(index_mboxname(oldstate), &init, &imapd_index);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(r));
goto error;
}
index_checkflags(imapd_index, 0, 0);
}
/* need index loaded to even parse searchargs! */
searchargs = new_searchargs(tag, GETSEARCH_CHARSET_FIRST,
&imapd_namespace, imapd_userid, imapd_authstate,
imapd_userisadmin || imapd_userisproxyadmin);
c = get_search_program(imapd_in, imapd_out, searchargs);
if (c == EOF) goto error;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Xconvsort\r\n", tag);
goto error;
}
if (updates)
r = index_convupdates(imapd_index, sortcrit, searchargs, windowargs);
else
r = index_convsort(imapd_index, sortcrit, searchargs, windowargs);
if (oldstate) {
index_close(&imapd_index);
imapd_index = oldstate;
}
if (r < 0) {
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(r));
goto error;
}
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
if (CONFIG_TIMING_VERBOSE) {
char *s = sortcrit_as_string(sortcrit);
syslog(LOG_DEBUG, "XCONVSORT (%s) processing time %s sec",
s, mytime);
free(s);
}
prot_printf(imapd_out, "%s OK %s (in %s secs)\r\n", tag,
error_message(IMAP_OK_COMPLETED), mytime);
out:
if (cstate) conversations_commit(&cstate);
freesortcrit(sortcrit);
freesearchargs(searchargs);
free_windowargs(windowargs);
return;
error:
if (cstate) conversations_commit(&cstate);
if (oldstate) {
if (imapd_index) index_close(&imapd_index);
imapd_index = oldstate;
}
eatline(imapd_in, (c == EOF ? ' ' : c));
goto out;
}
/*
* Perform a XCONVMULTISORT command. This is like XCONVSORT but returns
* search results from multiple folders. It still requires a selected
* mailbox, for two reasons:
*
* a) it's a useful shorthand for choosing what the current
* conversations scope is, and
*
* b) the code to parse a search program currently relies on a selected
* mailbox.
*
* Unlike ESEARCH it doesn't take folder names for scope, instead the
* search scope is implicitly the current conversation scope. This is
* implemented more or less by accident because both the Sphinx index
* and the conversations database are hardcoded to be per-user.
*/
static void cmd_xconvmultisort(char *tag)
{
int c;
struct sortcrit *sortcrit = NULL;
struct searchargs *searchargs = NULL;
struct windowargs *windowargs = NULL;
struct conversations_state *cstate = NULL;
clock_t start = clock();
char mytime[100];
int r;
if (backend_current) {
/* remote mailbox */
const char *cmd = "Xconvmultisort";
prot_printf(backend_current->out, "%s %s ", tag, cmd);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
assert(imapd_index);
if (!config_getswitch(IMAPOPT_CONVERSATIONS)) {
prot_printf(imapd_out, "%s BAD Unrecognized command\r\n", tag);
eatline(imapd_in, ' ');
return;
}
c = getsortcriteria(tag, &sortcrit);
if (c == EOF) goto error;
if (c != ' ') {
prot_printf(imapd_out, "%s BAD Missing window args in XConvMultiSort\r\n",
tag);
goto error;
}
c = parse_windowargs(tag, &windowargs, /*updates*/0);
if (c != ' ')
goto error;
/* open the conversations state first - we don't care if it fails,
* because that probably just means it's already open */
conversations_open_mbox(index_mboxname(imapd_index), &cstate);
/* need index loaded to even parse searchargs! */
searchargs = new_searchargs(tag, GETSEARCH_CHARSET_FIRST,
&imapd_namespace, imapd_userid, imapd_authstate,
imapd_userisadmin || imapd_userisproxyadmin);
c = get_search_program(imapd_in, imapd_out, searchargs);
if (c == EOF) goto error;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to XconvMultiSort\r\n", tag);
goto error;
}
r = index_convmultisort(imapd_index, sortcrit, searchargs, windowargs);
if (r < 0) {
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(r));
goto error;
}
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
if (CONFIG_TIMING_VERBOSE) {
char *s = sortcrit_as_string(sortcrit);
syslog(LOG_DEBUG, "XCONVMULTISORT (%s) processing time %s sec",
s, mytime);
free(s);
}
prot_printf(imapd_out, "%s OK %s (in %s secs)\r\n", tag,
error_message(IMAP_OK_COMPLETED), mytime);
out:
if (cstate) conversations_commit(&cstate);
freesortcrit(sortcrit);
freesearchargs(searchargs);
free_windowargs(windowargs);
return;
error:
if (cstate) conversations_commit(&cstate);
eatline(imapd_in, (c == EOF ? ' ' : c));
goto out;
}
static void cmd_xsnippets(char *tag)
{
int c;
struct searchargs *searchargs = NULL;
struct snippetargs *snippetargs = NULL;
clock_t start = clock();
char mytime[100];
int r;
if (backend_current) {
/* remote mailbox */
const char *cmd = "Xsnippets";
prot_printf(backend_current->out, "%s %s ", tag, cmd);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
assert(imapd_index);
c = get_snippetargs(&snippetargs);
if (c == EOF) {
prot_printf(imapd_out, "%s BAD Syntax error in snippet arguments\r\n", tag);
goto error;
}
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Unexpected arguments in Xsnippets\r\n", tag);
goto error;
}
/* need index loaded to even parse searchargs! */
searchargs = new_searchargs(tag, GETSEARCH_CHARSET_FIRST,
&imapd_namespace, imapd_userid, imapd_authstate,
imapd_userisadmin || imapd_userisproxyadmin);
c = get_search_program(imapd_in, imapd_out, searchargs);
if (c == EOF) goto error;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Xsnippets\r\n", tag);
goto error;
}
r = index_snippets(imapd_index, snippetargs, searchargs);
if (r < 0) {
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(r));
goto error;
}
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
prot_printf(imapd_out, "%s OK %s (in %s secs)\r\n", tag,
error_message(IMAP_OK_COMPLETED), mytime);
out:
freesearchargs(searchargs);
free_snippetargs(&snippetargs);
return;
error:
eatline(imapd_in, (c == EOF ? ' ' : c));
goto out;
}
static void cmd_xstats(char *tag, int c)
{
int metric;
if (backend_current) {
/* remote mailbox */
const char *cmd = "Xstats";
prot_printf(backend_current->out, "%s %s ", tag, cmd);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
if (c == EOF) {
prot_printf(imapd_out, "%s BAD Syntax error in Xstats arguments\r\n", tag);
goto error;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Xstats\r\n", tag);
goto error;
}
prot_printf(imapd_out, "* XSTATS");
for (metric = 0 ; metric < XSTATS_NUM_METRICS ; metric++)
prot_printf(imapd_out, " %s %u", xstats_names[metric], xstats[metric]);
prot_printf(imapd_out, "\r\n");
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
return;
error:
eatline(imapd_in, (c == EOF ? ' ' : c));
}
/*
* Perform a THREAD/UID THREAD command
*/
static void cmd_thread(char *tag, int usinguid)
{
static struct buf arg;
int c;
int alg;
struct searchargs *searchargs;
clock_t start = clock();
char mytime[100];
int n;
if (backend_current) {
/* remote mailbox */
const char *cmd = usinguid ? "UID Thread" : "Thread";
prot_printf(backend_current->out, "%s %s ", tag, cmd);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
/* local mailbox */
/* get algorithm */
c = getword(imapd_in, &arg);
if (c != ' ') {
prot_printf(imapd_out, "%s BAD Missing algorithm in Thread\r\n", tag);
eatline(imapd_in, c);
return;
}
if ((alg = find_thread_algorithm(arg.s)) == -1) {
prot_printf(imapd_out, "%s BAD Invalid Thread algorithm %s\r\n",
tag, arg.s);
eatline(imapd_in, c);
return;
}
searchargs = new_searchargs(tag, GETSEARCH_CHARSET_FIRST,
&imapd_namespace, imapd_userid, imapd_authstate,
imapd_userisadmin || imapd_userisproxyadmin);
c = get_search_program(imapd_in, imapd_out, searchargs);
if (c == EOF) {
eatline(imapd_in, ' ');
freesearchargs(searchargs);
return;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Thread\r\n", tag);
eatline(imapd_in, c);
freesearchargs(searchargs);
return;
}
n = index_thread(imapd_index, alg, searchargs, usinguid);
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
prot_printf(imapd_out, "%s OK %s (%d msgs in %s secs)\r\n", tag,
error_message(IMAP_OK_COMPLETED), n, mytime);
freesearchargs(searchargs);
return;
}
/*
* Perform a COPY/UID COPY command
*/
static void cmd_copy(char *tag, char *sequence, char *name, int usinguid, int ismove)
{
int r, myrights;
char *copyuid = NULL;
mbentry_t *mbentry = NULL;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(NULL, NULL, intname, &mbentry);
if (!r) myrights = cyrus_acl_myrights(imapd_authstate, mbentry->acl);
if (!r && backend_current) {
/* remote mailbox -> local or remote mailbox */
/* xxx start of separate proxy-only code
(remove when we move to a unified environment) */
struct backend *s = NULL;
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
mboxlist_entry_free(&mbentry);
if (!s) {
r = IMAP_SERVER_UNAVAILABLE;
goto done;
}
if (s != backend_current) {
/* this is the hard case; we have to fetch the messages and append
them to the other mailbox */
proxy_copy(tag, sequence, name, myrights, usinguid, s);
goto cleanup;
}
/* xxx end of separate proxy-only code */
/* simply send the COPY to the backend */
prot_printf(
backend_current->out,
"%s %s %s {" SIZE_T_FMT "+}\r\n%s\r\n",
tag,
usinguid ? (ismove ? "UID Move" : "UID Copy") : (ismove ? "Move" : "Copy"),
sequence,
strlen(name),
name
);
pipe_including_tag(backend_current, tag, 0);
goto cleanup;
}
else if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* local mailbox -> remote mailbox
*
* fetch the messages and APPEND them to the backend
*
* xxx completely untested
*/
struct backend *s = NULL;
int res;
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
mboxlist_entry_free(&mbentry);
if (!s) r = IMAP_SERVER_UNAVAILABLE;
else if (!CAPA(s, CAPA_MULTIAPPEND)) {
/* we need MULTIAPPEND for atomicity */
r = IMAP_REMOTE_NO_MULTIAPPEND;
}
if (r) goto done;
assert(!ismove); /* XXX - support proxying moves */
/* start the append */
prot_printf(s->out, "%s Append {" SIZE_T_FMT "+}\r\n%s",
tag, strlen(name), name);
/* append the messages */
r = index_copy_remote(imapd_index, sequence, usinguid, s->out);
if (!r) {
/* ok, finish the append; we need the UIDVALIDITY and UIDs
to return as part of our COPYUID response code */
char *appenduid, *b;
prot_printf(s->out, "\r\n");
res = pipe_until_tag(s, tag, 0);
if (res == PROXY_OK) {
if (myrights & ACL_READ) {
appenduid = strchr(s->last_result.s, '[');
/* skip over APPENDUID */
if (appenduid) {
appenduid += strlen("[appenduid ");
b = strchr(appenduid, ']');
if (b) *b = '\0';
prot_printf(imapd_out, "%s OK [COPYUID %s] %s\r\n", tag,
appenduid, error_message(IMAP_OK_COMPLETED));
} else
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
} else {
prot_printf(imapd_out, "%s %s", tag, s->last_result.s);
}
} else {
/* abort the append */
prot_printf(s->out, " {0}\r\n");
pipe_until_tag(s, tag, 0);
/* report failure */
prot_printf(imapd_out, "%s NO inter-server COPY failed\r\n", tag);
}
goto cleanup;
}
/* need permission to delete from source if it's a move */
if (!r && ismove && !(imapd_index->myrights & ACL_EXPUNGE))
r = IMAP_PERMISSION_DENIED;
/* local mailbox -> local mailbox */
if (!r) {
r = index_copy(imapd_index, sequence, usinguid, intname,
©uid, !config_getswitch(IMAPOPT_SINGLEINSTANCESTORE),
&imapd_namespace,
(imapd_userisadmin || imapd_userisproxyadmin), ismove,
ignorequota);
}
if (ismove && copyuid && !r) {
prot_printf(imapd_out, "* OK [COPYUID %s] %s\r\n",
copyuid, error_message(IMAP_OK_COMPLETED));
free(copyuid);
copyuid = NULL;
}
imapd_check(NULL, ismove || usinguid);
done:
if (r && !(usinguid && r == IMAP_NO_NOSUCHMSG)) {
prot_printf(imapd_out, "%s NO %s%s\r\n", tag,
(r == IMAP_MAILBOX_NONEXISTENT &&
mboxlist_createmailboxcheck(intname, 0, 0,
imapd_userisadmin,
imapd_userid, imapd_authstate,
NULL, NULL, 0) == 0)
? "[TRYCREATE] " : "", error_message(r));
}
else if (copyuid) {
prot_printf(imapd_out, "%s OK [COPYUID %s] %s\r\n", tag,
copyuid, error_message(IMAP_OK_COMPLETED));
free(copyuid);
}
else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
cleanup:
mboxlist_entry_free(&mbentry);
free(intname);
}
/*
* Perform an EXPUNGE command
* sequence == NULL if this isn't a UID EXPUNGE
*/
static void cmd_expunge(char *tag, char *sequence)
{
modseq_t old;
modseq_t new;
int r = 0;
if (backend_current) {
/* remote mailbox */
if (sequence) {
prot_printf(backend_current->out, "%s UID Expunge %s\r\n", tag,
sequence);
} else {
prot_printf(backend_current->out, "%s Expunge\r\n", tag);
}
pipe_including_tag(backend_current, tag, 0);
return;
}
/* local mailbox */
if (!index_hasrights(imapd_index, ACL_EXPUNGE))
r = IMAP_PERMISSION_DENIED;
old = index_highestmodseq(imapd_index);
if (!r) r = index_expunge(imapd_index, sequence, 1);
/* tell expunges */
if (!r) index_tellchanges(imapd_index, 1, sequence ? 1 : 0, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
return;
}
new = index_highestmodseq(imapd_index);
prot_printf(imapd_out, "%s OK ", tag);
if (new > old)
prot_printf(imapd_out, "[HIGHESTMODSEQ " MODSEQ_FMT "] ", new);
prot_printf(imapd_out, "%s\r\n", error_message(IMAP_OK_COMPLETED));
}
/*
* Perform a CREATE command
*/
static void cmd_create(char *tag, char *name, struct dlist *extargs, int localonly)
{
int r = 0;
int mbtype = 0;
const char *partition = NULL;
const char *server = NULL;
struct buf specialuse = BUF_INITIALIZER;
struct dlist *use;
/* We don't care about trailing hierarchy delimiters. */
if (name[0] && name[strlen(name)-1] == imapd_namespace.hier_sep) {
name[strlen(name)-1] = '\0';
}
mbname_t *mbname = mbname_from_extname(name, &imapd_namespace, imapd_userid);
dlist_getatom(extargs, "PARTITION", &partition);
dlist_getatom(extargs, "SERVER", &server);
const char *type = NULL;
dlist_getatom(extargs, "PARTITION", &partition);
dlist_getatom(extargs, "SERVER", &server);
if (dlist_getatom(extargs, "TYPE", &type)) {
if (!strcasecmp(type, "CALENDAR")) mbtype |= MBTYPE_CALENDAR;
else if (!strcasecmp(type, "COLLECTION")) mbtype |= MBTYPE_COLLECTION;
else if (!strcasecmp(type, "ADDRESSBOOK")) mbtype |= MBTYPE_ADDRESSBOOK;
else {
r = IMAP_MAILBOX_BADTYPE;
goto err;
}
}
use = dlist_getchild(extargs, "USE");
if (use) {
/* only user mailboxes can have specialuse, and they must be user toplevel folders */
if (!mbname_userid(mbname) || strarray_size(mbname_boxes(mbname)) != 1) {
r = IMAP_MAILBOX_SPECIALUSE;
goto err;
}
/* I would much prefer to create the specialuse annotation FIRST
* and do the sanity check on the values, so we can return the
* correct error. Sadly, that's a pain - so we compromise by
* "normalising" first */
struct dlist *item;
char *raw;
strarray_t *su = strarray_new();
for (item = use->head; item; item = item->next) {
strarray_append(su, dlist_cstring(item));
}
raw = strarray_join(su, " ");
strarray_free(su);
r = specialuse_validate(imapd_userid, raw, &specialuse);
free(raw);
if (r) {
prot_printf(imapd_out, "%s NO [USEATTR] %s\r\n", tag, error_message(r));
goto done;
}
}
// A non-admin is not allowed to specify the server nor partition on which
// to create the mailbox.
//
// However, this only applies to frontends. If we're a backend, a frontend will
// proxy the partition it wishes to create the mailbox on.
if ((server || partition) && !imapd_userisadmin) {
if (config_mupdate_config == IMAP_ENUM_MUPDATE_CONFIG_STANDARD ||
config_mupdate_config == IMAP_ENUM_MUPDATE_CONFIG_UNIFIED) {
if (!config_getstring(IMAPOPT_PROXYSERVERS)) {
r = IMAP_PERMISSION_DENIED;
goto err;
}
}
}
/* check for INBOX.INBOX creation by broken Apple clients */
const strarray_t *boxes = mbname_boxes(mbname);
if (strarray_size(boxes) > 1
&& !strcasecmp(strarray_nth(boxes, 0), "INBOX")
&& !strcasecmp(strarray_nth(boxes, 1), "INBOX"))
r = IMAP_MAILBOX_BADNAME;
if (r) {
err:
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
goto done;
}
// If the create command does not mandate the mailbox must be created
// locally, let's go and find the most appropriate location.
if (!localonly) {
// If we're running in a Murder, things get more complicated.
if (config_mupdate_server) {
// Consider your actions on a per type of topology basis.
//
// First up: Standard / discrete murder topology, with dedicated
// imap frontends, or unified -- both allow the IMAP server to either
// need to proxy through, or create locally.
if (
config_mupdate_config == IMAP_ENUM_MUPDATE_CONFIG_STANDARD ||
config_mupdate_config == IMAP_ENUM_MUPDATE_CONFIG_UNIFIED
) {
// The way that we detect whether we're a frontend is by testing
// for the proxy servers setting ... :/
if (!config_getstring(IMAPOPT_PROXYSERVERS)) {
// Find the parent mailbox, if any.
mbentry_t *parent = NULL;
// mboxlist_findparent either supplies the parent
// or has a return code of IMAP_MAILBOX_NONEXISTENT.
r = mboxlist_findparent(mbname_intname(mbname), &parent);
if (r) {
if (r != IMAP_MAILBOX_NONEXISTENT) {
prot_printf(imapd_out, "%s NO %s (%s:%d)\r\n", tag, error_message(r), __FILE__, __LINE__);
goto done;
}
}
if (!server && !partition) {
if (!parent) {
server = find_free_server();
if (!server) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(IMAP_SERVER_UNAVAILABLE));
goto done;
}
} else {
server = parent->server;
/* DO NOT set the partition:
only admins are allowed to do this
and the backend will use the partition
of the parent by default anyways.
partition = parent->partition;
*/
}
}
struct backend *s_conn = NULL;
s_conn = proxy_findserver(
server,
&imap_protocol,
proxy_userid,
&backend_cached,
&backend_current,
&backend_inbox,
imapd_in
);
if (!s_conn) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(IMAP_SERVER_UNAVAILABLE));
goto done;
}
// Huh?
if (imapd_userisadmin && supports_referrals) {
// "They are not an admin remotely, so let's refer them" --
// - Who is they?
// - How did imapd_userisadmin get set all of a sudden?
imapd_refer(tag, server, name);
referral_kick = 1;
return;
}
if (!CAPA(s_conn, CAPA_MUPDATE)) {
// Huh?
// "reserve mailbox on MUPDATE"
syslog(LOG_WARNING, "backend %s is not advertising any MUPDATE capability (%s:%d)", server, __FILE__, __LINE__);
}
// why not send a LOCALCREATE to the backend?
prot_printf(s_conn->out, "%s CREATE ", tag);
prot_printastring(s_conn->out, name);
// special use needs extended support, so pass through extargs
if (specialuse.len) {
prot_printf(s_conn->out, "(USE (%s)", buf_cstring(&specialuse));
if (partition) {
prot_printf(s_conn->out, " PARTITION ");
prot_printastring(s_conn->out, partition);
}
prot_putc(')', s_conn->out);
}
// Send partition as an atom, since its supported by older servers
else if (partition) {
prot_putc(' ', s_conn->out);
prot_printastring(s_conn->out, partition);
}
prot_printf(s_conn->out, "\r\n");
int res = pipe_until_tag(s_conn, tag, 0);
if (!CAPA(s_conn, CAPA_MUPDATE)) {
// Huh?
// "do MUPDATE create operations"
syslog(LOG_WARNING, "backend %s is not advertising any MUPDATE capability (%s:%d)", server, __FILE__, __LINE__);
}
/* make sure we've seen the update */
if (ultraparanoid && res == PROXY_OK) kick_mupdate();
imapd_check(s_conn, 0);
prot_printf(imapd_out, "%s %s", tag, s_conn->last_result.s);
goto done;
} else { // (!config_getstring(IMAPOPT_PROXYSERVERS))
// I have a standard murder config but also proxy servers configured; I'm a backend!
goto localcreate;
} // (!config_getstring(IMAPOPT_PROXYSERVERS))
} // (config_mupdate_config == IMAP_ENUM_MUPDATE_CONFIG_STANDARD)
else if (config_mupdate_config == IMAP_ENUM_MUPDATE_CONFIG_REPLICATED) {
// Everything is local
goto localcreate;
} // (config_mupdate_config == IMAP_ENUM_MUPDATE_CONFIG_REPLICATED)
else {
syslog(LOG_ERR, "murder configuration I cannot deal with");
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(IMAP_SERVER_UNAVAILABLE));
goto done;
}
} else { // (config_mupdate_server)
// I'm no part of a Murder, *everything* is localcreate
goto localcreate;
} // (config_mupdate_server)
} else { // (!localonly)
goto localcreate;
}
localcreate:
r = mboxlist_createmailbox(
mbname_intname(mbname), // const char name
mbtype, // int mbtype
partition, // const char partition
imapd_userisadmin || imapd_userisproxyadmin, // int isadmin
imapd_userid, // const char userid
imapd_authstate, // struct auth_state auth_state
localonly, // int localonly
localonly, // int forceuser
0, // int dbonly
1, // int notify
NULL // struct mailbox mailboxptr
);
#ifdef USE_AUTOCREATE
// Clausing autocreate for the INBOX
if (r == IMAP_PERMISSION_DENIED) {
if (!strcasecmp(name, "INBOX")) {
int autocreatequotastorage = config_getint(IMAPOPT_AUTOCREATE_QUOTA);
if (autocreatequotastorage > 0) {
r = mboxlist_createmailbox(
mbname_intname(mbname),
0,
partition,
1,
imapd_userid,
imapd_authstate,
0,
0,
0,
1,
NULL
);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
goto done;
}
int autocreatequotamessage = config_getint(IMAPOPT_AUTOCREATE_QUOTA_MESSAGES);
if ((autocreatequotastorage > 0) || (autocreatequotamessage > 0)) {
quota_t newquotas[QUOTA_NUMRESOURCES];
int res;
for (res = 0; res < QUOTA_NUMRESOURCES; res++) {
newquotas[res] = QUOTA_UNLIMITED;
}
newquotas[QUOTA_STORAGE] = autocreatequotastorage;
newquotas[QUOTA_MESSAGE] = autocreatequotamessage;
(void) mboxlist_setquotas(mbname_intname(mbname), newquotas, 0);
} // (autocreatequotastorage > 0) || (autocreatequotamessage > 0)
} else { // (autocreatequotastorage = config_getint(IMAPOPT_AUTOCREATEQUOTA))
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(IMAP_PERMISSION_DENIED));
goto done;
} // (autocreatequotastorage = config_getint(IMAPOPT_AUTOCREATEQUOTA))
} else { // (!strcasecmp(name, "INBOX"))
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(IMAP_PERMISSION_DENIED));
goto done;
} // (!strcasecmp(name, "INBOX"))
} else if (r) { // (r == IMAP_PERMISSION_DENIED)
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
goto done;
} else { // (r == IMAP_PERMISSION_DENIED)
/* no error: carry on */
} // (r == IMAP_PERMISSION_DENIED)
#else // USE_AUTOCREATE
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
goto done;
} // (r)
#endif // USE_AUTOCREATE
if (specialuse.len) {
r = annotatemore_write(mbname_intname(mbname), "/specialuse", mbname_userid(mbname), &specialuse);
if (r) {
/* XXX - failure here SHOULD cause a cleanup of the created mailbox */
syslog(
LOG_ERR,
"IOERROR: failed to write specialuse for %s on %s (%s) (%s:%d)",
imapd_userid,
mbname_intname(mbname),
buf_cstring(&specialuse),
__FILE__,
__LINE__
);
prot_printf(imapd_out, "%s NO %s (%s:%d)\r\n", tag, error_message(r), __FILE__, __LINE__);
goto done;
}
}
prot_printf(imapd_out, "%s OK Completed\r\n", tag);
imapd_check(NULL, 0);
done:
buf_free(&specialuse);
mbname_free(&mbname);
}
/* Callback for use by cmd_delete */
static int delmbox(const mbentry_t *mbentry, void *rock __attribute__((unused)))
{
int r;
if (!mboxlist_delayed_delete_isenabled()) {
r = mboxlist_deletemailbox(mbentry->name,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate, NULL,
0, 0, 0);
} else if ((imapd_userisadmin || imapd_userisproxyadmin) &&
mboxname_isdeletedmailbox(mbentry->name, NULL)) {
r = mboxlist_deletemailbox(mbentry->name,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate, NULL,
0, 0, 0);
} else {
r = mboxlist_delayed_deletemailbox(mbentry->name,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate, NULL,
0, 0, 0);
}
if (r) {
prot_printf(imapd_out, "* NO delete %s: %s\r\n",
mbentry->name, error_message(r));
}
return 0;
}
/*
* Perform a DELETE command
*/
static void cmd_delete(char *tag, char *name, int localonly, int force)
{
int r;
mbentry_t *mbentry = NULL;
struct mboxevent *mboxevent = NULL;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(NULL, NULL, intname, &mbentry);
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
struct backend *s = NULL;
int res;
if (supports_referrals) {
imapd_refer(tag, mbentry->server, name);
referral_kick = 1;
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
mboxlist_entry_free(&mbentry);
if (!s) r = IMAP_SERVER_UNAVAILABLE;
if (!r) {
prot_printf(s->out, "%s DELETE {" SIZE_T_FMT "+}\r\n%s\r\n",
tag, strlen(name), name);
res = pipe_until_tag(s, tag, 0);
if (!CAPA(s, CAPA_MUPDATE) && res == PROXY_OK) {
/* do MUPDATE delete operations */
}
/* make sure we've seen the update */
if (ultraparanoid && res == PROXY_OK) kick_mupdate();
}
imapd_check(s, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
/* we're allowed to reference last_result since the noop, if
sent, went to a different server */
prot_printf(imapd_out, "%s %s", tag, s->last_result.s);
}
free(intname);
return;
}
mboxlist_entry_free(&mbentry);
mboxevent = mboxevent_new(EVENT_MAILBOX_DELETE);
/* local mailbox */
if (!r) {
if (localonly || !mboxlist_delayed_delete_isenabled()) {
r = mboxlist_deletemailbox(intname,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate, mboxevent,
1-force, localonly, 0);
} else if ((imapd_userisadmin || imapd_userisproxyadmin) &&
mboxname_isdeletedmailbox(intname, NULL)) {
r = mboxlist_deletemailbox(intname,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate, mboxevent,
0 /* checkacl */, localonly, 0);
} else {
r = mboxlist_delayed_deletemailbox(intname,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate, mboxevent,
1-force, 0, 0);
}
}
/* send a MailboxDelete event notification */
if (!r)
mboxevent_notify(&mboxevent);
mboxevent_free(&mboxevent);
/* was it a top-level user mailbox? */
/* localonly deletes are only per-mailbox */
if (!r && !localonly && mboxname_isusermailbox(intname, 1)) {
char *userid = mboxname_to_userid(intname);
if (userid) {
r = mboxlist_usermboxtree(userid, delmbox, NULL, 0);
if (!r) r = user_deletedata(userid, 1);
free(userid);
}
}
if (!r && config_getswitch(IMAPOPT_DELETE_UNSUBSCRIBE)) {
mboxlist_changesub(intname, imapd_userid, imapd_authstate,
/* add */ 0, /* force */ 0, /* notify? */ 1);
}
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
}
else {
if (config_mupdate_server)
kick_mupdate();
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
free(intname);
}
struct renrock
{
const struct namespace *namespace;
int ol;
int nl;
int rename_user;
const char *olduser, *newuser;
char *newmailboxname;
const char *partition;
int found;
};
/* Callback for use by cmd_rename */
static int checkmboxname(const mbentry_t *mbentry, void *rock)
{
struct renrock *text = (struct renrock *)rock;
int r;
text->found++;
if((text->nl + strlen(mbentry->name + text->ol)) >= MAX_MAILBOX_BUFFER)
return IMAP_MAILBOX_BADNAME;
strcpy(text->newmailboxname + text->nl, mbentry->name + text->ol);
/* force create, but don't ignore policy. This is a filthy hack that
will go away when we refactor this code */
r = mboxlist_createmailboxcheck(text->newmailboxname, 0, text->partition, 1,
imapd_userid, imapd_authstate, NULL, NULL, 2);
return r;
}
/* Callback for use by cmd_rename */
static int renmbox(const mbentry_t *mbentry, void *rock)
{
struct renrock *text = (struct renrock *)rock;
char *oldextname = NULL, *newextname = NULL;
int r = 0;
uint32_t uidvalidity = mbentry->uidvalidity;
if((text->nl + strlen(mbentry->name + text->ol)) >= MAX_MAILBOX_BUFFER)
goto done;
strcpy(text->newmailboxname + text->nl, mbentry->name + text->ol);
/* check if a previous deleted mailbox existed */
mbentry_t *newmbentry = NULL;
r = mboxlist_lookup_allow_all(text->newmailboxname, &newmbentry, NULL);
/* XXX - otherwise we should probably reject now, but meh, save it for
* a real cleanup */
if (!r && newmbentry->mbtype == MBTYPE_DELETED) {
/* changing the unique id since last time? */
if (strcmpsafe(mbentry->uniqueid, newmbentry->uniqueid)) {
/* then the UIDVALIDITY must be higher than before */
if (uidvalidity <= newmbentry->uidvalidity)
uidvalidity = newmbentry->uidvalidity+1;
}
}
mboxlist_entry_free(&newmbentry);
/* don't notify implied rename in mailbox hierarchy */
r = mboxlist_renamemailbox(mbentry->name, text->newmailboxname,
text->partition, uidvalidity,
1, imapd_userid, imapd_authstate, NULL, 0, 0,
text->rename_user);
oldextname =
mboxname_to_external(mbentry->name, &imapd_namespace, imapd_userid);
newextname =
mboxname_to_external(text->newmailboxname, &imapd_namespace, imapd_userid);
if(r) {
prot_printf(imapd_out, "* NO rename %s %s: %s\r\n",
oldextname, newextname, error_message(r));
if (!RENAME_STOP_ON_ERROR) r = 0;
} else {
/* If we're renaming a user, change quotaroot and ACL */
if (text->rename_user) {
user_copyquotaroot(mbentry->name, text->newmailboxname);
user_renameacl(text->namespace, text->newmailboxname,
text->olduser, text->newuser);
}
prot_printf(imapd_out, "* OK rename %s %s\r\n",
oldextname, newextname);
}
done:
prot_flush(imapd_out);
free(oldextname);
free(newextname);
return r;
}
/*
* Perform a RENAME command
*/
static void cmd_rename(char *tag, char *oldname, char *newname, char *location)
{
int r = 0;
char *c;
char oldmailboxname[MAX_MAILBOX_BUFFER];
char newmailboxname[MAX_MAILBOX_BUFFER];
char oldmailboxname2[MAX_MAILBOX_BUFFER];
char newmailboxname2[MAX_MAILBOX_BUFFER];
char *oldextname = NULL;
char *newextname = NULL;
char *oldintname = NULL;
char *newintname = NULL;
char *olduser = NULL;
char *newuser = NULL;
int omlen, nmlen;
int subcount = 0; /* number of sub-folders found */
int recursive_rename = 1;
int rename_user = 0;
mbentry_t *mbentry = NULL;
struct renrock rock;
if (location && !imapd_userisadmin) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(IMAP_PERMISSION_DENIED));
return;
}
if (location && strcmp(oldname, newname)) {
prot_printf(imapd_out,
"%s NO Cross-server or cross-partition move w/rename not supported\r\n",
tag);
return;
}
oldintname = mboxname_from_external(oldname, &imapd_namespace, imapd_userid);
strncpy(oldmailboxname, oldintname, MAX_MAILBOX_NAME);
free(oldintname);
newintname = mboxname_from_external(newname, &imapd_namespace, imapd_userid);
strncpy(newmailboxname, newintname, MAX_MAILBOX_NAME);
free(newintname);
olduser = mboxname_to_userid(oldmailboxname);
newuser = mboxname_to_userid(newmailboxname);
/* Keep temporary copy: master is trashed */
strcpy(oldmailboxname2, oldmailboxname);
strcpy(newmailboxname2, newmailboxname);
r = mlookup(NULL, NULL, oldmailboxname, &mbentry);
if (!r && mbentry->mbtype & MBTYPE_REMOTE) {
/* remote mailbox */
struct backend *s = NULL;
int res;
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!s) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(IMAP_SERVER_UNAVAILABLE));
goto done;
}
// Server or partition is going to change
if (location) {
char *destserver = NULL;
char *destpart = NULL;
c = strchr(location, '!');
if (c) {
destserver = xstrndup(location, c - location);
destpart = xstrdup(c + 1);
} else {
destpart = xstrdup(location);
}
if (*destpart == '\0') {
free(destpart);
destpart = NULL;
}
if (!destserver || !strcmp(destserver, mbentry->server)) {
/* same server: proxy a rename */
prot_printf(s->out,
"%s RENAME \"%s\" \"%s\" %s\r\n",
tag,
oldname,
newname,
location);
} else {
/* different server: proxy an xfer */
prot_printf(s->out,
"%s XFER \"%s\" %s%s%s\r\n",
tag,
oldname,
destserver,
destpart ? " " : "",
destpart ? destpart : "");
}
if (destserver) free(destserver);
if (destpart) free(destpart);
res = pipe_until_tag(s, tag, 0);
/* make sure we've seen the update */
if (ultraparanoid && res == PROXY_OK) kick_mupdate();
} else { // (location)
// a simple rename, old name and new name must not be the same
if (!strcmp(oldname, newname)) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(IMAP_SERVER_UNAVAILABLE));
goto done;
}
prot_printf(s->out,
"%s RENAME \"%s\" \"%s\"\r\n",
tag,
oldname,
newname
);
res = pipe_until_tag(s, tag, 0);
/* make sure we've seen the update */
if (ultraparanoid && res == PROXY_OK) kick_mupdate();
}
imapd_check(s, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
/* we're allowed to reference last_result since the noop, if
sent, went to a different server */
prot_printf(imapd_out, "%s %s", tag, s->last_result.s);
}
goto done;
}
/* local mailbox */
if (location && !config_partitiondir(location)) {
/* invalid partition, assume its a server (remote destination) */
char *server;
char *partition;
/* dest partition? */
server = location;
partition = strchr(location, '!');
if (partition) *partition++ = '\0';
cmd_xfer(tag, oldname, server, partition);
goto done;
}
/* local rename: it's OK if the mailbox doesn't exist, we'll check
* if sub mailboxes can be renamed */
if (r == IMAP_MAILBOX_NONEXISTENT)
r = 0;
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
goto done;
}
/* local destination */
/* if this is my inbox, don't do recursive renames */
if (!strcasecmp(oldname, "inbox")) {
recursive_rename = 0;
}
/* check if we're an admin renaming a user */
else if (config_getswitch(IMAPOPT_ALLOWUSERMOVES) &&
mboxname_isusermailbox(oldmailboxname, 1) &&
mboxname_isusermailbox(newmailboxname, 1) &&
strcmp(oldmailboxname, newmailboxname) && /* different user */
imapd_userisadmin) {
rename_user = 1;
}
/* if we're renaming something inside of something else,
don't recursively rename stuff */
omlen = strlen(oldmailboxname);
nmlen = strlen(newmailboxname);
if (omlen < nmlen) {
if (!strncmp(oldmailboxname, newmailboxname, omlen) &&
newmailboxname[omlen] == '.') {
recursive_rename = 0;
}
} else {
if (!strncmp(oldmailboxname, newmailboxname, nmlen) &&
oldmailboxname[nmlen] == '.') {
recursive_rename = 0;
}
}
oldextname = mboxname_to_external(oldmailboxname, &imapd_namespace, imapd_userid);
newextname = mboxname_to_external(newmailboxname, &imapd_namespace, imapd_userid);
/* rename all mailboxes matching this */
if (recursive_rename && strcmp(oldmailboxname, newmailboxname)) {
int ol = omlen + 1;
int nl = nmlen + 1;
char ombn[MAX_MAILBOX_BUFFER];
char nmbn[MAX_MAILBOX_BUFFER];
strcpy(ombn, oldmailboxname);
strcpy(nmbn, newmailboxname);
strcat(ombn, ".");
strcat(nmbn, ".");
/* setup the rock */
rock.namespace = &imapd_namespace;
rock.found = 0;
rock.newmailboxname = nmbn;
rock.ol = ol;
rock.nl = nl;
rock.olduser = olduser;
rock.newuser = newuser;
rock.partition = location;
rock.rename_user = rename_user;
/* Check mboxnames to ensure we can write them all BEFORE we start */
r = mboxlist_allmbox(ombn, checkmboxname, &rock, 0);
subcount = rock.found;
}
/* attempt to rename the base mailbox */
if (!r) {
struct mboxevent *mboxevent = NULL;
uint32_t uidvalidity = mbentry ? mbentry->uidvalidity : 0;
/* don't send rename notification if we only change the partition */
if (strcmp(oldmailboxname, newmailboxname))
mboxevent = mboxevent_new(EVENT_MAILBOX_RENAME);
/* check if a previous deleted mailbox existed */
mbentry_t *newmbentry = NULL;
r = mboxlist_lookup_allow_all(newmailboxname, &newmbentry, NULL);
/* XXX - otherwise we should probably reject now, but meh, save it for
* a real cleanup */
if (!r && newmbentry->mbtype == MBTYPE_DELETED) {
/* changing the unique id since last time? */
if (!mbentry || strcmpsafe(mbentry->uniqueid, newmbentry->uniqueid)) {
/* then the UIDVALIDITY must be higher than before */
if (uidvalidity <= newmbentry->uidvalidity)
uidvalidity = newmbentry->uidvalidity+1;
}
}
mboxlist_entry_free(&newmbentry);
r = mboxlist_renamemailbox(oldmailboxname, newmailboxname, location,
0 /* uidvalidity */, imapd_userisadmin,
imapd_userid, imapd_authstate, mboxevent,
0, 0, rename_user);
/* it's OK to not exist if there are subfolders */
if (r == IMAP_MAILBOX_NONEXISTENT && subcount && !rename_user &&
mboxname_userownsmailbox(imapd_userid, oldmailboxname) &&
mboxname_userownsmailbox(imapd_userid, newmailboxname)) {
mboxevent_free(&mboxevent);
goto submboxes;
}
/* send a MailboxRename event notification if enabled */
if (!r)
mboxevent_notify(&mboxevent);
mboxevent_free(&mboxevent);
}
/* If we're renaming a user, take care of changing quotaroot, ACL,
seen state, subscriptions and sieve scripts */
if (!r && rename_user) {
user_copyquotaroot(oldmailboxname, newmailboxname);
user_renameacl(&imapd_namespace, newmailboxname, olduser, newuser);
user_renamedata(olduser, newuser);
/* XXX report status/progress of meta-data */
}
/* rename all mailboxes matching this */
if (!r && recursive_rename) {
prot_printf(imapd_out, "* OK rename %s %s\r\n",
oldextname, newextname);
prot_flush(imapd_out);
submboxes:
strcat(oldmailboxname, ".");
strcat(newmailboxname, ".");
/* setup the rock */
rock.namespace = &imapd_namespace;
rock.newmailboxname = newmailboxname;
rock.ol = omlen + 1;
rock.nl = nmlen + 1;
rock.olduser = olduser;
rock.newuser = newuser;
rock.partition = location;
rock.rename_user = rename_user;
/* add submailboxes; we pretend we're an admin since we successfully
renamed the parent - we're using internal names here */
r = mboxlist_allmbox(oldmailboxname, renmbox, &rock, 0);
}
/* take care of deleting old ACLs, subscriptions, seen state and quotas */
if (!r && rename_user) {
user_deletedata(olduser, 1);
/* allow the replica to get the correct new quotaroot
* and acls copied across */
sync_log_user(newuser);
/* allow the replica to clean up the old meta files */
sync_log_unuser(olduser);
}
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
if (config_mupdate_server)
kick_mupdate();
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
if (rename_user) sync_log_user(newuser);
}
done:
mboxlist_entry_free(&mbentry);
free(oldextname);
free(newextname);
free(olduser);
free(newuser);
}
/*
* Perform a RECONSTRUCT command
*/
static void cmd_reconstruct(const char *tag, const char *name, int recursive)
{
int r = 0;
char quotaroot[MAX_MAILBOX_BUFFER];
mbentry_t *mbentry = NULL;
struct mailbox *mailbox = NULL;
/* administrators only please */
if (!imapd_userisadmin)
r = IMAP_PERMISSION_DENIED;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
if (!r && !strcmpsafe(intname, index_mboxname(imapd_index)))
r = IMAP_MAILBOX_LOCKED;
if (!r) {
r = mlookup(tag, name, intname, &mbentry);
}
if (r == IMAP_MAILBOX_MOVED) {
free(intname);
return;
}
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
imapd_refer(tag, mbentry->server, name);
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
mboxlist_entry_free(&mbentry);
/* local mailbox */
if (!r) {
int pid;
/* Reconstruct it */
pid = fork();
if (pid == -1) {
r = IMAP_SYS_ERROR;
} else if (pid == 0) {
char buf[4096];
int ret;
/* Child - exec reconstruct*/
syslog(LOG_NOTICE, "Reconstructing '%s' (%s) for user '%s'",
intname, recursive ? "recursive" : "not recursive",
imapd_userid);
fclose(stdin);
fclose(stdout);
fclose(stderr);
ret = snprintf(buf, sizeof(buf), "%s/reconstruct", SBIN_DIR);
if(ret < 0 || ret >= (int) sizeof(buf)) {
/* in child, so fatailing won't disconnect our user */
fatal("reconstruct buffer not sufficiently big", EC_CONFIG);
}
if(recursive) {
execl(buf, buf, "-C", config_filename, "-r", "-f",
intname, NULL);
} else {
execl(buf, buf, "-C", config_filename, intname, NULL);
}
/* if we are here, we have a problem */
exit(-1);
} else {
int status;
/* Parent, wait on child */
if(waitpid(pid, &status, 0) < 0) r = IMAP_SYS_ERROR;
/* Did we fail? */
if(WEXITSTATUS(status) != 0) r = IMAP_SYS_ERROR;
}
}
/* Still in parent, need to re-quota the mailbox*/
/* Find its quota root */
if (!r)
r = mailbox_open_irl(intname, &mailbox);
if(!r) {
if(mailbox->quotaroot) {
strcpy(quotaroot, mailbox->quotaroot);
} else {
strcpy(quotaroot, intname);
}
mailbox_close(&mailbox);
}
/* Run quota -f */
if (!r) {
int pid;
pid = fork();
if(pid == -1) {
r = IMAP_SYS_ERROR;
} else if(pid == 0) {
char buf[4096];
int ret;
/* Child - exec reconstruct*/
syslog(LOG_NOTICE,
"Regenerating quota roots starting with '%s' for user '%s'",
intname, imapd_userid);
fclose(stdin);
fclose(stdout);
fclose(stderr);
ret = snprintf(buf, sizeof(buf), "%s/quota", SBIN_DIR);
if(ret < 0 || ret >= (int) sizeof(buf)) {
/* in child, so fatailing won't disconnect our user */
fatal("quota buffer not sufficiently big", EC_CONFIG);
}
execl(buf, buf, "-C", config_filename, "-f", quotaroot, NULL);
/* if we are here, we have a problem */
exit(-1);
} else {
int status;
/* Parent, wait on child */
if(waitpid(pid, &status, 0) < 0) r = IMAP_SYS_ERROR;
/* Did we fail? */
if(WEXITSTATUS(status) != 0) r = IMAP_SYS_ERROR;
}
}
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
free(intname);
}
/* number of times the callbacks for findall/findsub have been called */
static int list_callback_calls;
/*
* Parse LIST command arguments.
*/
static void getlistargs(char *tag, struct listargs *listargs)
{
static struct buf reference, buf;
int c;
/* Check for and parse LIST-EXTENDED selection options */
c = prot_getc(imapd_in);
if (c == '(') {
listargs->cmd = LIST_CMD_EXTENDED;
c = getlistselopts(tag, listargs);
if (c == EOF) {
eatline(imapd_in, c);
return;
}
}
else
prot_ungetc(c, imapd_in);
if (!strcmpsafe(imapd_magicplus, "+")) listargs->sel |= LIST_SEL_SUBSCRIBED;
else if (!strcasecmpsafe(imapd_magicplus, "+dav")) listargs->sel |= LIST_SEL_DAV;
/* Read in reference name */
c = getastring(imapd_in, imapd_out, &reference);
if (c == EOF && !*reference.s) {
prot_printf(imapd_out,
"%s BAD Missing required argument to List: reference name\r\n",
tag);
eatline(imapd_in, c);
return;
}
listargs->ref = reference.s;
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing required argument to List: mailbox pattern\r\n", tag);
eatline(imapd_in, c);
return;
}
/* Read in mailbox pattern(s) */
c = prot_getc(imapd_in);
if (c == '(') {
listargs->cmd = LIST_CMD_EXTENDED;
for (;;) {
c = getastring(imapd_in, imapd_out, &buf);
if (*buf.s)
strarray_append(&listargs->pat, buf.s);
if (c != ' ') break;
}
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Invalid syntax in List command\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
c = prot_getc(imapd_in);
}
else {
prot_ungetc(c, imapd_in);
c = getastring(imapd_in, imapd_out, &buf);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing required argument to List: mailbox pattern\r\n",
tag);
eatline(imapd_in, c);
goto freeargs;
}
strarray_append(&listargs->pat, buf.s);
}
/* Check for and parse LIST-EXTENDED return options */
if (c == ' ') {
listargs->cmd = LIST_CMD_EXTENDED;
c = getlistretopts(tag, listargs);
if (c == EOF) {
eatline(imapd_in, c);
goto freeargs;
}
}
/* check for CRLF */
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to List\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
#ifdef USE_AUTOCREATE
autocreate_inbox();
#endif // USE_AUTOCREATE
return;
freeargs:
strarray_fini(&listargs->pat);
strarray_fini(&listargs->metaitems);
return;
}
/*
* Perform a LIST, LSUB, RLIST or RLSUB command
*/
static void cmd_list(char *tag, struct listargs *listargs)
{
clock_t start = clock();
char mytime[100];
if (listargs->sel & LIST_SEL_REMOTE) {
if (!config_getswitch(IMAPOPT_PROXYD_DISABLE_MAILBOX_REFERRALS)) {
supports_referrals = !disable_referrals;
}
}
list_callback_calls = 0;
if (listargs->pat.count && !*(listargs->pat.data[0]) && (listargs->cmd == LIST_CMD_LIST)) {
/* special case: query top-level hierarchy separator */
prot_printf(imapd_out, "* LIST (\\Noselect) \"%c\" \"\"\r\n",
imapd_namespace.hier_sep);
} else if (listargs->pat.count && !*(listargs->pat.data[0]) && (listargs->cmd == LIST_CMD_XLIST)) {
/* special case: query top-level hierarchy separator */
prot_printf(imapd_out, "* XLIST (\\Noselect) \"%c\" \"\"\r\n",
imapd_namespace.hier_sep);
} else if ((listargs->cmd == LIST_CMD_LSUB) &&
(backend_inbox || (backend_inbox = proxy_findinboxserver(imapd_userid)))) {
/* remote inbox */
if (list_data_remote(backend_inbox, tag, listargs, NULL))
return;
} else {
list_data(listargs);
}
strarray_fini(&listargs->pat);
strarray_fini(&listargs->metaitems);
imapd_check((listargs->sel & LIST_SEL_SUBSCRIBED) ? NULL : backend_inbox, 0);
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
if ((listargs->sel & LIST_SEL_METADATA) && listargs->metaopts.maxsize &&
listargs->metaopts.biggest > listargs->metaopts.maxsize) {
prot_printf(imapd_out, "%s OK [METADATA LONGENTRIES %u] %s\r\n", tag,
(unsigned)listargs->metaopts.biggest, error_message(IMAP_OK_COMPLETED));
}
else {
prot_printf(imapd_out, "%s OK %s (%s secs", tag,
error_message(IMAP_OK_COMPLETED), mytime);
if (list_callback_calls)
prot_printf(imapd_out, " %u calls", list_callback_calls);
prot_printf(imapd_out, ")\r\n");
}
if (global_conversations) {
conversations_abort(&global_conversations);
global_conversations = NULL;
}
}
/*
* Perform a SUBSCRIBE (add is nonzero) or
* UNSUBSCRIBE (add is zero) command
*/
static void cmd_changesub(char *tag, char *namespace, char *name, int add)
{
const char *cmd = add ? "Subscribe" : "Unsubscribe";
int r = 0;
int force = config_getswitch(IMAPOPT_ALLOWALLSUBSCRIBE);
if (backend_inbox || (backend_inbox = proxy_findinboxserver(imapd_userid))) {
/* remote INBOX */
if (add) {
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(NULL, NULL, intname, NULL);
free(intname);
/* Doesn't exist on murder */
}
imapd_check(backend_inbox, 0);
if (!r) {
if (namespace) {
prot_printf(backend_inbox->out,
"%s %s {" SIZE_T_FMT "+}\r\n%s"
" {" SIZE_T_FMT "+}\r\n%s\r\n",
tag, cmd,
strlen(namespace), namespace,
strlen(name), name);
} else {
prot_printf(backend_inbox->out, "%s %s {" SIZE_T_FMT "+}\r\n%s\r\n",
tag, cmd,
strlen(name), name);
}
pipe_including_tag(backend_inbox, tag, 0);
}
else {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
}
return;
}
/* local INBOX */
if (namespace) lcase(namespace);
if (!namespace || !strcmp(namespace, "mailbox")) {
size_t len = strlen(name);
if (force && imapd_namespace.isalt &&
(((len == strlen(imapd_namespace.prefix[NAMESPACE_USER]) - 1) &&
!strncmp(name, imapd_namespace.prefix[NAMESPACE_USER], len)) ||
((len == strlen(imapd_namespace.prefix[NAMESPACE_SHARED]) - 1) &&
!strncmp(name, imapd_namespace.prefix[NAMESPACE_SHARED], len)))) {
r = 0;
}
else {
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mboxlist_changesub(intname, imapd_userid, imapd_authstate, add, force, 1);
free(intname);
}
}
else if (!strcmp(namespace, "bboard")) {
r = add ? IMAP_MAILBOX_NONEXISTENT : 0;
}
else {
prot_printf(imapd_out, "%s BAD Invalid %s subcommand\r\n", tag, cmd);
return;
}
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s: %s\r\n", tag, cmd, error_message(r));
}
else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
}
/*
* Perform a GETACL command
*/
static void cmd_getacl(const char *tag, const char *name)
{
int r, access;
char *acl;
char *rights, *nextid;
char *freeme = NULL;
mbentry_t *mbentry = NULL;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(tag, name, intname, &mbentry);
if (r == IMAP_MAILBOX_MOVED) return;
if (!r) {
access = cyrus_acl_myrights(imapd_authstate, mbentry->acl);
if (!(access & ACL_ADMIN) &&
!imapd_userisadmin &&
!mboxname_userownsmailbox(imapd_userid, intname)) {
r = (access & ACL_LOOKUP) ?
IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT;
}
}
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
prot_printf(imapd_out, "* ACL ");
prot_printastring(imapd_out, name);
freeme = acl = xstrdupnull(mbentry->acl);
while (acl) {
rights = strchr(acl, '\t');
if (!rights) break;
*rights++ = '\0';
nextid = strchr(rights, '\t');
if (!nextid) break;
*nextid++ = '\0';
prot_printf(imapd_out, " ");
prot_printastring(imapd_out, acl);
prot_printf(imapd_out, " ");
prot_printastring(imapd_out, rights);
acl = nextid;
}
prot_printf(imapd_out, "\r\n");
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
free(freeme);
mboxlist_entry_free(&mbentry);
free(intname);
}
/*
* Perform a LISTRIGHTS command
*/
static void cmd_listrights(char *tag, char *name, char *identifier)
{
int r, rights;
mbentry_t *mbentry = NULL;
struct auth_state *authstate;
const char *canon_identifier;
int implicit;
char rightsdesc[100], optional[33];
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(tag, name, intname, &mbentry);
if (r == IMAP_MAILBOX_MOVED) return;
if (!r) {
rights = cyrus_acl_myrights(imapd_authstate, mbentry->acl);
if (!rights && !imapd_userisadmin &&
!mboxname_userownsmailbox(imapd_userid, intname)) {
r = IMAP_MAILBOX_NONEXISTENT;
}
}
mboxlist_entry_free(&mbentry);
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
return;
}
authstate = auth_newstate(identifier);
if (global_authisa(authstate, IMAPOPT_ADMINS))
canon_identifier = identifier; /* don't canonify global admins */
else
canon_identifier = canonify_userid(identifier, imapd_userid, NULL);
auth_freestate(authstate);
if (!canon_identifier) {
implicit = 0;
}
else if (mboxname_userownsmailbox(canon_identifier, intname)) {
/* identifier's personal mailbox */
implicit = config_implicitrights;
}
else if (mboxname_isusermailbox(intname, 1)) {
/* anyone can post to an INBOX */
implicit = ACL_POST;
}
else {
implicit = 0;
}
/* calculate optional rights */
cyrus_acl_masktostr(implicit ^ (canon_identifier ? ACL_FULL : 0),
optional);
/* build the rights string */
if (implicit) {
cyrus_acl_masktostr(implicit, rightsdesc);
}
else {
strcpy(rightsdesc, "\"\"");
}
if (*optional) {
int i, n = strlen(optional);
char *p = rightsdesc + strlen(rightsdesc);
for (i = 0; i < n; i++) {
*p++ = ' ';
*p++ = optional[i];
}
*p = '\0';
}
prot_printf(imapd_out, "* LISTRIGHTS ");
prot_printastring(imapd_out, name);
(void)prot_putc(' ', imapd_out);
prot_printastring(imapd_out, identifier);
prot_printf(imapd_out, " %s", rightsdesc);
prot_printf(imapd_out, "\r\n%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
free(intname);
}
static int printmyrights(const char *extname, const mbentry_t *mbentry)
{
int rights = 0;
char str[ACL_MAXSTR];
rights = cyrus_acl_myrights(imapd_authstate, mbentry->acl);
/* Add in implicit rights */
if (imapd_userisadmin) {
rights |= ACL_LOOKUP|ACL_ADMIN;
}
else if (mboxname_userownsmailbox(imapd_userid, mbentry->name)) {
rights |= config_implicitrights;
}
if (!(rights & (ACL_LOOKUP|ACL_READ|ACL_INSERT|ACL_CREATE|ACL_DELETEMBOX|ACL_ADMIN))) {
return IMAP_MAILBOX_NONEXISTENT;
}
prot_printf(imapd_out, "* MYRIGHTS ");
prot_printastring(imapd_out, extname);
prot_printf(imapd_out, " ");
prot_printastring(imapd_out, cyrus_acl_masktostr(rights, str));
prot_printf(imapd_out, "\r\n");
return 0;
}
/*
* Perform a MYRIGHTS command
*/
static void cmd_myrights(const char *tag, const char *name)
{
mbentry_t *mbentry = NULL;
int r;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(tag, name, intname, &mbentry);
if (r == IMAP_MAILBOX_MOVED) return;
if (!r) r = printmyrights(name, mbentry);
mboxlist_entry_free(&mbentry);
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
return;
}
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
free(intname);
}
/*
* Perform a SETACL command
*/
static void cmd_setacl(char *tag, const char *name,
const char *identifier, const char *rights)
{
int r;
mbentry_t *mbentry = NULL;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
/* is it remote? */
r = mlookup(tag, name, intname, &mbentry);
if (r == IMAP_MAILBOX_MOVED) return;
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
struct backend *s = NULL;
int res;
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!s) r = IMAP_SERVER_UNAVAILABLE;
if (!r && imapd_userisadmin && supports_referrals) {
/* They aren't an admin remotely, so let's refer them */
imapd_refer(tag, mbentry->server, name);
referral_kick = 1;
mboxlist_entry_free(&mbentry);
return;
}
mboxlist_entry_free(&mbentry);
if (!r) {
if (rights) {
prot_printf(s->out,
"%s Setacl {" SIZE_T_FMT "+}\r\n%s"
" {" SIZE_T_FMT "+}\r\n%s {" SIZE_T_FMT "+}\r\n%s\r\n",
tag, strlen(name), name,
strlen(identifier), identifier,
strlen(rights), rights);
} else {
prot_printf(s->out,
"%s Deleteacl {" SIZE_T_FMT "+}\r\n%s"
" {" SIZE_T_FMT "+}\r\n%s\r\n",
tag, strlen(name), name,
strlen(identifier), identifier);
}
res = pipe_until_tag(s, tag, 0);
if (!CAPA(s, CAPA_MUPDATE) && res == PROXY_OK) {
/* setup new ACL in MUPDATE */
}
/* make sure we've seen the update */
if (ultraparanoid && res == PROXY_OK) kick_mupdate();
}
imapd_check(s, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
/* we're allowed to reference last_result since the noop, if
sent, went to a different server */
prot_printf(imapd_out, "%s %s", tag, s->last_result.s);
}
free(intname);
return;
}
mboxlist_entry_free(&mbentry);
/* local mailbox */
if (!r) {
char *err;
/* send BAD response if rights string contains unrecognised chars */
if (rights && *rights) {
r = cyrus_acl_checkstr(rights, &err);
if (r) {
prot_printf(imapd_out, "%s BAD %s\r\n", tag, err);
free(err);
free(intname);
return;
}
}
r = mboxlist_setacl(&imapd_namespace, intname, identifier, rights,
imapd_userisadmin || imapd_userisproxyadmin,
proxy_userid, imapd_authstate);
}
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
if (config_mupdate_server)
kick_mupdate();
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
free(intname);
}
static void print_quota_used(struct protstream *o, const struct quota *q)
{
int res;
const char *sep = "";
prot_putc('(', o);
for (res = 0 ; res < QUOTA_NUMRESOURCES ; res++) {
if (q->limits[res] >= 0) {
prot_printf(o, "%s%s " QUOTA_T_FMT " " QUOTA_T_FMT,
sep, quota_names[res],
q->useds[res]/quota_units[res],
q->limits[res]);
sep = " ";
}
}
prot_putc(')', o);
}
static void print_quota_limits(struct protstream *o, const struct quota *q)
{
int res;
const char *sep = "";
prot_putc('(', o);
for (res = 0 ; res < QUOTA_NUMRESOURCES ; res++) {
if (q->limits[res] >= 0) {
prot_printf(o, "%s%s " QUOTA_T_FMT,
sep, quota_names[res],
q->limits[res]);
sep = " ";
}
}
prot_putc(')', o);
}
/*
* Callback for (get|set)quota, to ensure that all of the
* submailboxes are on the same server.
*/
static int quota_cb(const mbentry_t *mbentry, void *rock)
{
const char *servername = (const char *)rock;
int r;
if (strcmp(servername, mbentry->server)) {
/* Not on same server as the root */
r = IMAP_NOT_SINGULAR_ROOT;
} else {
r = PROXY_OK;
}
return r;
}
/*
* Perform a GETQUOTA command
*/
static void cmd_getquota(const char *tag, const char *name)
{
int r;
char quotarootbuf[MAX_MAILBOX_BUFFER];
mbentry_t *mbentry = NULL;
struct quota q;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
quota_init(&q, intname);
imapd_check(NULL, 0);
if (!imapd_userisadmin && !imapd_userisproxyadmin) {
r = IMAP_PERMISSION_DENIED;
goto done;
}
r = mlookup(NULL, NULL, intname, &mbentry);
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
snprintf(quotarootbuf, sizeof(quotarootbuf), "%s.", intname);
r = mboxlist_allmbox(quotarootbuf, quota_cb, (void *)mbentry->server, 0);
if (r) goto done;
struct backend *s;
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!s) {
r = IMAP_SERVER_UNAVAILABLE;
goto done;
}
imapd_check(s, 0);
prot_printf(s->out, "%s Getquota {" SIZE_T_FMT "+}\r\n%s\r\n",
tag, strlen(name), name);
pipe_including_tag(s, tag, 0);
goto done;
}
/* local mailbox */
r = quota_read(&q, NULL, 0);
if (r) goto done;
prot_printf(imapd_out, "* QUOTA ");
prot_printastring(imapd_out, name);
prot_printf(imapd_out, " ");
print_quota_used(imapd_out, &q);
prot_printf(imapd_out, "\r\n");
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
done:
if (r) prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
mboxlist_entry_free(&mbentry);
quota_free(&q);
free(intname);
}
/*
* Perform a GETQUOTAROOT command
*/
static void cmd_getquotaroot(const char *tag, const char *name)
{
mbentry_t *mbentry = NULL;
struct mailbox *mailbox = NULL;
int myrights;
int r, doclose = 0;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(tag, name, intname, &mbentry);
if (r == IMAP_MAILBOX_MOVED) {
free(intname);
return;
}
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
struct backend *s;
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!s) r = IMAP_SERVER_UNAVAILABLE;
imapd_check(s, 0);
if (!r) {
prot_printf(s->out, "%s Getquotaroot {" SIZE_T_FMT "+}\r\n%s\r\n",
tag, strlen(name), name);
pipe_including_tag(s, tag, 0);
} else {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
}
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
mboxlist_entry_free(&mbentry);
/* local mailbox */
if (!r) {
r = mailbox_open_irl(intname, &mailbox);
if (!r) {
doclose = 1;
myrights = cyrus_acl_myrights(imapd_authstate, mailbox->acl);
}
}
if (!r) {
if (!imapd_userisadmin && !(myrights & ACL_READ)) {
r = (myrights & ACL_LOOKUP) ?
IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT;
}
}
if (!r) {
prot_printf(imapd_out, "* QUOTAROOT ");
prot_printastring(imapd_out, name);
if (mailbox->quotaroot) {
struct quota q;
char *extname = mboxname_to_external(mailbox->quotaroot, &imapd_namespace, imapd_userid);
prot_printf(imapd_out, " ");
prot_printastring(imapd_out, extname);
quota_init(&q, mailbox->quotaroot);
r = quota_read(&q, NULL, 0);
if (!r) {
prot_printf(imapd_out, "\r\n* QUOTA ");
prot_printastring(imapd_out, extname);
prot_putc(' ', imapd_out);
print_quota_used(imapd_out, &q);
}
quota_free(&q);
free(extname);
}
prot_printf(imapd_out, "\r\n");
}
if (doclose) mailbox_close(&mailbox);
free(intname);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
return;
}
imapd_check(NULL, 0);
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
/*
* Parse and perform a SETQUOTA command
* The command has been parsed up to the resource list
*/
void cmd_setquota(const char *tag, const char *quotaroot)
{
quota_t newquotas[QUOTA_NUMRESOURCES];
int res;
int c;
int force = 0;
static struct buf arg;
int r;
mbentry_t *mbentry = NULL;
char *intname = NULL;
if (!imapd_userisadmin && !imapd_userisproxyadmin) {
/* need to allow proxies so that mailbox moves can set initial quota
* roots */
r = IMAP_PERMISSION_DENIED;
goto out;
}
/* are we forcing the creation of a quotaroot by having a leading +? */
if (quotaroot[0] == '+') {
force = 1;
quotaroot++;
}
intname = mboxname_from_external(quotaroot, &imapd_namespace, imapd_userid);
r = mlookup(NULL, NULL, intname, &mbentry);
if (r == IMAP_MAILBOX_NONEXISTENT)
r = 0; /* will create a quotaroot anyway */
if (r)
goto out;
if (mbentry && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
struct backend *s;
char quotarootbuf[MAX_MAILBOX_BUFFER];
snprintf(quotarootbuf, sizeof(quotarootbuf), "%s.", intname);
r = mboxlist_allmbox(quotarootbuf, quota_cb, (void *)mbentry->server, 0);
if (r)
goto out;
imapd_check(NULL, 0);
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!s) {
r = IMAP_SERVER_UNAVAILABLE;
goto out;
}
imapd_check(s, 0);
prot_printf(s->out, "%s Setquota ", tag);
prot_printstring(s->out, quotaroot);
prot_putc(' ', s->out);
pipe_command(s, 0);
pipe_including_tag(s, tag, 0);
free(intname);
return;
}
mboxlist_entry_free(&mbentry);
/* local mailbox */
/* Now parse the arguments as a setquota_list */
c = prot_getc(imapd_in);
if (c != '(') goto badlist;
for (res = 0 ; res < QUOTA_NUMRESOURCES ; res++)
newquotas[res] = QUOTA_UNLIMITED;
for (;;) {
/* XXX - limit is actually stored in an int value */
int32_t limit = 0;
c = getword(imapd_in, &arg);
if ((c == ')') && !arg.s[0]) break;
if (c != ' ') goto badlist;
res = quota_name_to_resource(arg.s);
if (res < 0) {
r = IMAP_UNSUPPORTED_QUOTA;
goto out;
}
c = getsint32(imapd_in, &limit);
/* note: we accept >= 0 according to rfc2087,
* and also -1 to fix Bug #3559 */
if (limit < -1) goto badlist;
newquotas[res] = limit;
if (c == ')') break;
else if (c != ' ') goto badlist;
}
c = prot_getc(imapd_in);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out, "%s BAD Unexpected extra arguments to SETQUOTA\r\n", tag);
eatline(imapd_in, c);
return;
}
r = mboxlist_setquotas(intname, newquotas, force);
imapd_check(NULL, 0);
out:
mboxlist_entry_free(&mbentry);
free(intname);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
return;
}
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
return;
badlist:
prot_printf(imapd_out, "%s BAD Invalid quota list in Setquota\r\n", tag);
eatline(imapd_in, c);
free(intname);
}
#ifdef HAVE_SSL
/*
* this implements the STARTTLS command, as described in RFC 2595.
* one caveat: it assumes that no external layer is currently present.
* if a client executes this command, information about the external
* layer that was passed on the command line is disgarded. this should
* be fixed.
*/
/* imaps - whether this is an imaps transaction or not */
static void cmd_starttls(char *tag, int imaps)
{
int result;
int *layerp;
char *auth_id;
sasl_ssf_t ssf;
/* SASL and openssl have different ideas about whether ssf is signed */
layerp = (int *) &ssf;
if (imapd_starttls_done == 1)
{
prot_printf(imapd_out, "%s NO TLS already active\r\n", tag);
return;
}
result=tls_init_serverengine("imap",
5, /* depth to verify */
!imaps, /* can client auth? */
NULL);
if (result == -1) {
syslog(LOG_ERR, "error initializing TLS");
if (imaps == 0) {
prot_printf(imapd_out, "%s NO Error initializing TLS\r\n", tag);
} else {
shut_down(0);
}
return;
}
if (imaps == 0)
{
prot_printf(imapd_out, "%s OK Begin TLS negotiation now\r\n", tag);
/* must flush our buffers before starting tls */
prot_flush(imapd_out);
}
result=tls_start_servertls(0, /* read */
1, /* write */
imaps ? 180 : imapd_timeout,
layerp,
&auth_id,
&tls_conn);
/* if error */
if (result==-1) {
if (imaps == 0) {
prot_printf(imapd_out, "%s NO Starttls negotiation failed\r\n", tag);
syslog(LOG_NOTICE, "STARTTLS negotiation failed: %s", imapd_clienthost);
return;
} else {
syslog(LOG_NOTICE, "imaps TLS negotiation failed: %s", imapd_clienthost);
shut_down(0);
}
}
/* tell SASL about the negotiated layer */
result = sasl_setprop(imapd_saslconn, SASL_SSF_EXTERNAL, &ssf);
if (result == SASL_OK) {
saslprops.ssf = ssf;
result = sasl_setprop(imapd_saslconn, SASL_AUTH_EXTERNAL, auth_id);
}
if (result != SASL_OK) {
syslog(LOG_NOTICE, "sasl_setprop() failed: cmd_starttls()");
if (imaps == 0) {
fatal("sasl_setprop() failed: cmd_starttls()", EC_TEMPFAIL);
} else {
shut_down(0);
}
}
if(saslprops.authid) {
free(saslprops.authid);
saslprops.authid = NULL;
}
if(auth_id)
saslprops.authid = xstrdup(auth_id);
/* tell the prot layer about our new layers */
prot_settls(imapd_in, tls_conn);
prot_settls(imapd_out, tls_conn);
imapd_starttls_done = 1;
imapd_tls_required = 0;
#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
imapd_tls_comp = (void *) SSL_get_current_compression(tls_conn);
#endif
}
#else
void cmd_starttls(char *tag __attribute__((unused)),
int imaps __attribute__((unused)))
{
fatal("cmd_starttls() executed, but starttls isn't implemented!",
EC_SOFTWARE);
}
#endif // (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
static int parse_statusitems(unsigned *statusitemsp, const char **errstr)
{
static struct buf arg;
unsigned statusitems = 0;
int c;
int hasconv = config_getswitch(IMAPOPT_CONVERSATIONS);
c = prot_getc(imapd_in);
if (c != '(') return EOF;
c = getword(imapd_in, &arg);
if (arg.s[0] == '\0') return EOF;
for (;;) {
lcase(arg.s);
if (!strcmp(arg.s, "messages")) {
statusitems |= STATUS_MESSAGES;
}
else if (!strcmp(arg.s, "recent")) {
statusitems |= STATUS_RECENT;
}
else if (!strcmp(arg.s, "uidnext")) {
statusitems |= STATUS_UIDNEXT;
}
else if (!strcmp(arg.s, "uidvalidity")) {
statusitems |= STATUS_UIDVALIDITY;
}
else if (!strcmp(arg.s, "unseen")) {
statusitems |= STATUS_UNSEEN;
}
else if (!strcmp(arg.s, "highestmodseq")) {
statusitems |= STATUS_HIGHESTMODSEQ;
}
else if (hasconv && !strcmp(arg.s, "xconvexists")) {
statusitems |= STATUS_XCONVEXISTS;
}
else if (hasconv && !strcmp(arg.s, "xconvunseen")) {
statusitems |= STATUS_XCONVUNSEEN;
}
else if (hasconv && !strcmp(arg.s, "xconvmodseq")) {
statusitems |= STATUS_XCONVMODSEQ;
}
else {
static char buf[200];
snprintf(buf, 200, "Invalid Status attributes %s", arg.s);
*errstr = buf;
return EOF;
}
if (c == ' ') c = getword(imapd_in, &arg);
else break;
}
if (c != ')') {
*errstr = "Missing close parenthesis in Status";
return EOF;
}
c = prot_getc(imapd_in);
/* success */
*statusitemsp = statusitems;
return c;
}
static int print_statusline(const char *extname, unsigned statusitems,
struct statusdata *sd)
{
int sepchar;
prot_printf(imapd_out, "* STATUS ");
prot_printastring(imapd_out, extname);
prot_printf(imapd_out, " ");
sepchar = '(';
if (statusitems & STATUS_MESSAGES) {
prot_printf(imapd_out, "%cMESSAGES %u", sepchar, sd->messages);
sepchar = ' ';
}
if (statusitems & STATUS_RECENT) {
prot_printf(imapd_out, "%cRECENT %u", sepchar, sd->recent);
sepchar = ' ';
}
if (statusitems & STATUS_UIDNEXT) {
prot_printf(imapd_out, "%cUIDNEXT %u", sepchar, sd->uidnext);
sepchar = ' ';
}
if (statusitems & STATUS_UIDVALIDITY) {
prot_printf(imapd_out, "%cUIDVALIDITY %u", sepchar, sd->uidvalidity);
sepchar = ' ';
}
if (statusitems & STATUS_UNSEEN) {
prot_printf(imapd_out, "%cUNSEEN %u", sepchar, sd->unseen);
sepchar = ' ';
}
if (statusitems & STATUS_HIGHESTMODSEQ) {
prot_printf(imapd_out, "%cHIGHESTMODSEQ " MODSEQ_FMT,
sepchar, sd->highestmodseq);
sepchar = ' ';
}
if (statusitems & STATUS_XCONVEXISTS) {
prot_printf(imapd_out, "%cXCONVEXISTS %u", sepchar, sd->xconv.exists);
sepchar = ' ';
}
if (statusitems & STATUS_XCONVUNSEEN) {
prot_printf(imapd_out, "%cXCONVUNSEEN %u", sepchar, sd->xconv.unseen);
sepchar = ' ';
}
if (statusitems & STATUS_XCONVMODSEQ) {
prot_printf(imapd_out, "%cXCONVMODSEQ " MODSEQ_FMT, sepchar, sd->xconv.modseq);
sepchar = ' ';
}
prot_printf(imapd_out, ")\r\n");
return 0;
}
static int imapd_statusdata(const char *mailboxname, unsigned statusitems,
struct statusdata *sd)
{
int r;
struct conversations_state *state = NULL;
if (!(statusitems & STATUS_CONVITEMS)) goto nonconv;
statusitems &= ~STATUS_CONVITEMS; /* strip them for the regular lookup */
/* use the existing state if possible */
state = conversations_get_mbox(mailboxname);
/* otherwise fetch a new one! */
if (!state) {
if (global_conversations) {
conversations_abort(&global_conversations);
global_conversations = NULL;
}
r = conversations_open_mbox(mailboxname, &state);
if (r) {
/* maybe the mailbox doesn't even have conversations - just ignore */
goto nonconv;
}
global_conversations = state;
}
r = conversation_getstatus(state, mailboxname, &sd->xconv);
if (r) return r;
nonconv:
/* use the index status if we can so we get the 'alive' Recent count */
if (!strcmpsafe(mailboxname, index_mboxname(imapd_index)) && imapd_index->mailbox)
return index_status(imapd_index, sd);
/* fall back to generic lookup */
return status_lookup(mailboxname, imapd_userid, statusitems, sd);
}
/*
* Parse and perform a STATUS command
* The command has been parsed up to the attribute list
*/
static void cmd_status(char *tag, char *name)
{
int c;
unsigned statusitems = 0;
const char *errstr = "Bad status string";
mbentry_t *mbentry = NULL;
struct statusdata sdata = STATUSDATA_INIT;
int r = 0;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(tag, name, intname, &mbentry);
if (r == IMAP_MAILBOX_MOVED) {
/* Eat the argument */
eatline(imapd_in, prot_getc(imapd_in));
free(intname);
return;
}
if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
if (supports_referrals
&& config_getswitch(IMAPOPT_PROXYD_ALLOW_STATUS_REFERRAL)) {
imapd_refer(tag, mbentry->server, name);
/* Eat the argument */
eatline(imapd_in, prot_getc(imapd_in));
}
else {
struct backend *s;
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!s) r = IMAP_SERVER_UNAVAILABLE;
imapd_check(s, 0);
if (!r) {
prot_printf(s->out, "%s Status {" SIZE_T_FMT "+}\r\n%s ", tag,
strlen(name), name);
if (!pipe_command(s, 65536)) {
pipe_including_tag(s, tag, 0);
}
} else {
eatline(imapd_in, prot_getc(imapd_in));
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
}
}
goto done;
}
/* local mailbox */
imapd_check(NULL, 0);
c = parse_statusitems(&statusitems, &errstr);
if (c == EOF) {
prot_printf(imapd_out, "%s BAD %s\r\n", tag, errstr);
goto done;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Status\r\n", tag);
eatline(imapd_in, c);
goto done;
}
/* check permissions */
if (!r) {
int myrights = cyrus_acl_myrights(imapd_authstate, mbentry->acl);
if (!(myrights & ACL_READ)) {
r = (imapd_userisadmin || (myrights & ACL_LOOKUP)) ?
IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT;
}
}
if (!r) r = imapd_statusdata(intname, statusitems, &sdata);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(r));
}
else {
print_statusline(name, statusitems, &sdata);
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
done:
if (global_conversations) {
conversations_abort(&global_conversations);
global_conversations = NULL;
}
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
/* Callback for cmd_namespace to be passed to mboxlist_findall.
* For each top-level mailbox found, print a bit of the response
* if it is a shared namespace. The rock is used as an integer in
* order to ensure the namespace response is correct on a server with
* no shared namespace.
*/
static int namespacedata(struct findall_data *data, void *rock)
{
if (!data) return 0;
int* sawone = (int*) rock;
switch (data->mb_category) {
case MBNAME_INBOX:
case MBNAME_ALTINBOX:
case MBNAME_ALTPREFIX:
sawone[NAMESPACE_INBOX] = 1;
break;
case MBNAME_OTHERUSER:
sawone[NAMESPACE_USER] = 1;
break;
case MBNAME_SHARED:
sawone[NAMESPACE_SHARED] = 1;
break;
}
return 0;
}
/*
* Print out a response to the NAMESPACE command defined by
* RFC 2342.
*/
static void cmd_namespace(char* tag)
{
int sawone[3] = {0, 0, 0};
char* pattern;
if (SLEEZY_NAMESPACE) {
if (strlen(imapd_userid) + 5 >= MAX_MAILBOX_BUFFER)
sawone[NAMESPACE_INBOX] = 0;
else {
char *inbox = mboxname_user_mbox(imapd_userid, NULL);
sawone[NAMESPACE_INBOX] =
!mboxlist_lookup(inbox, NULL, NULL);
free(inbox);
}
sawone[NAMESPACE_USER] = imapd_userisadmin ? 1 : imapd_namespace.accessible[NAMESPACE_USER];
sawone[NAMESPACE_SHARED] = imapd_userisadmin ? 1 : imapd_namespace.accessible[NAMESPACE_SHARED];
} else {
pattern = xstrdup("%");
/* now find all the exciting toplevel namespaces -
* we're using internal names here
*/
mboxlist_findall(NULL, pattern, imapd_userisadmin, imapd_userid,
imapd_authstate, namespacedata, (void*) sawone);
free(pattern);
}
prot_printf(imapd_out, "* NAMESPACE");
if (sawone[NAMESPACE_INBOX]) {
prot_printf(imapd_out, " ((\"%s\" \"%c\"))",
imapd_namespace.prefix[NAMESPACE_INBOX],
imapd_namespace.hier_sep);
} else {
prot_printf(imapd_out, " NIL");
}
if (sawone[NAMESPACE_USER]) {
prot_printf(imapd_out, " ((\"%s\" \"%c\"))",
imapd_namespace.prefix[NAMESPACE_USER],
imapd_namespace.hier_sep);
} else {
prot_printf(imapd_out, " NIL");
}
if (sawone[NAMESPACE_SHARED]) {
prot_printf(imapd_out, " ((\"%s\" \"%c\"))",
imapd_namespace.prefix[NAMESPACE_SHARED],
imapd_namespace.hier_sep);
} else {
prot_printf(imapd_out, " NIL");
}
prot_printf(imapd_out, "\r\n");
imapd_check(NULL, 0);
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
static int parsecreateargs(struct dlist **extargs)
{
int c;
static struct buf arg, val;
struct dlist *res;
struct dlist *sub;
char *p;
const char *name;
res = dlist_newkvlist(NULL, "CREATE");
c = prot_getc(imapd_in);
if (c == '(') {
/* new style RFC4466 arguments */
do {
c = getword(imapd_in, &arg);
name = ucase(arg.s);
if (c != ' ') goto fail;
c = prot_getc(imapd_in);
if (c == '(') {
/* fun - more lists! */
sub = dlist_newlist(res, name);
do {
c = getword(imapd_in, &val);
dlist_setatom(sub, name, val.s);
} while (c == ' ');
if (c != ')') goto fail;
c = prot_getc(imapd_in);
}
else {
prot_ungetc(c, imapd_in);
c = getword(imapd_in, &val);
dlist_setatom(res, name, val.s);
}
} while (c == ' ');
if (c != ')') goto fail;
c = prot_getc(imapd_in);
}
else {
prot_ungetc(c, imapd_in);
c = getword(imapd_in, &arg);
if (c == EOF) goto fail;
p = strchr(arg.s, '!');
if (p) {
/* with a server */
*p = '\0';
dlist_setatom(res, "SERVER", arg.s);
dlist_setatom(res, "PARTITION", p+1);
}
else {
dlist_setatom(res, "PARTITION", arg.s);
}
}
*extargs = res;
return c;
fail:
dlist_free(&res);
return EOF;
}
/*
* Parse annotate fetch data.
*
* This is a generic routine which parses just the annotation data.
* Any surrounding command text must be parsed elsewhere, ie,
* GETANNOTATION, FETCH.
*/
static int parse_annotate_fetch_data(const char *tag,
int permessage_flag,
strarray_t *entries,
strarray_t *attribs)
{
int c;
static struct buf arg;
c = prot_getc(imapd_in);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation entry\r\n", tag);
goto baddata;
}
else if (c == '(') {
/* entry list */
do {
if (permessage_flag)
c = getastring(imapd_in, imapd_out, &arg);
else
c = getqstring(imapd_in, imapd_out, &arg);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation entry\r\n", tag);
goto baddata;
}
/* add the entry to the list */
strarray_append(entries, arg.s);
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close paren in annotation entry list \r\n",
tag);
goto baddata;
}
c = prot_getc(imapd_in);
}
else {
/* single entry -- add it to the list */
prot_ungetc(c, imapd_in);
if (permessage_flag)
c = getastring(imapd_in, imapd_out, &arg);
else
c = getqstring(imapd_in, imapd_out, &arg);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation entry\r\n", tag);
goto baddata;
}
strarray_append(entries, arg.s);
}
if (c != ' ' || (c = prot_getc(imapd_in)) == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation attribute(s)\r\n", tag);
goto baddata;
}
if (c == '(') {
/* attrib list */
do {
if (permessage_flag)
c = getastring(imapd_in, imapd_out, &arg);
else
c = getqstring(imapd_in, imapd_out, &arg);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation attribute(s)\r\n", tag);
goto baddata;
}
/* add the attrib to the list */
strarray_append(attribs, arg.s);
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close paren in "
"annotation attribute list\r\n", tag);
goto baddata;
}
c = prot_getc(imapd_in);
}
else {
/* single attrib */
prot_ungetc(c, imapd_in);
if (permessage_flag)
c = getastring(imapd_in, imapd_out, &arg);
else
c = getqstring(imapd_in, imapd_out, &arg);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation attribute\r\n", tag);
goto baddata;
}
strarray_append(attribs, arg.s);
}
return c;
baddata:
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
}
/*
* Parse either a single string or a (bracketed) list of strings.
* This is used up to three times in the GETMETADATA command.
*/
static int parse_metadata_string_or_list(const char *tag,
strarray_t *entries,
int *is_list)
{
int c;
static struct buf arg;
// Assume by default the arguments are a list of entries,
// until proven otherwise.
if (is_list) *is_list = 1;
c = prot_getc(imapd_in);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing metadata entry\r\n", tag);
goto baddata;
}
else if (c == '\r') {
return c;
}
else if (c == '(') {
/* entry list */
do {
c = getastring(imapd_in, imapd_out, &arg);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing metadata entry\r\n", tag);
goto baddata;
}
/* add the entry to the list */
strarray_append(entries, arg.s);
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close paren in metadata entry list \r\n",
tag);
goto baddata;
}
if (is_list) *is_list = 0;
c = prot_getc(imapd_in);
}
else {
/* single entry -- add it to the list */
prot_ungetc(c, imapd_in);
c = getastring(imapd_in, imapd_out, &arg);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing metadata entry\r\n", tag);
goto baddata;
}
strarray_append(entries, arg.s);
// It is only not a list if there are no wildcards
if (!strchr(arg.s, '*') && !strchr(arg.s, '%')) {
// Not a list
if (is_list) *is_list = 0;
}
}
if (c == ' ' || c == '\r' || c == ')') return c;
baddata:
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
}
/*
* Parse annotate store data.
*
* This is a generic routine which parses just the annotation data.
* Any surrounding command text must be parsed elsewhere, ie,
* SETANNOTATION, STORE, APPEND.
*
* Also parse RFC5257 per-message annotation store data, which
* is almost identical but differs in that entry names and attrib
* names are astrings rather than strings, and that the whole set
* of data *must* be enclosed in parentheses.
*/
static int parse_annotate_store_data(const char *tag,
int permessage_flag,
struct entryattlist **entryatts)
{
int c, islist = 0;
static struct buf entry, attrib, value;
struct attvaluelist *attvalues = NULL;
*entryatts = NULL;
c = prot_getc(imapd_in);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation entry\r\n", tag);
goto baddata;
}
else if (c == '(') {
/* entry list */
islist = 1;
}
else if (permessage_flag) {
prot_printf(imapd_out,
"%s BAD Missing paren for annotation entry\r\n", tag);
goto baddata;
}
else {
/* single entry -- put the char back */
prot_ungetc(c, imapd_in);
}
do {
/* get entry */
if (permessage_flag)
c = getastring(imapd_in, imapd_out, &entry);
else
c = getqstring(imapd_in, imapd_out, &entry);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation entry\r\n", tag);
goto baddata;
}
/* parse att-value list */
if (c != ' ' || (c = prot_getc(imapd_in)) != '(') {
prot_printf(imapd_out,
"%s BAD Missing annotation attribute-values list\r\n",
tag);
goto baddata;
}
do {
/* get attrib */
if (permessage_flag)
c = getastring(imapd_in, imapd_out, &attrib);
else
c = getqstring(imapd_in, imapd_out, &attrib);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation attribute\r\n", tag);
goto baddata;
}
/* get value */
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing annotation value\r\n", tag);
goto baddata;
}
c = getbnstring(imapd_in, imapd_out, &value);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing annotation value\r\n", tag);
goto baddata;
}
/* add the attrib-value pair to the list */
appendattvalue(&attvalues, attrib.s, &value);
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close paren in annotation "
"attribute-values list\r\n", tag);
goto baddata;
}
/* add the entry to the list */
appendentryatt(entryatts, entry.s, attvalues);
attvalues = NULL;
c = prot_getc(imapd_in);
} while (c == ' ');
if (islist) {
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close paren in annotation entry list \r\n",
tag);
goto baddata;
}
c = prot_getc(imapd_in);
}
return c;
baddata:
if (attvalues) freeattvalues(attvalues);
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
}
/*
* Parse metadata store data.
*
* This is a generic routine which parses just the annotation data.
* Any surrounding command text must be parsed elsewhere, ie,
* SETANNOTATION, STORE, APPEND.
*/
static int parse_metadata_store_data(const char *tag,
struct entryattlist **entryatts)
{
int c;
const char *name;
const char *att;
static struct buf entry, value;
struct attvaluelist *attvalues = NULL;
struct entryattlist *entryp;
int need_add;
*entryatts = NULL;
c = prot_getc(imapd_in);
if (c != '(') {
prot_printf(imapd_out,
"%s BAD Missing metadata entry list\r\n", tag);
goto baddata;
}
do {
/* get entry */
c = getastring(imapd_in, imapd_out, &entry);
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing metadata entry\r\n", tag);
goto baddata;
}
lcase(entry.s);
/* get value */
c = getbnstring(imapd_in, imapd_out, &value);
if (c == EOF) {
prot_printf(imapd_out,
"%s BAD Missing metadata value\r\n", tag);
goto baddata;
}
if (!strncmp(entry.s, "/private", 8) &&
(entry.s[8] == '\0' || entry.s[8] == '/')) {
att = "value.priv";
name = entry.s + 8;
}
else if (!strncmp(entry.s, "/shared", 7) &&
(entry.s[7] == '\0' || entry.s[7] == '/')) {
att = "value.shared";
name = entry.s + 7;
}
else {
prot_printf(imapd_out,
"%s BAD entry must begin with /shared or /private\r\n",
tag);
goto baddata;
}
need_add = 1;
for (entryp = *entryatts; entryp; entryp = entryp->next) {
if (strcmp(entryp->entry, name)) continue;
/* it's a match, have to append! */
appendattvalue(&entryp->attvalues, att, &value);
need_add = 0;
break;
}
if (need_add) {
appendattvalue(&attvalues, att, &value);
appendentryatt(entryatts, name, attvalues);
attvalues = NULL;
}
} while (c == ' ');
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close paren in annotation entry list \r\n",
tag);
goto baddata;
}
c = prot_getc(imapd_in);
return c;
baddata:
if (attvalues) freeattvalues(attvalues);
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
}
static void getannotation_response(const char *mboxname,
uint32_t uid
__attribute__((unused)),
const char *entry,
struct attvaluelist *attvalues,
void *rock __attribute__((unused)))
{
int sep = '(';
struct attvaluelist *l;
char *extname = *mboxname ?
mboxname_to_external(mboxname, &imapd_namespace, imapd_userid) :
xstrdup(""); /* server annotation */
prot_printf(imapd_out, "* ANNOTATION ");
prot_printastring(imapd_out, extname);
prot_putc(' ', imapd_out);
prot_printstring(imapd_out, entry);
prot_putc(' ', imapd_out);
for (l = attvalues ; l ; l = l->next) {
prot_putc(sep, imapd_out);
sep = ' ';
prot_printstring(imapd_out, l->attrib);
prot_putc(' ', imapd_out);
prot_printmap(imapd_out, l->value.s, l->value.len);
}
prot_printf(imapd_out, ")\r\n");
free(extname);
}
struct annot_fetch_rock
{
strarray_t *entries;
strarray_t *attribs;
annotate_fetch_cb_t callback;
void *cbrock;
};
static int annot_fetch_cb(annotate_state_t *astate, void *rock)
{
struct annot_fetch_rock *arock = rock;
return annotate_state_fetch(astate, arock->entries, arock->attribs,
arock->callback, arock->cbrock);
}
struct annot_store_rock
{
struct entryattlist *entryatts;
};
static int annot_store_cb(annotate_state_t *astate, void *rock)
{
struct annot_store_rock *arock = rock;
return annotate_state_store(astate, arock->entryatts);
}
/*
* Common code used to apply a function to every mailbox which matches
* a mailbox pattern, with an annotate_state_t* set up to point to the
* mailbox.
*/
struct apply_rock {
annotate_state_t *state;
int (*proc)(annotate_state_t *, void *data);
void *data;
char lastname[MAX_MAILBOX_PATH+1];
unsigned int nseen;
};
static int apply_cb(struct findall_data *data, void* rock)
{
if (!data) return 0;
struct apply_rock *arock = (struct apply_rock *)rock;
annotate_state_t *state = arock->state;
int r;
/* Suppress any output of a partial match */
if (!data->mbname)
return 0;
strlcpy(arock->lastname, mbname_intname(data->mbname), sizeof(arock->lastname));
// malloc extra-long to have room for pattern shenanigans later
/* NOTE: this is a fricking horrible abuse of layers. We'll be passing the
* extname less horribly one day */
const char *extname = mbname_extname(data->mbname, &imapd_namespace, imapd_userid);
mbentry_t *backdoor = (mbentry_t *)data->mbentry;
backdoor->ext_name = xmalloc(strlen(extname)+1);
strcpy(backdoor->ext_name, extname);
r = annotate_state_set_mailbox_mbe(state, data->mbentry);
if (r) return r;
r = arock->proc(state, arock->data);
arock->nseen++;
return r;
}
static int apply_mailbox_pattern(annotate_state_t *state,
const char *pattern,
int (*proc)(annotate_state_t *, void *),
void *data)
{
struct apply_rock arock;
int r = 0;
memset(&arock, 0, sizeof(arock));
arock.state = state;
arock.proc = proc;
arock.data = data;
r = mboxlist_findall(&imapd_namespace,
pattern,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid,
imapd_authstate,
apply_cb, &arock);
if (!r && !arock.nseen)
r = IMAP_MAILBOX_NONEXISTENT;
return r;
}
static int apply_mailbox_array(annotate_state_t *state,
const strarray_t *mboxes,
int (*proc)(annotate_state_t *, void *),
void *rock)
{
int i;
mbentry_t *mbentry = NULL;
char *intname = NULL;
int r = 0;
for (i = 0 ; i < mboxes->count ; i++) {
intname = mboxname_from_external(strarray_nth(mboxes, i), &imapd_namespace, imapd_userid);
r = mboxlist_lookup(intname, &mbentry, NULL);
if (r)
break;
r = annotate_state_set_mailbox_mbe(state, mbentry);
if (r)
break;
r = proc(state, rock);
if (r)
break;
mboxlist_entry_free(&mbentry);
free(intname);
intname = NULL;
}
mboxlist_entry_free(&mbentry);
free(intname);
return r;
}
/*
* Perform a GETANNOTATION command
*
* The command has been parsed up to the entries
*/
static void cmd_getannotation(const char *tag, char *mboxpat)
{
int c, r = 0;
strarray_t entries = STRARRAY_INITIALIZER;
strarray_t attribs = STRARRAY_INITIALIZER;
annotate_state_t *astate = NULL;
c = parse_annotate_fetch_data(tag, /*permessage_flag*/0, &entries, &attribs);
if (c == EOF) {
eatline(imapd_in, c);
goto freeargs;
}
/* check for CRLF */
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Getannotation\r\n",
tag);
eatline(imapd_in, c);
goto freeargs;
}
astate = annotate_state_new();
annotate_state_set_auth(astate,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate);
if (!*mboxpat) {
r = annotate_state_set_server(astate);
if (!r)
r = annotate_state_fetch(astate, &entries, &attribs,
getannotation_response, NULL);
}
else {
struct annot_fetch_rock arock;
arock.entries = &entries;
arock.attribs = &attribs;
arock.callback = getannotation_response;
arock.cbrock = NULL;
r = apply_mailbox_pattern(astate, mboxpat, annot_fetch_cb, &arock);
}
/* we didn't write anything */
annotate_state_abort(&astate);
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n",
tag, error_message(IMAP_OK_COMPLETED));
}
freeargs:
strarray_fini(&entries);
strarray_fini(&attribs);
}
static void getmetadata_response(const char *mboxname,
uint32_t uid __attribute__((unused)),
const char *entry,
struct attvaluelist *attvalues,
void *rock)
{
struct getmetadata_options *opts = (struct getmetadata_options *)rock;
if (strcmpsafe(mboxname, opts->lastname) || !entry) {
if (opts->items.count) {
char *extname = NULL;
size_t i;
if (opts->lastname)
extname = mboxname_to_external(opts->lastname, &imapd_namespace, imapd_userid);
else
extname = xstrdup("");
prot_printf(imapd_out, "* METADATA ");
prot_printastring(imapd_out, extname);
prot_putc(' ', imapd_out);
for (i = 0; i + 1 < opts->items.count; i+=2) {
prot_putc(i ? ' ' : '(', imapd_out);
const struct buf *key = bufarray_nth(&opts->items, i);
prot_printmap(imapd_out, key->s, key->len);
prot_putc(' ', imapd_out);
const struct buf *val = bufarray_nth(&opts->items, i+1);
prot_printmap(imapd_out, val->s, val->len);
}
prot_printf(imapd_out, ")\r\n");
free(extname);
}
free(opts->lastname);
opts->lastname = xstrdupnull(mboxname);
bufarray_fini(&opts->items);
}
struct attvaluelist *l;
struct buf buf = BUF_INITIALIZER;
for (l = attvalues ; l ; l = l->next) {
/* size check */
if (opts->maxsize && l->value.len >= opts->maxsize) {
if (l->value.len > opts->biggest) opts->biggest = l->value.len;
continue;
}
/* check if it's a value we print... */
buf_reset(&buf);
if (!strcmp(l->attrib, "value.shared"))
buf_appendcstr(&buf, "/shared");
else if (!strcmp(l->attrib, "value.priv"))
buf_appendcstr(&buf, "/private");
else
continue;
buf_appendcstr(&buf, entry);
bufarray_append(&opts->items, &buf);
bufarray_append(&opts->items, &l->value);
}
buf_free(&buf);
}
static int parse_getmetadata_options(const strarray_t *sa,
struct getmetadata_options *opts)
{
int i;
int n = 0;
struct getmetadata_options dummy = OPTS_INITIALIZER;
if (!opts) opts = &dummy;
for (i = 0 ; i < sa->count ; i+=2) {
const char *option = sa->data[i];
const char *value = sa->data[i+1];
if (!value)
return -1;
if (!strcasecmp(option, "MAXSIZE")) {
char *end = NULL;
/* we add one so that it's "less than" maxsize
* and zero works but is still true */
opts->maxsize = strtoul(value, &end, 10) + 1;
if (!end || *end || end == value)
return -1;
n++;
}
else if (!strcasecmp(option, "DEPTH")) {
if (!strcmp(value, "0"))
opts->depth = 0;
else if (!strcmp(value, "1"))
opts->depth = 1;
else if (!strcasecmp(value, "infinity"))
opts->depth = -1;
else
return -1;
n++;
}
else {
return 0;
}
}
return n;
}
static int _metadata_to_annotate(const strarray_t *entries,
strarray_t *newa, strarray_t *newe,
const char *tag, int depth)
{
int i;
int have_shared = 0;
int have_private = 0;
/* we need to rewrite the entries and attribs to match the way that
* the old annotation system works. */
for (i = 0 ; i < entries->count ; i++) {
char *ent = entries->data[i];
char entry[MAX_MAILBOX_NAME+1];
lcase(ent);
/* there's no way to perfect this - unfortunately - the old style
* syntax doesn't support everything. XXX - will be nice to get
* rid of this... */
if (!strncmp(ent, "/private", 8) &&
(ent[8] == '\0' || ent[8] == '/')) {
xstrncpy(entry, ent + 8, MAX_MAILBOX_NAME);
have_private = 1;
}
else if (!strncmp(ent, "/shared", 7) &&
(ent[7] == '\0' || ent[7] == '/')) {
xstrncpy(entry, ent + 7, MAX_MAILBOX_NAME);
have_shared = 1;
}
else {
if (tag)
prot_printf(imapd_out,
"%s BAD entry must begin with /shared or /private\r\n",
tag);
return IMAP_NO_NOSUCHMSG;
}
strarray_append(newe, entry);
if (depth == 1) {
strncat(entry, "/%", MAX_MAILBOX_NAME);
strarray_append(newe, entry);
}
else if (depth == -1) {
strncat(entry, "/*", MAX_MAILBOX_NAME);
strarray_append(newe, entry);
}
}
if (have_private) strarray_append(newa, "value.priv");
if (have_shared) strarray_append(newa, "value.shared");
return 0;
}
/*
* Perform a GETMETADATA command
*
* The command has been parsed up to the mailbox
*/
static void cmd_getmetadata(const char *tag)
{
int c, r = 0;
strarray_t lists[3] = { STRARRAY_INITIALIZER,
STRARRAY_INITIALIZER,
STRARRAY_INITIALIZER };
int is_list[3] = { 1, 1, 1 };
int nlists = 0;
strarray_t *options = NULL;
strarray_t *mboxes = NULL;
strarray_t *entries = NULL;
strarray_t newe = STRARRAY_INITIALIZER;
strarray_t newa = STRARRAY_INITIALIZER;
struct buf arg1 = BUF_INITIALIZER;
int mbox_is_pattern = 0;
struct getmetadata_options opts = OPTS_INITIALIZER;
annotate_state_t *astate = NULL;
while (nlists < 3)
{
c = parse_metadata_string_or_list(tag, &lists[nlists], &is_list[nlists]);
nlists++;
if (c == '\r' || c == EOF)
break;
}
/* check for CRLF */
if (c == '\r') {
c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Getannotation\r\n",
tag);
eatline(imapd_in, c);
goto freeargs;
}
} else {
// Make sure this line is gone
eatline(imapd_in, c);
}
/*
* We have three strings or lists of strings. Now to figure out
* what's what. We have two complicating factors. First, due to
* a erratum in RFC5464 and our earlier misreading of the document,
* we historically supported specifying the options *after* the
* mailbox name. Second, we have for a few months now supported
* a non-standard extension where a list of mailbox names could
* be supplied instead of just a single one. So we have to apply
* some rules. We support the following syntaxes:
*
* --- no options
* mailbox entry
* mailbox (entries)
* (mailboxes) entry
* (mailboxes) (entries)
*
* --- options in the correct place (per the ABNF in RFC5464)
* (options) mailbox entry
* (options) mailbox (entries)
* (options) (mailboxes) entry
* (options) (mailboxes) (entries)
*
* --- options in the wrong place (per the examples in RFC5464)
* mailbox (options) entry
* mailbox (options) (entries)
* (mailboxes) (options) entry
* (mailboxes) (options) (entries)
*/
if (nlists < 2)
goto missingargs;
entries = &lists[nlists-1]; /* entries always last */
if (nlists == 2) {
/* no options */
mboxes = &lists[0];
mbox_is_pattern = is_list[0];
}
if (nlists == 3) {
/* options, either before or after */
int r0 = (parse_getmetadata_options(&lists[0], NULL) > 0);
int r1 = (parse_getmetadata_options(&lists[1], NULL) > 0);
switch ((r1<<1)|r0) {
case 0:
/* neither are valid options */
goto missingargs;
case 1:
/* (options) (mailboxes) */
options = &lists[0];
mboxes = &lists[1];
mbox_is_pattern = is_list[1];
break;
case 2:
/* (mailboxes) (options) */
mboxes = &lists[0];
mbox_is_pattern = is_list[0];
options = &lists[1];
break;
case 3:
/* both appear like valid options */
prot_printf(imapd_out,
"%s BAD Too many option lists for Getmetadata\r\n",
tag);
eatline(imapd_in, c);
goto freeargs;
}
}
if (options) parse_getmetadata_options(options, &opts);
if (_metadata_to_annotate(entries, &newa, &newe, tag, opts.depth))
goto freeargs;
astate = annotate_state_new();
annotate_state_set_auth(astate,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate);
if (!mboxes->count || !strcmpsafe(mboxes->data[0], NULL)) {
r = annotate_state_set_server(astate);
if (!r)
r = annotate_state_fetch(astate, &newe, &newa,
getmetadata_response, &opts);
}
else {
struct annot_fetch_rock arock;
arock.entries = &newe;
arock.attribs = &newa;
arock.callback = getmetadata_response;
arock.cbrock = &opts;
if (mbox_is_pattern)
r = apply_mailbox_pattern(astate, mboxes->data[0], annot_fetch_cb, &arock);
else
r = apply_mailbox_array(astate, mboxes, annot_fetch_cb, &arock);
}
/* we didn't write anything */
annotate_state_abort(&astate);
getmetadata_response(NULL, 0, NULL, NULL, &opts);
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else if (opts.maxsize && opts.biggest > opts.maxsize) {
prot_printf(imapd_out, "%s OK [METADATA LONGENTRIES %u] %s\r\n",
tag, (unsigned)opts.biggest, error_message(IMAP_OK_COMPLETED));
} else {
prot_printf(imapd_out, "%s OK %s\r\n",
tag, error_message(IMAP_OK_COMPLETED));
}
freeargs:
strarray_fini(&lists[0]);
strarray_fini(&lists[1]);
strarray_fini(&lists[2]);
strarray_fini(&newe);
strarray_fini(&newa);
buf_free(&arg1);
return;
missingargs:
prot_printf(imapd_out, "%s BAD Missing arguments to Getmetadata\r\n", tag);
eatline(imapd_in, c);
goto freeargs;
}
/*
* Perform a SETANNOTATION command
*
* The command has been parsed up to the entry-att list
*/
static void cmd_setannotation(const char *tag, char *mboxpat)
{
int c, r = 0;
struct entryattlist *entryatts = NULL;
annotate_state_t *astate = NULL;
c = parse_annotate_store_data(tag, 0, &entryatts);
if (c == EOF) {
eatline(imapd_in, c);
goto freeargs;
}
/* check for CRLF */
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Setannotation\r\n",
tag);
eatline(imapd_in, c);
goto freeargs;
}
astate = annotate_state_new();
annotate_state_set_auth(astate, imapd_userisadmin,
imapd_userid, imapd_authstate);
if (!r) {
if (!*mboxpat) {
r = annotate_state_set_server(astate);
if (!r)
r = annotate_state_store(astate, entryatts);
}
else {
struct annot_store_rock arock;
arock.entryatts = entryatts;
r = apply_mailbox_pattern(astate, mboxpat, annot_store_cb, &arock);
}
}
if (!r)
annotate_state_commit(&astate);
else
annotate_state_abort(&astate);
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
freeargs:
if (entryatts) freeentryatts(entryatts);
}
/*
* Perform a SETMETADATA command
*
* The command has been parsed up to the entry-att list
*/
static void cmd_setmetadata(const char *tag, char *mboxpat)
{
int c, r = 0;
struct entryattlist *entryatts = NULL;
annotate_state_t *astate = NULL;
c = parse_metadata_store_data(tag, &entryatts);
if (c == EOF) {
eatline(imapd_in, c);
goto freeargs;
}
/* check for CRLF */
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Setmetadata\r\n",
tag);
eatline(imapd_in, c);
goto freeargs;
}
astate = annotate_state_new();
annotate_state_set_auth(astate, imapd_userisadmin,
imapd_userid, imapd_authstate);
if (!r) {
if (!*mboxpat) {
r = annotate_state_set_server(astate);
if (!r)
r = annotate_state_store(astate, entryatts);
}
else {
struct annot_store_rock arock;
arock.entryatts = entryatts;
r = apply_mailbox_pattern(astate, mboxpat, annot_store_cb, &arock);
}
}
if (!r)
r = annotate_state_commit(&astate);
else
annotate_state_abort(&astate);
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
freeargs:
if (entryatts) freeentryatts(entryatts);
return;
}
static void cmd_xrunannotator(const char *tag, const char *sequence,
int usinguid)
{
const char *cmd = usinguid ? "UID Xrunannotator" : "Xrunannotator";
clock_t start = clock();
char mytime[100];
int c, r = 0;
if (backend_current) {
/* remote mailbox */
prot_printf(backend_current->out, "%s %s %s ", tag, cmd, sequence);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
return;
}
/* local mailbox */
/* we're expecting no more arguments */
c = prot_getc(imapd_in);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out, "%s BAD Unexpected extra arguments to %s\r\n", tag, cmd);
eatline(imapd_in, c);
return;
}
r = index_run_annotator(imapd_index, sequence, usinguid,
&imapd_namespace, imapd_userisadmin);
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
if (r)
prot_printf(imapd_out, "%s NO %s (%s sec)\r\n", tag,
error_message(r), mytime);
else
prot_printf(imapd_out, "%s OK %s (%s sec)\r\n", tag,
error_message(IMAP_OK_COMPLETED), mytime);
}
static void cmd_xwarmup(const char *tag)
{
const char *cmd = "Xwarmup";
clock_t start = clock();
char mytime[100];
struct buf arg = BUF_INITIALIZER;
int warmup_flags = 0;
struct seqset *uids = NULL;
/* We deal with the mboxlist API instead of the index_state API or
* mailbox API to avoid the overhead of index_open(), which will
* block while reading all the cyrus.index...we want to be
* non-blocking */
struct mboxlist_entry *mbentry = NULL;
int myrights;
int c, r = 0;
char *intname = NULL;
/* parse arguments: expect <mboxname> '('<warmup-items>')' */
c = getastring(imapd_in, imapd_out, &arg);
if (c != ' ') {
syntax_error:
prot_printf(imapd_out, "%s BAD syntax error in %s\r\n", tag, cmd);
eatline(imapd_in, c);
goto out_noprint;
}
intname = mboxname_from_external(arg.s, &imapd_namespace, imapd_userid);
r = mboxlist_lookup(intname, &mbentry, NULL);
if (r) goto out;
/* Do a permissions check to avoid server DoS opportunity. But we
* only need read permission to warmup a mailbox. Also, be careful
* to avoid telling the client about the existance of mailboxes to
* which he doesn't have LOOKUP rights. */
r = IMAP_PERMISSION_DENIED;
myrights = (mbentry->acl ? cyrus_acl_myrights(imapd_authstate, mbentry->acl) : 0);
if (imapd_userisadmin)
r = 0;
else if (!(myrights & ACL_LOOKUP))
r = IMAP_MAILBOX_NONEXISTENT;
else if (myrights & ACL_READ)
r = 0;
if (r) goto out;
if (mbentry->mbtype & MBTYPE_REMOTE) {
/* remote mailbox */
struct backend *be;
be = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!be) {
r = IMAP_SERVER_UNAVAILABLE;
goto out;
}
prot_printf(be->out, "%s %s %s ", tag, cmd, arg.s);
if (!pipe_command(backend_current, 65536)) {
pipe_including_tag(backend_current, tag, 0);
}
goto out;
}
/* local mailbox */
/* parse the arguments after the mailbox */
c = prot_getc(imapd_in);
if (c != '(') goto syntax_error;
for (;;) {
c = getword(imapd_in, &arg);
if (arg.len) {
if (!strcasecmp(arg.s, "index"))
warmup_flags |= WARMUP_INDEX;
else if (!strcasecmp(arg.s, "conversations"))
warmup_flags |= WARMUP_CONVERSATIONS;
else if (!strcasecmp(arg.s, "annotations"))
warmup_flags |= WARMUP_ANNOTATIONS;
else if (!strcasecmp(arg.s, "folderstatus"))
warmup_flags |= WARMUP_FOLDERSTATUS;
else if (!strcasecmp(arg.s, "search"))
warmup_flags |= WARMUP_SEARCH;
else if (!strcasecmp(arg.s, "uids")) {
if (c != ' ') goto syntax_error;
c = getword(imapd_in, &arg);
if (c == EOF) goto syntax_error;
if (!imparse_issequence(arg.s)) goto syntax_error;
uids = seqset_parse(arg.s, NULL, /*maxval*/0);
if (!uids) goto syntax_error;
}
else if (!strcasecmp(arg.s, "all"))
warmup_flags |= WARMUP_ALL;
else
goto syntax_error;
}
if (c == ')')
break;
if (c != ' ') goto syntax_error;
}
/* we're expecting no more arguments */
c = prot_getc(imapd_in);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto syntax_error;
r = index_warmup(mbentry, warmup_flags, uids);
out:
snprintf(mytime, sizeof(mytime), "%2.3f",
(clock() - start) / (double) CLOCKS_PER_SEC);
if (r)
prot_printf(imapd_out, "%s NO %s (%s sec)\r\n", tag,
error_message(r), mytime);
else
prot_printf(imapd_out, "%s OK %s (%s sec)\r\n", tag,
error_message(IMAP_OK_COMPLETED), mytime);
out_noprint:
mboxlist_entry_free(&mbentry);
free(intname);
buf_free(&arg);
if (uids) seqset_free(uids);
}
static void free_snippetargs(struct snippetargs **sap)
{
while (*sap) {
struct snippetargs *sa = *sap;
*sap = sa->next;
free(sa->mboxname);
free(sa->uids.data);
free(sa);
}
}
static int get_snippetargs(struct snippetargs **sap)
{
int c;
struct snippetargs **prevp = sap;
struct snippetargs *sa = NULL;
struct buf arg = BUF_INITIALIZER;
uint32_t uid;
char *intname = NULL;
c = prot_getc(imapd_in);
if (c != '(') goto syntax_error;
for (;;) {
c = prot_getc(imapd_in);
if (c == ')') break;
if (c != '(') goto syntax_error;
c = getastring(imapd_in, imapd_out, &arg);
if (c != ' ') goto syntax_error;
intname = mboxname_from_external(buf_cstring(&arg), &imapd_namespace, imapd_userid);
/* allocate a new snippetargs */
sa = xzmalloc(sizeof(struct snippetargs));
sa->mboxname = xstrdup(intname);
/* append to the list */
*prevp = sa;
prevp = &sa->next;
c = getuint32(imapd_in, &sa->uidvalidity);
if (c != ' ') goto syntax_error;
c = prot_getc(imapd_in);
if (c != '(') break;
for (;;) {
c = getuint32(imapd_in, &uid);
if (c != ' ' && c != ')') goto syntax_error;
if (sa->uids.count + 1 > sa->uids.alloc) {
sa->uids.alloc += 64;
sa->uids.data = xrealloc(sa->uids.data,
sizeof(uint32_t) * sa->uids.alloc);
}
sa->uids.data[sa->uids.count++] = uid;
if (c == ')') break;
}
c = prot_getc(imapd_in);
if (c != ')') goto syntax_error;
}
c = prot_getc(imapd_in);
if (c != ' ') goto syntax_error;
out:
free(intname);
buf_free(&arg);
return c;
syntax_error:
free_snippetargs(sap);
c = EOF;
goto out;
}
static void cmd_dump(char *tag, char *name, int uid_start)
{
int r = 0;
struct mailbox *mailbox = NULL;
/* administrators only please */
if (!imapd_userisadmin)
r = IMAP_PERMISSION_DENIED;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
if (!r) r = mailbox_open_irl(intname, &mailbox);
if (!r) r = dump_mailbox(tag, mailbox, uid_start, MAILBOX_MINOR_VERSION,
imapd_in, imapd_out, imapd_authstate);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
if (mailbox) mailbox_close(&mailbox);
free(intname);
}
static void cmd_undump(char *tag, char *name)
{
int r = 0;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
/* administrators only please */
if (!imapd_userisadmin)
r = IMAP_PERMISSION_DENIED;
if (!r) r = mlookup(tag, name, intname, NULL);
if (!r) r = undump_mailbox(intname, imapd_in, imapd_out, imapd_authstate);
if (r) {
prot_printf(imapd_out, "%s NO %s%s\r\n",
tag,
(r == IMAP_MAILBOX_NONEXISTENT &&
mboxlist_createmailboxcheck(intname, 0, 0,
imapd_userisadmin,
imapd_userid, imapd_authstate,
NULL, NULL, 0) == 0)
? "[TRYCREATE] " : "", error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
free(intname);
}
static int getresult(struct protstream *p, const char *tag)
{
char buf[4096];
char *str = (char *) buf;
while(1) {
if (!prot_fgets(str, sizeof(buf), p)) {
return IMAP_SERVER_UNAVAILABLE;
}
if (!strncmp(str, tag, strlen(tag))) {
str += strlen(tag);
if(!*str) {
/* We got a tag, but no response */
return IMAP_SERVER_UNAVAILABLE;
}
str++;
if (!strncasecmp(str, "OK ", 3)) { return 0; }
if (!strncasecmp(str, "NO ", 3)) { return IMAP_REMOTE_DENIED; }
return IMAP_SERVER_UNAVAILABLE; /* huh? */
}
/* skip this line, we don't really care */
}
}
/* given 2 protstreams and a mailbox, gets the acl and then wipes it */
static int trashacl(struct protstream *pin, struct protstream *pout,
char *mailbox)
{
int i=0, j=0;
char tagbuf[128];
int c; /* getword() returns an int */
struct buf cmd, tmp, user;
int r = 0;
memset(&cmd, 0, sizeof(struct buf));
memset(&tmp, 0, sizeof(struct buf));
memset(&user, 0, sizeof(struct buf));
prot_printf(pout, "ACL0 GETACL {" SIZE_T_FMT "+}\r\n%s\r\n",
strlen(mailbox), mailbox);
while(1) {
c = prot_getc(pin);
if (c != '*') {
prot_ungetc(c, pin);
r = getresult(pin, "ACL0");
break;
}
c = prot_getc(pin); /* skip SP */
c = getword(pin, &cmd);
if (c == EOF) {
r = IMAP_SERVER_UNAVAILABLE;
break;
}
if (!strncmp(cmd.s, "ACL", 3)) {
while(c != '\n') {
/* An ACL response, we should send a DELETEACL command */
c = getastring(pin, pout, &tmp);
if (c == EOF) {
r = IMAP_SERVER_UNAVAILABLE;
goto cleanup;
}
if(c == '\r') {
c = prot_getc(pin);
if(c != '\n') {
r = IMAP_SERVER_UNAVAILABLE;
goto cleanup;
}
}
if(c == '\n') break; /* end of * ACL */
c = getastring(pin, pout, &user);
if (c == EOF) {
r = IMAP_SERVER_UNAVAILABLE;
goto cleanup;
}
snprintf(tagbuf, sizeof(tagbuf), "ACL%d", ++i);
prot_printf(pout, "%s DELETEACL {" SIZE_T_FMT "+}\r\n%s"
" {" SIZE_T_FMT "+}\r\n%s\r\n",
tagbuf, strlen(mailbox), mailbox,
strlen(user.s), user.s);
if(c == '\r') {
c = prot_getc(pin);
if(c != '\n') {
r = IMAP_SERVER_UNAVAILABLE;
goto cleanup;
}
}
/* if the next character is \n, we'll exit the loop */
}
}
else {
/* skip this line, we don't really care */
eatline(pin, c);
}
}
cleanup:
/* Now cleanup after all the DELETEACL commands */
if(!r) {
while(j < i) {
snprintf(tagbuf, sizeof(tagbuf), "ACL%d", ++j);
r = getresult(pin, tagbuf);
if (r) break;
}
}
if(r) eatline(pin, c);
buf_free(&user);
buf_free(&tmp);
buf_free(&cmd);
return r;
}
static int dumpacl(struct protstream *pin, struct protstream *pout,
const char *mboxname, const char *acl_in)
{
int r = 0;
char tag[128];
int tagnum = 1;
char *rights, *nextid;
char *acl_safe = acl_in ? xstrdup(acl_in) : NULL;
char *acl = acl_safe;
while (acl) {
rights = strchr(acl, '\t');
if (!rights) break;
*rights++ = '\0';
nextid = strchr(rights, '\t');
if (!nextid) break;
*nextid++ = '\0';
snprintf(tag, sizeof(tag), "SACL%d", tagnum++);
prot_printf(pout, "%s SETACL {" SIZE_T_FMT "+}\r\n%s"
" {" SIZE_T_FMT "+}\r\n%s {" SIZE_T_FMT "+}\r\n%s\r\n",
tag,
strlen(mboxname), mboxname,
strlen(acl), acl,
strlen(rights), rights);
r = getresult(pin, tag);
if (r) break;
acl = nextid;
}
if(acl_safe) free(acl_safe);
return r;
}
enum {
XFER_MOVING_USER = -1,
XFER_DEACTIVATED = 1,
XFER_REMOTE_CREATED,
XFER_LOCAL_MOVING,
XFER_UNDUMPED,
};
struct xfer_item {
mbentry_t *mbentry;
char extname[MAX_MAILBOX_NAME];
struct mailbox *mailbox;
int state;
struct xfer_item *next;
};
struct xfer_header {
struct backend *be;
int remoteversion;
unsigned long use_replication;
struct buf tagbuf;
char *userid;
char *toserver;
char *topart;
struct seen *seendb;
struct xfer_item *items;
};
static int xfer_mupdate(int isactivate,
const char *mboxname, const char *part,
const char *servername, const char *acl)
{
char buf[MAX_PARTITION_LEN+HOSTNAME_SIZE+2];
int retry = 0;
int r = 0;
/* no mupdate handle */
if (!mupdate_h) return 0;
snprintf(buf, sizeof(buf), "%s!%s", servername, part);
retry:
/* make the change */
if (isactivate)
r = mupdate_activate(mupdate_h, mboxname, buf, acl);
else
r = mupdate_deactivate(mupdate_h, mboxname, buf);
if (r && !retry) {
syslog(LOG_INFO, "MUPDATE: lost connection, retrying");
mupdate_disconnect(&mupdate_h);
r = mupdate_connect(config_mupdate_server, NULL, &mupdate_h, NULL);
if (r) {
syslog(LOG_INFO, "Failed to connect to mupdate '%s'",
config_mupdate_server);
}
else {
retry = 1;
goto retry;
}
}
return r;
}
/* nothing you can do about failures, just try to clean up */
static void xfer_cleanup(struct xfer_header *xfer)
{
struct xfer_item *item, *next;
/* remove items */
item = xfer->items;
while (item) {
next = item->next;
mboxlist_entry_free(&item->mbentry);
free(item);
item = next;
}
xfer->items = NULL;
free(xfer->topart);
free(xfer->userid);
xfer->topart = xfer->userid = NULL;
seen_close(&xfer->seendb);
xfer->seendb = NULL;
}
static void xfer_done(struct xfer_header **xferptr)
{
struct xfer_header *xfer = *xferptr;
syslog(LOG_INFO, "XFER: disconnecting from servers");
free(xfer->toserver);
buf_free(&xfer->tagbuf);
xfer_cleanup(xfer);
free(xfer);
*xferptr = NULL;
}
static int backend_version(struct backend *be)
{
const char *minor;
/* IMPORTANT:
*
* When adding checks for new versions, you must also backport these
* checks to previous versions (especially 2.4 and 2.5).
*
* Otherwise, old versions will be unable to recognise the new version,
* assume it is ancient, and downgrade the index to the oldest version
* supported (version 6, prior to v2.3).
*/
/* It's like looking in the mirror and not suffering from schizophrenia */
if (strstr(be->banner, cyrus_version())) {
return MAILBOX_MINOR_VERSION;
}
/* master branch? */
if (strstr(be->banner, "Cyrus IMAP 3.0")) {
return 13;
}
/* version 2.5 is 13 */
if (strstr(be->banner, "Cyrus IMAP 2.5.")
|| strstr(be->banner, "Cyrus IMAP Murder 2.5.")
|| strstr(be->banner, "git2.5.")) {
return 13;
}
/* version 2.4 was all 12 */
if (strstr(be->banner, "v2.4.") || strstr(be->banner, "git2.4.")) {
return 12;
}
minor = strstr(be->banner, "v2.3.");
if (!minor) return 6;
/* at least version 2.3.10 */
if (minor[1] != ' ') {
return 10;
}
/* single digit version, figure out which */
switch (minor[0]) {
case '0':
case '1':
case '2':
case '3':
return 7;
break;
case '4':
case '5':
case '6':
return 8;
break;
case '7':
case '8':
case '9':
return 9;
break;
}
/* fallthrough, shouldn't happen */
return 6;
}
static int xfer_init(const char *toserver, struct xfer_header **xferptr)
{
struct xfer_header *xfer = xzmalloc(sizeof(struct xfer_header));
int r;
syslog(LOG_INFO, "XFER: connecting to server '%s'", toserver);
/* Get a connection to the remote backend */
xfer->be = proxy_findserver(toserver, &imap_protocol, "", &backend_cached,
NULL, NULL, imapd_in);
if (!xfer->be) {
syslog(LOG_ERR, "Failed to connect to server '%s'", toserver);
r = IMAP_SERVER_UNAVAILABLE;
goto fail;
}
xfer->remoteversion = backend_version(xfer->be);
if (xfer->be->capability & CAPA_REPLICATION) {
syslog(LOG_INFO, "XFER: destination supports replication");
xfer->use_replication = 1;
/* attach our IMAP tag buffer to our protstreams as userdata */
xfer->be->in->userdata = xfer->be->out->userdata = &xfer->tagbuf;
}
xfer->toserver = xstrdup(toserver);
xfer->topart = NULL;
xfer->seendb = NULL;
/* connect to mupdate server if configured */
if (config_mupdate_server && !mupdate_h) {
syslog(LOG_INFO, "XFER: connecting to mupdate '%s'",
config_mupdate_server);
r = mupdate_connect(config_mupdate_server, NULL, &mupdate_h, NULL);
if (r) {
syslog(LOG_INFO, "Failed to connect to mupdate '%s'",
config_mupdate_server);
goto fail;
}
}
*xferptr = xfer;
return 0;
fail:
xfer_done(&xfer);
return r;
}
static int xfer_localcreate(struct xfer_header *xfer)
{
struct xfer_item *item;
int r;
syslog(LOG_INFO, "XFER: creating mailboxes on destination");
for (item = xfer->items; item; item = item->next) {
if (xfer->topart) {
/* need to send partition as an atom */
prot_printf(xfer->be->out, "LC1 LOCALCREATE {" SIZE_T_FMT "+}\r\n%s %s\r\n",
strlen(item->extname), item->extname, xfer->topart);
} else {
prot_printf(xfer->be->out, "LC1 LOCALCREATE {" SIZE_T_FMT "+}\r\n%s\r\n",
strlen(item->extname), item->extname);
}
r = getresult(xfer->be->in, "LC1");
if (r) {
syslog(LOG_ERR, "Could not move mailbox: %s, LOCALCREATE failed",
item->mbentry->name);
return r;
}
item->state = XFER_REMOTE_CREATED;
}
return 0;
}
static int xfer_backport_seen_item(struct xfer_item *item,
struct seen *seendb)
{
struct mailbox *mailbox = item->mailbox;
struct seqset *outlist = NULL;
struct seendata sd = SEENDATA_INITIALIZER;
int r;
outlist = seqset_init(mailbox->i.last_uid, SEQ_MERGE);
struct mailbox_iter *iter = mailbox_iter_init(mailbox, 0, ITER_SKIP_EXPUNGED);
const message_t *msg;
while ((msg = mailbox_iter_step(iter))) {
const struct index_record *record = msg_record(msg);
if (record->system_flags & FLAG_SEEN)
seqset_add(outlist, record->uid, 1);
else
seqset_add(outlist, record->uid, 0);
}
mailbox_iter_done(&iter);
sd.lastread = mailbox->i.recenttime;
sd.lastuid = mailbox->i.recentuid;
sd.lastchange = mailbox->i.last_appenddate;
sd.seenuids = seqset_cstring(outlist);
if (!sd.seenuids) sd.seenuids = xstrdup("");
r = seen_write(seendb, mailbox->uniqueid, &sd);
seen_freedata(&sd);
seqset_free(outlist);
return r;
}
static int xfer_deactivate(struct xfer_header *xfer)
{
struct xfer_item *item;
int r;
syslog(LOG_INFO, "XFER: deactivating mailboxes");
/* Step 3: mupdate.DEACTIVATE(mailbox, newserver) */
for (item = xfer->items; item; item = item->next) {
r = xfer_mupdate(0, item->mbentry->name, item->mbentry->partition,
config_servername, item->mbentry->acl);
if (r) {
syslog(LOG_ERR,
"Could not move mailbox: %s, MUPDATE DEACTIVATE failed",
item->mbentry->name);
return r;
}
item->state = XFER_DEACTIVATED;
}
return 0;
}
static int xfer_undump(struct xfer_header *xfer)
{
struct xfer_item *item;
int r;
mbentry_t *newentry;
struct mailbox *mailbox = NULL;
syslog(LOG_INFO, "XFER: dumping mailboxes to destination");
for (item = xfer->items; item; item = item->next) {
r = mailbox_open_irl(item->mbentry->name, &mailbox);
if (r) {
syslog(LOG_ERR,
"Failed to open mailbox %s for dump_mailbox() %s",
item->mbentry->name, error_message(r));
return r;
}
/* Step 3.5: Set mailbox as MOVING on local server */
/* XXX - this code is awful... need a sane way to manage mbentries */
newentry = mboxlist_entry_create();
newentry->name = xstrdupnull(item->mbentry->name);
newentry->acl = xstrdupnull(item->mbentry->acl);
newentry->server = xstrdupnull(xfer->toserver);
newentry->partition = xstrdupnull(xfer->topart);
newentry->mbtype = item->mbentry->mbtype|MBTYPE_MOVING;
r = mboxlist_update(newentry, 1);
mboxlist_entry_free(&newentry);
if (r) {
syslog(LOG_ERR,
"Could not move mailbox: %s, mboxlist_update() failed %s",
item->mbentry->name, error_message(r));
}
else item->state = XFER_LOCAL_MOVING;
if (!r && xfer->seendb) {
/* Backport the user's seendb on-the-fly */
item->mailbox = mailbox;
r = xfer_backport_seen_item(item, xfer->seendb);
if (r) syslog(LOG_WARNING,
"Failed to backport seen state for mailbox '%s'",
item->mbentry->name);
/* Need to close seendb before dumping Inbox (last item) */
if (!item->next) seen_close(&xfer->seendb);
}
/* Step 4: Dump local -> remote */
if (!r) {
prot_printf(xfer->be->out, "D01 UNDUMP {" SIZE_T_FMT "+}\r\n%s ",
strlen(item->extname), item->extname);
r = dump_mailbox(NULL, mailbox, 0, xfer->remoteversion,
xfer->be->in, xfer->be->out, imapd_authstate);
if (r) {
syslog(LOG_ERR,
"Could not move mailbox: %s, dump_mailbox() failed %s",
item->mbentry->name, error_message(r));
}
}
mailbox_close(&mailbox);
if (r) return r;
r = getresult(xfer->be->in, "D01");
if (r) {
syslog(LOG_ERR, "Could not move mailbox: %s, UNDUMP failed %s",
item->mbentry->name, error_message(r));
return r;
}
/* Step 5: Set ACL on remote */
r = trashacl(xfer->be->in, xfer->be->out,
item->extname);
if (r) {
syslog(LOG_ERR, "Could not clear remote acl on %s",
item->mbentry->name);
return r;
}
r = dumpacl(xfer->be->in, xfer->be->out,
item->extname, item->mbentry->acl);
if (r) {
syslog(LOG_ERR, "Could not set remote acl on %s",
item->mbentry->name);
return r;
}
item->state = XFER_UNDUMPED;
}
return 0;
}
static int xfer_addusermbox(const mbentry_t *mbentry, void *rock)
{
struct xfer_header *xfer = (struct xfer_header *)rock;
/* Skip remote mailbox */
if (mbentry->mbtype & MBTYPE_REMOTE)
return 0;
struct xfer_item *item = xzmalloc(sizeof(struct xfer_item));
// re-read, because we don't have a handy clone function yet
int r = mboxlist_lookup(mbentry->name, &item->mbentry, 0);
if (r) return r;
char *extname = mboxname_to_external(item->mbentry->name, &imapd_namespace, imapd_userid);
strncpy(item->extname, extname, sizeof(item->extname));
free(extname);
item->mailbox = NULL;
item->state = 0;
/* and link on to the list (reverse order) */
item->next = xfer->items;
xfer->items = item;
return 0;
}
static int xfer_initialsync(struct xfer_header *xfer)
{
unsigned flags = SYNC_FLAG_LOGGING | SYNC_FLAG_LOCALONLY;
int r;
if (xfer->userid) {
struct xfer_item *item, *next;
syslog(LOG_INFO, "XFER: initial sync of user %s", xfer->userid);
r = sync_do_user(xfer->userid, xfer->topart, xfer->be,
/*channelp*/NULL, flags);
if (r) return r;
/* User moves may take a while, do another non-blocking sync */
syslog(LOG_INFO, "XFER: second sync of user %s", xfer->userid);
r = sync_do_user(xfer->userid, xfer->topart, xfer->be,
/*channelp*/NULL, flags);
if (r) return r;
/* User may have renamed/deleted a mailbox while syncing,
recreate the submailboxes list */
for (item = xfer->items; item; item = next) {
next = item->next;
mboxlist_entry_free(&item->mbentry);
free(item);
}
xfer->items = NULL;
r = mboxlist_usermboxtree(xfer->userid, xfer_addusermbox,
xfer, MBOXTREE_DELETED);
}
else {
struct sync_name_list *mboxname_list = sync_name_list_create();
syslog(LOG_INFO, "XFER: initial sync of mailbox %s",
xfer->items->mbentry->name);
sync_name_list_add(mboxname_list, xfer->items->mbentry->name);
r = sync_do_mailboxes(mboxname_list, xfer->topart, xfer->be,
/*channelp*/NULL, flags);
sync_name_list_free(&mboxname_list);
}
return r;
}
/*
* This is similar to do_folders() from sync_support, but for a single mailbox.
* It is needed for xfer_finalsync(), which needs to hold a single exclusive
* lock on the mailbox for the duration of this operation.
*/
static int sync_mailbox(struct mailbox *mailbox,
struct sync_folder_list *replica_folders,
const char *topart,
struct backend *be)
{
int r = 0;
struct sync_folder_list *master_folders = NULL;
struct sync_reserve_list *reserve_guids = NULL;
struct sync_msgid_list *part_list;
struct sync_reserve *reserve;
struct sync_folder *mfolder, *rfolder;
struct sync_annot_list *annots = NULL;
modseq_t xconvmodseq = 0;
unsigned flags = SYNC_FLAG_LOGGING | SYNC_FLAG_LOCALONLY;
if (!topart) topart = mailbox->part;
reserve_guids = sync_reserve_list_create(SYNC_MSGID_LIST_HASH_SIZE);
part_list = sync_reserve_partlist(reserve_guids, topart);
/* always send mailbox annotations */
r = read_annotations(mailbox, NULL, &annots);
if (r) {
syslog(LOG_ERR, "sync_mailbox(): read annotations failed: %s '%s'",
mailbox->name, error_message(r));
goto cleanup;
}
/* xconvmodseq */
if (mailbox_has_conversations(mailbox)) {
r = mailbox_get_xconvmodseq(mailbox, &xconvmodseq);
if (r) {
syslog(LOG_ERR, "sync_mailbox(): mailbox get xconvmodseq failed: %s '%s'",
mailbox->name, error_message(r));
goto cleanup;
}
}
master_folders = sync_folder_list_create();
sync_folder_list_add(master_folders,
mailbox->uniqueid, mailbox->name,
mailbox->mbtype,
mailbox->part,
mailbox->acl,
mailbox->i.options,
mailbox->i.uidvalidity,
mailbox->i.last_uid,
mailbox->i.highestmodseq,
mailbox->i.synccrcs,
mailbox->i.recentuid,
mailbox->i.recenttime,
mailbox->i.pop3_last_login,
mailbox->i.pop3_show_after,
annots,
xconvmodseq,
/* ispartial */0);
annots = NULL; /* list took ownership */
mfolder = master_folders->head;
/* when mfolder->mailbox is set, sync_update_mailbox will use it rather
* than obtaining its own (short-lived) locks */
mfolder->mailbox = mailbox;
uint32_t fromuid = 0;
rfolder = sync_folder_lookup(replica_folders, mfolder->uniqueid);
if (rfolder) {
rfolder->mark = 1;
/* does it need a rename? */
if (strcmp(mfolder->name, rfolder->name) ||
strcmp(topart, rfolder->part)) {
/* bail and retry */
syslog(LOG_NOTICE,
"XFER: rename %s!%s -> %s!%s during final sync"
" - must try XFER again",
mfolder->name, mfolder->part, rfolder->name, rfolder->part);
r = IMAP_AGAIN;
goto cleanup;
}
fromuid = rfolder->last_uid;
}
sync_find_reserve_messages(mailbox, fromuid, mailbox->i.last_uid, part_list);
reserve = reserve_guids->head;
r = sync_reserve_partition(reserve->part, replica_folders,
reserve->list, be);
if (r) {
syslog(LOG_ERR, "sync_mailbox(): reserve partition failed: %s '%s'",
mfolder->name, error_message(r));
goto cleanup;
}
r = sync_update_mailbox(mfolder, rfolder, topart, reserve_guids, be, flags);
if (r) {
syslog(LOG_ERR, "sync_mailbox(): update failed: %s '%s'",
mfolder->name, error_message(r));
}
cleanup:
sync_reserve_list_free(&reserve_guids);
sync_folder_list_free(&master_folders);
sync_annot_list_free(&annots);
return r;
}
static int xfer_finalsync(struct xfer_header *xfer)
{
struct sync_name_list *master_quotaroots = sync_name_list_create();
struct sync_folder_list *replica_folders = sync_folder_list_create();
struct sync_folder *rfolder;
struct sync_name_list *replica_subs = NULL;
struct sync_sieve_list *replica_sieve = NULL;
struct sync_seen_list *replica_seen = NULL;
struct sync_quota_list *replica_quota = sync_quota_list_create();
const char *cmd;
struct dlist *kl = NULL;
struct xfer_item *item;
struct mailbox *mailbox = NULL;
mbentry_t newentry;
unsigned flags = SYNC_FLAG_LOGGING | SYNC_FLAG_LOCALONLY;
int r;
if (xfer->userid) {
syslog(LOG_INFO, "XFER: final sync of user %s", xfer->userid);
replica_subs = sync_name_list_create();
replica_sieve = sync_sieve_list_create();
replica_seen = sync_seen_list_create();
cmd = "USER";
kl = dlist_setatom(NULL, cmd, xfer->userid);
}
else {
syslog(LOG_INFO, "XFER: final sync of mailbox %s",
xfer->items->mbentry->name);
cmd = "MAILBOXES";
kl = dlist_newlist(NULL, cmd);
dlist_setatom(kl, "MBOXNAME", xfer->items->mbentry->name);
}
sync_send_lookup(kl, xfer->be->out);
dlist_free(&kl);
r = sync_response_parse(xfer->be->in, cmd, replica_folders, replica_subs,
replica_sieve, replica_seen, replica_quota);
if (r) goto done;
for (item = xfer->items; item; item = item->next) {
r = mailbox_open_iwl(item->mbentry->name, &mailbox);
if (!r) r = sync_mailbox_version_check(&mailbox);
if (r) {
syslog(LOG_ERR,
"Failed to open mailbox %s for xfer_final_sync() %s",
item->mbentry->name, error_message(r));
goto done;
}
/* Open cyrus.annotations before we set mailbox to MOVING and
change its location to destination server and partition */
r = mailbox_get_annotate_state(mailbox, ANNOTATE_ANY_UID, NULL);
if (r) {
syslog(LOG_ERR,
"Failed to get annotate state for mailbox %s"
" for xfer_final_sync() %s",
mailbox->name, error_message(r));
mailbox_close(&mailbox);
goto done;
}
/* Step 3.5: Set mailbox as MOVING on local server */
/* XXX - this code is awful... need a sane way to manage mbentries */
newentry.name = item->mbentry->name;
newentry.acl = item->mbentry->acl;
newentry.uniqueid = item->mbentry->uniqueid;
newentry.uidvalidity = item->mbentry->uidvalidity;
newentry.mbtype = item->mbentry->mbtype|MBTYPE_MOVING;
newentry.server = xfer->toserver;
newentry.partition = xfer->topart;
r = mboxlist_update(&newentry, 1);
if (r) {
syslog(LOG_ERR,
"Could not move mailbox: %s, mboxlist_update() failed %s",
item->mbentry->name, error_message(r));
}
else item->state = XFER_LOCAL_MOVING;
/* Step 4: Sync local -> remote */
if (!r) {
r = sync_mailbox(mailbox, replica_folders, xfer->topart, xfer->be);
if (r) {
syslog(LOG_ERR,
"Could not move mailbox: %s, sync_mailbox() failed %s",
item->mbentry->name, error_message(r));
}
else {
if (mailbox->quotaroot &&
!sync_name_lookup(master_quotaroots, mailbox->quotaroot)) {
sync_name_list_add(master_quotaroots, mailbox->quotaroot);
}
r = sync_do_annotation(mailbox->name, xfer->be, flags);
if (r) {
syslog(LOG_ERR, "Could not move mailbox: %s,"
" sync_do_annotation() failed %s",
item->mbentry->name, error_message(r));
}
}
}
mailbox_close(&mailbox);
if (r) goto done;
item->state = XFER_UNDUMPED;
}
/* Delete folders on replica which no longer exist on master */
for (rfolder = replica_folders->head; rfolder; rfolder = rfolder->next) {
if (rfolder->mark) continue;
r = sync_folder_delete(rfolder->name, xfer->be, flags);
if (r) {
syslog(LOG_ERR, "sync_folder_delete(): failed: %s '%s'",
rfolder->name, error_message(r));
goto done;
}
}
/* Handle any mailbox/user metadata */
r = sync_do_user_quota(master_quotaroots, replica_quota, xfer->be, flags);
if (!r && xfer->userid) {
r = sync_do_user_seen(xfer->userid, replica_seen, xfer->be, flags);
if (!r) r = sync_do_user_sub(xfer->userid, replica_subs,
xfer->be, flags);
if (!r) r = sync_do_user_sieve(xfer->userid, replica_sieve,
xfer->be, flags);
}
done:
sync_name_list_free(&master_quotaroots);
sync_folder_list_free(&replica_folders);
if (replica_subs) sync_name_list_free(&replica_subs);
if (replica_sieve) sync_sieve_list_free(&replica_sieve);
if (replica_seen) sync_seen_list_free(&replica_seen);
if (replica_quota) sync_quota_list_free(&replica_quota);
return r;
}
static int xfer_reactivate(struct xfer_header *xfer)
{
struct xfer_item *item;
int r;
syslog(LOG_INFO, "XFER: reactivating mailboxes");
if (!mupdate_h) return 0;
/* 6.5) Kick remote server to correct mupdate entry */
for (item = xfer->items; item; item = item->next) {
prot_printf(xfer->be->out, "MP1 MUPDATEPUSH {" SIZE_T_FMT "+}\r\n%s\r\n",
strlen(item->extname), item->extname);
r = getresult(xfer->be->in, "MP1");
if (r) {
syslog(LOG_ERR, "MUPDATE: can't activate mailbox entry '%s': %s",
item->mbentry->name, error_message(r));
}
}
return 0;
}
static int xfer_delete(struct xfer_header *xfer)
{
mbentry_t *newentry = NULL;
struct xfer_item *item;
int r;
syslog(LOG_INFO, "XFER: deleting mailboxes on source");
/* 7) local delete of mailbox
* & remove local "remote" mailboxlist entry */
for (item = xfer->items; item; item = item->next) {
/* Set mailbox as DELETED on local server
(need to also reset to local partition,
otherwise mailbox can not be opened for deletion) */
/* XXX - this code is awful... need a sane way to manage mbentries */
newentry = mboxlist_entry_create();
newentry->name = xstrdupnull(item->mbentry->name);
newentry->acl = xstrdupnull(item->mbentry->acl);
newentry->server = xstrdupnull(item->mbentry->server);
newentry->partition = xstrdupnull(item->mbentry->partition);
newentry->mbtype = item->mbentry->mbtype|MBTYPE_DELETED;
r = mboxlist_update(newentry, 1);
mboxlist_entry_free(&newentry);
if (r) {
syslog(LOG_ERR,
"Could not move mailbox: %s, mboxlist_update failed (%s)",
item->mbentry->name, error_message(r));
}
/* Note that we do not check the ACL, and we don't update MUPDATE */
/* note also that we need to remember to let proxyadmins do this */
/* On a unified system, the subsequent MUPDATE PUSH on the remote
should repopulate the local mboxlist entry */
r = mboxlist_deletemailbox(item->mbentry->name,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate, NULL, 0, 1, 0);
if (r) {
syslog(LOG_ERR,
"Could not delete local mailbox during move of %s",
item->mbentry->name);
/* can't abort now! */
}
}
return 0;
}
static void xfer_recover(struct xfer_header *xfer)
{
struct xfer_item *item;
int r;
syslog(LOG_INFO, "XFER: recovering");
/* Backout any changes - we stop on first untouched mailbox */
for (item = xfer->items; item && item->state; item = item->next) {
switch (item->state) {
case XFER_UNDUMPED:
case XFER_LOCAL_MOVING:
/* Unset mailbox as MOVING on local server */
r = mboxlist_update(item->mbentry, 1);
if (r) {
syslog(LOG_ERR,
"Could not back out MOVING flag during move of %s (%s)",
item->mbentry->name, error_message(r));
}
case XFER_REMOTE_CREATED:
if (!xfer->use_replication) {
/* Delete remote mailbox */
prot_printf(xfer->be->out,
"LD1 LOCALDELETE {" SIZE_T_FMT "+}\r\n%s\r\n",
strlen(item->extname), item->extname);
r = getresult(xfer->be->in, "LD1");
if (r) {
syslog(LOG_ERR,
"Could not back out remote mailbox during move of %s (%s)",
item->mbentry->name, error_message(r));
}
}
case XFER_DEACTIVATED:
/* Tell murder it's back here and active */
r = xfer_mupdate(1, item->mbentry->name, item->mbentry->partition,
config_servername, item->mbentry->acl);
if (r) {
syslog(LOG_ERR,
"Could not back out mupdate during move of %s (%s)",
item->mbentry->name, error_message(r));
}
}
}
}
static int do_xfer(struct xfer_header *xfer)
{
int r = 0;
if (xfer->use_replication) {
/* Initial non-blocking sync */
r = xfer_initialsync(xfer);
if (r) return r;
}
r = xfer_deactivate(xfer);
if (!r) {
if (xfer->use_replication) {
/* Final sync with write locks on mailboxes */
r = xfer_finalsync(xfer);
}
else {
r = xfer_localcreate(xfer);
if (!r) r = xfer_undump(xfer);
}
}
if (r) {
/* Something failed, revert back to local server */
xfer_recover(xfer);
return r;
}
/* Successful dump of all mailboxes to remote server.
* Remove them locally and activate them on remote.
* Note - we don't report errors if this fails! */
xfer_delete(xfer);
xfer_reactivate(xfer);
return 0;
}
static int xfer_setquotaroot(struct xfer_header *xfer, const char *mboxname)
{
struct quota q;
int r;
syslog(LOG_INFO, "XFER: setting quota root %s", mboxname);
quota_init(&q, mboxname);
r = quota_read(&q, NULL, 0);
if (r == IMAP_QUOTAROOT_NONEXISTENT) return 0;
if (r) return r;
/* note use of + to force the setting of a nonexistant
* quotaroot */
char *extname = mboxname_to_external(mboxname, &imapd_namespace, imapd_userid);
prot_printf(xfer->be->out, "Q01 SETQUOTA {" SIZE_T_FMT "+}\r\n+%s ",
strlen(extname)+1, extname);
free(extname);
print_quota_limits(xfer->be->out, &q);
prot_printf(xfer->be->out, "\r\n");
quota_free(&q);
r = getresult(xfer->be->in, "Q01");
if (r) syslog(LOG_ERR,
"Could not move mailbox: %s, " \
"failed setting initial quota root\r\n",
mboxname);
return r;
}
struct xfer_list {
const struct namespace *ns;
const char *userid;
const char *part;
short allow_usersubs;
struct xfer_item *mboxes;
};
static int xfer_addmbox(struct findall_data *data, void *rock)
{
if (!data) return 0;
struct xfer_list *list = (struct xfer_list *) rock;
if (!data->mbentry) {
/* No partial matches */
return 0;
}
if (list->part && strcmp(data->mbentry->partition, list->part)) {
/* Not on specified partition */
return 0;
}
/* Only add shared mailboxes, targeted user submailboxes, or user INBOXes */
if (!mbname_localpart(data->mbname) || list->allow_usersubs ||
(!mbname_isdeleted(data->mbname) && !strarray_size(mbname_boxes(data->mbname)))) {
const char *extname = mbname_extname(data->mbname, list->ns, list->userid);
struct xfer_item *mbox = xzmalloc(sizeof(struct xfer_item));
mbox->mbentry = mboxlist_entry_copy(data->mbentry);
strncpy(mbox->extname, extname, sizeof(mbox->extname));
if (mbname_localpart(data->mbname) && !list->allow_usersubs) {
/* User INBOX */
mbox->state = XFER_MOVING_USER;
}
/* Add link on to the list (reverse order) */
mbox->next = list->mboxes;
list->mboxes = mbox;
}
return 0;
}
static void cmd_xfer(const char *tag, const char *name,
const char *toserver, const char *topart)
{
int r = 0, partial_success = 0, mbox_count = 0;
struct xfer_header *xfer = NULL;
struct xfer_list list = { &imapd_namespace, imapd_userid, NULL, 0, NULL };
struct xfer_item *item, *next;
char *intname = NULL;
/* administrators only please */
/* however, proxys can do this, if their authzid is an admin */
if (!imapd_userisadmin && !imapd_userisproxyadmin) {
r = IMAP_PERMISSION_DENIED;
goto done;
}
if (!strcmp(toserver, config_servername)) {
r = IMAP_BAD_SERVER;
goto done;
}
/* Build list of users/mailboxes to transfer */
if (config_partitiondir(name)) {
/* entire partition */
list.part = name;
mboxlist_findall(NULL, "*", 1, NULL, NULL, xfer_addmbox, &list);
} else {
/* mailbox pattern */
mbname_t *mbname;
intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
mbname = mbname_from_intname(intname);
if (mbname_localpart(mbname) &&
(mbname_isdeleted(mbname) || strarray_size(mbname_boxes(mbname)))) {
/* targeted a user submailbox */
list.allow_usersubs = 1;
}
mbname_free(&mbname);
mboxlist_findall(NULL, intname, 1, NULL, NULL, xfer_addmbox, &list);
free(intname);
}
r = xfer_init(toserver, &xfer);
if (r) goto done;
for (item = list.mboxes; item; item = next) {
mbentry_t *mbentry = item->mbentry;
/* NOTE: Since XFER can only be used by an admin, and we always connect
* to the destination backend as an admin, we take advantage of the fact
* that admins *always* use a consistent mailbox naming scheme.
* So, 'name' should be used in any command we send to a backend, and
* 'intname' is the internal name to be used for mupdate and findall.
*/
r = 0;
intname = mbentry->name;
xfer->topart = xstrdup(topart ? topart : mbentry->partition);
/* if we are not moving a user, just move the one mailbox */
if (item->state != XFER_MOVING_USER) {
syslog(LOG_INFO, "XFER: mailbox '%s' -> %s!%s",
mbentry->name, xfer->toserver, xfer->topart);
/* is the selected mailbox the one we're moving? */
if (!strcmpsafe(intname, index_mboxname(imapd_index))) {
r = IMAP_MAILBOX_LOCKED;
goto next;
}
/* we're moving this mailbox */
xfer_addusermbox(mbentry, xfer);
mbox_count++;
r = do_xfer(xfer);
} else {
xfer->userid = mboxname_to_userid(intname);
syslog(LOG_INFO, "XFER: user '%s' -> %s!%s",
xfer->userid, xfer->toserver, xfer->topart);
if (!config_getswitch(IMAPOPT_ALLOWUSERMOVES)) {
/* not configured to allow user moves */
r = IMAP_MAILBOX_NOTSUPPORTED;
} else if (!strcmp(xfer->userid, imapd_userid)) {
/* don't move your own inbox, that could be troublesome */
r = IMAP_MAILBOX_NOTSUPPORTED;
} else if (!strncmpsafe(intname, index_mboxname(imapd_index),
strlen(intname))) {
/* selected mailbox is in the namespace we're moving */
r = IMAP_MAILBOX_LOCKED;
}
if (r) goto next;
if (!xfer->use_replication) {
/* set the quotaroot if needed */
r = xfer_setquotaroot(xfer, intname);
if (r) goto next;
/* backport the seen file if needed */
if (xfer->remoteversion < 12) {
r = seen_open(xfer->userid, SEEN_CREATE, &xfer->seendb);
if (r) goto next;
}
}
r = mboxlist_usermboxtree(xfer->userid, xfer_addusermbox,
xfer, MBOXTREE_DELETED);
/* NOTE: mailboxes were added in reverse, so the inbox is
* done last */
r = do_xfer(xfer);
if (r) goto next;
/* this was a successful user move, and we need to delete
certain user meta-data (but not seen state!) */
syslog(LOG_INFO, "XFER: deleting user metadata");
user_deletedata(xfer->userid, 0);
}
next:
if (r) {
if (xfer->userid)
prot_printf(imapd_out, "* NO USER %s (%s)\r\n",
xfer->userid, error_message(r));
else
prot_printf(imapd_out, "* NO MAILBOX \"%s\" (%s)\r\n",
item->extname, error_message(r));
} else {
partial_success = 1;
if (xfer->userid)
prot_printf(imapd_out, "* OK USER %s\r\n", xfer->userid);
else
prot_printf(imapd_out, "* OK MAILBOX \"%s\"\r\n", item->extname);
}
prot_flush(imapd_out);
mboxlist_entry_free(&mbentry);
next = item->next;
free(item);
if (xfer->userid || mbox_count > 1000) {
/* RESTART after each user or after every 1000 mailboxes */
mbox_count = 0;
sync_send_restart(xfer->be->out);
r = sync_parse_response("RESTART", xfer->be->in, NULL);
if (r) goto done;
}
xfer_cleanup(xfer);
if (partial_success) r = 0;
}
done:
if (xfer) xfer_done(&xfer);
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag,
error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
return;
}
#define SORTGROWSIZE 10
/*
* Parse sort criteria
*/
static int getsortcriteria(char *tag, struct sortcrit **sortcrit)
{
int c;
static struct buf criteria;
int nsort, n;
int hasconv = config_getswitch(IMAPOPT_CONVERSATIONS);
*sortcrit = NULL;
c = prot_getc(imapd_in);
if (c != '(') goto missingcrit;
c = getword(imapd_in, &criteria);
if (criteria.s[0] == '\0') goto missingcrit;
nsort = 0;
n = 0;
for (;;) {
if (n >= nsort - 1) { /* leave room for implicit criterion */
/* (Re)allocate an array for sort criteria */
nsort += SORTGROWSIZE;
*sortcrit =
(struct sortcrit *) xrealloc(*sortcrit,
nsort * sizeof(struct sortcrit));
/* Zero out the newly added sortcrit */
memset((*sortcrit)+n, 0, SORTGROWSIZE * sizeof(struct sortcrit));
}
lcase(criteria.s);
if (!strcmp(criteria.s, "reverse")) {
(*sortcrit)[n].flags |= SORT_REVERSE;
goto nextcrit;
}
else if (!strcmp(criteria.s, "arrival"))
(*sortcrit)[n].key = SORT_ARRIVAL;
else if (!strcmp(criteria.s, "cc"))
(*sortcrit)[n].key = SORT_CC;
else if (!strcmp(criteria.s, "date"))
(*sortcrit)[n].key = SORT_DATE;
else if (!strcmp(criteria.s, "displayfrom"))
(*sortcrit)[n].key = SORT_DISPLAYFROM;
else if (!strcmp(criteria.s, "displayto"))
(*sortcrit)[n].key = SORT_DISPLAYTO;
else if (!strcmp(criteria.s, "from"))
(*sortcrit)[n].key = SORT_FROM;
else if (!strcmp(criteria.s, "size"))
(*sortcrit)[n].key = SORT_SIZE;
else if (!strcmp(criteria.s, "subject"))
(*sortcrit)[n].key = SORT_SUBJECT;
else if (!strcmp(criteria.s, "to"))
(*sortcrit)[n].key = SORT_TO;
else if (!strcmp(criteria.s, "annotation")) {
const char *userid = NULL;
(*sortcrit)[n].key = SORT_ANNOTATION;
if (c != ' ') goto missingarg;
c = getastring(imapd_in, imapd_out, &criteria);
if (c != ' ') goto missingarg;
(*sortcrit)[n].args.annot.entry = xstrdup(criteria.s);
c = getastring(imapd_in, imapd_out, &criteria);
if (c == EOF) goto missingarg;
if (!strcmp(criteria.s, "value.shared"))
userid = "";
else if (!strcmp(criteria.s, "value.priv"))
userid = imapd_userid;
else
goto missingarg;
(*sortcrit)[n].args.annot.userid = xstrdup(userid);
}
else if (!strcmp(criteria.s, "modseq"))
(*sortcrit)[n].key = SORT_MODSEQ;
else if (!strcmp(criteria.s, "uid"))
(*sortcrit)[n].key = SORT_UID;
else if (!strcmp(criteria.s, "hasflag")) {
(*sortcrit)[n].key = SORT_HASFLAG;
if (c != ' ') goto missingarg;
c = getastring(imapd_in, imapd_out, &criteria);
if (c == EOF) goto missingarg;
(*sortcrit)[n].args.flag.name = xstrdup(criteria.s);
}
else if (hasconv && !strcmp(criteria.s, "convmodseq"))
(*sortcrit)[n].key = SORT_CONVMODSEQ;
else if (hasconv && !strcmp(criteria.s, "convexists"))
(*sortcrit)[n].key = SORT_CONVEXISTS;
else if (hasconv && !strcmp(criteria.s, "convsize"))
(*sortcrit)[n].key = SORT_CONVSIZE;
else if (hasconv && !strcmp(criteria.s, "hasconvflag")) {
(*sortcrit)[n].key = SORT_HASCONVFLAG;
if (c != ' ') goto missingarg;
c = getastring(imapd_in, imapd_out, &criteria);
if (c == EOF) goto missingarg;
(*sortcrit)[n].args.flag.name = xstrdup(criteria.s);
}
else if (!strcmp(criteria.s, "folder"))
(*sortcrit)[n].key = SORT_FOLDER;
else if (!strcmp(criteria.s, "relevancy"))
(*sortcrit)[n].key = SORT_RELEVANCY;
else if (!strcmp(criteria.s, "spamscore"))
(*sortcrit)[n].key = SORT_SPAMSCORE;
else {
prot_printf(imapd_out, "%s BAD Invalid Sort criterion %s\r\n",
tag, criteria.s);
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
}
n++;
nextcrit:
if (c == ' ') c = getword(imapd_in, &criteria);
else break;
}
if ((*sortcrit)[n].flags & SORT_REVERSE && !(*sortcrit)[n].key) {
prot_printf(imapd_out,
"%s BAD Missing Sort criterion to reverse\r\n", tag);
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
}
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close parenthesis in Sort\r\n", tag);
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
}
/* Terminate the list with the implicit sort criterion */
(*sortcrit)[n++].key = SORT_SEQUENCE;
c = prot_getc(imapd_in);
return c;
missingcrit:
prot_printf(imapd_out, "%s BAD Missing Sort criteria\r\n", tag);
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
missingarg:
prot_printf(imapd_out, "%s BAD Missing argument to Sort criterion %s\r\n",
tag, criteria.s);
if (c != EOF) prot_ungetc(c, imapd_in);
return EOF;
}
static int parse_windowargs(const char *tag,
struct windowargs **wa,
int updates)
{
struct windowargs windowargs;
struct buf arg = BUF_INITIALIZER;
struct buf ext_folder = BUF_INITIALIZER;
int c;
memset(&windowargs, 0, sizeof(windowargs));
c = prot_getc(imapd_in);
if (c == EOF)
goto out;
if (c != '(') {
/* no window args at all */
prot_ungetc(c, imapd_in);
goto out;
}
for (;;)
{
c = prot_getc(imapd_in);
if (c == EOF)
goto out;
if (c == ')')
break; /* end of window args */
prot_ungetc(c, imapd_in);
c = getword(imapd_in, &arg);
if (!arg.len)
goto syntax_error;
if (!strcasecmp(arg.s, "CONVERSATIONS"))
windowargs.conversations = 1;
else if (!strcasecmp(arg.s, "POSITION")) {
if (updates)
goto syntax_error;
if (c != ' ')
goto syntax_error;
c = prot_getc(imapd_in);
if (c != '(')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.position);
if (c != ' ')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.limit);
if (c != ')')
goto syntax_error;
c = prot_getc(imapd_in);
if (windowargs.position == 0)
goto syntax_error;
}
else if (!strcasecmp(arg.s, "ANCHOR")) {
if (updates)
goto syntax_error;
if (c != ' ')
goto syntax_error;
c = prot_getc(imapd_in);
if (c != '(')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.anchor);
if (c != ' ')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.offset);
if (c != ' ')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.limit);
if (c != ')')
goto syntax_error;
c = prot_getc(imapd_in);
if (windowargs.anchor == 0)
goto syntax_error;
}
else if (!strcasecmp(arg.s, "MULTIANCHOR")) {
if (updates)
goto syntax_error;
if (c != ' ')
goto syntax_error;
c = prot_getc(imapd_in);
if (c != '(')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.anchor);
if (c != ' ')
goto syntax_error;
c = getastring(imapd_in, imapd_out, &ext_folder);
if (c != ' ')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.offset);
if (c != ' ')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.limit);
if (c != ')')
goto syntax_error;
c = prot_getc(imapd_in);
if (windowargs.anchor == 0)
goto syntax_error;
}
else if (!strcasecmp(arg.s, "CHANGEDSINCE")) {
if (!updates)
goto syntax_error;
windowargs.changedsince = 1;
if (c != ' ')
goto syntax_error;
c = prot_getc(imapd_in);
if (c != '(')
goto syntax_error;
c = getmodseq(imapd_in, &windowargs.modseq);
if (c != ' ')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.uidnext);
if (c != ')')
goto syntax_error;
c = prot_getc(imapd_in);
} else if (!strcasecmp(arg.s, "UPTO")) {
if (!updates)
goto syntax_error;
if (c != ' ')
goto syntax_error;
c = prot_getc(imapd_in);
if (c != '(')
goto syntax_error;
c = getuint32(imapd_in, &windowargs.upto);
if (c != ')')
goto syntax_error;
c = prot_getc(imapd_in);
if (windowargs.upto == 0)
goto syntax_error;
}
else
goto syntax_error;
if (c == ')')
break;
if (c != ' ')
goto syntax_error;
}
c = prot_getc(imapd_in);
if (c != ' ')
goto syntax_error;
out:
/* these two are mutually exclusive */
if (windowargs.anchor && windowargs.position)
goto syntax_error;
/* changedsince is mandatory for XCONVUPDATES
* and illegal for XCONVSORT */
if (!!updates != windowargs.changedsince)
goto syntax_error;
if (ext_folder.len) {
windowargs.anchorfolder = mboxname_from_external(buf_cstring(&ext_folder),
&imapd_namespace,
imapd_userid);
}
*wa = xmemdup(&windowargs, sizeof(windowargs));
buf_free(&ext_folder);
buf_free(&arg);
return c;
syntax_error:
free(windowargs.anchorfolder);
buf_free(&ext_folder);
prot_printf(imapd_out, "%s BAD Syntax error in window arguments\r\n", tag);
return EOF;
}
static void free_windowargs(struct windowargs *wa)
{
if (!wa)
return;
free(wa->anchorfolder);
free(wa);
}
/*
* Parse LIST selection options.
* The command has been parsed up to and including the opening '('.
*/
static int getlistselopts(char *tag, struct listargs *args)
{
int c;
static struct buf buf;
if ( (c = prot_getc(imapd_in)) == ')')
return prot_getc(imapd_in);
else
prot_ungetc(c, imapd_in);
for (;;) {
c = getword(imapd_in, &buf);
if (!*buf.s) {
prot_printf(imapd_out,
"%s BAD Invalid syntax in List command\r\n",
tag);
return EOF;
}
lcase(buf.s);
if (!strcmp(buf.s, "subscribed")) {
args->sel |= LIST_SEL_SUBSCRIBED;
args->ret |= LIST_RET_SUBSCRIBED;
} else if (!strcmp(buf.s, "vendor.cmu-dav")) {
args->sel |= LIST_SEL_DAV;
} else if (!strcmp(buf.s, "remote")) {
args->sel |= LIST_SEL_REMOTE;
} else if (!strcmp(buf.s, "recursivematch")) {
args->sel |= LIST_SEL_RECURSIVEMATCH;
} else if (!strcmp(buf.s, "special-use")) {
args->sel |= LIST_SEL_SPECIALUSE;
args->ret |= LIST_RET_SPECIALUSE;
} else if (!strcmp(buf.s, "metadata")) {
struct getmetadata_options opts = OPTS_INITIALIZER;
args->sel |= LIST_SEL_METADATA;
args->ret |= LIST_RET_METADATA;
strarray_t options = STRARRAY_INITIALIZER;
c = parse_metadata_string_or_list(tag, &options, NULL);
parse_getmetadata_options(&options, &opts);
args->metaopts = opts;
strarray_fini(&options);
if (c == EOF) return EOF;
} else {
prot_printf(imapd_out,
"%s BAD Invalid List selection option \"%s\"\r\n",
tag, buf.s);
return EOF;
}
if (c != ' ') break;
}
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close parenthesis for List selection options\r\n", tag);
return EOF;
}
if (args->sel & list_select_mod_opts
&& ! (args->sel & list_select_base_opts)) {
prot_printf(imapd_out,
"%s BAD Invalid combination of selection options\r\n",
tag);
return EOF;
}
return prot_getc(imapd_in);
}
/*
* Parse LIST return options.
* The command has been parsed up to and including the ' ' before RETURN.
*/
static int getlistretopts(char *tag, struct listargs *args)
{
static struct buf buf;
int c;
c = getword(imapd_in, &buf);
if (!*buf.s) {
prot_printf(imapd_out,
"%s BAD Invalid syntax in List command\r\n", tag);
return EOF;
}
lcase(buf.s);
if (strcasecmp(buf.s, "return")) {
prot_printf(imapd_out,
"%s BAD Unexpected extra argument to List: \"%s\"\r\n",
tag, buf.s);
return EOF;
}
if (c != ' ' || (c = prot_getc(imapd_in)) != '(') {
prot_printf(imapd_out,
"%s BAD Missing return argument list\r\n", tag);
return EOF;
}
if ( (c = prot_getc(imapd_in)) == ')')
return prot_getc(imapd_in);
else
prot_ungetc(c, imapd_in);
for (;;) {
c = getword(imapd_in, &buf);
if (!*buf.s) {
prot_printf(imapd_out,
"%s BAD Invalid syntax in List command\r\n", tag);
return EOF;
}
lcase(buf.s);
if (!strcmp(buf.s, "subscribed"))
args->ret |= LIST_RET_SUBSCRIBED;
else if (!strcmp(buf.s, "children"))
args->ret |= LIST_RET_CHILDREN;
else if (!strcmp(buf.s, "myrights"))
args->ret |= LIST_RET_MYRIGHTS;
else if (!strcmp(buf.s, "special-use"))
args->ret |= LIST_RET_SPECIALUSE;
else if (!strcmp(buf.s, "status")) {
const char *errstr = "Bad status string";
args->ret |= LIST_RET_STATUS;
c = parse_statusitems(&args->statusitems, &errstr);
if (c == EOF) {
prot_printf(imapd_out, "%s BAD %s", tag, errstr);
return EOF;
}
}
else if (!strcmp(buf.s, "metadata")) {
args->ret |= LIST_RET_METADATA;
/* outputs the error for us */
c = parse_metadata_string_or_list(tag, &args->metaitems, NULL);
if (c == EOF) return EOF;
}
else {
prot_printf(imapd_out,
"%s BAD Invalid List return option \"%s\"\r\n",
tag, buf.s);
return EOF;
}
if (c != ' ') break;
}
if (c != ')') {
prot_printf(imapd_out,
"%s BAD Missing close parenthesis for List return options\r\n", tag);
return EOF;
}
return prot_getc(imapd_in);
}
/*
* Parse a string in IMAP date-time format (and some more
* obscure legacy formats too) to a time_t. Parses both
* date and time parts. See cyrus_parsetime() for formats.
*
* Returns: the next character read from imapd_in, or
* or EOF on error.
*/
static int getdatetime(time_t *date)
{
int c;
int r;
int i = 0;
char buf[RFC3501_DATETIME_MAX+1];
c = prot_getc(imapd_in);
if (c != '\"')
goto baddate;
while ((c = prot_getc(imapd_in)) != '\"') {
if (i >= RFC3501_DATETIME_MAX)
goto baddate;
buf[i++] = c;
}
buf[i] = '\0';
r = time_from_rfc3501(buf, date);
if (r < 0)
goto baddate;
c = prot_getc(imapd_in);
return c;
baddate:
prot_ungetc(c, imapd_in);
return EOF;
}
/*
* Append 'section', 'fields', 'trail' to the fieldlist 'l'.
*/
static void appendfieldlist(struct fieldlist **l, char *section,
strarray_t *fields, char *trail,
void *d, size_t size)
{
struct fieldlist **tail = l;
while (*tail) tail = &(*tail)->next;
*tail = (struct fieldlist *)xmalloc(sizeof(struct fieldlist));
(*tail)->section = xstrdup(section);
(*tail)->fields = fields;
(*tail)->trail = xstrdup(trail);
if(d && size) {
(*tail)->rock = xmalloc(size);
memcpy((*tail)->rock, d, size);
} else {
(*tail)->rock = NULL;
}
(*tail)->next = 0;
}
/*
* Free the fieldlist 'l'
*/
static void freefieldlist(struct fieldlist *l)
{
struct fieldlist *n;
while (l) {
n = l->next;
free(l->section);
strarray_free(l->fields);
free(l->trail);
if (l->rock) free(l->rock);
free((char *)l);
l = n;
}
}
static int set_haschildren(const mbentry_t *mbentry __attribute__((unused)),
void *rock)
{
uint32_t *attributes = (uint32_t *)rock;
list_callback_calls++;
*attributes |= MBOX_ATTRIBUTE_HASCHILDREN;
return CYRUSDB_DONE;
}
static void specialuse_flags(const mbentry_t *mbentry, struct buf *attrib,
int isxlist)
{
if (!mbentry) return;
char *inbox = mboxname_user_mbox(imapd_userid, NULL);
int inboxlen = strlen(inbox);
/* doesn't match inbox, not xlistable */
if (strncmp(mbentry->name, inbox, inboxlen)) {
free(inbox);
return;
}
/* inbox - only print if command is XLIST */
if (mbentry->name[inboxlen] == '\0') {
if (isxlist) buf_init_ro_cstr(attrib, "\\Inbox");
}
/* subdir */
else if (mbentry->name[inboxlen] == '.') {
/* check if there's a special use flag set */
annotatemore_lookup(mbentry->name, "/specialuse", imapd_userid, attrib);
}
free(inbox);
/* otherwise it's actually another user who matches for
* the substr. Ok to just print nothing */
}
static void printmetadata(const mbentry_t *mbentry,
const strarray_t *entries,
struct getmetadata_options *opts)
{
annotate_state_t *astate = annotate_state_new();
strarray_t newa = STRARRAY_INITIALIZER;
strarray_t newe = STRARRAY_INITIALIZER;
annotate_state_set_auth(astate,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_userid, imapd_authstate);
int r = annotate_state_set_mailbox_mbe(astate, mbentry);
if (r) goto done;
r = _metadata_to_annotate(entries, &newa, &newe, NULL, opts->depth);
if (r) goto done;
annotate_state_fetch(astate, &newe, &newa, getmetadata_response, opts);
getmetadata_response(NULL, 0, NULL, NULL, opts);
done:
annotate_state_abort(&astate);
}
/* Print LIST or LSUB untagged response */
static void list_response(const char *extname, const mbentry_t *mbentry,
uint32_t attributes, struct listargs *listargs)
{
int r;
struct statusdata sdata = STATUSDATA_INIT;
struct buf specialuse = BUF_INITIALIZER;
if ((attributes & MBOX_ATTRIBUTE_NONEXISTENT)) {
if (!(listargs->cmd == LIST_CMD_EXTENDED)) {
attributes |= MBOX_ATTRIBUTE_NOSELECT;
attributes &= ~MBOX_ATTRIBUTE_NONEXISTENT;
}
}
else if (listargs->scan) {
/* SCAN mailbox for content */
if (!strcmpsafe(mbentry->name, index_mboxname(imapd_index))) {
/* currently selected mailbox */
if (!index_scan(imapd_index, listargs->scan))
return; /* no matching messages */
}
else {
/* other local mailbox */
struct index_state *state;
struct index_init init;
int doclose = 0;
memset(&init, 0, sizeof(struct index_init));
init.userid = imapd_userid;
init.authstate = imapd_authstate;
init.out = imapd_out;
r = index_open(mbentry->name, &init, &state);
if (!r)
doclose = 1;
if (!r && index_hasrights(state, ACL_READ)) {
r = (imapd_userisadmin || index_hasrights(state, ACL_LOOKUP)) ?
IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT;
}
if (!r) {
if (!index_scan(state, listargs->scan)) {
r = -1; /* no matching messages */
}
}
if (doclose) index_close(&state);
if (r) return;
}
}
/* figure out \Has(No)Children if necessary
This is mainly used for LIST (SUBSCRIBED) RETURN (CHILDREN)
*/
uint32_t have_childinfo =
MBOX_ATTRIBUTE_HASCHILDREN | MBOX_ATTRIBUTE_HASNOCHILDREN;
if ((listargs->ret & LIST_RET_CHILDREN) && !(attributes & have_childinfo)) {
if (imapd_namespace.isalt && !strcmp(extname, "INBOX")) {
/* don't look inside INBOX under altnamespace, its children aren't children */
}
else {
char *intname = NULL, *freeme = NULL;
/* if we got here via subscribed_cb, mbentry isn't set */
if (mbentry)
intname = mbentry->name;
else
intname = freeme = mboxname_from_external(extname, &imapd_namespace, imapd_userid);
mboxlist_mboxtree(intname, set_haschildren, &attributes, MBOXTREE_SKIP_ROOT);
if (freeme) free(freeme);
}
if (!(attributes & MBOX_ATTRIBUTE_HASCHILDREN))
attributes |= MBOX_ATTRIBUTE_HASNOCHILDREN;
}
if (attributes & (MBOX_ATTRIBUTE_NONEXISTENT | MBOX_ATTRIBUTE_NOSELECT)) {
int keep = 0;
/* extended get told everything */
if (listargs->cmd == LIST_CMD_EXTENDED) {
keep = 1;
}
/* we have to mention this, it has children */
if (listargs->cmd == LIST_CMD_LSUB) {
/* subscribed children need a mention */
if (attributes & MBOX_ATTRIBUTE_CHILDINFO_SUBSCRIBED)
keep = 1;
/* if mupdate is configured we can't drop out, we might
* be a backend and need to report folders that don't
* exist on this backend - this is awful and complex
* and brittle and should be changed */
if (config_mupdate_server)
keep = 1;
}
else if (attributes & MBOX_ATTRIBUTE_HASCHILDREN)
keep = 1;
if (!keep) return;
}
if (listargs->cmd == LIST_CMD_LSUB) {
/* \Noselect has a special second meaning with (R)LSUB */
if ( !(attributes & MBOX_ATTRIBUTE_SUBSCRIBED)
&& attributes & MBOX_ATTRIBUTE_CHILDINFO_SUBSCRIBED)
attributes |= MBOX_ATTRIBUTE_NOSELECT | MBOX_ATTRIBUTE_HASCHILDREN;
attributes &= ~MBOX_ATTRIBUTE_SUBSCRIBED;
}
/* As CHILDINFO extended data item is not allowed if the
* RECURSIVEMATCH selection option is not specified */
if (!(listargs->sel & LIST_SEL_RECURSIVEMATCH)) {
attributes &= ~MBOX_ATTRIBUTE_CHILDINFO_SUBSCRIBED;
}
/* no inferiors means no children (this basically means the INBOX
* in alt namespace mode */
if (attributes & MBOX_ATTRIBUTE_NOINFERIORS)
attributes &= ~MBOX_ATTRIBUTE_HASCHILDREN;
/* you can't have both! If it's had children, it has children */
if (attributes & MBOX_ATTRIBUTE_HASCHILDREN)
attributes &= ~MBOX_ATTRIBUTE_HASNOCHILDREN;
/* remove redundant flags */
if (listargs->cmd == LIST_CMD_EXTENDED) {
/* \NoInferiors implies \HasNoChildren */
if (attributes & MBOX_ATTRIBUTE_NOINFERIORS)
attributes &= ~MBOX_ATTRIBUTE_HASNOCHILDREN;
/* \NonExistent implies \Noselect */
if (attributes & MBOX_ATTRIBUTE_NONEXISTENT)
attributes &= ~MBOX_ATTRIBUTE_NOSELECT;
}
if (config_getswitch(IMAPOPT_SPECIALUSEALWAYS) ||
listargs->cmd == LIST_CMD_XLIST ||
listargs->ret & LIST_RET_SPECIALUSE) {
specialuse_flags(mbentry, &specialuse, listargs->cmd == LIST_CMD_XLIST);
}
if (listargs->sel & LIST_SEL_SPECIALUSE) {
/* check that this IS a specialuse folder */
if (!buf_len(&specialuse)) return;
}
/* can we read the status data ? */
if ((listargs->ret & LIST_RET_STATUS) && mbentry) {
r = imapd_statusdata(mbentry->name, listargs->statusitems, &sdata);
if (r) {
/* RFC 5819: the STATUS response MUST NOT be returned and the
* LIST response MUST include the \NoSelect attribute. */
attributes |= MBOX_ATTRIBUTE_NOSELECT;
}
}
print_listresponse(listargs->cmd, extname,
imapd_namespace.hier_sep, attributes, &specialuse);
buf_free(&specialuse);
if ((listargs->ret & LIST_RET_STATUS) &&
!(attributes & MBOX_ATTRIBUTE_NOSELECT)) {
/* output the status line now, per rfc 5819 */
if (mbentry) print_statusline(extname, listargs->statusitems, &sdata);
}
if ((listargs->ret & LIST_RET_MYRIGHTS) &&
!(attributes & MBOX_ATTRIBUTE_NOSELECT)) {
if (mbentry) printmyrights(extname, mbentry);
}
if ((listargs->ret & LIST_RET_METADATA) &&
!(attributes & MBOX_ATTRIBUTE_NOSELECT)) {
if (mbentry)
printmetadata(mbentry, &listargs->metaitems, &listargs->metaopts);
}
}
static void _addsubs(struct list_rock *rock)
{
if (!rock->subs) return;
if (!rock->last_mbentry) return;
int i;
const char *last_name = rock->last_mbentry->name;
int namelen = strlen(last_name);
for (i = 0; i < rock->subs->count; i++) {
const char *name = strarray_nth(rock->subs, i);
if (strncmp(last_name, name, namelen))
continue;
else if (!name[namelen]) {
if ((rock->last_attributes & MBOX_ATTRIBUTE_NONEXISTENT))
rock->last_attributes |= MBOX_ATTRIBUTE_CHILDINFO_SUBSCRIBED;
else
rock->last_attributes |= MBOX_ATTRIBUTE_SUBSCRIBED;
}
else if (name[namelen] == '.')
rock->last_attributes |= MBOX_ATTRIBUTE_CHILDINFO_SUBSCRIBED;
}
}
static int perform_output(const char *extname, const mbentry_t *mbentry, struct list_rock *rock)
{
/* skip non-responsive mailboxes early, so they don't break sub folder detection */
if (mbentry && !imapd_userisadmin) {
if (mbentry->mbtype == MBTYPE_NETNEWS) return 0;
if (!(rock->listargs->sel & LIST_SEL_DAV)) {
if (mboxname_iscalendarmailbox(mbentry->name, mbentry->mbtype)) return 0;
if (mboxname_isaddressbookmailbox(mbentry->name, mbentry->mbtype)) return 0;
if (mboxname_isdavdrivemailbox(mbentry->name, mbentry->mbtype)) return 0;
if (mboxname_isdavnotificationsmailbox(mbentry->name, mbentry->mbtype)) return 0;
}
}
if (mbentry && (mbentry->mbtype & MBTYPE_REMOTE)) {
struct listargs *listargs = rock->listargs;
if (hash_lookup(mbentry->server, &rock->server_table)) {
/* already proxied to this backend server */
return 0;
}
if (listargs->scan ||
(listargs->ret &
(LIST_RET_SPECIALUSE | LIST_RET_STATUS | LIST_RET_METADATA))) {
/* remote mailbox that we need to fetch metadata from */
struct backend *s;
hash_insert(mbentry->server,
(void *)0xDEADBEEF, &rock->server_table);
s = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (s) {
char mytag[128];
proxy_gentag(mytag, sizeof(mytag));
if (listargs->scan) {
/* Send SCAN command to backend */
prot_printf(s->out, "%s Scan {%tu+}\r\n%s {%tu+}\r\n%s"
" {%tu+}\r\n%s\r\n",
mytag, strlen(listargs->ref), listargs->ref,
strlen(listargs->pat.data[0]),
listargs->pat.data[0],
strlen(listargs->scan), listargs->scan);
pipe_until_tag(s, mytag, 0);
}
else {
/* Send LIST command to backend */
list_data_remote(s, mytag, listargs, rock->subs);
}
}
return 0;
}
}
if (rock->last_name) {
if (extname) {
/* same again */
if (!strcmp(rock->last_name, extname)) return 0;
size_t extlen = strlen(extname);
if (extlen < strlen(rock->last_name)
&& rock->last_name[extlen] == imapd_namespace.hier_sep
&& !strncmp(rock->last_name, extname, extlen))
return 0; /* skip duplicate or reversed calls */
}
_addsubs(rock);
/* check if we need to filter out this mailbox */
if (!(rock->listargs->sel & LIST_SEL_SUBSCRIBED) ||
(rock->last_attributes &
(MBOX_ATTRIBUTE_SUBSCRIBED | MBOX_ATTRIBUTE_CHILDINFO_SUBSCRIBED))) {
list_response(rock->last_name, rock->last_mbentry,
rock->last_attributes, rock->listargs);
}
free(rock->last_name);
rock->last_name = NULL;
mboxlist_entry_free(&rock->last_mbentry);
}
if (extname) {
rock->last_name = xstrdup(extname);
if (mbentry) rock->last_mbentry = mboxlist_entry_copy(mbentry);
}
rock->last_attributes = 0;
rock->last_category = 0;
return 1;
}
/* callback for mboxlist_findall
* used when the SUBSCRIBED selection option is NOT given */
static int list_cb(struct findall_data *data, void *rockp)
{
struct list_rock *rock = (struct list_rock *)rockp;
if (!data) {
if (!(rock->last_attributes & MBOX_ATTRIBUTE_HASCHILDREN))
rock->last_attributes |= MBOX_ATTRIBUTE_HASNOCHILDREN;
perform_output(NULL, NULL, rock);
return 0;
}
size_t last_len = (rock->last_name ? strlen(rock->last_name) : 0);
const char *extname = data->extname;
int last_name_is_ancestor =
rock->last_name
&& strlen(extname) >= last_len
&& extname[last_len] == imapd_namespace.hier_sep
&& !memcmp(rock->last_name, extname, last_len);
list_callback_calls++;
/* list_response will calculate haschildren/hasnochildren flags later
* if they're required but not yet set, but it's a little cheaper to
* precalculate them now while we're iterating the mailboxes anyway.
*/
if (last_name_is_ancestor || (rock->last_name && !data->mbname && !strcmp(rock->last_name, extname)))
rock->last_attributes |= MBOX_ATTRIBUTE_HASCHILDREN;
else if (!(rock->last_attributes & MBOX_ATTRIBUTE_HASCHILDREN))
rock->last_attributes |= MBOX_ATTRIBUTE_HASNOCHILDREN;
if (!perform_output(data->extname, data->mbentry, rock))
return 0;
if (!data->mbname)
rock->last_attributes |= MBOX_ATTRIBUTE_HASCHILDREN | MBOX_ATTRIBUTE_NONEXISTENT;
else if (data->mb_category == MBNAME_ALTINBOX)
rock->last_attributes |= MBOX_ATTRIBUTE_NOINFERIORS;
return 0;
}
/* callback for mboxlist_findsub
* used when SUBSCRIBED but not RECURSIVEMATCH is given */
static int subscribed_cb(struct findall_data *data, void *rockp)
{
struct list_rock *rock = (struct list_rock *)rockp;
if (!data) {
perform_output(NULL, NULL, rock);
return 0;
}
size_t last_len = (rock->last_name ? strlen(rock->last_name) : 0);
const char *extname = data->extname;
int last_name_is_ancestor =
rock->last_name
&& strlen(extname) >= last_len
&& extname[last_len] == imapd_namespace.hier_sep
&& !memcmp(rock->last_name, extname, last_len);
list_callback_calls++;
if (last_name_is_ancestor ||
(rock->last_name && !data->mbname && !strcmp(rock->last_name, extname)))
rock->last_attributes |= MBOX_ATTRIBUTE_HASCHILDREN;
if (data->mbname) { /* exact match */
mbentry_t *mbentry = NULL;
mboxlist_lookup(mbname_intname(data->mbname), &mbentry, NULL);
perform_output(extname, mbentry, rock);
mboxlist_entry_free(&mbentry);
rock->last_attributes |= MBOX_ATTRIBUTE_SUBSCRIBED;
if (mboxlist_lookup(mbname_intname(data->mbname), NULL, NULL))
rock->last_attributes |= MBOX_ATTRIBUTE_NONEXISTENT;
if (data->mb_category == MBNAME_ALTINBOX)
rock->last_attributes |= MBOX_ATTRIBUTE_NOINFERIORS;
}
else if (rock->listargs->cmd == LIST_CMD_LSUB) {
/* special case: for LSUB,
* mailbox names that match the pattern but aren't subscribed
* must also be returned if they have a child mailbox that is
* subscribed */
perform_output(extname, data->mbentry, rock);
rock->last_attributes |= MBOX_ATTRIBUTE_CHILDINFO_SUBSCRIBED;
}
return 0;
}
/*
* Takes the "reference name" and "mailbox name" arguments of the LIST command
* and returns a "canonical LIST pattern". The caller is responsible for
* free()ing the returned string.
*/
static char *canonical_list_pattern(const char *reference, const char *pattern)
{
int patlen = strlen(pattern);
int reflen = strlen(reference);
char *buf = xmalloc(patlen + reflen + 1);
buf[0] = '\0';
if (*reference) {
if (reference[reflen-1] == imapd_namespace.hier_sep &&
pattern[0] == imapd_namespace.hier_sep)
--reflen;
memcpy(buf, reference, reflen);
buf[reflen] = '\0';
}
strcat(buf, pattern);
return buf;
}
/*
* Turns the strings in patterns into "canonical LIST pattern"s. Also
* translates any hierarchy separators.
*/
static void canonical_list_patterns(const char *reference,
strarray_t *patterns)
{
static int ignorereference = 0;
int i;
/* Ignore the reference argument?
(the behavior in 1.5.10 & older) */
if (ignorereference == 0)
ignorereference = config_getswitch(IMAPOPT_IGNOREREFERENCE);
for (i = 0 ; i < patterns->count ; i++) {
char *p = patterns->data[i];
if (!ignorereference || p[0] == imapd_namespace.hier_sep) {
strarray_setm(patterns, i,
canonical_list_pattern(reference, p));
p = patterns->data[i];
}
}
}
static void list_data_remotesubscriptions(struct listargs *listargs)
{
/* Need to fetch subscription list from backend_inbox */
struct list_rock rock;
char mytag[128];
memset(&rock, 0, sizeof(struct list_rock));
rock.listargs = listargs;
rock.subs = strarray_new();
construct_hash_table(&rock.server_table, 10, 1);
proxy_gentag(mytag, sizeof(mytag));
if ((listargs->sel & LIST_SEL_SUBSCRIBED) &&
!(listargs->sel & (LIST_SEL_SPECIALUSE | LIST_SEL_METADATA))) {
/* Subscriptions are the only selection criteria.
Send client request as-is to backend_inbox.
Responses will be piped to the client as we build subs list.
*/
list_data_remote(backend_inbox, mytag, listargs, rock.subs);
/* Don't proxy to backend_inbox again */
hash_insert(backend_inbox->hostname,
(void *)0xDEADBEEF, &rock.server_table);
}
else {
/* Multiple selection criteria or need to return subscription info.
Just fetch subscriptions without piping responses to the client.
If we send entire client request, subscribed mailboxes on
non-Inbox servers might be filtered out due to lack of metadata
to meet the selection criteria.
Note that we end up sending two requests to backend_inbox,
but there doesn't appear to be any way around this.
*/
struct listargs myargs;
memcpy(&myargs, listargs, sizeof(struct listargs));
myargs.sel = LIST_SEL_SUBSCRIBED;
myargs.ret = 0;
list_data_remote(backend_inbox, mytag, &myargs, rock.subs);
}
/* find */
mboxlist_findallmulti(&imapd_namespace, &listargs->pat,
imapd_userisadmin, imapd_userid,
imapd_authstate, list_cb, &rock);
strarray_free(rock.subs);
free_hash_table(&rock.server_table, NULL);
if (rock.last_name) free(rock.last_name);
}
/* callback for mboxlist_findsub
* used by list_data_recursivematch */
static int recursivematch_cb(struct findall_data *data, void *rockp)
{
if (!data) return 0;
struct list_rock_recursivematch *rock = (struct list_rock_recursivematch *)rockp;
list_callback_calls++;
const char *extname = data->extname;
/* skip non-responsive mailboxes early, so they don't break sub folder detection */
if (!(imapd_userisadmin || (rock->listargs->sel & LIST_SEL_DAV))) {
mbname_t *mbname = (mbname_t *) data->mbname;
const char *intname;
int r;
if (!mbname) {
mbname = mbname_from_extname(extname, &imapd_namespace, imapd_userid);
}
intname = mbname_intname(mbname);
r = mboxname_iscalendarmailbox(intname, 0) ||
mboxname_isaddressbookmailbox(intname, 0) ||
mboxname_isdavdrivemailbox(intname, 0) ||
mboxname_isdavnotificationsmailbox(intname, 0);
if (!data->mbname) mbname_free(&mbname);
if (r) return 0;
}
uint32_t *list_info = hash_lookup(extname, &rock->table);
if (!list_info) {
list_info = xzmalloc(sizeof(uint32_t));
hash_insert(extname, list_info, &rock->table);
rock->count++;
}
if (data->mbname) { /* exact match */
*list_info |= MBOX_ATTRIBUTE_SUBSCRIBED;
}
else {
*list_info |= MBOX_ATTRIBUTE_CHILDINFO_SUBSCRIBED | MBOX_ATTRIBUTE_HASCHILDREN;
}
return 0;
}
/* callback for hash_enumerate */
static void copy_to_array(const char *key, void *data, void *void_rock)
{
uint32_t *attributes = (uint32_t *)data;
struct list_rock_recursivematch *rock =
(struct list_rock_recursivematch *)void_rock;
assert(rock->count > 0);
rock->array[--rock->count].name = key;
rock->array[rock->count].attributes = *attributes;
}
/* Comparator for sorting an array of struct list_entry by mboxname. */
static int list_entry_comparator(const void *p1, const void *p2) {
const struct list_entry *e1 = (struct list_entry *)p1;
const struct list_entry *e2 = (struct list_entry *)p2;
return bsearch_compare_mbox(e1->name, e2->name);
}
static void list_data_recursivematch(struct listargs *listargs) {
struct list_rock_recursivematch rock;
rock.count = 0;
rock.listargs = listargs;
construct_hash_table(&rock.table, 100, 1);
/* find */
mboxlist_findsubmulti(&imapd_namespace, &listargs->pat, imapd_userisadmin, imapd_userid,
imapd_authstate, recursivematch_cb, &rock, 1);
if (rock.count) {
int i;
int entries = rock.count;
/* sort */
rock.array = xmalloc(entries * (sizeof(struct list_entry)));
hash_enumerate(&rock.table, copy_to_array, &rock);
qsort(rock.array, entries, sizeof(struct list_entry),
list_entry_comparator);
assert(rock.count == 0);
/* print */
for (i = 0; i < entries; i++) {
if (!rock.array[i].name) continue;
mbentry_t *mbentry = NULL;
mboxlist_lookup(rock.array[i].name, &mbentry, NULL);
list_response(rock.array[i].name,
mbentry,
rock.array[i].attributes,
rock.listargs);
mboxlist_entry_free(&mbentry);
}
free(rock.array);
}
free_hash_table(&rock.table, free);
}
/* Retrieves the data and prints the untagged responses for a LIST command. */
static void list_data(struct listargs *listargs)
{
canonical_list_patterns(listargs->ref, &listargs->pat);
/* Check to see if we should only list the personal namespace */
if (!(listargs->cmd == LIST_CMD_EXTENDED)
&& !strcmp(listargs->pat.data[0], "*")
&& config_getswitch(IMAPOPT_FOOLSTUPIDCLIENTS)) {
strarray_set(&listargs->pat, 0, "INBOX*");
}
if ((listargs->ret & LIST_RET_SUBSCRIBED) &&
(backend_inbox || (backend_inbox = proxy_findinboxserver(imapd_userid)))) {
list_data_remotesubscriptions(listargs);
}
else if (listargs->sel & LIST_SEL_RECURSIVEMATCH) {
list_data_recursivematch(listargs);
}
else {
struct list_rock rock;
memset(&rock, 0, sizeof(struct list_rock));
rock.listargs = listargs;
if (listargs->sel & LIST_SEL_SUBSCRIBED) {
mboxlist_findsubmulti(&imapd_namespace, &listargs->pat,
imapd_userisadmin, imapd_userid,
imapd_authstate, subscribed_cb, &rock, 1);
}
else {
if (config_mupdate_server) {
/* In case we proxy to backends due to select/return criteria */
construct_hash_table(&rock.server_table, 10, 1);
}
/* XXX: is there a cheaper way to figure out \Subscribed? */
if (listargs->ret & LIST_RET_SUBSCRIBED) {
rock.subs = mboxlist_sublist(imapd_userid);
}
mboxlist_findallmulti(&imapd_namespace, &listargs->pat,
imapd_userisadmin, imapd_userid,
imapd_authstate, list_cb, &rock);
if (rock.subs) strarray_free(rock.subs);
if (rock.server_table.size)
free_hash_table(&rock.server_table, NULL);
}
if (rock.last_name) free(rock.last_name);
}
}
/*
* Retrieves the data and prints the untagged responses for a LIST command in
* the case of a remote inbox.
*/
static int list_data_remote(struct backend *be, char *tag,
struct listargs *listargs, strarray_t *subs)
{
if ((listargs->cmd == LIST_CMD_EXTENDED) &&
!CAPA(be, CAPA_LISTEXTENDED)) {
/* client wants to use extended list command but backend doesn't
* support it */
prot_printf(imapd_out,
"%s NO Backend server does not support LIST-EXTENDED\r\n",
tag);
return IMAP_MAILBOX_NOTSUPPORTED;
}
/* print tag, command and list selection options */
if (listargs->cmd == LIST_CMD_LSUB) {
prot_printf(be->out, "%s Lsub ", tag);
} else if (listargs->cmd == LIST_CMD_XLIST) {
prot_printf(be->out, "%s Xlist ", tag);
} else {
prot_printf(be->out, "%s List ", tag);
uint32_t select_mask = listargs->sel;
if (be != backend_inbox) {
/* don't send subscribed selection options to non-Inbox backend */
select_mask &= ~(LIST_SEL_SUBSCRIBED | LIST_SEL_RECURSIVEMATCH);
}
/* print list selection options */
if (select_mask) {
const char *select_opts[] = {
/* XXX MUST be in same order as LIST_SEL_* bitmask */
"subscribed", "remote", "recursivematch",
"special-use", "vendor.cmu-dav", "metadata", NULL
};
char c = '(';
int i;
for (i = 0; select_opts[i]; i++) {
unsigned opt = (1 << i);
if (!(select_mask & opt)) continue;
prot_printf(be->out, "%c%s", c, select_opts[i]);
c = ' ';
if (opt == LIST_SEL_METADATA) {
/* print metadata options */
prot_puts(be->out, " (depth ");
if (listargs->metaopts.depth < 0) {
prot_puts(be->out, "infinity");
}
else {
prot_printf(be->out, "%d",
listargs->metaopts.depth);
}
if (listargs->metaopts.maxsize) {
prot_printf(be->out, " maxsize %zu",
listargs->metaopts.maxsize);
}
(void)prot_putc(')', be->out);
}
}
prot_puts(be->out, ") ");
}
}
/* print reference argument */
prot_printf(be->out,
"{%tu+}\r\n%s ", strlen(listargs->ref), listargs->ref);
/* print mailbox pattern(s) */
if (listargs->pat.count > 1) {
char **p;
char c = '(';
for (p = listargs->pat.data ; *p ; p++) {
prot_printf(be->out,
"%c{%tu+}\r\n%s", c, strlen(*p), *p);
c = ' ';
}
(void)prot_putc(')', be->out);
} else {
prot_printf(be->out, "{%tu+}\r\n%s",
strlen(listargs->pat.data[0]), listargs->pat.data[0]);
}
/* print list return options */
if (listargs->ret && listargs->cmd == LIST_CMD_EXTENDED) {
const char *return_opts[] = {
/* XXX MUST be in same order as LIST_RET_* bitmask */
"subscribed", "children", "special-use",
"status ", "myrights", "metadata ", NULL
};
char c = '(';
int i, j;
prot_puts(be->out, " return ");
for (i = 0; return_opts[i]; i++) {
unsigned opt = (1 << i);
if (!(listargs->ret & opt)) continue;
prot_printf(be->out, "%c%s", c, return_opts[i]);
c = ' ';
if (opt == LIST_RET_STATUS) {
/* print status items */
const char *status_items[] = {
/* XXX MUST be in same order as STATUS_* bitmask */
"messages", "recent", "uidnext", "uidvalidity", "unseen",
"highestmodseq", "xconvexists", "xconvunseen",
"xconvmodseq", NULL
};
c = '(';
for (j = 0; status_items[j]; j++) {
if (!(listargs->statusitems & (1 << j))) continue;
prot_printf(be->out, "%c%s", c, status_items[j]);
c = ' ';
}
(void)prot_putc(')', be->out);
}
else if (opt == LIST_RET_METADATA) {
/* print metadata items */
int n = strarray_size(&listargs->metaitems);
c = '(';
for (j = 0; j < n; j++) {
prot_printf(be->out, "%c\"%s\"", c,
strarray_nth(&listargs->metaitems, j));
c = ' ';
}
(void)prot_putc(')', be->out);
}
}
(void)prot_putc(')', be->out);
}
prot_printf(be->out, "\r\n");
pipe_lsub(be, imapd_userid, tag, 0, listargs, subs);
return 0;
}
/* Reset the given sasl_conn_t to a sane state */
static int reset_saslconn(sasl_conn_t **conn)
{
int ret;
sasl_security_properties_t *secprops = NULL;
sasl_dispose(conn);
/* do initialization typical of service_main */
ret = sasl_server_new("imap", config_servername,
NULL, NULL, NULL,
NULL, 0, conn);
if(ret != SASL_OK) return ret;
if(saslprops.ipremoteport)
ret = sasl_setprop(*conn, SASL_IPREMOTEPORT,
saslprops.ipremoteport);
if(ret != SASL_OK) return ret;
if(saslprops.iplocalport)
ret = sasl_setprop(*conn, SASL_IPLOCALPORT,
saslprops.iplocalport);
if(ret != SASL_OK) return ret;
secprops = mysasl_secprops(0);
ret = sasl_setprop(*conn, SASL_SEC_PROPS, secprops);
if(ret != SASL_OK) return ret;
/* end of service_main initialization excepting SSF */
/* If we have TLS/SSL info, set it */
if(saslprops.ssf) {
ret = sasl_setprop(*conn, SASL_SSF_EXTERNAL, &saslprops.ssf);
} else {
ret = sasl_setprop(*conn, SASL_SSF_EXTERNAL, &extprops_ssf);
}
if(ret != SASL_OK) return ret;
if(saslprops.authid) {
ret = sasl_setprop(*conn, SASL_AUTH_EXTERNAL, saslprops.authid);
if(ret != SASL_OK) return ret;
}
/* End TLS/SSL Info */
return SASL_OK;
}
static void cmd_mupdatepush(char *tag, char *name)
{
int r = 0, retry = 0;
mbentry_t *mbentry = NULL;
char buf[MAX_PARTITION_LEN + HOSTNAME_SIZE + 2];
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
if (!imapd_userisadmin) {
r = IMAP_PERMISSION_DENIED;
goto done;
}
if (!config_mupdate_server) {
r = IMAP_SERVER_UNAVAILABLE;
goto done;
}
r = mlookup(tag, name, intname, &mbentry);
if (r) goto done;
/* Push mailbox to mupdate server */
if (!mupdate_h) {
syslog(LOG_INFO, "XFER: connecting to mupdate '%s'",
config_mupdate_server);
r = mupdate_connect(config_mupdate_server, NULL, &mupdate_h, NULL);
retry = 1;
if (r) {
syslog(LOG_INFO, "Failed to connect to mupdate '%s'",
config_mupdate_server);
goto done;
}
}
snprintf(buf, sizeof(buf), "%s!%s",
config_servername, mbentry->partition);
retry:
r = mupdate_activate(mupdate_h, intname, buf, mbentry->acl);
if (r && !retry) {
syslog(LOG_INFO, "MUPDATE: lost connection, retrying");
mupdate_disconnect(&mupdate_h);
r = mupdate_connect(config_mupdate_server, NULL, &mupdate_h, NULL);
if (r) {
syslog(LOG_INFO, "Failed to connect to mupdate '%s'",
config_mupdate_server);
}
else {
retry = 1;
goto retry;
}
}
done:
mboxlist_entry_free(&mbentry);
free(intname);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
}
else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
}
#ifdef HAVE_SSL
enum {
URLAUTH_ALG_HMAC_SHA1 = 0 /* HMAC-SHA1 */
};
static void cmd_urlfetch(char *tag)
{
struct mboxkey *mboxkey_db;
int c, r, doclose;
static struct buf arg, param;
struct imapurl url;
struct index_state *state;
uint32_t msgno;
mbentry_t *mbentry = NULL;
time_t now = time(NULL);
unsigned extended, params;
prot_printf(imapd_out, "* URLFETCH");
do {
char *intname = NULL;
extended = params = 0;
/* See if its an extended URLFETCH */
c = prot_getc(imapd_in);
if (c == '(') extended = 1;
else prot_ungetc(c, imapd_in);
c = getastring(imapd_in, imapd_out, &arg);
(void)prot_putc(' ', imapd_out);
prot_printstring(imapd_out, arg.s);
if (extended) {
while (c == ' ') {
c = getword(imapd_in, ¶m);
ucase(param.s);
if (!strcmp(param.s, "BODY")) {
if (params & (URLFETCH_BODY | URLFETCH_BINARY)) goto badext;
params |= URLFETCH_BODY;
} else if (!strcmp(param.s, "BINARY")) {
if (params & (URLFETCH_BODY | URLFETCH_BINARY)) goto badext;
params |= URLFETCH_BINARY;
} else if (!strcmp(param.s, "BODYPARTSTRUCTURE")) {
if (params & URLFETCH_BODYPARTSTRUCTURE) goto badext;
params |= URLFETCH_BODYPARTSTRUCTURE;
} else {
goto badext;
}
}
if (c != ')') goto badext;
c = prot_getc(imapd_in);
}
doclose = 0;
r = imapurl_fromURL(&url, arg.s);
/* validate the URL */
if (r || !url.user || !url.server || !url.mailbox || !url.uid ||
(url.section && !*url.section) ||
(url.urlauth.access && !(url.urlauth.mech && url.urlauth.token))) {
/* missing info */
r = IMAP_BADURL;
} else if (strcmp(url.server, config_servername)) {
/* wrong server */
r = IMAP_BADURL;
} else if (url.urlauth.expire &&
url.urlauth.expire < mktime(gmtime(&now))) {
/* expired */
r = IMAP_BADURL;
} else if (url.urlauth.access) {
/* check mechanism & authorization */
int authorized = 0;
if (!strcasecmp(url.urlauth.mech, "INTERNAL")) {
if (!strncasecmp(url.urlauth.access, "submit+", 7) &&
global_authisa(imapd_authstate, IMAPOPT_SUBMITSERVERS)) {
/* authorized submit server */
authorized = 1;
} else if (!strncasecmp(url.urlauth.access, "user+", 5) &&
!strcmp(url.urlauth.access+5, imapd_userid)) {
/* currently authorized user */
authorized = 1;
} else if (!strcasecmp(url.urlauth.access, "authuser") &&
strcmp(imapd_userid, "anonymous")) {
/* any non-anonymous authorized user */
authorized = 1;
} else if (!strcasecmp(url.urlauth.access, "anonymous")) {
/* anyone */
authorized = 1;
}
}
if (!authorized) r = IMAP_BADURL;
}
if (r) goto err;
intname = mboxname_from_external(url.mailbox, &imapd_namespace, url.user);
r = mlookup(NULL, NULL, intname, &mbentry);
if (r) goto err;
if ((mbentry->mbtype & MBTYPE_REMOTE)) {
/* remote mailbox */
struct backend *be;
be = proxy_findserver(mbentry->server, &imap_protocol,
proxy_userid, &backend_cached,
&backend_current, &backend_inbox, imapd_in);
if (!be) {
r = IMAP_SERVER_UNAVAILABLE;
} else {
/* XXX proxy command to backend */
}
free(url.freeme);
mboxlist_entry_free(&mbentry);
free(intname);
continue;
}
mboxlist_entry_free(&mbentry);
/* local mailbox */
if (url.urlauth.token) {
/* validate the URLAUTH token */
/* yes, this is evil, in-place conversion from hex
* to binary */
if (hex_to_bin(url.urlauth.token, 0,
(unsigned char *) url.urlauth.token) < 1) {
r = IMAP_BADURL;
break;
}
/* first byte is the algorithm used to create token */
switch (url.urlauth.token[0]) {
case URLAUTH_ALG_HMAC_SHA1: {
const char *key;
size_t keylen;
unsigned char vtoken[EVP_MAX_MD_SIZE];
unsigned int vtoken_len;
r = mboxkey_open(url.user, 0, &mboxkey_db);
if (r) break;
r = mboxkey_read(mboxkey_db, intname, &key, &keylen);
if (r) break;
HMAC(EVP_sha1(), key, keylen, (unsigned char *) arg.s,
url.urlauth.rump_len, vtoken, &vtoken_len);
mboxkey_close(mboxkey_db);
if (memcmp(vtoken, url.urlauth.token+1, vtoken_len)) {
r = IMAP_BADURL;
}
break;
}
default:
r = IMAP_BADURL;
break;
}
}
if (r) goto err;
if (!strcmp(index_mboxname(imapd_index), intname)) {
state = imapd_index;
}
else {
/* not the currently selected mailbox, so try to open it */
r = index_open(intname, NULL, &state);
if (!r)
doclose = 1;
if (!r && !url.urlauth.access &&
!(state->myrights & ACL_READ)) {
r = (imapd_userisadmin ||
(state->myrights & ACL_LOOKUP)) ?
IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT;
}
}
if (r) goto err;
if (url.uidvalidity &&
(state->mailbox->i.uidvalidity != url.uidvalidity)) {
r = IMAP_BADURL;
} else if (!url.uid || !(msgno = index_finduid(state, url.uid)) ||
(index_getuid(state, msgno) != url.uid)) {
r = IMAP_BADURL;
} else {
r = index_urlfetch(state, msgno, params, url.section,
url.start_octet, url.octet_count,
imapd_out, NULL);
}
if (doclose)
index_close(&state);
err:
free(url.freeme);
if (r) prot_printf(imapd_out, " NIL");
free(intname);
} while (c == ' ');
prot_printf(imapd_out, "\r\n");
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to URLFETCH\r\n", tag);
eatline(imapd_in, c);
}
else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
return;
badext:
prot_printf(imapd_out, " NIL\r\n");
prot_printf(imapd_out,
"%s BAD Invalid extended URLFETCH parameters\r\n", tag);
eatline(imapd_in, c);
}
#define MBOX_KEY_LEN 16 /* 128 bits */
static void cmd_genurlauth(char *tag)
{
struct mboxkey *mboxkey_db;
int first = 1;
int c, r;
static struct buf arg1, arg2;
struct imapurl url;
char newkey[MBOX_KEY_LEN];
char *urlauth = NULL;
const char *key;
size_t keylen;
unsigned char token[EVP_MAX_MD_SIZE+1]; /* +1 for algorithm */
unsigned int token_len;
mbentry_t *mbentry = NULL;
time_t now = time(NULL);
r = mboxkey_open(imapd_userid, MBOXKEY_CREATE, &mboxkey_db);
if (r) {
prot_printf(imapd_out,
"%s NO Cannot open mailbox key db for %s: %s\r\n",
tag, imapd_userid, error_message(r));
return;
}
do {
char *intname = NULL;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') {
prot_printf(imapd_out,
"%s BAD Missing required argument to Genurlauth\r\n",
tag);
eatline(imapd_in, c);
return;
}
c = getword(imapd_in, &arg2);
if (strcasecmp(arg2.s, "INTERNAL")) {
prot_printf(imapd_out,
"%s BAD Unknown auth mechanism to Genurlauth %s\r\n",
tag, arg2.s);
eatline(imapd_in, c);
return;
}
r = imapurl_fromURL(&url, arg1.s);
/* validate the URL */
if (r || !url.user || !url.server || !url.mailbox || !url.uid ||
(url.section && !*url.section) || !url.urlauth.access) {
r = IMAP_BADURL;
} else if (strcmp(url.user, imapd_userid)) {
/* not using currently authorized user's namespace */
r = IMAP_BADURL;
} else if (strcmp(url.server, config_servername)) {
/* wrong server */
r = IMAP_BADURL;
} else if (url.urlauth.expire &&
url.urlauth.expire < mktime(gmtime(&now))) {
/* already expired */
r = IMAP_BADURL;
}
if (r) goto err;
intname = mboxname_from_external(url.mailbox, &imapd_namespace, imapd_userid);
r = mlookup(NULL, NULL, intname, &mbentry);
if (r) {
prot_printf(imapd_out,
"%s BAD Poorly specified URL to Genurlauth %s\r\n",
tag, arg1.s);
eatline(imapd_in, c);
free(url.freeme);
free(intname);
return;
}
if (mbentry->mbtype & MBTYPE_REMOTE) {
/* XXX proxy to backend */
mboxlist_entry_free(&mbentry);
free(url.freeme);
free(intname);
continue;
}
mboxlist_entry_free(&mbentry);
/* lookup key */
r = mboxkey_read(mboxkey_db, intname, &key, &keylen);
if (r) {
syslog(LOG_ERR, "DBERROR: error fetching mboxkey: %s",
cyrusdb_strerror(r));
}
else if (!key) {
/* create a new key */
RAND_bytes((unsigned char *) newkey, MBOX_KEY_LEN);
key = newkey;
keylen = MBOX_KEY_LEN;
r = mboxkey_write(mboxkey_db, intname, key, keylen);
if (r) {
syslog(LOG_ERR, "DBERROR: error writing new mboxkey: %s",
cyrusdb_strerror(r));
}
}
if (r) {
err:
eatline(imapd_in, c);
prot_printf(imapd_out,
"%s NO Error authorizing %s: %s\r\n",
tag, arg1.s, cyrusdb_strerror(r));
free(url.freeme);
free(intname);
return;
}
/* first byte is the algorithm used to create token */
token[0] = URLAUTH_ALG_HMAC_SHA1;
HMAC(EVP_sha1(), key, keylen, (unsigned char *) arg1.s, strlen(arg1.s),
token+1, &token_len);
token_len++;
urlauth = xrealloc(urlauth, strlen(arg1.s) + 10 +
2 * (EVP_MAX_MD_SIZE+1) + 1);
strcpy(urlauth, arg1.s);
strcat(urlauth, ":internal:");
bin_to_hex(token, token_len, urlauth+strlen(urlauth), BH_LOWER);
if (first) {
prot_printf(imapd_out, "* GENURLAUTH");
first = 0;
}
(void)prot_putc(' ', imapd_out);
prot_printstring(imapd_out, urlauth);
free(intname);
free(url.freeme);
} while (c == ' ');
if (!first) prot_printf(imapd_out, "\r\n");
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to GENURLAUTH\r\n", tag);
eatline(imapd_in, c);
}
else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
free(urlauth);
mboxkey_close(mboxkey_db);
}
static void cmd_resetkey(char *tag, char *name,
char *mechanism __attribute__((unused)))
/* XXX we don't support any external mechanisms, so we ignore it */
{
int r;
if (name) {
/* delete key for specified mailbox */
struct mboxkey *mboxkey_db;
mbentry_t *mbentry = NULL;
char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(NULL, NULL, intname, &mbentry);
if (r) {
prot_printf(imapd_out, "%s NO Error removing key: %s\r\n",
tag, error_message(r));
free(intname);
return;
}
if (mbentry->mbtype & MBTYPE_REMOTE) {
/* XXX proxy to backend */
mboxlist_entry_free(&mbentry);
free(intname);
return;
}
mboxlist_entry_free(&mbentry);
r = mboxkey_open(imapd_userid, MBOXKEY_CREATE, &mboxkey_db);
if (!r) {
r = mboxkey_write(mboxkey_db, intname, NULL, 0);
mboxkey_close(mboxkey_db);
}
if (r) {
prot_printf(imapd_out, "%s NO Error removing key: %s\r\n",
tag, cyrusdb_strerror(r));
} else {
prot_printf(imapd_out,
"%s OK [URLMECH INTERNAL] key removed\r\n", tag);
}
free(intname);
}
else {
/* delete ALL keys */
/* XXX what do we do about multiple backends? */
r = mboxkey_delete_user(imapd_userid);
if (r) {
prot_printf(imapd_out, "%s NO Error removing keys: %s\r\n",
tag, cyrusdb_strerror(r));
} else {
prot_printf(imapd_out, "%s OK All keys removed\r\n", tag);
}
}
}
#endif /* HAVE_SSL */
#ifdef HAVE_ZLIB
static void cmd_compress(char *tag, char *alg)
{
if (imapd_compress_done) {
prot_printf(imapd_out,
"%s BAD [COMPRESSIONACTIVE] DEFLATE active via COMPRESS\r\n",
tag);
}
#if defined(HAVE_SSL) && (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
else if (imapd_tls_comp) {
prot_printf(imapd_out,
"%s NO [COMPRESSIONACTIVE] %s active via TLS\r\n",
tag, SSL_COMP_get_name(imapd_tls_comp));
}
#endif // defined(HAVE_SSL) && (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
else if (strcasecmp(alg, "DEFLATE")) {
prot_printf(imapd_out,
"%s NO Unknown COMPRESS algorithm: %s\r\n", tag, alg);
}
else if (ZLIB_VERSION[0] != zlibVersion()[0]) {
prot_printf(imapd_out,
"%s NO Error initializing %s (incompatible zlib version)\r\n",
tag, alg);
}
else {
prot_printf(imapd_out,
"%s OK %s active\r\n", tag, alg);
/* enable (de)compression for the prot layer */
prot_setcompress(imapd_in);
prot_setcompress(imapd_out);
imapd_compress_done = 1;
}
}
#endif /* HAVE_ZLIB */
static void cmd_enable(char *tag)
{
static struct buf arg;
int c;
unsigned new_capa = 0;
/* RFC5161 says that enable while selected is actually bogus,
* but it's no skin off our nose to support it, so don't
* bother checking */
do {
c = getword(imapd_in, &arg);
if (!arg.s[0]) {
prot_printf(imapd_out,
"\r\n%s BAD Missing required argument to Enable\r\n",
tag);
eatline(imapd_in, c);
return;
}
if (!strcasecmp(arg.s, "condstore"))
new_capa |= CAPA_CONDSTORE;
else if (!strcasecmp(arg.s, "qresync"))
new_capa |= CAPA_QRESYNC | CAPA_CONDSTORE;
} while (c == ' ');
/* check for CRLF */
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Enable\r\n", tag);
eatline(imapd_in, c);
return;
}
int started = 0;
if (!(client_capa & CAPA_CONDSTORE) &&
(new_capa & CAPA_CONDSTORE)) {
if (!started) prot_printf(imapd_out, "* ENABLED");
started = 1;
prot_printf(imapd_out, " CONDSTORE");
}
if (!(client_capa & CAPA_QRESYNC) &&
(new_capa & CAPA_QRESYNC)) {
if (!started) prot_printf(imapd_out, "* ENABLED");
started = 1;
prot_printf(imapd_out, " QRESYNC");
}
if (started) prot_printf(imapd_out, "\r\n");
/* track the new capabilities */
client_capa |= new_capa;
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
static void cmd_xkillmy(const char *tag, const char *cmdname)
{
char *cmd = xstrdup(cmdname);
char *p;
/* normalise to imapd conventions */
if (Uislower(cmd[0]))
cmd[0] = toupper((unsigned char) cmd[0]);
for (p = cmd+1; *p; p++) {
if (Uisupper(*p)) *p = tolower((unsigned char) *p);
}
proc_killusercmd(imapd_userid, cmd, SIGUSR2);
free(cmd);
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
static void cmd_xforever(const char *tag)
{
unsigned n = 1;
int r = 0;
while (!r) {
sleep(1);
prot_printf(imapd_out, "* FOREVER %u\r\n", n++);
prot_flush(imapd_out);
r = cmd_cancelled();
}
prot_printf(imapd_out, "%s OK %s\r\n", tag, error_message(r));
}
static void cmd_xmeid(const char *tag, const char *id)
{
mboxevent_set_client_id(id);
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
/***************************** server-side sync *****************************/
static void cmd_syncapply(const char *tag, struct dlist *kin, struct sync_reserve_list *reserve_list)
{
struct sync_state sync_state = {
imapd_userid,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_authstate,
&imapd_namespace,
imapd_out,
0 /* local_only */
};
/* administrators only please */
if (!imapd_userisadmin) {
syslog(LOG_ERR, "SYNCERROR: invalid user %s trying to sync", imapd_userid);
prot_printf(imapd_out, "%s NO only admininstrators may use sync commands\r\n", tag);
return;
}
const char *resp = sync_apply(kin, reserve_list, &sync_state);
prot_printf(imapd_out, "%s %s\r\n", tag, resp);
/* Reset inactivity timer in case we spent a long time processing data */
prot_resettimeout(imapd_in);
}
static void cmd_syncget(const char *tag, struct dlist *kin)
{
struct sync_state sync_state = {
imapd_userid,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_authstate,
&imapd_namespace,
imapd_out,
0 /* local_only */
};
/* administrators only please */
if (!imapd_userisadmin) {
syslog(LOG_ERR, "SYNCERROR: invalid user %s trying to sync", imapd_userid);
prot_printf(imapd_out, "%s NO only admininstrators may use sync commands\r\n", tag);
return;
}
const char *resp = sync_get(kin, &sync_state);
prot_printf(imapd_out, "%s %s\r\n", tag, resp);
/* Reset inactivity timer in case we spent a long time processing data */
prot_resettimeout(imapd_in);
}
/* partition_list is simple linked list of names used by cmd_syncrestart */
struct partition_list {
struct partition_list *next;
char *name;
};
static struct partition_list *
partition_list_add(char *name, struct partition_list *pl)
{
struct partition_list *p;
/* Is name already on list? */
for (p=pl; p; p = p->next) {
if (!strcmp(p->name, name))
return(pl);
}
/* Add entry to start of list and return new list */
p = xzmalloc(sizeof(struct partition_list));
p->next = pl;
p->name = xstrdup(name);
return(p);
}
static void
partition_list_free(struct partition_list *current)
{
while (current) {
struct partition_list *next = current->next;
free(current->name);
free(current);
current = next;
}
}
static void cmd_syncrestart(const char *tag, struct sync_reserve_list **reserve_listp, int re_alloc)
{
struct sync_reserve *res;
struct sync_reserve_list *l = *reserve_listp;
struct sync_msgid *msg;
int hash_size = l->hash_size;
struct partition_list *p, *pl = NULL;
for (res = l->head; res; res = res->next) {
for (msg = res->list->head; msg; msg = msg->next) {
if (!msg->fname) continue;
pl = partition_list_add(res->part, pl);
unlink(msg->fname);
}
}
sync_reserve_list_free(reserve_listp);
/* Remove all <partition>/sync./<pid> directories referred to above */
for (p=pl; p ; p = p->next) {
static char buf[MAX_MAILBOX_PATH];
snprintf(buf, MAX_MAILBOX_PATH, "%s/sync./%lu",
config_partitiondir(p->name), (unsigned long)getpid());
rmdir(buf);
/* and the archive partition too */
snprintf(buf, MAX_MAILBOX_PATH, "%s/sync./%lu",
config_archivepartitiondir(p->name), (unsigned long)getpid());
rmdir(buf);
}
partition_list_free(pl);
if (re_alloc) {
*reserve_listp = sync_reserve_list_create(hash_size);
prot_printf(imapd_out, "%s OK Restarting\r\n", tag);
}
else
*reserve_listp = NULL;
}
static void cmd_syncrestore(const char *tag, struct dlist *kin,
struct sync_reserve_list *reserve_list)
{
struct sync_state sync_state = {
imapd_userid,
imapd_userisadmin || imapd_userisproxyadmin,
imapd_authstate,
&imapd_namespace,
imapd_out,
0 /* local_only */
};
/* administrators only please */
if (!imapd_userisadmin) {
syslog(LOG_ERR, "SYNCERROR: invalid user %s trying to sync", imapd_userid);
prot_printf(imapd_out, "%s NO only admininstrators may use sync commands\r\n", tag);
return;
}
const char *resp = sync_restore(kin, reserve_list, &sync_state);
prot_printf(imapd_out, "%s %s\r\n", tag, resp);
/* Reset inactivity timer in case we spent a long time processing data */
prot_resettimeout(imapd_in);
}
static void cmd_xapplepushservice(const char *tag,
struct applepushserviceargs *applepushserviceargs)
{
int r = 0;
strarray_t notif_mailboxes = STRARRAY_INITIALIZER;
int i;
mbentry_t *mbentry = NULL;
const char *aps_topic = config_getstring(IMAPOPT_APS_TOPIC);
if (!aps_topic) {
syslog(LOG_ERR,
"aps_topic not configured, can't complete XAPPLEPUSHSERVICE response");
prot_printf(imapd_out, "%s NO Server configuration error\r\n", tag);
return;
}
if (!buf_len(&applepushserviceargs->aps_account_id)) {
prot_printf(imapd_out, "%s NO Missing APNS account ID\r\n", tag);
return;
}
if (!buf_len(&applepushserviceargs->aps_device_token)) {
prot_printf(imapd_out, "%s NO Missing APNS device token\r\n", tag);
return;
}
if (!buf_len(&applepushserviceargs->aps_subtopic)) {
prot_printf(imapd_out, "%s NO Missing APNS sub-topic\r\n", tag);
return;
}
// v1 is inbox-only, so override the mailbox list
if (applepushserviceargs->aps_version == 1) {
strarray_truncate(&applepushserviceargs->mailboxes, 0);
strarray_push(&applepushserviceargs->mailboxes, "INBOX");
applepushserviceargs->aps_version = 1;
}
else {
// 2 is the most we support
applepushserviceargs->aps_version = 2;
}
for (i = 0; i < strarray_size(&applepushserviceargs->mailboxes); i++) {
const char *name = strarray_nth(&applepushserviceargs->mailboxes, i);
char *intname =
mboxname_from_external(name, &imapd_namespace, imapd_userid);
r = mlookup(tag, name, intname, &mbentry);
if (!r && mbentry->mbtype == 0) {
strarray_push(¬if_mailboxes, name);
if (applepushserviceargs->aps_version >= 2) {
prot_puts(imapd_out, "* XAPPLEPUSHSERVICE \"mailbox\" ");
prot_printstring(imapd_out, name);
prot_puts(imapd_out, "\r\n");
}
}
mboxlist_entry_free(&mbentry);
free(intname);
}
prot_printf(imapd_out,
"* XAPPLEPUSHSERVICE \"aps-version\" \"%d\" \"aps-topic\" \"%s\"\r\n",
applepushserviceargs->aps_version, aps_topic);
prot_printf(imapd_out, "%s OK XAPPLEPUSHSERVICE completed.\r\n", tag);
struct mboxevent *mboxevent = mboxevent_new(EVENT_APPLEPUSHSERVICE);
mboxevent_set_applepushservice(mboxevent, applepushserviceargs,
¬if_mailboxes, imapd_userid);
mboxevent_notify(&mboxevent);
mboxevent_free(&mboxevent);
buf_release(&applepushserviceargs->aps_account_id);
buf_release(&applepushserviceargs->aps_device_token);
buf_release(&applepushserviceargs->aps_subtopic);
strarray_fini(&applepushserviceargs->mailboxes);
strarray_fini(¬if_mailboxes);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2627_0 |
crossvul-cpp_data_good_5845_25 | /*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* PACKET - implements raw packet sockets.
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Alan Cox, <gw4pts@gw4pts.ampr.org>
*
* Fixes:
* Alan Cox : verify_area() now used correctly
* Alan Cox : new skbuff lists, look ma no backlogs!
* Alan Cox : tidied skbuff lists.
* Alan Cox : Now uses generic datagram routines I
* added. Also fixed the peek/read crash
* from all old Linux datagram code.
* Alan Cox : Uses the improved datagram code.
* Alan Cox : Added NULL's for socket options.
* Alan Cox : Re-commented the code.
* Alan Cox : Use new kernel side addressing
* Rob Janssen : Correct MTU usage.
* Dave Platt : Counter leaks caused by incorrect
* interrupt locking and some slightly
* dubious gcc output. Can you read
* compiler: it said _VOLATILE_
* Richard Kooijman : Timestamp fixes.
* Alan Cox : New buffers. Use sk->mac.raw.
* Alan Cox : sendmsg/recvmsg support.
* Alan Cox : Protocol setting support
* Alexey Kuznetsov : Untied from IPv4 stack.
* Cyrus Durgin : Fixed kerneld for kmod.
* Michal Ostrowski : Module initialization cleanup.
* Ulises Alonso : Frame number limit removal and
* packet_set_ring memory leak.
* Eric Biederman : Allow for > 8 byte hardware addresses.
* The convention is that longer addresses
* will simply extend the hardware address
* byte arrays at the end of sockaddr_ll
* and packet_mreq.
* Johann Baudy : Added TX RING.
* Chetan Loke : Implemented TPACKET_V3 block abstraction
* layer.
* Copyright (C) 2011, <lokec@ccs.neu.edu>
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/capability.h>
#include <linux/fcntl.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/if_packet.h>
#include <linux/wireless.h>
#include <linux/kernel.h>
#include <linux/kmod.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <net/net_namespace.h>
#include <net/ip.h>
#include <net/protocol.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <asm/uaccess.h>
#include <asm/ioctls.h>
#include <asm/page.h>
#include <asm/cacheflush.h>
#include <asm/io.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/poll.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <linux/if_vlan.h>
#include <linux/virtio_net.h>
#include <linux/errqueue.h>
#include <linux/net_tstamp.h>
#include <linux/reciprocal_div.h>
#ifdef CONFIG_INET
#include <net/inet_common.h>
#endif
#include "internal.h"
/*
Assumptions:
- if device has no dev->hard_header routine, it adds and removes ll header
inside itself. In this case ll header is invisible outside of device,
but higher levels still should reserve dev->hard_header_len.
Some devices are enough clever to reallocate skb, when header
will not fit to reserved space (tunnel), another ones are silly
(PPP).
- packet socket receives packets with pulled ll header,
so that SOCK_RAW should push it back.
On receive:
-----------
Incoming, dev->hard_header!=NULL
mac_header -> ll header
data -> data
Outgoing, dev->hard_header!=NULL
mac_header -> ll header
data -> ll header
Incoming, dev->hard_header==NULL
mac_header -> UNKNOWN position. It is very likely, that it points to ll
header. PPP makes it, that is wrong, because introduce
assymetry between rx and tx paths.
data -> data
Outgoing, dev->hard_header==NULL
mac_header -> data. ll header is still not built!
data -> data
Resume
If dev->hard_header==NULL we are unlikely to restore sensible ll header.
On transmit:
------------
dev->hard_header != NULL
mac_header -> ll header
data -> ll header
dev->hard_header == NULL (ll header is added by device, we cannot control it)
mac_header -> data
data -> data
We should set nh.raw on output to correct posistion,
packet classifier depends on it.
*/
/* Private packet socket structures. */
/* identical to struct packet_mreq except it has
* a longer address field.
*/
struct packet_mreq_max {
int mr_ifindex;
unsigned short mr_type;
unsigned short mr_alen;
unsigned char mr_address[MAX_ADDR_LEN];
};
union tpacket_uhdr {
struct tpacket_hdr *h1;
struct tpacket2_hdr *h2;
struct tpacket3_hdr *h3;
void *raw;
};
static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
int closing, int tx_ring);
#define V3_ALIGNMENT (8)
#define BLK_HDR_LEN (ALIGN(sizeof(struct tpacket_block_desc), V3_ALIGNMENT))
#define BLK_PLUS_PRIV(sz_of_priv) \
(BLK_HDR_LEN + ALIGN((sz_of_priv), V3_ALIGNMENT))
#define PGV_FROM_VMALLOC 1
#define BLOCK_STATUS(x) ((x)->hdr.bh1.block_status)
#define BLOCK_NUM_PKTS(x) ((x)->hdr.bh1.num_pkts)
#define BLOCK_O2FP(x) ((x)->hdr.bh1.offset_to_first_pkt)
#define BLOCK_LEN(x) ((x)->hdr.bh1.blk_len)
#define BLOCK_SNUM(x) ((x)->hdr.bh1.seq_num)
#define BLOCK_O2PRIV(x) ((x)->offset_to_priv)
#define BLOCK_PRIV(x) ((void *)((char *)(x) + BLOCK_O2PRIV(x)))
struct packet_sock;
static int tpacket_snd(struct packet_sock *po, struct msghdr *msg);
static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev);
static void *packet_previous_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status);
static void packet_increment_head(struct packet_ring_buffer *buff);
static int prb_curr_blk_in_use(struct tpacket_kbdq_core *,
struct tpacket_block_desc *);
static void *prb_dispatch_next_block(struct tpacket_kbdq_core *,
struct packet_sock *);
static void prb_retire_current_block(struct tpacket_kbdq_core *,
struct packet_sock *, unsigned int status);
static int prb_queue_frozen(struct tpacket_kbdq_core *);
static void prb_open_block(struct tpacket_kbdq_core *,
struct tpacket_block_desc *);
static void prb_retire_rx_blk_timer_expired(unsigned long);
static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *);
static void prb_init_blk_timer(struct packet_sock *,
struct tpacket_kbdq_core *,
void (*func) (unsigned long));
static void prb_fill_rxhash(struct tpacket_kbdq_core *, struct tpacket3_hdr *);
static void prb_clear_rxhash(struct tpacket_kbdq_core *,
struct tpacket3_hdr *);
static void prb_fill_vlan_info(struct tpacket_kbdq_core *,
struct tpacket3_hdr *);
static void packet_flush_mclist(struct sock *sk);
struct packet_skb_cb {
unsigned int origlen;
union {
struct sockaddr_pkt pkt;
struct sockaddr_ll ll;
} sa;
};
#define PACKET_SKB_CB(__skb) ((struct packet_skb_cb *)((__skb)->cb))
#define GET_PBDQC_FROM_RB(x) ((struct tpacket_kbdq_core *)(&(x)->prb_bdqc))
#define GET_PBLOCK_DESC(x, bid) \
((struct tpacket_block_desc *)((x)->pkbdq[(bid)].buffer))
#define GET_CURR_PBLOCK_DESC_FROM_CORE(x) \
((struct tpacket_block_desc *)((x)->pkbdq[(x)->kactive_blk_num].buffer))
#define GET_NEXT_PRB_BLK_NUM(x) \
(((x)->kactive_blk_num < ((x)->knum_blocks-1)) ? \
((x)->kactive_blk_num+1) : 0)
static void __fanout_unlink(struct sock *sk, struct packet_sock *po);
static void __fanout_link(struct sock *sk, struct packet_sock *po);
/* register_prot_hook must be invoked with the po->bind_lock held,
* or from a context in which asynchronous accesses to the packet
* socket is not possible (packet_create()).
*/
static void register_prot_hook(struct sock *sk)
{
struct packet_sock *po = pkt_sk(sk);
if (!po->running) {
if (po->fanout)
__fanout_link(sk, po);
else
dev_add_pack(&po->prot_hook);
sock_hold(sk);
po->running = 1;
}
}
/* {,__}unregister_prot_hook() must be invoked with the po->bind_lock
* held. If the sync parameter is true, we will temporarily drop
* the po->bind_lock and do a synchronize_net to make sure no
* asynchronous packet processing paths still refer to the elements
* of po->prot_hook. If the sync parameter is false, it is the
* callers responsibility to take care of this.
*/
static void __unregister_prot_hook(struct sock *sk, bool sync)
{
struct packet_sock *po = pkt_sk(sk);
po->running = 0;
if (po->fanout)
__fanout_unlink(sk, po);
else
__dev_remove_pack(&po->prot_hook);
__sock_put(sk);
if (sync) {
spin_unlock(&po->bind_lock);
synchronize_net();
spin_lock(&po->bind_lock);
}
}
static void unregister_prot_hook(struct sock *sk, bool sync)
{
struct packet_sock *po = pkt_sk(sk);
if (po->running)
__unregister_prot_hook(sk, sync);
}
static inline __pure struct page *pgv_to_page(void *addr)
{
if (is_vmalloc_addr(addr))
return vmalloc_to_page(addr);
return virt_to_page(addr);
}
static void __packet_set_status(struct packet_sock *po, void *frame, int status)
{
union tpacket_uhdr h;
h.raw = frame;
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_status = status;
flush_dcache_page(pgv_to_page(&h.h1->tp_status));
break;
case TPACKET_V2:
h.h2->tp_status = status;
flush_dcache_page(pgv_to_page(&h.h2->tp_status));
break;
case TPACKET_V3:
default:
WARN(1, "TPACKET version not supported.\n");
BUG();
}
smp_wmb();
}
static int __packet_get_status(struct packet_sock *po, void *frame)
{
union tpacket_uhdr h;
smp_rmb();
h.raw = frame;
switch (po->tp_version) {
case TPACKET_V1:
flush_dcache_page(pgv_to_page(&h.h1->tp_status));
return h.h1->tp_status;
case TPACKET_V2:
flush_dcache_page(pgv_to_page(&h.h2->tp_status));
return h.h2->tp_status;
case TPACKET_V3:
default:
WARN(1, "TPACKET version not supported.\n");
BUG();
return 0;
}
}
static __u32 tpacket_get_timestamp(struct sk_buff *skb, struct timespec *ts,
unsigned int flags)
{
struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
if (shhwtstamps) {
if ((flags & SOF_TIMESTAMPING_SYS_HARDWARE) &&
ktime_to_timespec_cond(shhwtstamps->syststamp, ts))
return TP_STATUS_TS_SYS_HARDWARE;
if ((flags & SOF_TIMESTAMPING_RAW_HARDWARE) &&
ktime_to_timespec_cond(shhwtstamps->hwtstamp, ts))
return TP_STATUS_TS_RAW_HARDWARE;
}
if (ktime_to_timespec_cond(skb->tstamp, ts))
return TP_STATUS_TS_SOFTWARE;
return 0;
}
static __u32 __packet_set_timestamp(struct packet_sock *po, void *frame,
struct sk_buff *skb)
{
union tpacket_uhdr h;
struct timespec ts;
__u32 ts_status;
if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
return 0;
h.raw = frame;
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_sec = ts.tv_sec;
h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
break;
case TPACKET_V2:
h.h2->tp_sec = ts.tv_sec;
h.h2->tp_nsec = ts.tv_nsec;
break;
case TPACKET_V3:
default:
WARN(1, "TPACKET version not supported.\n");
BUG();
}
/* one flush is safe, as both fields always lie on the same cacheline */
flush_dcache_page(pgv_to_page(&h.h1->tp_sec));
smp_wmb();
return ts_status;
}
static void *packet_lookup_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
unsigned int position,
int status)
{
unsigned int pg_vec_pos, frame_offset;
union tpacket_uhdr h;
pg_vec_pos = position / rb->frames_per_block;
frame_offset = position % rb->frames_per_block;
h.raw = rb->pg_vec[pg_vec_pos].buffer +
(frame_offset * rb->frame_size);
if (status != __packet_get_status(po, h.raw))
return NULL;
return h.raw;
}
static void *packet_current_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
return packet_lookup_frame(po, rb, rb->head, status);
}
static void prb_del_retire_blk_timer(struct tpacket_kbdq_core *pkc)
{
del_timer_sync(&pkc->retire_blk_timer);
}
static void prb_shutdown_retire_blk_timer(struct packet_sock *po,
int tx_ring,
struct sk_buff_head *rb_queue)
{
struct tpacket_kbdq_core *pkc;
pkc = tx_ring ? &po->tx_ring.prb_bdqc : &po->rx_ring.prb_bdqc;
spin_lock(&rb_queue->lock);
pkc->delete_blk_timer = 1;
spin_unlock(&rb_queue->lock);
prb_del_retire_blk_timer(pkc);
}
static void prb_init_blk_timer(struct packet_sock *po,
struct tpacket_kbdq_core *pkc,
void (*func) (unsigned long))
{
init_timer(&pkc->retire_blk_timer);
pkc->retire_blk_timer.data = (long)po;
pkc->retire_blk_timer.function = func;
pkc->retire_blk_timer.expires = jiffies;
}
static void prb_setup_retire_blk_timer(struct packet_sock *po, int tx_ring)
{
struct tpacket_kbdq_core *pkc;
if (tx_ring)
BUG();
pkc = tx_ring ? &po->tx_ring.prb_bdqc : &po->rx_ring.prb_bdqc;
prb_init_blk_timer(po, pkc, prb_retire_rx_blk_timer_expired);
}
static int prb_calc_retire_blk_tmo(struct packet_sock *po,
int blk_size_in_bytes)
{
struct net_device *dev;
unsigned int mbits = 0, msec = 0, div = 0, tmo = 0;
struct ethtool_cmd ecmd;
int err;
u32 speed;
rtnl_lock();
dev = __dev_get_by_index(sock_net(&po->sk), po->ifindex);
if (unlikely(!dev)) {
rtnl_unlock();
return DEFAULT_PRB_RETIRE_TOV;
}
err = __ethtool_get_settings(dev, &ecmd);
speed = ethtool_cmd_speed(&ecmd);
rtnl_unlock();
if (!err) {
/*
* If the link speed is so slow you don't really
* need to worry about perf anyways
*/
if (speed < SPEED_1000 || speed == SPEED_UNKNOWN) {
return DEFAULT_PRB_RETIRE_TOV;
} else {
msec = 1;
div = speed / 1000;
}
}
mbits = (blk_size_in_bytes * 8) / (1024 * 1024);
if (div)
mbits /= div;
tmo = mbits * msec;
if (div)
return tmo+1;
return tmo;
}
static void prb_init_ft_ops(struct tpacket_kbdq_core *p1,
union tpacket_req_u *req_u)
{
p1->feature_req_word = req_u->req3.tp_feature_req_word;
}
static void init_prb_bdqc(struct packet_sock *po,
struct packet_ring_buffer *rb,
struct pgv *pg_vec,
union tpacket_req_u *req_u, int tx_ring)
{
struct tpacket_kbdq_core *p1 = &rb->prb_bdqc;
struct tpacket_block_desc *pbd;
memset(p1, 0x0, sizeof(*p1));
p1->knxt_seq_num = 1;
p1->pkbdq = pg_vec;
pbd = (struct tpacket_block_desc *)pg_vec[0].buffer;
p1->pkblk_start = pg_vec[0].buffer;
p1->kblk_size = req_u->req3.tp_block_size;
p1->knum_blocks = req_u->req3.tp_block_nr;
p1->hdrlen = po->tp_hdrlen;
p1->version = po->tp_version;
p1->last_kactive_blk_num = 0;
po->stats.stats3.tp_freeze_q_cnt = 0;
if (req_u->req3.tp_retire_blk_tov)
p1->retire_blk_tov = req_u->req3.tp_retire_blk_tov;
else
p1->retire_blk_tov = prb_calc_retire_blk_tmo(po,
req_u->req3.tp_block_size);
p1->tov_in_jiffies = msecs_to_jiffies(p1->retire_blk_tov);
p1->blk_sizeof_priv = req_u->req3.tp_sizeof_priv;
prb_init_ft_ops(p1, req_u);
prb_setup_retire_blk_timer(po, tx_ring);
prb_open_block(p1, pbd);
}
/* Do NOT update the last_blk_num first.
* Assumes sk_buff_head lock is held.
*/
static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *pkc)
{
mod_timer(&pkc->retire_blk_timer,
jiffies + pkc->tov_in_jiffies);
pkc->last_kactive_blk_num = pkc->kactive_blk_num;
}
/*
* Timer logic:
* 1) We refresh the timer only when we open a block.
* By doing this we don't waste cycles refreshing the timer
* on packet-by-packet basis.
*
* With a 1MB block-size, on a 1Gbps line, it will take
* i) ~8 ms to fill a block + ii) memcpy etc.
* In this cut we are not accounting for the memcpy time.
*
* So, if the user sets the 'tmo' to 10ms then the timer
* will never fire while the block is still getting filled
* (which is what we want). However, the user could choose
* to close a block early and that's fine.
*
* But when the timer does fire, we check whether or not to refresh it.
* Since the tmo granularity is in msecs, it is not too expensive
* to refresh the timer, lets say every '8' msecs.
* Either the user can set the 'tmo' or we can derive it based on
* a) line-speed and b) block-size.
* prb_calc_retire_blk_tmo() calculates the tmo.
*
*/
static void prb_retire_rx_blk_timer_expired(unsigned long data)
{
struct packet_sock *po = (struct packet_sock *)data;
struct tpacket_kbdq_core *pkc = &po->rx_ring.prb_bdqc;
unsigned int frozen;
struct tpacket_block_desc *pbd;
spin_lock(&po->sk.sk_receive_queue.lock);
frozen = prb_queue_frozen(pkc);
pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
if (unlikely(pkc->delete_blk_timer))
goto out;
/* We only need to plug the race when the block is partially filled.
* tpacket_rcv:
* lock(); increment BLOCK_NUM_PKTS; unlock()
* copy_bits() is in progress ...
* timer fires on other cpu:
* we can't retire the current block because copy_bits
* is in progress.
*
*/
if (BLOCK_NUM_PKTS(pbd)) {
while (atomic_read(&pkc->blk_fill_in_prog)) {
/* Waiting for skb_copy_bits to finish... */
cpu_relax();
}
}
if (pkc->last_kactive_blk_num == pkc->kactive_blk_num) {
if (!frozen) {
prb_retire_current_block(pkc, po, TP_STATUS_BLK_TMO);
if (!prb_dispatch_next_block(pkc, po))
goto refresh_timer;
else
goto out;
} else {
/* Case 1. Queue was frozen because user-space was
* lagging behind.
*/
if (prb_curr_blk_in_use(pkc, pbd)) {
/*
* Ok, user-space is still behind.
* So just refresh the timer.
*/
goto refresh_timer;
} else {
/* Case 2. queue was frozen,user-space caught up,
* now the link went idle && the timer fired.
* We don't have a block to close.So we open this
* block and restart the timer.
* opening a block thaws the queue,restarts timer
* Thawing/timer-refresh is a side effect.
*/
prb_open_block(pkc, pbd);
goto out;
}
}
}
refresh_timer:
_prb_refresh_rx_retire_blk_timer(pkc);
out:
spin_unlock(&po->sk.sk_receive_queue.lock);
}
static void prb_flush_block(struct tpacket_kbdq_core *pkc1,
struct tpacket_block_desc *pbd1, __u32 status)
{
/* Flush everything minus the block header */
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
u8 *start, *end;
start = (u8 *)pbd1;
/* Skip the block header(we know header WILL fit in 4K) */
start += PAGE_SIZE;
end = (u8 *)PAGE_ALIGN((unsigned long)pkc1->pkblk_end);
for (; start < end; start += PAGE_SIZE)
flush_dcache_page(pgv_to_page(start));
smp_wmb();
#endif
/* Now update the block status. */
BLOCK_STATUS(pbd1) = status;
/* Flush the block header */
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
start = (u8 *)pbd1;
flush_dcache_page(pgv_to_page(start));
smp_wmb();
#endif
}
/*
* Side effect:
*
* 1) flush the block
* 2) Increment active_blk_num
*
* Note:We DONT refresh the timer on purpose.
* Because almost always the next block will be opened.
*/
static void prb_close_block(struct tpacket_kbdq_core *pkc1,
struct tpacket_block_desc *pbd1,
struct packet_sock *po, unsigned int stat)
{
__u32 status = TP_STATUS_USER | stat;
struct tpacket3_hdr *last_pkt;
struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
if (po->stats.stats3.tp_drops)
status |= TP_STATUS_LOSING;
last_pkt = (struct tpacket3_hdr *)pkc1->prev;
last_pkt->tp_next_offset = 0;
/* Get the ts of the last pkt */
if (BLOCK_NUM_PKTS(pbd1)) {
h1->ts_last_pkt.ts_sec = last_pkt->tp_sec;
h1->ts_last_pkt.ts_nsec = last_pkt->tp_nsec;
} else {
/* Ok, we tmo'd - so get the current time */
struct timespec ts;
getnstimeofday(&ts);
h1->ts_last_pkt.ts_sec = ts.tv_sec;
h1->ts_last_pkt.ts_nsec = ts.tv_nsec;
}
smp_wmb();
/* Flush the block */
prb_flush_block(pkc1, pbd1, status);
pkc1->kactive_blk_num = GET_NEXT_PRB_BLK_NUM(pkc1);
}
static void prb_thaw_queue(struct tpacket_kbdq_core *pkc)
{
pkc->reset_pending_on_curr_blk = 0;
}
/*
* Side effect of opening a block:
*
* 1) prb_queue is thawed.
* 2) retire_blk_timer is refreshed.
*
*/
static void prb_open_block(struct tpacket_kbdq_core *pkc1,
struct tpacket_block_desc *pbd1)
{
struct timespec ts;
struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
smp_rmb();
/* We could have just memset this but we will lose the
* flexibility of making the priv area sticky
*/
BLOCK_SNUM(pbd1) = pkc1->knxt_seq_num++;
BLOCK_NUM_PKTS(pbd1) = 0;
BLOCK_LEN(pbd1) = BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
getnstimeofday(&ts);
h1->ts_first_pkt.ts_sec = ts.tv_sec;
h1->ts_first_pkt.ts_nsec = ts.tv_nsec;
pkc1->pkblk_start = (char *)pbd1;
pkc1->nxt_offset = pkc1->pkblk_start + BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
BLOCK_O2FP(pbd1) = (__u32)BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
BLOCK_O2PRIV(pbd1) = BLK_HDR_LEN;
pbd1->version = pkc1->version;
pkc1->prev = pkc1->nxt_offset;
pkc1->pkblk_end = pkc1->pkblk_start + pkc1->kblk_size;
prb_thaw_queue(pkc1);
_prb_refresh_rx_retire_blk_timer(pkc1);
smp_wmb();
}
/*
* Queue freeze logic:
* 1) Assume tp_block_nr = 8 blocks.
* 2) At time 't0', user opens Rx ring.
* 3) Some time past 't0', kernel starts filling blocks starting from 0 .. 7
* 4) user-space is either sleeping or processing block '0'.
* 5) tpacket_rcv is currently filling block '7', since there is no space left,
* it will close block-7,loop around and try to fill block '0'.
* call-flow:
* __packet_lookup_frame_in_block
* prb_retire_current_block()
* prb_dispatch_next_block()
* |->(BLOCK_STATUS == USER) evaluates to true
* 5.1) Since block-0 is currently in-use, we just freeze the queue.
* 6) Now there are two cases:
* 6.1) Link goes idle right after the queue is frozen.
* But remember, the last open_block() refreshed the timer.
* When this timer expires,it will refresh itself so that we can
* re-open block-0 in near future.
* 6.2) Link is busy and keeps on receiving packets. This is a simple
* case and __packet_lookup_frame_in_block will check if block-0
* is free and can now be re-used.
*/
static void prb_freeze_queue(struct tpacket_kbdq_core *pkc,
struct packet_sock *po)
{
pkc->reset_pending_on_curr_blk = 1;
po->stats.stats3.tp_freeze_q_cnt++;
}
#define TOTAL_PKT_LEN_INCL_ALIGN(length) (ALIGN((length), V3_ALIGNMENT))
/*
* If the next block is free then we will dispatch it
* and return a good offset.
* Else, we will freeze the queue.
* So, caller must check the return value.
*/
static void *prb_dispatch_next_block(struct tpacket_kbdq_core *pkc,
struct packet_sock *po)
{
struct tpacket_block_desc *pbd;
smp_rmb();
/* 1. Get current block num */
pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
/* 2. If this block is currently in_use then freeze the queue */
if (TP_STATUS_USER & BLOCK_STATUS(pbd)) {
prb_freeze_queue(pkc, po);
return NULL;
}
/*
* 3.
* open this block and return the offset where the first packet
* needs to get stored.
*/
prb_open_block(pkc, pbd);
return (void *)pkc->nxt_offset;
}
static void prb_retire_current_block(struct tpacket_kbdq_core *pkc,
struct packet_sock *po, unsigned int status)
{
struct tpacket_block_desc *pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
/* retire/close the current block */
if (likely(TP_STATUS_KERNEL == BLOCK_STATUS(pbd))) {
/*
* Plug the case where copy_bits() is in progress on
* cpu-0 and tpacket_rcv() got invoked on cpu-1, didn't
* have space to copy the pkt in the current block and
* called prb_retire_current_block()
*
* We don't need to worry about the TMO case because
* the timer-handler already handled this case.
*/
if (!(status & TP_STATUS_BLK_TMO)) {
while (atomic_read(&pkc->blk_fill_in_prog)) {
/* Waiting for skb_copy_bits to finish... */
cpu_relax();
}
}
prb_close_block(pkc, pbd, po, status);
return;
}
}
static int prb_curr_blk_in_use(struct tpacket_kbdq_core *pkc,
struct tpacket_block_desc *pbd)
{
return TP_STATUS_USER & BLOCK_STATUS(pbd);
}
static int prb_queue_frozen(struct tpacket_kbdq_core *pkc)
{
return pkc->reset_pending_on_curr_blk;
}
static void prb_clear_blk_fill_status(struct packet_ring_buffer *rb)
{
struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
atomic_dec(&pkc->blk_fill_in_prog);
}
static void prb_fill_rxhash(struct tpacket_kbdq_core *pkc,
struct tpacket3_hdr *ppd)
{
ppd->hv1.tp_rxhash = skb_get_rxhash(pkc->skb);
}
static void prb_clear_rxhash(struct tpacket_kbdq_core *pkc,
struct tpacket3_hdr *ppd)
{
ppd->hv1.tp_rxhash = 0;
}
static void prb_fill_vlan_info(struct tpacket_kbdq_core *pkc,
struct tpacket3_hdr *ppd)
{
if (vlan_tx_tag_present(pkc->skb)) {
ppd->hv1.tp_vlan_tci = vlan_tx_tag_get(pkc->skb);
ppd->tp_status = TP_STATUS_VLAN_VALID;
} else {
ppd->hv1.tp_vlan_tci = 0;
ppd->tp_status = TP_STATUS_AVAILABLE;
}
}
static void prb_run_all_ft_ops(struct tpacket_kbdq_core *pkc,
struct tpacket3_hdr *ppd)
{
prb_fill_vlan_info(pkc, ppd);
if (pkc->feature_req_word & TP_FT_REQ_FILL_RXHASH)
prb_fill_rxhash(pkc, ppd);
else
prb_clear_rxhash(pkc, ppd);
}
static void prb_fill_curr_block(char *curr,
struct tpacket_kbdq_core *pkc,
struct tpacket_block_desc *pbd,
unsigned int len)
{
struct tpacket3_hdr *ppd;
ppd = (struct tpacket3_hdr *)curr;
ppd->tp_next_offset = TOTAL_PKT_LEN_INCL_ALIGN(len);
pkc->prev = curr;
pkc->nxt_offset += TOTAL_PKT_LEN_INCL_ALIGN(len);
BLOCK_LEN(pbd) += TOTAL_PKT_LEN_INCL_ALIGN(len);
BLOCK_NUM_PKTS(pbd) += 1;
atomic_inc(&pkc->blk_fill_in_prog);
prb_run_all_ft_ops(pkc, ppd);
}
/* Assumes caller has the sk->rx_queue.lock */
static void *__packet_lookup_frame_in_block(struct packet_sock *po,
struct sk_buff *skb,
int status,
unsigned int len
)
{
struct tpacket_kbdq_core *pkc;
struct tpacket_block_desc *pbd;
char *curr, *end;
pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
/* Queue is frozen when user space is lagging behind */
if (prb_queue_frozen(pkc)) {
/*
* Check if that last block which caused the queue to freeze,
* is still in_use by user-space.
*/
if (prb_curr_blk_in_use(pkc, pbd)) {
/* Can't record this packet */
return NULL;
} else {
/*
* Ok, the block was released by user-space.
* Now let's open that block.
* opening a block also thaws the queue.
* Thawing is a side effect.
*/
prb_open_block(pkc, pbd);
}
}
smp_mb();
curr = pkc->nxt_offset;
pkc->skb = skb;
end = (char *)pbd + pkc->kblk_size;
/* first try the current block */
if (curr+TOTAL_PKT_LEN_INCL_ALIGN(len) < end) {
prb_fill_curr_block(curr, pkc, pbd, len);
return (void *)curr;
}
/* Ok, close the current block */
prb_retire_current_block(pkc, po, 0);
/* Now, try to dispatch the next block */
curr = (char *)prb_dispatch_next_block(pkc, po);
if (curr) {
pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
prb_fill_curr_block(curr, pkc, pbd, len);
return (void *)curr;
}
/*
* No free blocks are available.user_space hasn't caught up yet.
* Queue was just frozen and now this packet will get dropped.
*/
return NULL;
}
static void *packet_current_rx_frame(struct packet_sock *po,
struct sk_buff *skb,
int status, unsigned int len)
{
char *curr = NULL;
switch (po->tp_version) {
case TPACKET_V1:
case TPACKET_V2:
curr = packet_lookup_frame(po, &po->rx_ring,
po->rx_ring.head, status);
return curr;
case TPACKET_V3:
return __packet_lookup_frame_in_block(po, skb, status, len);
default:
WARN(1, "TPACKET version not supported\n");
BUG();
return NULL;
}
}
static void *prb_lookup_block(struct packet_sock *po,
struct packet_ring_buffer *rb,
unsigned int idx,
int status)
{
struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
struct tpacket_block_desc *pbd = GET_PBLOCK_DESC(pkc, idx);
if (status != BLOCK_STATUS(pbd))
return NULL;
return pbd;
}
static int prb_previous_blk_num(struct packet_ring_buffer *rb)
{
unsigned int prev;
if (rb->prb_bdqc.kactive_blk_num)
prev = rb->prb_bdqc.kactive_blk_num-1;
else
prev = rb->prb_bdqc.knum_blocks-1;
return prev;
}
/* Assumes caller has held the rx_queue.lock */
static void *__prb_previous_block(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
unsigned int previous = prb_previous_blk_num(rb);
return prb_lookup_block(po, rb, previous, status);
}
static void *packet_previous_rx_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
if (po->tp_version <= TPACKET_V2)
return packet_previous_frame(po, rb, status);
return __prb_previous_block(po, rb, status);
}
static void packet_increment_rx_head(struct packet_sock *po,
struct packet_ring_buffer *rb)
{
switch (po->tp_version) {
case TPACKET_V1:
case TPACKET_V2:
return packet_increment_head(rb);
case TPACKET_V3:
default:
WARN(1, "TPACKET version not supported.\n");
BUG();
return;
}
}
static void *packet_previous_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
unsigned int previous = rb->head ? rb->head - 1 : rb->frame_max;
return packet_lookup_frame(po, rb, previous, status);
}
static void packet_increment_head(struct packet_ring_buffer *buff)
{
buff->head = buff->head != buff->frame_max ? buff->head+1 : 0;
}
static bool packet_rcv_has_room(struct packet_sock *po, struct sk_buff *skb)
{
struct sock *sk = &po->sk;
bool has_room;
if (po->prot_hook.func != tpacket_rcv)
return (atomic_read(&sk->sk_rmem_alloc) + skb->truesize)
<= sk->sk_rcvbuf;
spin_lock(&sk->sk_receive_queue.lock);
if (po->tp_version == TPACKET_V3)
has_room = prb_lookup_block(po, &po->rx_ring,
po->rx_ring.prb_bdqc.kactive_blk_num,
TP_STATUS_KERNEL);
else
has_room = packet_lookup_frame(po, &po->rx_ring,
po->rx_ring.head,
TP_STATUS_KERNEL);
spin_unlock(&sk->sk_receive_queue.lock);
return has_room;
}
static void packet_sock_destruct(struct sock *sk)
{
skb_queue_purge(&sk->sk_error_queue);
WARN_ON(atomic_read(&sk->sk_rmem_alloc));
WARN_ON(atomic_read(&sk->sk_wmem_alloc));
if (!sock_flag(sk, SOCK_DEAD)) {
pr_err("Attempt to release alive packet socket: %p\n", sk);
return;
}
sk_refcnt_debug_dec(sk);
}
static int fanout_rr_next(struct packet_fanout *f, unsigned int num)
{
int x = atomic_read(&f->rr_cur) + 1;
if (x >= num)
x = 0;
return x;
}
static unsigned int fanout_demux_hash(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
return reciprocal_divide(skb->rxhash, num);
}
static unsigned int fanout_demux_lb(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
int cur, old;
cur = atomic_read(&f->rr_cur);
while ((old = atomic_cmpxchg(&f->rr_cur, cur,
fanout_rr_next(f, num))) != cur)
cur = old;
return cur;
}
static unsigned int fanout_demux_cpu(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
return smp_processor_id() % num;
}
static unsigned int fanout_demux_rnd(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
return reciprocal_divide(prandom_u32(), num);
}
static unsigned int fanout_demux_rollover(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int idx, unsigned int skip,
unsigned int num)
{
unsigned int i, j;
i = j = min_t(int, f->next[idx], num - 1);
do {
if (i != skip && packet_rcv_has_room(pkt_sk(f->arr[i]), skb)) {
if (i != j)
f->next[idx] = i;
return i;
}
if (++i == num)
i = 0;
} while (i != j);
return idx;
}
static bool fanout_has_flag(struct packet_fanout *f, u16 flag)
{
return f->flags & (flag >> 8);
}
static int packet_rcv_fanout(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct packet_fanout *f = pt->af_packet_priv;
unsigned int num = f->num_members;
struct packet_sock *po;
unsigned int idx;
if (!net_eq(dev_net(dev), read_pnet(&f->net)) ||
!num) {
kfree_skb(skb);
return 0;
}
switch (f->type) {
case PACKET_FANOUT_HASH:
default:
if (fanout_has_flag(f, PACKET_FANOUT_FLAG_DEFRAG)) {
skb = ip_check_defrag(skb, IP_DEFRAG_AF_PACKET);
if (!skb)
return 0;
}
skb_get_rxhash(skb);
idx = fanout_demux_hash(f, skb, num);
break;
case PACKET_FANOUT_LB:
idx = fanout_demux_lb(f, skb, num);
break;
case PACKET_FANOUT_CPU:
idx = fanout_demux_cpu(f, skb, num);
break;
case PACKET_FANOUT_RND:
idx = fanout_demux_rnd(f, skb, num);
break;
case PACKET_FANOUT_ROLLOVER:
idx = fanout_demux_rollover(f, skb, 0, (unsigned int) -1, num);
break;
}
po = pkt_sk(f->arr[idx]);
if (fanout_has_flag(f, PACKET_FANOUT_FLAG_ROLLOVER) &&
unlikely(!packet_rcv_has_room(po, skb))) {
idx = fanout_demux_rollover(f, skb, idx, idx, num);
po = pkt_sk(f->arr[idx]);
}
return po->prot_hook.func(skb, dev, &po->prot_hook, orig_dev);
}
DEFINE_MUTEX(fanout_mutex);
EXPORT_SYMBOL_GPL(fanout_mutex);
static LIST_HEAD(fanout_list);
static void __fanout_link(struct sock *sk, struct packet_sock *po)
{
struct packet_fanout *f = po->fanout;
spin_lock(&f->lock);
f->arr[f->num_members] = sk;
smp_wmb();
f->num_members++;
spin_unlock(&f->lock);
}
static void __fanout_unlink(struct sock *sk, struct packet_sock *po)
{
struct packet_fanout *f = po->fanout;
int i;
spin_lock(&f->lock);
for (i = 0; i < f->num_members; i++) {
if (f->arr[i] == sk)
break;
}
BUG_ON(i >= f->num_members);
f->arr[i] = f->arr[f->num_members - 1];
f->num_members--;
spin_unlock(&f->lock);
}
static bool match_fanout_group(struct packet_type *ptype, struct sock * sk)
{
if (ptype->af_packet_priv == (void*)((struct packet_sock *)sk)->fanout)
return true;
return false;
}
static int fanout_add(struct sock *sk, u16 id, u16 type_flags)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_fanout *f, *match;
u8 type = type_flags & 0xff;
u8 flags = type_flags >> 8;
int err;
switch (type) {
case PACKET_FANOUT_ROLLOVER:
if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
return -EINVAL;
case PACKET_FANOUT_HASH:
case PACKET_FANOUT_LB:
case PACKET_FANOUT_CPU:
case PACKET_FANOUT_RND:
break;
default:
return -EINVAL;
}
if (!po->running)
return -EINVAL;
if (po->fanout)
return -EALREADY;
mutex_lock(&fanout_mutex);
match = NULL;
list_for_each_entry(f, &fanout_list, list) {
if (f->id == id &&
read_pnet(&f->net) == sock_net(sk)) {
match = f;
break;
}
}
err = -EINVAL;
if (match && match->flags != flags)
goto out;
if (!match) {
err = -ENOMEM;
match = kzalloc(sizeof(*match), GFP_KERNEL);
if (!match)
goto out;
write_pnet(&match->net, sock_net(sk));
match->id = id;
match->type = type;
match->flags = flags;
atomic_set(&match->rr_cur, 0);
INIT_LIST_HEAD(&match->list);
spin_lock_init(&match->lock);
atomic_set(&match->sk_ref, 0);
match->prot_hook.type = po->prot_hook.type;
match->prot_hook.dev = po->prot_hook.dev;
match->prot_hook.func = packet_rcv_fanout;
match->prot_hook.af_packet_priv = match;
match->prot_hook.id_match = match_fanout_group;
dev_add_pack(&match->prot_hook);
list_add(&match->list, &fanout_list);
}
err = -EINVAL;
if (match->type == type &&
match->prot_hook.type == po->prot_hook.type &&
match->prot_hook.dev == po->prot_hook.dev) {
err = -ENOSPC;
if (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) {
__dev_remove_pack(&po->prot_hook);
po->fanout = match;
atomic_inc(&match->sk_ref);
__fanout_link(sk, po);
err = 0;
}
}
out:
mutex_unlock(&fanout_mutex);
return err;
}
static void fanout_release(struct sock *sk)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_fanout *f;
f = po->fanout;
if (!f)
return;
mutex_lock(&fanout_mutex);
po->fanout = NULL;
if (atomic_dec_and_test(&f->sk_ref)) {
list_del(&f->list);
dev_remove_pack(&f->prot_hook);
kfree(f);
}
mutex_unlock(&fanout_mutex);
}
static const struct proto_ops packet_ops;
static const struct proto_ops packet_ops_spkt;
static int packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct sockaddr_pkt *spkt;
/*
* When we registered the protocol we saved the socket in the data
* field for just this event.
*/
sk = pt->af_packet_priv;
/*
* Yank back the headers [hope the device set this
* right or kerboom...]
*
* Incoming packets have ll header pulled,
* push it back.
*
* For outgoing ones skb->data == skb_mac_header(skb)
* so that this procedure is noop.
*/
if (skb->pkt_type == PACKET_LOOPBACK)
goto out;
if (!net_eq(dev_net(dev), sock_net(sk)))
goto out;
skb = skb_share_check(skb, GFP_ATOMIC);
if (skb == NULL)
goto oom;
/* drop any routing info */
skb_dst_drop(skb);
/* drop conntrack reference */
nf_reset(skb);
spkt = &PACKET_SKB_CB(skb)->sa.pkt;
skb_push(skb, skb->data - skb_mac_header(skb));
/*
* The SOCK_PACKET socket receives _all_ frames.
*/
spkt->spkt_family = dev->type;
strlcpy(spkt->spkt_device, dev->name, sizeof(spkt->spkt_device));
spkt->spkt_protocol = skb->protocol;
/*
* Charge the memory to the socket. This is done specifically
* to prevent sockets using all the memory up.
*/
if (sock_queue_rcv_skb(sk, skb) == 0)
return 0;
out:
kfree_skb(skb);
oom:
return 0;
}
/*
* Output a raw packet to a device layer. This bypasses all the other
* protocol layers and you must therefore supply it with a complete frame
*/
static int packet_sendmsg_spkt(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct sockaddr_pkt *saddr = (struct sockaddr_pkt *)msg->msg_name;
struct sk_buff *skb = NULL;
struct net_device *dev;
__be16 proto = 0;
int err;
int extra_len = 0;
/*
* Get and verify the address.
*/
if (saddr) {
if (msg->msg_namelen < sizeof(struct sockaddr))
return -EINVAL;
if (msg->msg_namelen == sizeof(struct sockaddr_pkt))
proto = saddr->spkt_protocol;
} else
return -ENOTCONN; /* SOCK_PACKET must be sent giving an address */
/*
* Find the device first to size check it
*/
saddr->spkt_device[sizeof(saddr->spkt_device) - 1] = 0;
retry:
rcu_read_lock();
dev = dev_get_by_name_rcu(sock_net(sk), saddr->spkt_device);
err = -ENODEV;
if (dev == NULL)
goto out_unlock;
err = -ENETDOWN;
if (!(dev->flags & IFF_UP))
goto out_unlock;
/*
* You may not queue a frame bigger than the mtu. This is the lowest level
* raw protocol and you must do your own fragmentation at this level.
*/
if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
if (!netif_supports_nofcs(dev)) {
err = -EPROTONOSUPPORT;
goto out_unlock;
}
extra_len = 4; /* We're doing our own CRC */
}
err = -EMSGSIZE;
if (len > dev->mtu + dev->hard_header_len + VLAN_HLEN + extra_len)
goto out_unlock;
if (!skb) {
size_t reserved = LL_RESERVED_SPACE(dev);
int tlen = dev->needed_tailroom;
unsigned int hhlen = dev->header_ops ? dev->hard_header_len : 0;
rcu_read_unlock();
skb = sock_wmalloc(sk, len + reserved + tlen, 0, GFP_KERNEL);
if (skb == NULL)
return -ENOBUFS;
/* FIXME: Save some space for broken drivers that write a hard
* header at transmission time by themselves. PPP is the notable
* one here. This should really be fixed at the driver level.
*/
skb_reserve(skb, reserved);
skb_reset_network_header(skb);
/* Try to align data part correctly */
if (hhlen) {
skb->data -= hhlen;
skb->tail -= hhlen;
if (len < hhlen)
skb_reset_network_header(skb);
}
err = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len);
if (err)
goto out_free;
goto retry;
}
if (len > (dev->mtu + dev->hard_header_len + extra_len)) {
/* Earlier code assumed this would be a VLAN pkt,
* double-check this now that we have the actual
* packet in hand.
*/
struct ethhdr *ehdr;
skb_reset_mac_header(skb);
ehdr = eth_hdr(skb);
if (ehdr->h_proto != htons(ETH_P_8021Q)) {
err = -EMSGSIZE;
goto out_unlock;
}
}
skb->protocol = proto;
skb->dev = dev;
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
sock_tx_timestamp(sk, &skb_shinfo(skb)->tx_flags);
if (unlikely(extra_len == 4))
skb->no_fcs = 1;
skb_probe_transport_header(skb, 0);
dev_queue_xmit(skb);
rcu_read_unlock();
return len;
out_unlock:
rcu_read_unlock();
out_free:
kfree_skb(skb);
return err;
}
static unsigned int run_filter(const struct sk_buff *skb,
const struct sock *sk,
unsigned int res)
{
struct sk_filter *filter;
rcu_read_lock();
filter = rcu_dereference(sk->sk_filter);
if (filter != NULL)
res = SK_RUN_FILTER(filter, skb);
rcu_read_unlock();
return res;
}
/*
* This function makes lazy skb cloning in hope that most of packets
* are discarded by BPF.
*
* Note tricky part: we DO mangle shared skb! skb->data, skb->len
* and skb->cb are mangled. It works because (and until) packets
* falling here are owned by current CPU. Output packets are cloned
* by dev_queue_xmit_nit(), input packets are processed by net_bh
* sequencially, so that if we return skb to original state on exit,
* we will not harm anyone.
*/
static int packet_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct sockaddr_ll *sll;
struct packet_sock *po;
u8 *skb_head = skb->data;
int skb_len = skb->len;
unsigned int snaplen, res;
if (skb->pkt_type == PACKET_LOOPBACK)
goto drop;
sk = pt->af_packet_priv;
po = pkt_sk(sk);
if (!net_eq(dev_net(dev), sock_net(sk)))
goto drop;
skb->dev = dev;
if (dev->header_ops) {
/* The device has an explicit notion of ll header,
* exported to higher levels.
*
* Otherwise, the device hides details of its frame
* structure, so that corresponding packet head is
* never delivered to user.
*/
if (sk->sk_type != SOCK_DGRAM)
skb_push(skb, skb->data - skb_mac_header(skb));
else if (skb->pkt_type == PACKET_OUTGOING) {
/* Special case: outgoing packets have ll header at head */
skb_pull(skb, skb_network_offset(skb));
}
}
snaplen = skb->len;
res = run_filter(skb, sk, snaplen);
if (!res)
goto drop_n_restore;
if (snaplen > res)
snaplen = res;
if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
goto drop_n_acct;
if (skb_shared(skb)) {
struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
if (nskb == NULL)
goto drop_n_acct;
if (skb_head != skb->data) {
skb->data = skb_head;
skb->len = skb_len;
}
consume_skb(skb);
skb = nskb;
}
BUILD_BUG_ON(sizeof(*PACKET_SKB_CB(skb)) + MAX_ADDR_LEN - 8 >
sizeof(skb->cb));
sll = &PACKET_SKB_CB(skb)->sa.ll;
sll->sll_family = AF_PACKET;
sll->sll_hatype = dev->type;
sll->sll_protocol = skb->protocol;
sll->sll_pkttype = skb->pkt_type;
if (unlikely(po->origdev))
sll->sll_ifindex = orig_dev->ifindex;
else
sll->sll_ifindex = dev->ifindex;
sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
PACKET_SKB_CB(skb)->origlen = skb->len;
if (pskb_trim(skb, snaplen))
goto drop_n_acct;
skb_set_owner_r(skb, sk);
skb->dev = NULL;
skb_dst_drop(skb);
/* drop conntrack reference */
nf_reset(skb);
spin_lock(&sk->sk_receive_queue.lock);
po->stats.stats1.tp_packets++;
skb->dropcount = atomic_read(&sk->sk_drops);
__skb_queue_tail(&sk->sk_receive_queue, skb);
spin_unlock(&sk->sk_receive_queue.lock);
sk->sk_data_ready(sk, skb->len);
return 0;
drop_n_acct:
spin_lock(&sk->sk_receive_queue.lock);
po->stats.stats1.tp_drops++;
atomic_inc(&sk->sk_drops);
spin_unlock(&sk->sk_receive_queue.lock);
drop_n_restore:
if (skb_head != skb->data && skb_shared(skb)) {
skb->data = skb_head;
skb->len = skb_len;
}
drop:
consume_skb(skb);
return 0;
}
static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct packet_sock *po;
struct sockaddr_ll *sll;
union tpacket_uhdr h;
u8 *skb_head = skb->data;
int skb_len = skb->len;
unsigned int snaplen, res;
unsigned long status = TP_STATUS_USER;
unsigned short macoff, netoff, hdrlen;
struct sk_buff *copy_skb = NULL;
struct timespec ts;
__u32 ts_status;
if (skb->pkt_type == PACKET_LOOPBACK)
goto drop;
sk = pt->af_packet_priv;
po = pkt_sk(sk);
if (!net_eq(dev_net(dev), sock_net(sk)))
goto drop;
if (dev->header_ops) {
if (sk->sk_type != SOCK_DGRAM)
skb_push(skb, skb->data - skb_mac_header(skb));
else if (skb->pkt_type == PACKET_OUTGOING) {
/* Special case: outgoing packets have ll header at head */
skb_pull(skb, skb_network_offset(skb));
}
}
if (skb->ip_summed == CHECKSUM_PARTIAL)
status |= TP_STATUS_CSUMNOTREADY;
snaplen = skb->len;
res = run_filter(skb, sk, snaplen);
if (!res)
goto drop_n_restore;
if (snaplen > res)
snaplen = res;
if (sk->sk_type == SOCK_DGRAM) {
macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
po->tp_reserve;
} else {
unsigned int maclen = skb_network_offset(skb);
netoff = TPACKET_ALIGN(po->tp_hdrlen +
(maclen < 16 ? 16 : maclen)) +
po->tp_reserve;
macoff = netoff - maclen;
}
if (po->tp_version <= TPACKET_V2) {
if (macoff + snaplen > po->rx_ring.frame_size) {
if (po->copy_thresh &&
atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {
if (skb_shared(skb)) {
copy_skb = skb_clone(skb, GFP_ATOMIC);
} else {
copy_skb = skb_get(skb);
skb_head = skb->data;
}
if (copy_skb)
skb_set_owner_r(copy_skb, sk);
}
snaplen = po->rx_ring.frame_size - macoff;
if ((int)snaplen < 0)
snaplen = 0;
}
}
spin_lock(&sk->sk_receive_queue.lock);
h.raw = packet_current_rx_frame(po, skb,
TP_STATUS_KERNEL, (macoff+snaplen));
if (!h.raw)
goto ring_is_full;
if (po->tp_version <= TPACKET_V2) {
packet_increment_rx_head(po, &po->rx_ring);
/*
* LOSING will be reported till you read the stats,
* because it's COR - Clear On Read.
* Anyways, moving it for V1/V2 only as V3 doesn't need this
* at packet level.
*/
if (po->stats.stats1.tp_drops)
status |= TP_STATUS_LOSING;
}
po->stats.stats1.tp_packets++;
if (copy_skb) {
status |= TP_STATUS_COPY;
__skb_queue_tail(&sk->sk_receive_queue, copy_skb);
}
spin_unlock(&sk->sk_receive_queue.lock);
skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
getnstimeofday(&ts);
status |= ts_status;
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_len = skb->len;
h.h1->tp_snaplen = snaplen;
h.h1->tp_mac = macoff;
h.h1->tp_net = netoff;
h.h1->tp_sec = ts.tv_sec;
h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
hdrlen = sizeof(*h.h1);
break;
case TPACKET_V2:
h.h2->tp_len = skb->len;
h.h2->tp_snaplen = snaplen;
h.h2->tp_mac = macoff;
h.h2->tp_net = netoff;
h.h2->tp_sec = ts.tv_sec;
h.h2->tp_nsec = ts.tv_nsec;
if (vlan_tx_tag_present(skb)) {
h.h2->tp_vlan_tci = vlan_tx_tag_get(skb);
status |= TP_STATUS_VLAN_VALID;
} else {
h.h2->tp_vlan_tci = 0;
}
h.h2->tp_padding = 0;
hdrlen = sizeof(*h.h2);
break;
case TPACKET_V3:
/* tp_nxt_offset,vlan are already populated above.
* So DONT clear those fields here
*/
h.h3->tp_status |= status;
h.h3->tp_len = skb->len;
h.h3->tp_snaplen = snaplen;
h.h3->tp_mac = macoff;
h.h3->tp_net = netoff;
h.h3->tp_sec = ts.tv_sec;
h.h3->tp_nsec = ts.tv_nsec;
hdrlen = sizeof(*h.h3);
break;
default:
BUG();
}
sll = h.raw + TPACKET_ALIGN(hdrlen);
sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
sll->sll_family = AF_PACKET;
sll->sll_hatype = dev->type;
sll->sll_protocol = skb->protocol;
sll->sll_pkttype = skb->pkt_type;
if (unlikely(po->origdev))
sll->sll_ifindex = orig_dev->ifindex;
else
sll->sll_ifindex = dev->ifindex;
smp_mb();
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
{
u8 *start, *end;
if (po->tp_version <= TPACKET_V2) {
end = (u8 *)PAGE_ALIGN((unsigned long)h.raw
+ macoff + snaplen);
for (start = h.raw; start < end; start += PAGE_SIZE)
flush_dcache_page(pgv_to_page(start));
}
smp_wmb();
}
#endif
if (po->tp_version <= TPACKET_V2)
__packet_set_status(po, h.raw, status);
else
prb_clear_blk_fill_status(&po->rx_ring);
sk->sk_data_ready(sk, 0);
drop_n_restore:
if (skb_head != skb->data && skb_shared(skb)) {
skb->data = skb_head;
skb->len = skb_len;
}
drop:
kfree_skb(skb);
return 0;
ring_is_full:
po->stats.stats1.tp_drops++;
spin_unlock(&sk->sk_receive_queue.lock);
sk->sk_data_ready(sk, 0);
kfree_skb(copy_skb);
goto drop_n_restore;
}
static void tpacket_destruct_skb(struct sk_buff *skb)
{
struct packet_sock *po = pkt_sk(skb->sk);
void *ph;
if (likely(po->tx_ring.pg_vec)) {
__u32 ts;
ph = skb_shinfo(skb)->destructor_arg;
BUG_ON(atomic_read(&po->tx_ring.pending) == 0);
atomic_dec(&po->tx_ring.pending);
ts = __packet_set_timestamp(po, ph, skb);
__packet_set_status(po, ph, TP_STATUS_AVAILABLE | ts);
}
sock_wfree(skb);
}
static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
void *frame, struct net_device *dev, int size_max,
__be16 proto, unsigned char *addr, int hlen)
{
union tpacket_uhdr ph;
int to_write, offset, len, tp_len, nr_frags, len_max;
struct socket *sock = po->sk.sk_socket;
struct page *page;
void *data;
int err;
ph.raw = frame;
skb->protocol = proto;
skb->dev = dev;
skb->priority = po->sk.sk_priority;
skb->mark = po->sk.sk_mark;
sock_tx_timestamp(&po->sk, &skb_shinfo(skb)->tx_flags);
skb_shinfo(skb)->destructor_arg = ph.raw;
switch (po->tp_version) {
case TPACKET_V2:
tp_len = ph.h2->tp_len;
break;
default:
tp_len = ph.h1->tp_len;
break;
}
if (unlikely(tp_len > size_max)) {
pr_err("packet size is too long (%d > %d)\n", tp_len, size_max);
return -EMSGSIZE;
}
skb_reserve(skb, hlen);
skb_reset_network_header(skb);
skb_probe_transport_header(skb, 0);
if (po->tp_tx_has_off) {
int off_min, off_max, off;
off_min = po->tp_hdrlen - sizeof(struct sockaddr_ll);
off_max = po->tx_ring.frame_size - tp_len;
if (sock->type == SOCK_DGRAM) {
switch (po->tp_version) {
case TPACKET_V2:
off = ph.h2->tp_net;
break;
default:
off = ph.h1->tp_net;
break;
}
} else {
switch (po->tp_version) {
case TPACKET_V2:
off = ph.h2->tp_mac;
break;
default:
off = ph.h1->tp_mac;
break;
}
}
if (unlikely((off < off_min) || (off_max < off)))
return -EINVAL;
data = ph.raw + off;
} else {
data = ph.raw + po->tp_hdrlen - sizeof(struct sockaddr_ll);
}
to_write = tp_len;
if (sock->type == SOCK_DGRAM) {
err = dev_hard_header(skb, dev, ntohs(proto), addr,
NULL, tp_len);
if (unlikely(err < 0))
return -EINVAL;
} else if (dev->hard_header_len) {
/* net device doesn't like empty head */
if (unlikely(tp_len <= dev->hard_header_len)) {
pr_err("packet size is too short (%d < %d)\n",
tp_len, dev->hard_header_len);
return -EINVAL;
}
skb_push(skb, dev->hard_header_len);
err = skb_store_bits(skb, 0, data,
dev->hard_header_len);
if (unlikely(err))
return err;
data += dev->hard_header_len;
to_write -= dev->hard_header_len;
}
offset = offset_in_page(data);
len_max = PAGE_SIZE - offset;
len = ((to_write > len_max) ? len_max : to_write);
skb->data_len = to_write;
skb->len += to_write;
skb->truesize += to_write;
atomic_add(to_write, &po->sk.sk_wmem_alloc);
while (likely(to_write)) {
nr_frags = skb_shinfo(skb)->nr_frags;
if (unlikely(nr_frags >= MAX_SKB_FRAGS)) {
pr_err("Packet exceed the number of skb frags(%lu)\n",
MAX_SKB_FRAGS);
return -EFAULT;
}
page = pgv_to_page(data);
data += len;
flush_dcache_page(page);
get_page(page);
skb_fill_page_desc(skb, nr_frags, page, offset, len);
to_write -= len;
offset = 0;
len_max = PAGE_SIZE;
len = ((to_write > len_max) ? len_max : to_write);
}
return tp_len;
}
static int tpacket_snd(struct packet_sock *po, struct msghdr *msg)
{
struct sk_buff *skb;
struct net_device *dev;
__be16 proto;
bool need_rls_dev = false;
int err, reserve = 0;
void *ph;
struct sockaddr_ll *saddr = (struct sockaddr_ll *)msg->msg_name;
int tp_len, size_max;
unsigned char *addr;
int len_sum = 0;
int status = TP_STATUS_AVAILABLE;
int hlen, tlen;
mutex_lock(&po->pg_vec_lock);
if (saddr == NULL) {
dev = po->prot_hook.dev;
proto = po->num;
addr = NULL;
} else {
err = -EINVAL;
if (msg->msg_namelen < sizeof(struct sockaddr_ll))
goto out;
if (msg->msg_namelen < (saddr->sll_halen
+ offsetof(struct sockaddr_ll,
sll_addr)))
goto out;
proto = saddr->sll_protocol;
addr = saddr->sll_addr;
dev = dev_get_by_index(sock_net(&po->sk), saddr->sll_ifindex);
need_rls_dev = true;
}
err = -ENXIO;
if (unlikely(dev == NULL))
goto out;
reserve = dev->hard_header_len;
err = -ENETDOWN;
if (unlikely(!(dev->flags & IFF_UP)))
goto out_put;
size_max = po->tx_ring.frame_size
- (po->tp_hdrlen - sizeof(struct sockaddr_ll));
if (size_max > dev->mtu + reserve)
size_max = dev->mtu + reserve;
do {
ph = packet_current_frame(po, &po->tx_ring,
TP_STATUS_SEND_REQUEST);
if (unlikely(ph == NULL)) {
schedule();
continue;
}
status = TP_STATUS_SEND_REQUEST;
hlen = LL_RESERVED_SPACE(dev);
tlen = dev->needed_tailroom;
skb = sock_alloc_send_skb(&po->sk,
hlen + tlen + sizeof(struct sockaddr_ll),
0, &err);
if (unlikely(skb == NULL))
goto out_status;
tp_len = tpacket_fill_skb(po, skb, ph, dev, size_max, proto,
addr, hlen);
if (unlikely(tp_len < 0)) {
if (po->tp_loss) {
__packet_set_status(po, ph,
TP_STATUS_AVAILABLE);
packet_increment_head(&po->tx_ring);
kfree_skb(skb);
continue;
} else {
status = TP_STATUS_WRONG_FORMAT;
err = tp_len;
goto out_status;
}
}
skb->destructor = tpacket_destruct_skb;
__packet_set_status(po, ph, TP_STATUS_SENDING);
atomic_inc(&po->tx_ring.pending);
status = TP_STATUS_SEND_REQUEST;
err = dev_queue_xmit(skb);
if (unlikely(err > 0)) {
err = net_xmit_errno(err);
if (err && __packet_get_status(po, ph) ==
TP_STATUS_AVAILABLE) {
/* skb was destructed already */
skb = NULL;
goto out_status;
}
/*
* skb was dropped but not destructed yet;
* let's treat it like congestion or err < 0
*/
err = 0;
}
packet_increment_head(&po->tx_ring);
len_sum += tp_len;
} while (likely((ph != NULL) ||
((!(msg->msg_flags & MSG_DONTWAIT)) &&
(atomic_read(&po->tx_ring.pending))))
);
err = len_sum;
goto out_put;
out_status:
__packet_set_status(po, ph, status);
kfree_skb(skb);
out_put:
if (need_rls_dev)
dev_put(dev);
out:
mutex_unlock(&po->pg_vec_lock);
return err;
}
static struct sk_buff *packet_alloc_skb(struct sock *sk, size_t prepad,
size_t reserve, size_t len,
size_t linear, int noblock,
int *err)
{
struct sk_buff *skb;
/* Under a page? Don't bother with paged skb. */
if (prepad + len < PAGE_SIZE || !linear)
linear = len;
skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
err, 0);
if (!skb)
return NULL;
skb_reserve(skb, reserve);
skb_put(skb, linear);
skb->data_len = len - linear;
skb->len += len - linear;
return skb;
}
static int packet_snd(struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct sockaddr_ll *saddr = (struct sockaddr_ll *)msg->msg_name;
struct sk_buff *skb;
struct net_device *dev;
__be16 proto;
bool need_rls_dev = false;
unsigned char *addr;
int err, reserve = 0;
struct virtio_net_hdr vnet_hdr = { 0 };
int offset = 0;
int vnet_hdr_len;
struct packet_sock *po = pkt_sk(sk);
unsigned short gso_type = 0;
int hlen, tlen;
int extra_len = 0;
/*
* Get and verify the address.
*/
if (saddr == NULL) {
dev = po->prot_hook.dev;
proto = po->num;
addr = NULL;
} else {
err = -EINVAL;
if (msg->msg_namelen < sizeof(struct sockaddr_ll))
goto out;
if (msg->msg_namelen < (saddr->sll_halen + offsetof(struct sockaddr_ll, sll_addr)))
goto out;
proto = saddr->sll_protocol;
addr = saddr->sll_addr;
dev = dev_get_by_index(sock_net(sk), saddr->sll_ifindex);
need_rls_dev = true;
}
err = -ENXIO;
if (dev == NULL)
goto out_unlock;
if (sock->type == SOCK_RAW)
reserve = dev->hard_header_len;
err = -ENETDOWN;
if (!(dev->flags & IFF_UP))
goto out_unlock;
if (po->has_vnet_hdr) {
vnet_hdr_len = sizeof(vnet_hdr);
err = -EINVAL;
if (len < vnet_hdr_len)
goto out_unlock;
len -= vnet_hdr_len;
err = memcpy_fromiovec((void *)&vnet_hdr, msg->msg_iov,
vnet_hdr_len);
if (err < 0)
goto out_unlock;
if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
(vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 >
vnet_hdr.hdr_len))
vnet_hdr.hdr_len = vnet_hdr.csum_start +
vnet_hdr.csum_offset + 2;
err = -EINVAL;
if (vnet_hdr.hdr_len > len)
goto out_unlock;
if (vnet_hdr.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
switch (vnet_hdr.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
case VIRTIO_NET_HDR_GSO_TCPV4:
gso_type = SKB_GSO_TCPV4;
break;
case VIRTIO_NET_HDR_GSO_TCPV6:
gso_type = SKB_GSO_TCPV6;
break;
case VIRTIO_NET_HDR_GSO_UDP:
gso_type = SKB_GSO_UDP;
break;
default:
goto out_unlock;
}
if (vnet_hdr.gso_type & VIRTIO_NET_HDR_GSO_ECN)
gso_type |= SKB_GSO_TCP_ECN;
if (vnet_hdr.gso_size == 0)
goto out_unlock;
}
}
if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
if (!netif_supports_nofcs(dev)) {
err = -EPROTONOSUPPORT;
goto out_unlock;
}
extra_len = 4; /* We're doing our own CRC */
}
err = -EMSGSIZE;
if (!gso_type && (len > dev->mtu + reserve + VLAN_HLEN + extra_len))
goto out_unlock;
err = -ENOBUFS;
hlen = LL_RESERVED_SPACE(dev);
tlen = dev->needed_tailroom;
skb = packet_alloc_skb(sk, hlen + tlen, hlen, len, vnet_hdr.hdr_len,
msg->msg_flags & MSG_DONTWAIT, &err);
if (skb == NULL)
goto out_unlock;
skb_set_network_header(skb, reserve);
err = -EINVAL;
if (sock->type == SOCK_DGRAM &&
(offset = dev_hard_header(skb, dev, ntohs(proto), addr, NULL, len)) < 0)
goto out_free;
/* Returns -EFAULT on error */
err = skb_copy_datagram_from_iovec(skb, offset, msg->msg_iov, 0, len);
if (err)
goto out_free;
sock_tx_timestamp(sk, &skb_shinfo(skb)->tx_flags);
if (!gso_type && (len > dev->mtu + reserve + extra_len)) {
/* Earlier code assumed this would be a VLAN pkt,
* double-check this now that we have the actual
* packet in hand.
*/
struct ethhdr *ehdr;
skb_reset_mac_header(skb);
ehdr = eth_hdr(skb);
if (ehdr->h_proto != htons(ETH_P_8021Q)) {
err = -EMSGSIZE;
goto out_free;
}
}
skb->protocol = proto;
skb->dev = dev;
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
if (po->has_vnet_hdr) {
if (vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
if (!skb_partial_csum_set(skb, vnet_hdr.csum_start,
vnet_hdr.csum_offset)) {
err = -EINVAL;
goto out_free;
}
}
skb_shinfo(skb)->gso_size = vnet_hdr.gso_size;
skb_shinfo(skb)->gso_type = gso_type;
/* Header must be checked, and gso_segs computed. */
skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
skb_shinfo(skb)->gso_segs = 0;
len += vnet_hdr_len;
}
skb_probe_transport_header(skb, reserve);
if (unlikely(extra_len == 4))
skb->no_fcs = 1;
/*
* Now send it
*/
err = dev_queue_xmit(skb);
if (err > 0 && (err = net_xmit_errno(err)) != 0)
goto out_unlock;
if (need_rls_dev)
dev_put(dev);
return len;
out_free:
kfree_skb(skb);
out_unlock:
if (dev && need_rls_dev)
dev_put(dev);
out:
return err;
}
static int packet_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
if (po->tx_ring.pg_vec)
return tpacket_snd(po, msg);
else
return packet_snd(sock, msg, len);
}
/*
* Close a PACKET socket. This is fairly simple. We immediately go
* to 'closed' state and remove our protocol entry in the device list.
*/
static int packet_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct packet_sock *po;
struct net *net;
union tpacket_req_u req_u;
if (!sk)
return 0;
net = sock_net(sk);
po = pkt_sk(sk);
mutex_lock(&net->packet.sklist_lock);
sk_del_node_init_rcu(sk);
mutex_unlock(&net->packet.sklist_lock);
preempt_disable();
sock_prot_inuse_add(net, sk->sk_prot, -1);
preempt_enable();
spin_lock(&po->bind_lock);
unregister_prot_hook(sk, false);
if (po->prot_hook.dev) {
dev_put(po->prot_hook.dev);
po->prot_hook.dev = NULL;
}
spin_unlock(&po->bind_lock);
packet_flush_mclist(sk);
if (po->rx_ring.pg_vec) {
memset(&req_u, 0, sizeof(req_u));
packet_set_ring(sk, &req_u, 1, 0);
}
if (po->tx_ring.pg_vec) {
memset(&req_u, 0, sizeof(req_u));
packet_set_ring(sk, &req_u, 1, 1);
}
fanout_release(sk);
synchronize_net();
/*
* Now the socket is dead. No more input will appear.
*/
sock_orphan(sk);
sock->sk = NULL;
/* Purge queues */
skb_queue_purge(&sk->sk_receive_queue);
sk_refcnt_debug_release(sk);
sock_put(sk);
return 0;
}
/*
* Attach a packet hook.
*/
static int packet_do_bind(struct sock *sk, struct net_device *dev, __be16 protocol)
{
struct packet_sock *po = pkt_sk(sk);
if (po->fanout) {
if (dev)
dev_put(dev);
return -EINVAL;
}
lock_sock(sk);
spin_lock(&po->bind_lock);
unregister_prot_hook(sk, true);
po->num = protocol;
po->prot_hook.type = protocol;
if (po->prot_hook.dev)
dev_put(po->prot_hook.dev);
po->prot_hook.dev = dev;
po->ifindex = dev ? dev->ifindex : 0;
if (protocol == 0)
goto out_unlock;
if (!dev || (dev->flags & IFF_UP)) {
register_prot_hook(sk);
} else {
sk->sk_err = ENETDOWN;
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_error_report(sk);
}
out_unlock:
spin_unlock(&po->bind_lock);
release_sock(sk);
return 0;
}
/*
* Bind a packet socket to a device
*/
static int packet_bind_spkt(struct socket *sock, struct sockaddr *uaddr,
int addr_len)
{
struct sock *sk = sock->sk;
char name[15];
struct net_device *dev;
int err = -ENODEV;
/*
* Check legality
*/
if (addr_len != sizeof(struct sockaddr))
return -EINVAL;
strlcpy(name, uaddr->sa_data, sizeof(name));
dev = dev_get_by_name(sock_net(sk), name);
if (dev)
err = packet_do_bind(sk, dev, pkt_sk(sk)->num);
return err;
}
static int packet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sockaddr_ll *sll = (struct sockaddr_ll *)uaddr;
struct sock *sk = sock->sk;
struct net_device *dev = NULL;
int err;
/*
* Check legality
*/
if (addr_len < sizeof(struct sockaddr_ll))
return -EINVAL;
if (sll->sll_family != AF_PACKET)
return -EINVAL;
if (sll->sll_ifindex) {
err = -ENODEV;
dev = dev_get_by_index(sock_net(sk), sll->sll_ifindex);
if (dev == NULL)
goto out;
}
err = packet_do_bind(sk, dev, sll->sll_protocol ? : pkt_sk(sk)->num);
out:
return err;
}
static struct proto packet_proto = {
.name = "PACKET",
.owner = THIS_MODULE,
.obj_size = sizeof(struct packet_sock),
};
/*
* Create a packet of type SOCK_PACKET.
*/
static int packet_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
struct packet_sock *po;
__be16 proto = (__force __be16)protocol; /* weird, but documented */
int err;
if (!ns_capable(net->user_ns, CAP_NET_RAW))
return -EPERM;
if (sock->type != SOCK_DGRAM && sock->type != SOCK_RAW &&
sock->type != SOCK_PACKET)
return -ESOCKTNOSUPPORT;
sock->state = SS_UNCONNECTED;
err = -ENOBUFS;
sk = sk_alloc(net, PF_PACKET, GFP_KERNEL, &packet_proto);
if (sk == NULL)
goto out;
sock->ops = &packet_ops;
if (sock->type == SOCK_PACKET)
sock->ops = &packet_ops_spkt;
sock_init_data(sock, sk);
po = pkt_sk(sk);
sk->sk_family = PF_PACKET;
po->num = proto;
sk->sk_destruct = packet_sock_destruct;
sk_refcnt_debug_inc(sk);
/*
* Attach a protocol block
*/
spin_lock_init(&po->bind_lock);
mutex_init(&po->pg_vec_lock);
po->prot_hook.func = packet_rcv;
if (sock->type == SOCK_PACKET)
po->prot_hook.func = packet_rcv_spkt;
po->prot_hook.af_packet_priv = sk;
if (proto) {
po->prot_hook.type = proto;
register_prot_hook(sk);
}
mutex_lock(&net->packet.sklist_lock);
sk_add_node_rcu(sk, &net->packet.sklist);
mutex_unlock(&net->packet.sklist_lock);
preempt_disable();
sock_prot_inuse_add(net, &packet_proto, 1);
preempt_enable();
return 0;
out:
return err;
}
/*
* Pull a packet from our receive queue and hand it to the user.
* If necessary we block.
*/
static int packet_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sock *sk = sock->sk;
struct sk_buff *skb;
int copied, err;
int vnet_hdr_len = 0;
err = -EINVAL;
if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))
goto out;
#if 0
/* What error should we return now? EUNATTACH? */
if (pkt_sk(sk)->ifindex < 0)
return -ENODEV;
#endif
if (flags & MSG_ERRQUEUE) {
err = sock_recv_errqueue(sk, msg, len,
SOL_PACKET, PACKET_TX_TIMESTAMP);
goto out;
}
/*
* Call the generic datagram receiver. This handles all sorts
* of horrible races and re-entrancy so we can forget about it
* in the protocol layers.
*
* Now it will return ENETDOWN, if device have just gone down,
* but then it will block.
*/
skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
/*
* An error occurred so return it. Because skb_recv_datagram()
* handles the blocking we don't see and worry about blocking
* retries.
*/
if (skb == NULL)
goto out;
if (pkt_sk(sk)->has_vnet_hdr) {
struct virtio_net_hdr vnet_hdr = { 0 };
err = -EINVAL;
vnet_hdr_len = sizeof(vnet_hdr);
if (len < vnet_hdr_len)
goto out_free;
len -= vnet_hdr_len;
if (skb_is_gso(skb)) {
struct skb_shared_info *sinfo = skb_shinfo(skb);
/* This is a hint as to how much should be linear. */
vnet_hdr.hdr_len = skb_headlen(skb);
vnet_hdr.gso_size = sinfo->gso_size;
if (sinfo->gso_type & SKB_GSO_TCPV4)
vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
else if (sinfo->gso_type & SKB_GSO_TCPV6)
vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
else if (sinfo->gso_type & SKB_GSO_UDP)
vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP;
else if (sinfo->gso_type & SKB_GSO_FCOE)
goto out_free;
else
BUG();
if (sinfo->gso_type & SKB_GSO_TCP_ECN)
vnet_hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
} else
vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE;
if (skb->ip_summed == CHECKSUM_PARTIAL) {
vnet_hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
vnet_hdr.csum_start = skb_checksum_start_offset(skb);
vnet_hdr.csum_offset = skb->csum_offset;
} else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
vnet_hdr.flags = VIRTIO_NET_HDR_F_DATA_VALID;
} /* else everything is zero */
err = memcpy_toiovec(msg->msg_iov, (void *)&vnet_hdr,
vnet_hdr_len);
if (err < 0)
goto out_free;
}
/* You lose any data beyond the buffer you gave. If it worries
* a user program they can ask the device for its MTU
* anyway.
*/
copied = skb->len;
if (copied > len) {
copied = len;
msg->msg_flags |= MSG_TRUNC;
}
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto out_free;
sock_recv_ts_and_drops(msg, sk, skb);
if (msg->msg_name) {
/* If the address length field is there to be filled
* in, we fill it in now.
*/
if (sock->type == SOCK_PACKET) {
msg->msg_namelen = sizeof(struct sockaddr_pkt);
} else {
struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
msg->msg_namelen = sll->sll_halen +
offsetof(struct sockaddr_ll, sll_addr);
}
memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa,
msg->msg_namelen);
}
if (pkt_sk(sk)->auxdata) {
struct tpacket_auxdata aux;
aux.tp_status = TP_STATUS_USER;
if (skb->ip_summed == CHECKSUM_PARTIAL)
aux.tp_status |= TP_STATUS_CSUMNOTREADY;
aux.tp_len = PACKET_SKB_CB(skb)->origlen;
aux.tp_snaplen = skb->len;
aux.tp_mac = 0;
aux.tp_net = skb_network_offset(skb);
if (vlan_tx_tag_present(skb)) {
aux.tp_vlan_tci = vlan_tx_tag_get(skb);
aux.tp_status |= TP_STATUS_VLAN_VALID;
} else {
aux.tp_vlan_tci = 0;
}
aux.tp_padding = 0;
put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);
}
/*
* Free or return the buffer as appropriate. Again this
* hides all the races and re-entrancy issues from us.
*/
err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);
out_free:
skb_free_datagram(sk, skb);
out:
return err;
}
static int packet_getname_spkt(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct net_device *dev;
struct sock *sk = sock->sk;
if (peer)
return -EOPNOTSUPP;
uaddr->sa_family = AF_PACKET;
memset(uaddr->sa_data, 0, sizeof(uaddr->sa_data));
rcu_read_lock();
dev = dev_get_by_index_rcu(sock_net(sk), pkt_sk(sk)->ifindex);
if (dev)
strlcpy(uaddr->sa_data, dev->name, sizeof(uaddr->sa_data));
rcu_read_unlock();
*uaddr_len = sizeof(*uaddr);
return 0;
}
static int packet_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct net_device *dev;
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_ll *, sll, uaddr);
if (peer)
return -EOPNOTSUPP;
sll->sll_family = AF_PACKET;
sll->sll_ifindex = po->ifindex;
sll->sll_protocol = po->num;
sll->sll_pkttype = 0;
rcu_read_lock();
dev = dev_get_by_index_rcu(sock_net(sk), po->ifindex);
if (dev) {
sll->sll_hatype = dev->type;
sll->sll_halen = dev->addr_len;
memcpy(sll->sll_addr, dev->dev_addr, dev->addr_len);
} else {
sll->sll_hatype = 0; /* Bad: we have no ARPHRD_UNSPEC */
sll->sll_halen = 0;
}
rcu_read_unlock();
*uaddr_len = offsetof(struct sockaddr_ll, sll_addr) + sll->sll_halen;
return 0;
}
static int packet_dev_mc(struct net_device *dev, struct packet_mclist *i,
int what)
{
switch (i->type) {
case PACKET_MR_MULTICAST:
if (i->alen != dev->addr_len)
return -EINVAL;
if (what > 0)
return dev_mc_add(dev, i->addr);
else
return dev_mc_del(dev, i->addr);
break;
case PACKET_MR_PROMISC:
return dev_set_promiscuity(dev, what);
break;
case PACKET_MR_ALLMULTI:
return dev_set_allmulti(dev, what);
break;
case PACKET_MR_UNICAST:
if (i->alen != dev->addr_len)
return -EINVAL;
if (what > 0)
return dev_uc_add(dev, i->addr);
else
return dev_uc_del(dev, i->addr);
break;
default:
break;
}
return 0;
}
static void packet_dev_mclist(struct net_device *dev, struct packet_mclist *i, int what)
{
for ( ; i; i = i->next) {
if (i->ifindex == dev->ifindex)
packet_dev_mc(dev, i, what);
}
}
static int packet_mc_add(struct sock *sk, struct packet_mreq_max *mreq)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_mclist *ml, *i;
struct net_device *dev;
int err;
rtnl_lock();
err = -ENODEV;
dev = __dev_get_by_index(sock_net(sk), mreq->mr_ifindex);
if (!dev)
goto done;
err = -EINVAL;
if (mreq->mr_alen > dev->addr_len)
goto done;
err = -ENOBUFS;
i = kmalloc(sizeof(*i), GFP_KERNEL);
if (i == NULL)
goto done;
err = 0;
for (ml = po->mclist; ml; ml = ml->next) {
if (ml->ifindex == mreq->mr_ifindex &&
ml->type == mreq->mr_type &&
ml->alen == mreq->mr_alen &&
memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
ml->count++;
/* Free the new element ... */
kfree(i);
goto done;
}
}
i->type = mreq->mr_type;
i->ifindex = mreq->mr_ifindex;
i->alen = mreq->mr_alen;
memcpy(i->addr, mreq->mr_address, i->alen);
i->count = 1;
i->next = po->mclist;
po->mclist = i;
err = packet_dev_mc(dev, i, 1);
if (err) {
po->mclist = i->next;
kfree(i);
}
done:
rtnl_unlock();
return err;
}
static int packet_mc_drop(struct sock *sk, struct packet_mreq_max *mreq)
{
struct packet_mclist *ml, **mlp;
rtnl_lock();
for (mlp = &pkt_sk(sk)->mclist; (ml = *mlp) != NULL; mlp = &ml->next) {
if (ml->ifindex == mreq->mr_ifindex &&
ml->type == mreq->mr_type &&
ml->alen == mreq->mr_alen &&
memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
if (--ml->count == 0) {
struct net_device *dev;
*mlp = ml->next;
dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
if (dev)
packet_dev_mc(dev, ml, -1);
kfree(ml);
}
rtnl_unlock();
return 0;
}
}
rtnl_unlock();
return -EADDRNOTAVAIL;
}
static void packet_flush_mclist(struct sock *sk)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_mclist *ml;
if (!po->mclist)
return;
rtnl_lock();
while ((ml = po->mclist) != NULL) {
struct net_device *dev;
po->mclist = ml->next;
dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
if (dev != NULL)
packet_dev_mc(dev, ml, -1);
kfree(ml);
}
rtnl_unlock();
}
static int
packet_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
int ret;
if (level != SOL_PACKET)
return -ENOPROTOOPT;
switch (optname) {
case PACKET_ADD_MEMBERSHIP:
case PACKET_DROP_MEMBERSHIP:
{
struct packet_mreq_max mreq;
int len = optlen;
memset(&mreq, 0, sizeof(mreq));
if (len < sizeof(struct packet_mreq))
return -EINVAL;
if (len > sizeof(mreq))
len = sizeof(mreq);
if (copy_from_user(&mreq, optval, len))
return -EFAULT;
if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address)))
return -EINVAL;
if (optname == PACKET_ADD_MEMBERSHIP)
ret = packet_mc_add(sk, &mreq);
else
ret = packet_mc_drop(sk, &mreq);
return ret;
}
case PACKET_RX_RING:
case PACKET_TX_RING:
{
union tpacket_req_u req_u;
int len;
switch (po->tp_version) {
case TPACKET_V1:
case TPACKET_V2:
len = sizeof(req_u.req);
break;
case TPACKET_V3:
default:
len = sizeof(req_u.req3);
break;
}
if (optlen < len)
return -EINVAL;
if (pkt_sk(sk)->has_vnet_hdr)
return -EINVAL;
if (copy_from_user(&req_u.req, optval, len))
return -EFAULT;
return packet_set_ring(sk, &req_u, 0,
optname == PACKET_TX_RING);
}
case PACKET_COPY_THRESH:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
pkt_sk(sk)->copy_thresh = val;
return 0;
}
case PACKET_VERSION:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
switch (val) {
case TPACKET_V1:
case TPACKET_V2:
case TPACKET_V3:
po->tp_version = val;
return 0;
default:
return -EINVAL;
}
}
case PACKET_RESERVE:
{
unsigned int val;
if (optlen != sizeof(val))
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->tp_reserve = val;
return 0;
}
case PACKET_LOSS:
{
unsigned int val;
if (optlen != sizeof(val))
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->tp_loss = !!val;
return 0;
}
case PACKET_AUXDATA:
{
int val;
if (optlen < sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->auxdata = !!val;
return 0;
}
case PACKET_ORIGDEV:
{
int val;
if (optlen < sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->origdev = !!val;
return 0;
}
case PACKET_VNET_HDR:
{
int val;
if (sock->type != SOCK_RAW)
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (optlen < sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->has_vnet_hdr = !!val;
return 0;
}
case PACKET_TIMESTAMP:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->tp_tstamp = val;
return 0;
}
case PACKET_FANOUT:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
return fanout_add(sk, val & 0xffff, val >> 16);
}
case PACKET_TX_HAS_OFF:
{
unsigned int val;
if (optlen != sizeof(val))
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->tp_tx_has_off = !!val;
return 0;
}
default:
return -ENOPROTOOPT;
}
}
static int packet_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
int len;
int val, lv = sizeof(val);
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
void *data = &val;
union tpacket_stats_u st;
if (level != SOL_PACKET)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
switch (optname) {
case PACKET_STATISTICS:
spin_lock_bh(&sk->sk_receive_queue.lock);
memcpy(&st, &po->stats, sizeof(st));
memset(&po->stats, 0, sizeof(po->stats));
spin_unlock_bh(&sk->sk_receive_queue.lock);
if (po->tp_version == TPACKET_V3) {
lv = sizeof(struct tpacket_stats_v3);
st.stats3.tp_packets += st.stats3.tp_drops;
data = &st.stats3;
} else {
lv = sizeof(struct tpacket_stats);
st.stats1.tp_packets += st.stats1.tp_drops;
data = &st.stats1;
}
break;
case PACKET_AUXDATA:
val = po->auxdata;
break;
case PACKET_ORIGDEV:
val = po->origdev;
break;
case PACKET_VNET_HDR:
val = po->has_vnet_hdr;
break;
case PACKET_VERSION:
val = po->tp_version;
break;
case PACKET_HDRLEN:
if (len > sizeof(int))
len = sizeof(int);
if (copy_from_user(&val, optval, len))
return -EFAULT;
switch (val) {
case TPACKET_V1:
val = sizeof(struct tpacket_hdr);
break;
case TPACKET_V2:
val = sizeof(struct tpacket2_hdr);
break;
case TPACKET_V3:
val = sizeof(struct tpacket3_hdr);
break;
default:
return -EINVAL;
}
break;
case PACKET_RESERVE:
val = po->tp_reserve;
break;
case PACKET_LOSS:
val = po->tp_loss;
break;
case PACKET_TIMESTAMP:
val = po->tp_tstamp;
break;
case PACKET_FANOUT:
val = (po->fanout ?
((u32)po->fanout->id |
((u32)po->fanout->type << 16) |
((u32)po->fanout->flags << 24)) :
0);
break;
case PACKET_TX_HAS_OFF:
val = po->tp_tx_has_off;
break;
default:
return -ENOPROTOOPT;
}
if (len > lv)
len = lv;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, data, len))
return -EFAULT;
return 0;
}
static int packet_notifier(struct notifier_block *this,
unsigned long msg, void *ptr)
{
struct sock *sk;
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
struct net *net = dev_net(dev);
rcu_read_lock();
sk_for_each_rcu(sk, &net->packet.sklist) {
struct packet_sock *po = pkt_sk(sk);
switch (msg) {
case NETDEV_UNREGISTER:
if (po->mclist)
packet_dev_mclist(dev, po->mclist, -1);
/* fallthrough */
case NETDEV_DOWN:
if (dev->ifindex == po->ifindex) {
spin_lock(&po->bind_lock);
if (po->running) {
__unregister_prot_hook(sk, false);
sk->sk_err = ENETDOWN;
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_error_report(sk);
}
if (msg == NETDEV_UNREGISTER) {
po->ifindex = -1;
if (po->prot_hook.dev)
dev_put(po->prot_hook.dev);
po->prot_hook.dev = NULL;
}
spin_unlock(&po->bind_lock);
}
break;
case NETDEV_UP:
if (dev->ifindex == po->ifindex) {
spin_lock(&po->bind_lock);
if (po->num)
register_prot_hook(sk);
spin_unlock(&po->bind_lock);
}
break;
}
}
rcu_read_unlock();
return NOTIFY_DONE;
}
static int packet_ioctl(struct socket *sock, unsigned int cmd,
unsigned long arg)
{
struct sock *sk = sock->sk;
switch (cmd) {
case SIOCOUTQ:
{
int amount = sk_wmem_alloc_get(sk);
return put_user(amount, (int __user *)arg);
}
case SIOCINQ:
{
struct sk_buff *skb;
int amount = 0;
spin_lock_bh(&sk->sk_receive_queue.lock);
skb = skb_peek(&sk->sk_receive_queue);
if (skb)
amount = skb->len;
spin_unlock_bh(&sk->sk_receive_queue.lock);
return put_user(amount, (int __user *)arg);
}
case SIOCGSTAMP:
return sock_get_timestamp(sk, (struct timeval __user *)arg);
case SIOCGSTAMPNS:
return sock_get_timestampns(sk, (struct timespec __user *)arg);
#ifdef CONFIG_INET
case SIOCADDRT:
case SIOCDELRT:
case SIOCDARP:
case SIOCGARP:
case SIOCSARP:
case SIOCGIFADDR:
case SIOCSIFADDR:
case SIOCGIFBRDADDR:
case SIOCSIFBRDADDR:
case SIOCGIFNETMASK:
case SIOCSIFNETMASK:
case SIOCGIFDSTADDR:
case SIOCSIFDSTADDR:
case SIOCSIFFLAGS:
return inet_dgram_ops.ioctl(sock, cmd, arg);
#endif
default:
return -ENOIOCTLCMD;
}
return 0;
}
static unsigned int packet_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
unsigned int mask = datagram_poll(file, sock, wait);
spin_lock_bh(&sk->sk_receive_queue.lock);
if (po->rx_ring.pg_vec) {
if (!packet_previous_rx_frame(po, &po->rx_ring,
TP_STATUS_KERNEL))
mask |= POLLIN | POLLRDNORM;
}
spin_unlock_bh(&sk->sk_receive_queue.lock);
spin_lock_bh(&sk->sk_write_queue.lock);
if (po->tx_ring.pg_vec) {
if (packet_current_frame(po, &po->tx_ring, TP_STATUS_AVAILABLE))
mask |= POLLOUT | POLLWRNORM;
}
spin_unlock_bh(&sk->sk_write_queue.lock);
return mask;
}
/* Dirty? Well, I still did not learn better way to account
* for user mmaps.
*/
static void packet_mm_open(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
struct socket *sock = file->private_data;
struct sock *sk = sock->sk;
if (sk)
atomic_inc(&pkt_sk(sk)->mapped);
}
static void packet_mm_close(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
struct socket *sock = file->private_data;
struct sock *sk = sock->sk;
if (sk)
atomic_dec(&pkt_sk(sk)->mapped);
}
static const struct vm_operations_struct packet_mmap_ops = {
.open = packet_mm_open,
.close = packet_mm_close,
};
static void free_pg_vec(struct pgv *pg_vec, unsigned int order,
unsigned int len)
{
int i;
for (i = 0; i < len; i++) {
if (likely(pg_vec[i].buffer)) {
if (is_vmalloc_addr(pg_vec[i].buffer))
vfree(pg_vec[i].buffer);
else
free_pages((unsigned long)pg_vec[i].buffer,
order);
pg_vec[i].buffer = NULL;
}
}
kfree(pg_vec);
}
static char *alloc_one_pg_vec_page(unsigned long order)
{
char *buffer = NULL;
gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
__GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
buffer = (char *) __get_free_pages(gfp_flags, order);
if (buffer)
return buffer;
/*
* __get_free_pages failed, fall back to vmalloc
*/
buffer = vzalloc((1 << order) * PAGE_SIZE);
if (buffer)
return buffer;
/*
* vmalloc failed, lets dig into swap here
*/
gfp_flags &= ~__GFP_NORETRY;
buffer = (char *)__get_free_pages(gfp_flags, order);
if (buffer)
return buffer;
/*
* complete and utter failure
*/
return NULL;
}
static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
{
unsigned int block_nr = req->tp_block_nr;
struct pgv *pg_vec;
int i;
pg_vec = kcalloc(block_nr, sizeof(struct pgv), GFP_KERNEL);
if (unlikely(!pg_vec))
goto out;
for (i = 0; i < block_nr; i++) {
pg_vec[i].buffer = alloc_one_pg_vec_page(order);
if (unlikely(!pg_vec[i].buffer))
goto out_free_pgvec;
}
out:
return pg_vec;
out_free_pgvec:
free_pg_vec(pg_vec, order, block_nr);
pg_vec = NULL;
goto out;
}
static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
int closing, int tx_ring)
{
struct pgv *pg_vec = NULL;
struct packet_sock *po = pkt_sk(sk);
int was_running, order = 0;
struct packet_ring_buffer *rb;
struct sk_buff_head *rb_queue;
__be16 num;
int err = -EINVAL;
/* Added to avoid minimal code churn */
struct tpacket_req *req = &req_u->req;
/* Opening a Tx-ring is NOT supported in TPACKET_V3 */
if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) {
WARN(1, "Tx-ring is not supported.\n");
goto out;
}
rb = tx_ring ? &po->tx_ring : &po->rx_ring;
rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
err = -EBUSY;
if (!closing) {
if (atomic_read(&po->mapped))
goto out;
if (atomic_read(&rb->pending))
goto out;
}
if (req->tp_block_nr) {
/* Sanity tests and some calculations */
err = -EBUSY;
if (unlikely(rb->pg_vec))
goto out;
switch (po->tp_version) {
case TPACKET_V1:
po->tp_hdrlen = TPACKET_HDRLEN;
break;
case TPACKET_V2:
po->tp_hdrlen = TPACKET2_HDRLEN;
break;
case TPACKET_V3:
po->tp_hdrlen = TPACKET3_HDRLEN;
break;
}
err = -EINVAL;
if (unlikely((int)req->tp_block_size <= 0))
goto out;
if (unlikely(req->tp_block_size & (PAGE_SIZE - 1)))
goto out;
if (unlikely(req->tp_frame_size < po->tp_hdrlen +
po->tp_reserve))
goto out;
if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1)))
goto out;
rb->frames_per_block = req->tp_block_size/req->tp_frame_size;
if (unlikely(rb->frames_per_block <= 0))
goto out;
if (unlikely((rb->frames_per_block * req->tp_block_nr) !=
req->tp_frame_nr))
goto out;
err = -ENOMEM;
order = get_order(req->tp_block_size);
pg_vec = alloc_pg_vec(req, order);
if (unlikely(!pg_vec))
goto out;
switch (po->tp_version) {
case TPACKET_V3:
/* Transmit path is not supported. We checked
* it above but just being paranoid
*/
if (!tx_ring)
init_prb_bdqc(po, rb, pg_vec, req_u, tx_ring);
break;
default:
break;
}
}
/* Done */
else {
err = -EINVAL;
if (unlikely(req->tp_frame_nr))
goto out;
}
lock_sock(sk);
/* Detach socket from network */
spin_lock(&po->bind_lock);
was_running = po->running;
num = po->num;
if (was_running) {
po->num = 0;
__unregister_prot_hook(sk, false);
}
spin_unlock(&po->bind_lock);
synchronize_net();
err = -EBUSY;
mutex_lock(&po->pg_vec_lock);
if (closing || atomic_read(&po->mapped) == 0) {
err = 0;
spin_lock_bh(&rb_queue->lock);
swap(rb->pg_vec, pg_vec);
rb->frame_max = (req->tp_frame_nr - 1);
rb->head = 0;
rb->frame_size = req->tp_frame_size;
spin_unlock_bh(&rb_queue->lock);
swap(rb->pg_vec_order, order);
swap(rb->pg_vec_len, req->tp_block_nr);
rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE;
po->prot_hook.func = (po->rx_ring.pg_vec) ?
tpacket_rcv : packet_rcv;
skb_queue_purge(rb_queue);
if (atomic_read(&po->mapped))
pr_err("packet_mmap: vma is busy: %d\n",
atomic_read(&po->mapped));
}
mutex_unlock(&po->pg_vec_lock);
spin_lock(&po->bind_lock);
if (was_running) {
po->num = num;
register_prot_hook(sk);
}
spin_unlock(&po->bind_lock);
if (closing && (po->tp_version > TPACKET_V2)) {
/* Because we don't support block-based V3 on tx-ring */
if (!tx_ring)
prb_shutdown_retire_blk_timer(po, tx_ring, rb_queue);
}
release_sock(sk);
if (pg_vec)
free_pg_vec(pg_vec, order, req->tp_block_nr);
out:
return err;
}
static int packet_mmap(struct file *file, struct socket *sock,
struct vm_area_struct *vma)
{
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
unsigned long size, expected_size;
struct packet_ring_buffer *rb;
unsigned long start;
int err = -EINVAL;
int i;
if (vma->vm_pgoff)
return -EINVAL;
mutex_lock(&po->pg_vec_lock);
expected_size = 0;
for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
if (rb->pg_vec) {
expected_size += rb->pg_vec_len
* rb->pg_vec_pages
* PAGE_SIZE;
}
}
if (expected_size == 0)
goto out;
size = vma->vm_end - vma->vm_start;
if (size != expected_size)
goto out;
start = vma->vm_start;
for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
if (rb->pg_vec == NULL)
continue;
for (i = 0; i < rb->pg_vec_len; i++) {
struct page *page;
void *kaddr = rb->pg_vec[i].buffer;
int pg_num;
for (pg_num = 0; pg_num < rb->pg_vec_pages; pg_num++) {
page = pgv_to_page(kaddr);
err = vm_insert_page(vma, start, page);
if (unlikely(err))
goto out;
start += PAGE_SIZE;
kaddr += PAGE_SIZE;
}
}
}
atomic_inc(&po->mapped);
vma->vm_ops = &packet_mmap_ops;
err = 0;
out:
mutex_unlock(&po->pg_vec_lock);
return err;
}
static const struct proto_ops packet_ops_spkt = {
.family = PF_PACKET,
.owner = THIS_MODULE,
.release = packet_release,
.bind = packet_bind_spkt,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = packet_getname_spkt,
.poll = datagram_poll,
.ioctl = packet_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = packet_sendmsg_spkt,
.recvmsg = packet_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static const struct proto_ops packet_ops = {
.family = PF_PACKET,
.owner = THIS_MODULE,
.release = packet_release,
.bind = packet_bind,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = packet_getname,
.poll = packet_poll,
.ioctl = packet_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = packet_setsockopt,
.getsockopt = packet_getsockopt,
.sendmsg = packet_sendmsg,
.recvmsg = packet_recvmsg,
.mmap = packet_mmap,
.sendpage = sock_no_sendpage,
};
static const struct net_proto_family packet_family_ops = {
.family = PF_PACKET,
.create = packet_create,
.owner = THIS_MODULE,
};
static struct notifier_block packet_netdev_notifier = {
.notifier_call = packet_notifier,
};
#ifdef CONFIG_PROC_FS
static void *packet_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(RCU)
{
struct net *net = seq_file_net(seq);
rcu_read_lock();
return seq_hlist_start_head_rcu(&net->packet.sklist, *pos);
}
static void *packet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct net *net = seq_file_net(seq);
return seq_hlist_next_rcu(v, &net->packet.sklist, pos);
}
static void packet_seq_stop(struct seq_file *seq, void *v)
__releases(RCU)
{
rcu_read_unlock();
}
static int packet_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq, "sk RefCnt Type Proto Iface R Rmem User Inode\n");
else {
struct sock *s = sk_entry(v);
const struct packet_sock *po = pkt_sk(s);
seq_printf(seq,
"%pK %-6d %-4d %04x %-5d %1d %-6u %-6u %-6lu\n",
s,
atomic_read(&s->sk_refcnt),
s->sk_type,
ntohs(po->num),
po->ifindex,
po->running,
atomic_read(&s->sk_rmem_alloc),
from_kuid_munged(seq_user_ns(seq), sock_i_uid(s)),
sock_i_ino(s));
}
return 0;
}
static const struct seq_operations packet_seq_ops = {
.start = packet_seq_start,
.next = packet_seq_next,
.stop = packet_seq_stop,
.show = packet_seq_show,
};
static int packet_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &packet_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations packet_seq_fops = {
.owner = THIS_MODULE,
.open = packet_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
static int __net_init packet_net_init(struct net *net)
{
mutex_init(&net->packet.sklist_lock);
INIT_HLIST_HEAD(&net->packet.sklist);
if (!proc_create("packet", 0, net->proc_net, &packet_seq_fops))
return -ENOMEM;
return 0;
}
static void __net_exit packet_net_exit(struct net *net)
{
remove_proc_entry("packet", net->proc_net);
}
static struct pernet_operations packet_net_ops = {
.init = packet_net_init,
.exit = packet_net_exit,
};
static void __exit packet_exit(void)
{
unregister_netdevice_notifier(&packet_netdev_notifier);
unregister_pernet_subsys(&packet_net_ops);
sock_unregister(PF_PACKET);
proto_unregister(&packet_proto);
}
static int __init packet_init(void)
{
int rc = proto_register(&packet_proto, 0);
if (rc != 0)
goto out;
sock_register(&packet_family_ops);
register_pernet_subsys(&packet_net_ops);
register_netdevice_notifier(&packet_netdev_notifier);
out:
return rc;
}
module_init(packet_init);
module_exit(packet_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_PACKET);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_25 |
crossvul-cpp_data_bad_5845_9 | /*
BlueZ - Bluetooth protocol stack for Linux
Copyright (C) 2000-2001 Qualcomm Incorporated
Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
/* Bluetooth HCI sockets. */
#include <linux/export.h>
#include <asm/unaligned.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include <net/bluetooth/hci_mon.h>
static atomic_t monitor_promisc = ATOMIC_INIT(0);
/* ----- HCI socket interface ----- */
static inline int hci_test_bit(int nr, void *addr)
{
return *((__u32 *) addr + (nr >> 5)) & ((__u32) 1 << (nr & 31));
}
/* Security filter */
static struct hci_sec_filter hci_sec_filter = {
/* Packet types */
0x10,
/* Events */
{ 0x1000d9fe, 0x0000b00c },
/* Commands */
{
{ 0x0 },
/* OGF_LINK_CTL */
{ 0xbe000006, 0x00000001, 0x00000000, 0x00 },
/* OGF_LINK_POLICY */
{ 0x00005200, 0x00000000, 0x00000000, 0x00 },
/* OGF_HOST_CTL */
{ 0xaab00200, 0x2b402aaa, 0x05220154, 0x00 },
/* OGF_INFO_PARAM */
{ 0x000002be, 0x00000000, 0x00000000, 0x00 },
/* OGF_STATUS_PARAM */
{ 0x000000ea, 0x00000000, 0x00000000, 0x00 }
}
};
static struct bt_sock_list hci_sk_list = {
.lock = __RW_LOCK_UNLOCKED(hci_sk_list.lock)
};
static bool is_filtered_packet(struct sock *sk, struct sk_buff *skb)
{
struct hci_filter *flt;
int flt_type, flt_event;
/* Apply filter */
flt = &hci_pi(sk)->filter;
if (bt_cb(skb)->pkt_type == HCI_VENDOR_PKT)
flt_type = 0;
else
flt_type = bt_cb(skb)->pkt_type & HCI_FLT_TYPE_BITS;
if (!test_bit(flt_type, &flt->type_mask))
return true;
/* Extra filter for event packets only */
if (bt_cb(skb)->pkt_type != HCI_EVENT_PKT)
return false;
flt_event = (*(__u8 *)skb->data & HCI_FLT_EVENT_BITS);
if (!hci_test_bit(flt_event, &flt->event_mask))
return true;
/* Check filter only when opcode is set */
if (!flt->opcode)
return false;
if (flt_event == HCI_EV_CMD_COMPLETE &&
flt->opcode != get_unaligned((__le16 *)(skb->data + 3)))
return true;
if (flt_event == HCI_EV_CMD_STATUS &&
flt->opcode != get_unaligned((__le16 *)(skb->data + 4)))
return true;
return false;
}
/* Send frame to RAW socket */
void hci_send_to_sock(struct hci_dev *hdev, struct sk_buff *skb)
{
struct sock *sk;
struct sk_buff *skb_copy = NULL;
BT_DBG("hdev %p len %d", hdev, skb->len);
read_lock(&hci_sk_list.lock);
sk_for_each(sk, &hci_sk_list.head) {
struct sk_buff *nskb;
if (sk->sk_state != BT_BOUND || hci_pi(sk)->hdev != hdev)
continue;
/* Don't send frame to the socket it came from */
if (skb->sk == sk)
continue;
if (hci_pi(sk)->channel == HCI_CHANNEL_RAW) {
if (is_filtered_packet(sk, skb))
continue;
} else if (hci_pi(sk)->channel == HCI_CHANNEL_USER) {
if (!bt_cb(skb)->incoming)
continue;
if (bt_cb(skb)->pkt_type != HCI_EVENT_PKT &&
bt_cb(skb)->pkt_type != HCI_ACLDATA_PKT &&
bt_cb(skb)->pkt_type != HCI_SCODATA_PKT)
continue;
} else {
/* Don't send frame to other channel types */
continue;
}
if (!skb_copy) {
/* Create a private copy with headroom */
skb_copy = __pskb_copy(skb, 1, GFP_ATOMIC);
if (!skb_copy)
continue;
/* Put type byte before the data */
memcpy(skb_push(skb_copy, 1), &bt_cb(skb)->pkt_type, 1);
}
nskb = skb_clone(skb_copy, GFP_ATOMIC);
if (!nskb)
continue;
if (sock_queue_rcv_skb(sk, nskb))
kfree_skb(nskb);
}
read_unlock(&hci_sk_list.lock);
kfree_skb(skb_copy);
}
/* Send frame to control socket */
void hci_send_to_control(struct sk_buff *skb, struct sock *skip_sk)
{
struct sock *sk;
BT_DBG("len %d", skb->len);
read_lock(&hci_sk_list.lock);
sk_for_each(sk, &hci_sk_list.head) {
struct sk_buff *nskb;
/* Skip the original socket */
if (sk == skip_sk)
continue;
if (sk->sk_state != BT_BOUND)
continue;
if (hci_pi(sk)->channel != HCI_CHANNEL_CONTROL)
continue;
nskb = skb_clone(skb, GFP_ATOMIC);
if (!nskb)
continue;
if (sock_queue_rcv_skb(sk, nskb))
kfree_skb(nskb);
}
read_unlock(&hci_sk_list.lock);
}
/* Send frame to monitor socket */
void hci_send_to_monitor(struct hci_dev *hdev, struct sk_buff *skb)
{
struct sock *sk;
struct sk_buff *skb_copy = NULL;
__le16 opcode;
if (!atomic_read(&monitor_promisc))
return;
BT_DBG("hdev %p len %d", hdev, skb->len);
switch (bt_cb(skb)->pkt_type) {
case HCI_COMMAND_PKT:
opcode = __constant_cpu_to_le16(HCI_MON_COMMAND_PKT);
break;
case HCI_EVENT_PKT:
opcode = __constant_cpu_to_le16(HCI_MON_EVENT_PKT);
break;
case HCI_ACLDATA_PKT:
if (bt_cb(skb)->incoming)
opcode = __constant_cpu_to_le16(HCI_MON_ACL_RX_PKT);
else
opcode = __constant_cpu_to_le16(HCI_MON_ACL_TX_PKT);
break;
case HCI_SCODATA_PKT:
if (bt_cb(skb)->incoming)
opcode = __constant_cpu_to_le16(HCI_MON_SCO_RX_PKT);
else
opcode = __constant_cpu_to_le16(HCI_MON_SCO_TX_PKT);
break;
default:
return;
}
read_lock(&hci_sk_list.lock);
sk_for_each(sk, &hci_sk_list.head) {
struct sk_buff *nskb;
if (sk->sk_state != BT_BOUND)
continue;
if (hci_pi(sk)->channel != HCI_CHANNEL_MONITOR)
continue;
if (!skb_copy) {
struct hci_mon_hdr *hdr;
/* Create a private copy with headroom */
skb_copy = __pskb_copy(skb, HCI_MON_HDR_SIZE,
GFP_ATOMIC);
if (!skb_copy)
continue;
/* Put header before the data */
hdr = (void *) skb_push(skb_copy, HCI_MON_HDR_SIZE);
hdr->opcode = opcode;
hdr->index = cpu_to_le16(hdev->id);
hdr->len = cpu_to_le16(skb->len);
}
nskb = skb_clone(skb_copy, GFP_ATOMIC);
if (!nskb)
continue;
if (sock_queue_rcv_skb(sk, nskb))
kfree_skb(nskb);
}
read_unlock(&hci_sk_list.lock);
kfree_skb(skb_copy);
}
static void send_monitor_event(struct sk_buff *skb)
{
struct sock *sk;
BT_DBG("len %d", skb->len);
read_lock(&hci_sk_list.lock);
sk_for_each(sk, &hci_sk_list.head) {
struct sk_buff *nskb;
if (sk->sk_state != BT_BOUND)
continue;
if (hci_pi(sk)->channel != HCI_CHANNEL_MONITOR)
continue;
nskb = skb_clone(skb, GFP_ATOMIC);
if (!nskb)
continue;
if (sock_queue_rcv_skb(sk, nskb))
kfree_skb(nskb);
}
read_unlock(&hci_sk_list.lock);
}
static struct sk_buff *create_monitor_event(struct hci_dev *hdev, int event)
{
struct hci_mon_hdr *hdr;
struct hci_mon_new_index *ni;
struct sk_buff *skb;
__le16 opcode;
switch (event) {
case HCI_DEV_REG:
skb = bt_skb_alloc(HCI_MON_NEW_INDEX_SIZE, GFP_ATOMIC);
if (!skb)
return NULL;
ni = (void *) skb_put(skb, HCI_MON_NEW_INDEX_SIZE);
ni->type = hdev->dev_type;
ni->bus = hdev->bus;
bacpy(&ni->bdaddr, &hdev->bdaddr);
memcpy(ni->name, hdev->name, 8);
opcode = __constant_cpu_to_le16(HCI_MON_NEW_INDEX);
break;
case HCI_DEV_UNREG:
skb = bt_skb_alloc(0, GFP_ATOMIC);
if (!skb)
return NULL;
opcode = __constant_cpu_to_le16(HCI_MON_DEL_INDEX);
break;
default:
return NULL;
}
__net_timestamp(skb);
hdr = (void *) skb_push(skb, HCI_MON_HDR_SIZE);
hdr->opcode = opcode;
hdr->index = cpu_to_le16(hdev->id);
hdr->len = cpu_to_le16(skb->len - HCI_MON_HDR_SIZE);
return skb;
}
static void send_monitor_replay(struct sock *sk)
{
struct hci_dev *hdev;
read_lock(&hci_dev_list_lock);
list_for_each_entry(hdev, &hci_dev_list, list) {
struct sk_buff *skb;
skb = create_monitor_event(hdev, HCI_DEV_REG);
if (!skb)
continue;
if (sock_queue_rcv_skb(sk, skb))
kfree_skb(skb);
}
read_unlock(&hci_dev_list_lock);
}
/* Generate internal stack event */
static void hci_si_event(struct hci_dev *hdev, int type, int dlen, void *data)
{
struct hci_event_hdr *hdr;
struct hci_ev_stack_internal *ev;
struct sk_buff *skb;
skb = bt_skb_alloc(HCI_EVENT_HDR_SIZE + sizeof(*ev) + dlen, GFP_ATOMIC);
if (!skb)
return;
hdr = (void *) skb_put(skb, HCI_EVENT_HDR_SIZE);
hdr->evt = HCI_EV_STACK_INTERNAL;
hdr->plen = sizeof(*ev) + dlen;
ev = (void *) skb_put(skb, sizeof(*ev) + dlen);
ev->type = type;
memcpy(ev->data, data, dlen);
bt_cb(skb)->incoming = 1;
__net_timestamp(skb);
bt_cb(skb)->pkt_type = HCI_EVENT_PKT;
hci_send_to_sock(hdev, skb);
kfree_skb(skb);
}
void hci_sock_dev_event(struct hci_dev *hdev, int event)
{
struct hci_ev_si_device ev;
BT_DBG("hdev %s event %d", hdev->name, event);
/* Send event to monitor */
if (atomic_read(&monitor_promisc)) {
struct sk_buff *skb;
skb = create_monitor_event(hdev, event);
if (skb) {
send_monitor_event(skb);
kfree_skb(skb);
}
}
/* Send event to sockets */
ev.event = event;
ev.dev_id = hdev->id;
hci_si_event(NULL, HCI_EV_SI_DEVICE, sizeof(ev), &ev);
if (event == HCI_DEV_UNREG) {
struct sock *sk;
/* Detach sockets from device */
read_lock(&hci_sk_list.lock);
sk_for_each(sk, &hci_sk_list.head) {
bh_lock_sock_nested(sk);
if (hci_pi(sk)->hdev == hdev) {
hci_pi(sk)->hdev = NULL;
sk->sk_err = EPIPE;
sk->sk_state = BT_OPEN;
sk->sk_state_change(sk);
hci_dev_put(hdev);
}
bh_unlock_sock(sk);
}
read_unlock(&hci_sk_list.lock);
}
}
static int hci_sock_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct hci_dev *hdev;
BT_DBG("sock %p sk %p", sock, sk);
if (!sk)
return 0;
hdev = hci_pi(sk)->hdev;
if (hci_pi(sk)->channel == HCI_CHANNEL_MONITOR)
atomic_dec(&monitor_promisc);
bt_sock_unlink(&hci_sk_list, sk);
if (hdev) {
if (hci_pi(sk)->channel == HCI_CHANNEL_USER) {
mgmt_index_added(hdev);
clear_bit(HCI_USER_CHANNEL, &hdev->dev_flags);
hci_dev_close(hdev->id);
}
atomic_dec(&hdev->promisc);
hci_dev_put(hdev);
}
sock_orphan(sk);
skb_queue_purge(&sk->sk_receive_queue);
skb_queue_purge(&sk->sk_write_queue);
sock_put(sk);
return 0;
}
static int hci_sock_blacklist_add(struct hci_dev *hdev, void __user *arg)
{
bdaddr_t bdaddr;
int err;
if (copy_from_user(&bdaddr, arg, sizeof(bdaddr)))
return -EFAULT;
hci_dev_lock(hdev);
err = hci_blacklist_add(hdev, &bdaddr, BDADDR_BREDR);
hci_dev_unlock(hdev);
return err;
}
static int hci_sock_blacklist_del(struct hci_dev *hdev, void __user *arg)
{
bdaddr_t bdaddr;
int err;
if (copy_from_user(&bdaddr, arg, sizeof(bdaddr)))
return -EFAULT;
hci_dev_lock(hdev);
err = hci_blacklist_del(hdev, &bdaddr, BDADDR_BREDR);
hci_dev_unlock(hdev);
return err;
}
/* Ioctls that require bound socket */
static int hci_sock_bound_ioctl(struct sock *sk, unsigned int cmd,
unsigned long arg)
{
struct hci_dev *hdev = hci_pi(sk)->hdev;
if (!hdev)
return -EBADFD;
if (test_bit(HCI_USER_CHANNEL, &hdev->dev_flags))
return -EBUSY;
if (hdev->dev_type != HCI_BREDR)
return -EOPNOTSUPP;
switch (cmd) {
case HCISETRAW:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (test_bit(HCI_QUIRK_RAW_DEVICE, &hdev->quirks))
return -EPERM;
if (arg)
set_bit(HCI_RAW, &hdev->flags);
else
clear_bit(HCI_RAW, &hdev->flags);
return 0;
case HCIGETCONNINFO:
return hci_get_conn_info(hdev, (void __user *) arg);
case HCIGETAUTHINFO:
return hci_get_auth_info(hdev, (void __user *) arg);
case HCIBLOCKADDR:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return hci_sock_blacklist_add(hdev, (void __user *) arg);
case HCIUNBLOCKADDR:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return hci_sock_blacklist_del(hdev, (void __user *) arg);
}
return -ENOIOCTLCMD;
}
static int hci_sock_ioctl(struct socket *sock, unsigned int cmd,
unsigned long arg)
{
void __user *argp = (void __user *) arg;
struct sock *sk = sock->sk;
int err;
BT_DBG("cmd %x arg %lx", cmd, arg);
lock_sock(sk);
if (hci_pi(sk)->channel != HCI_CHANNEL_RAW) {
err = -EBADFD;
goto done;
}
release_sock(sk);
switch (cmd) {
case HCIGETDEVLIST:
return hci_get_dev_list(argp);
case HCIGETDEVINFO:
return hci_get_dev_info(argp);
case HCIGETCONNLIST:
return hci_get_conn_list(argp);
case HCIDEVUP:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return hci_dev_open(arg);
case HCIDEVDOWN:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return hci_dev_close(arg);
case HCIDEVRESET:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return hci_dev_reset(arg);
case HCIDEVRESTAT:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return hci_dev_reset_stat(arg);
case HCISETSCAN:
case HCISETAUTH:
case HCISETENCRYPT:
case HCISETPTYPE:
case HCISETLINKPOL:
case HCISETLINKMODE:
case HCISETACLMTU:
case HCISETSCOMTU:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return hci_dev_cmd(cmd, argp);
case HCIINQUIRY:
return hci_inquiry(argp);
}
lock_sock(sk);
err = hci_sock_bound_ioctl(sk, cmd, arg);
done:
release_sock(sk);
return err;
}
static int hci_sock_bind(struct socket *sock, struct sockaddr *addr,
int addr_len)
{
struct sockaddr_hci haddr;
struct sock *sk = sock->sk;
struct hci_dev *hdev = NULL;
int len, err = 0;
BT_DBG("sock %p sk %p", sock, sk);
if (!addr)
return -EINVAL;
memset(&haddr, 0, sizeof(haddr));
len = min_t(unsigned int, sizeof(haddr), addr_len);
memcpy(&haddr, addr, len);
if (haddr.hci_family != AF_BLUETOOTH)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state == BT_BOUND) {
err = -EALREADY;
goto done;
}
switch (haddr.hci_channel) {
case HCI_CHANNEL_RAW:
if (hci_pi(sk)->hdev) {
err = -EALREADY;
goto done;
}
if (haddr.hci_dev != HCI_DEV_NONE) {
hdev = hci_dev_get(haddr.hci_dev);
if (!hdev) {
err = -ENODEV;
goto done;
}
atomic_inc(&hdev->promisc);
}
hci_pi(sk)->hdev = hdev;
break;
case HCI_CHANNEL_USER:
if (hci_pi(sk)->hdev) {
err = -EALREADY;
goto done;
}
if (haddr.hci_dev == HCI_DEV_NONE) {
err = -EINVAL;
goto done;
}
if (!capable(CAP_NET_ADMIN)) {
err = -EPERM;
goto done;
}
hdev = hci_dev_get(haddr.hci_dev);
if (!hdev) {
err = -ENODEV;
goto done;
}
if (test_bit(HCI_UP, &hdev->flags) ||
test_bit(HCI_INIT, &hdev->flags) ||
test_bit(HCI_SETUP, &hdev->dev_flags)) {
err = -EBUSY;
hci_dev_put(hdev);
goto done;
}
if (test_and_set_bit(HCI_USER_CHANNEL, &hdev->dev_flags)) {
err = -EUSERS;
hci_dev_put(hdev);
goto done;
}
mgmt_index_removed(hdev);
err = hci_dev_open(hdev->id);
if (err) {
clear_bit(HCI_USER_CHANNEL, &hdev->dev_flags);
hci_dev_put(hdev);
goto done;
}
atomic_inc(&hdev->promisc);
hci_pi(sk)->hdev = hdev;
break;
case HCI_CHANNEL_CONTROL:
if (haddr.hci_dev != HCI_DEV_NONE) {
err = -EINVAL;
goto done;
}
if (!capable(CAP_NET_ADMIN)) {
err = -EPERM;
goto done;
}
break;
case HCI_CHANNEL_MONITOR:
if (haddr.hci_dev != HCI_DEV_NONE) {
err = -EINVAL;
goto done;
}
if (!capable(CAP_NET_RAW)) {
err = -EPERM;
goto done;
}
send_monitor_replay(sk);
atomic_inc(&monitor_promisc);
break;
default:
err = -EINVAL;
goto done;
}
hci_pi(sk)->channel = haddr.hci_channel;
sk->sk_state = BT_BOUND;
done:
release_sock(sk);
return err;
}
static int hci_sock_getname(struct socket *sock, struct sockaddr *addr,
int *addr_len, int peer)
{
struct sockaddr_hci *haddr = (struct sockaddr_hci *) addr;
struct sock *sk = sock->sk;
struct hci_dev *hdev;
int err = 0;
BT_DBG("sock %p sk %p", sock, sk);
if (peer)
return -EOPNOTSUPP;
lock_sock(sk);
hdev = hci_pi(sk)->hdev;
if (!hdev) {
err = -EBADFD;
goto done;
}
*addr_len = sizeof(*haddr);
haddr->hci_family = AF_BLUETOOTH;
haddr->hci_dev = hdev->id;
haddr->hci_channel= hci_pi(sk)->channel;
done:
release_sock(sk);
return err;
}
static void hci_sock_cmsg(struct sock *sk, struct msghdr *msg,
struct sk_buff *skb)
{
__u32 mask = hci_pi(sk)->cmsg_mask;
if (mask & HCI_CMSG_DIR) {
int incoming = bt_cb(skb)->incoming;
put_cmsg(msg, SOL_HCI, HCI_CMSG_DIR, sizeof(incoming),
&incoming);
}
if (mask & HCI_CMSG_TSTAMP) {
#ifdef CONFIG_COMPAT
struct compat_timeval ctv;
#endif
struct timeval tv;
void *data;
int len;
skb_get_timestamp(skb, &tv);
data = &tv;
len = sizeof(tv);
#ifdef CONFIG_COMPAT
if (!COMPAT_USE_64BIT_TIME &&
(msg->msg_flags & MSG_CMSG_COMPAT)) {
ctv.tv_sec = tv.tv_sec;
ctv.tv_usec = tv.tv_usec;
data = &ctv;
len = sizeof(ctv);
}
#endif
put_cmsg(msg, SOL_HCI, HCI_CMSG_TSTAMP, len, data);
}
}
static int hci_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
int noblock = flags & MSG_DONTWAIT;
struct sock *sk = sock->sk;
struct sk_buff *skb;
int copied, err;
BT_DBG("sock %p, sk %p", sock, sk);
if (flags & (MSG_OOB))
return -EOPNOTSUPP;
if (sk->sk_state == BT_CLOSED)
return 0;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
return err;
msg->msg_namelen = 0;
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
skb_reset_transport_header(skb);
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
switch (hci_pi(sk)->channel) {
case HCI_CHANNEL_RAW:
hci_sock_cmsg(sk, msg, skb);
break;
case HCI_CHANNEL_USER:
case HCI_CHANNEL_CONTROL:
case HCI_CHANNEL_MONITOR:
sock_recv_timestamp(msg, sk, skb);
break;
}
skb_free_datagram(sk, skb);
return err ? : copied;
}
static int hci_sock_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct hci_dev *hdev;
struct sk_buff *skb;
int err;
BT_DBG("sock %p sk %p", sock, sk);
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_NOSIGNAL|MSG_ERRQUEUE))
return -EINVAL;
if (len < 4 || len > HCI_MAX_FRAME_SIZE)
return -EINVAL;
lock_sock(sk);
switch (hci_pi(sk)->channel) {
case HCI_CHANNEL_RAW:
case HCI_CHANNEL_USER:
break;
case HCI_CHANNEL_CONTROL:
err = mgmt_control(sk, msg, len);
goto done;
case HCI_CHANNEL_MONITOR:
err = -EOPNOTSUPP;
goto done;
default:
err = -EINVAL;
goto done;
}
hdev = hci_pi(sk)->hdev;
if (!hdev) {
err = -EBADFD;
goto done;
}
if (!test_bit(HCI_UP, &hdev->flags)) {
err = -ENETDOWN;
goto done;
}
skb = bt_skb_send_alloc(sk, len, msg->msg_flags & MSG_DONTWAIT, &err);
if (!skb)
goto done;
if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {
err = -EFAULT;
goto drop;
}
bt_cb(skb)->pkt_type = *((unsigned char *) skb->data);
skb_pull(skb, 1);
if (hci_pi(sk)->channel == HCI_CHANNEL_RAW &&
bt_cb(skb)->pkt_type == HCI_COMMAND_PKT) {
u16 opcode = get_unaligned_le16(skb->data);
u16 ogf = hci_opcode_ogf(opcode);
u16 ocf = hci_opcode_ocf(opcode);
if (((ogf > HCI_SFLT_MAX_OGF) ||
!hci_test_bit(ocf & HCI_FLT_OCF_BITS,
&hci_sec_filter.ocf_mask[ogf])) &&
!capable(CAP_NET_RAW)) {
err = -EPERM;
goto drop;
}
if (test_bit(HCI_RAW, &hdev->flags) || (ogf == 0x3f)) {
skb_queue_tail(&hdev->raw_q, skb);
queue_work(hdev->workqueue, &hdev->tx_work);
} else {
/* Stand-alone HCI commands must be flaged as
* single-command requests.
*/
bt_cb(skb)->req.start = true;
skb_queue_tail(&hdev->cmd_q, skb);
queue_work(hdev->workqueue, &hdev->cmd_work);
}
} else {
if (!capable(CAP_NET_RAW)) {
err = -EPERM;
goto drop;
}
if (hci_pi(sk)->channel == HCI_CHANNEL_USER &&
bt_cb(skb)->pkt_type != HCI_COMMAND_PKT &&
bt_cb(skb)->pkt_type != HCI_ACLDATA_PKT &&
bt_cb(skb)->pkt_type != HCI_SCODATA_PKT) {
err = -EINVAL;
goto drop;
}
skb_queue_tail(&hdev->raw_q, skb);
queue_work(hdev->workqueue, &hdev->tx_work);
}
err = len;
done:
release_sock(sk);
return err;
drop:
kfree_skb(skb);
goto done;
}
static int hci_sock_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int len)
{
struct hci_ufilter uf = { .opcode = 0 };
struct sock *sk = sock->sk;
int err = 0, opt = 0;
BT_DBG("sk %p, opt %d", sk, optname);
lock_sock(sk);
if (hci_pi(sk)->channel != HCI_CHANNEL_RAW) {
err = -EBADFD;
goto done;
}
switch (optname) {
case HCI_DATA_DIR:
if (get_user(opt, (int __user *)optval)) {
err = -EFAULT;
break;
}
if (opt)
hci_pi(sk)->cmsg_mask |= HCI_CMSG_DIR;
else
hci_pi(sk)->cmsg_mask &= ~HCI_CMSG_DIR;
break;
case HCI_TIME_STAMP:
if (get_user(opt, (int __user *)optval)) {
err = -EFAULT;
break;
}
if (opt)
hci_pi(sk)->cmsg_mask |= HCI_CMSG_TSTAMP;
else
hci_pi(sk)->cmsg_mask &= ~HCI_CMSG_TSTAMP;
break;
case HCI_FILTER:
{
struct hci_filter *f = &hci_pi(sk)->filter;
uf.type_mask = f->type_mask;
uf.opcode = f->opcode;
uf.event_mask[0] = *((u32 *) f->event_mask + 0);
uf.event_mask[1] = *((u32 *) f->event_mask + 1);
}
len = min_t(unsigned int, len, sizeof(uf));
if (copy_from_user(&uf, optval, len)) {
err = -EFAULT;
break;
}
if (!capable(CAP_NET_RAW)) {
uf.type_mask &= hci_sec_filter.type_mask;
uf.event_mask[0] &= *((u32 *) hci_sec_filter.event_mask + 0);
uf.event_mask[1] &= *((u32 *) hci_sec_filter.event_mask + 1);
}
{
struct hci_filter *f = &hci_pi(sk)->filter;
f->type_mask = uf.type_mask;
f->opcode = uf.opcode;
*((u32 *) f->event_mask + 0) = uf.event_mask[0];
*((u32 *) f->event_mask + 1) = uf.event_mask[1];
}
break;
default:
err = -ENOPROTOOPT;
break;
}
done:
release_sock(sk);
return err;
}
static int hci_sock_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct hci_ufilter uf;
struct sock *sk = sock->sk;
int len, opt, err = 0;
BT_DBG("sk %p, opt %d", sk, optname);
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
if (hci_pi(sk)->channel != HCI_CHANNEL_RAW) {
err = -EBADFD;
goto done;
}
switch (optname) {
case HCI_DATA_DIR:
if (hci_pi(sk)->cmsg_mask & HCI_CMSG_DIR)
opt = 1;
else
opt = 0;
if (put_user(opt, optval))
err = -EFAULT;
break;
case HCI_TIME_STAMP:
if (hci_pi(sk)->cmsg_mask & HCI_CMSG_TSTAMP)
opt = 1;
else
opt = 0;
if (put_user(opt, optval))
err = -EFAULT;
break;
case HCI_FILTER:
{
struct hci_filter *f = &hci_pi(sk)->filter;
memset(&uf, 0, sizeof(uf));
uf.type_mask = f->type_mask;
uf.opcode = f->opcode;
uf.event_mask[0] = *((u32 *) f->event_mask + 0);
uf.event_mask[1] = *((u32 *) f->event_mask + 1);
}
len = min_t(unsigned int, len, sizeof(uf));
if (copy_to_user(optval, &uf, len))
err = -EFAULT;
break;
default:
err = -ENOPROTOOPT;
break;
}
done:
release_sock(sk);
return err;
}
static const struct proto_ops hci_sock_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.release = hci_sock_release,
.bind = hci_sock_bind,
.getname = hci_sock_getname,
.sendmsg = hci_sock_sendmsg,
.recvmsg = hci_sock_recvmsg,
.ioctl = hci_sock_ioctl,
.poll = datagram_poll,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = hci_sock_setsockopt,
.getsockopt = hci_sock_getsockopt,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.mmap = sock_no_mmap
};
static struct proto hci_sk_proto = {
.name = "HCI",
.owner = THIS_MODULE,
.obj_size = sizeof(struct hci_pinfo)
};
static int hci_sock_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
BT_DBG("sock %p", sock);
if (sock->type != SOCK_RAW)
return -ESOCKTNOSUPPORT;
sock->ops = &hci_sock_ops;
sk = sk_alloc(net, PF_BLUETOOTH, GFP_ATOMIC, &hci_sk_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
sock_reset_flag(sk, SOCK_ZAPPED);
sk->sk_protocol = protocol;
sock->state = SS_UNCONNECTED;
sk->sk_state = BT_OPEN;
bt_sock_link(&hci_sk_list, sk);
return 0;
}
static const struct net_proto_family hci_sock_family_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.create = hci_sock_create,
};
int __init hci_sock_init(void)
{
int err;
err = proto_register(&hci_sk_proto, 0);
if (err < 0)
return err;
err = bt_sock_register(BTPROTO_HCI, &hci_sock_family_ops);
if (err < 0) {
BT_ERR("HCI socket registration failed");
goto error;
}
err = bt_procfs_init(&init_net, "hci", &hci_sk_list, NULL);
if (err < 0) {
BT_ERR("Failed to create HCI proc file");
bt_sock_unregister(BTPROTO_HCI);
goto error;
}
BT_INFO("HCI socket layer initialized");
return 0;
error:
proto_unregister(&hci_sk_proto);
return err;
}
void hci_sock_cleanup(void)
{
bt_procfs_cleanup(&init_net, "hci");
bt_sock_unregister(BTPROTO_HCI);
proto_unregister(&hci_sk_proto);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5845_9 |
crossvul-cpp_data_bad_5613_1 | /*
* Kernel-based Virtual Machine driver for Linux
*
* This module enables machines with Intel VT-x extensions to run virtual
* machines without emulation or binary translation.
*
* Copyright (C) 2006 Qumranet, Inc.
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Authors:
* Avi Kivity <avi@qumranet.com>
* Yaniv Kamay <yaniv@qumranet.com>
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
*/
#include "iodev.h"
#include <linux/kvm_host.h>
#include <linux/kvm.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/percpu.h>
#include <linux/mm.h>
#include <linux/miscdevice.h>
#include <linux/vmalloc.h>
#include <linux/reboot.h>
#include <linux/debugfs.h>
#include <linux/highmem.h>
#include <linux/file.h>
#include <linux/syscore_ops.h>
#include <linux/cpu.h>
#include <linux/sched.h>
#include <linux/cpumask.h>
#include <linux/smp.h>
#include <linux/anon_inodes.h>
#include <linux/profile.h>
#include <linux/kvm_para.h>
#include <linux/pagemap.h>
#include <linux/mman.h>
#include <linux/swap.h>
#include <linux/bitops.h>
#include <linux/spinlock.h>
#include <linux/compat.h>
#include <linux/srcu.h>
#include <linux/hugetlb.h>
#include <linux/slab.h>
#include <asm/processor.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <asm/pgtable.h>
#include "coalesced_mmio.h"
#include "async_pf.h"
#define CREATE_TRACE_POINTS
#include <trace/events/kvm.h>
MODULE_AUTHOR("Qumranet");
MODULE_LICENSE("GPL");
/*
* Ordering of locks:
*
* kvm->lock --> kvm->slots_lock --> kvm->irq_lock
*/
DEFINE_RAW_SPINLOCK(kvm_lock);
LIST_HEAD(vm_list);
static cpumask_var_t cpus_hardware_enabled;
static int kvm_usage_count = 0;
static atomic_t hardware_enable_failed;
struct kmem_cache *kvm_vcpu_cache;
EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
static __read_mostly struct preempt_ops kvm_preempt_ops;
struct dentry *kvm_debugfs_dir;
static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
unsigned long arg);
static int hardware_enable_all(void);
static void hardware_disable_all(void);
static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
bool kvm_rebooting;
EXPORT_SYMBOL_GPL(kvm_rebooting);
static bool largepages_enabled = true;
static struct page *hwpoison_page;
static pfn_t hwpoison_pfn;
static struct page *fault_page;
static pfn_t fault_pfn;
inline int kvm_is_mmio_pfn(pfn_t pfn)
{
if (pfn_valid(pfn)) {
int reserved;
struct page *tail = pfn_to_page(pfn);
struct page *head = compound_trans_head(tail);
reserved = PageReserved(head);
if (head != tail) {
/*
* "head" is not a dangling pointer
* (compound_trans_head takes care of that)
* but the hugepage may have been splitted
* from under us (and we may not hold a
* reference count on the head page so it can
* be reused before we run PageReferenced), so
* we've to check PageTail before returning
* what we just read.
*/
smp_rmb();
if (PageTail(tail))
return reserved;
}
return PageReserved(tail);
}
return true;
}
/*
* Switches to specified vcpu, until a matching vcpu_put()
*/
void vcpu_load(struct kvm_vcpu *vcpu)
{
int cpu;
mutex_lock(&vcpu->mutex);
if (unlikely(vcpu->pid != current->pids[PIDTYPE_PID].pid)) {
/* The thread running this VCPU changed. */
struct pid *oldpid = vcpu->pid;
struct pid *newpid = get_task_pid(current, PIDTYPE_PID);
rcu_assign_pointer(vcpu->pid, newpid);
synchronize_rcu();
put_pid(oldpid);
}
cpu = get_cpu();
preempt_notifier_register(&vcpu->preempt_notifier);
kvm_arch_vcpu_load(vcpu, cpu);
put_cpu();
}
void vcpu_put(struct kvm_vcpu *vcpu)
{
preempt_disable();
kvm_arch_vcpu_put(vcpu);
preempt_notifier_unregister(&vcpu->preempt_notifier);
preempt_enable();
mutex_unlock(&vcpu->mutex);
}
static void ack_flush(void *_completed)
{
}
static bool make_all_cpus_request(struct kvm *kvm, unsigned int req)
{
int i, cpu, me;
cpumask_var_t cpus;
bool called = true;
struct kvm_vcpu *vcpu;
zalloc_cpumask_var(&cpus, GFP_ATOMIC);
me = get_cpu();
kvm_for_each_vcpu(i, vcpu, kvm) {
kvm_make_request(req, vcpu);
cpu = vcpu->cpu;
/* Set ->requests bit before we read ->mode */
smp_mb();
if (cpus != NULL && cpu != -1 && cpu != me &&
kvm_vcpu_exiting_guest_mode(vcpu) != OUTSIDE_GUEST_MODE)
cpumask_set_cpu(cpu, cpus);
}
if (unlikely(cpus == NULL))
smp_call_function_many(cpu_online_mask, ack_flush, NULL, 1);
else if (!cpumask_empty(cpus))
smp_call_function_many(cpus, ack_flush, NULL, 1);
else
called = false;
put_cpu();
free_cpumask_var(cpus);
return called;
}
void kvm_flush_remote_tlbs(struct kvm *kvm)
{
int dirty_count = kvm->tlbs_dirty;
smp_mb();
if (make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
++kvm->stat.remote_tlb_flush;
cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
}
void kvm_reload_remote_mmus(struct kvm *kvm)
{
make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
}
int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
{
struct page *page;
int r;
mutex_init(&vcpu->mutex);
vcpu->cpu = -1;
vcpu->kvm = kvm;
vcpu->vcpu_id = id;
vcpu->pid = NULL;
init_waitqueue_head(&vcpu->wq);
kvm_async_pf_vcpu_init(vcpu);
page = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (!page) {
r = -ENOMEM;
goto fail;
}
vcpu->run = page_address(page);
r = kvm_arch_vcpu_init(vcpu);
if (r < 0)
goto fail_free_run;
return 0;
fail_free_run:
free_page((unsigned long)vcpu->run);
fail:
return r;
}
EXPORT_SYMBOL_GPL(kvm_vcpu_init);
void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
{
put_pid(vcpu->pid);
kvm_arch_vcpu_uninit(vcpu);
free_page((unsigned long)vcpu->run);
}
EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
{
return container_of(mn, struct kvm, mmu_notifier);
}
static void kvm_mmu_notifier_invalidate_page(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long address)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int need_tlb_flush, idx;
/*
* When ->invalidate_page runs, the linux pte has been zapped
* already but the page is still allocated until
* ->invalidate_page returns. So if we increase the sequence
* here the kvm page fault will notice if the spte can't be
* established because the page is going to be freed. If
* instead the kvm page fault establishes the spte before
* ->invalidate_page runs, kvm_unmap_hva will release it
* before returning.
*
* The sequence increase only need to be seen at spin_unlock
* time, and not at spin_lock time.
*
* Increasing the sequence after the spin_unlock would be
* unsafe because the kvm page fault could then establish the
* pte after kvm_unmap_hva returned, without noticing the page
* is going to be freed.
*/
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
kvm->mmu_notifier_seq++;
need_tlb_flush = kvm_unmap_hva(kvm, address) | kvm->tlbs_dirty;
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
/* we've to flush the tlb before the pages can be freed */
if (need_tlb_flush)
kvm_flush_remote_tlbs(kvm);
}
static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long address,
pte_t pte)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int idx;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
kvm->mmu_notifier_seq++;
kvm_set_spte_hva(kvm, address, pte);
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
}
static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long start,
unsigned long end)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int need_tlb_flush = 0, idx;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
/*
* The count increase must become visible at unlock time as no
* spte can be established without taking the mmu_lock and
* count is also read inside the mmu_lock critical section.
*/
kvm->mmu_notifier_count++;
for (; start < end; start += PAGE_SIZE)
need_tlb_flush |= kvm_unmap_hva(kvm, start);
need_tlb_flush |= kvm->tlbs_dirty;
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
/* we've to flush the tlb before the pages can be freed */
if (need_tlb_flush)
kvm_flush_remote_tlbs(kvm);
}
static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long start,
unsigned long end)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
spin_lock(&kvm->mmu_lock);
/*
* This sequence increase will notify the kvm page fault that
* the page that is going to be mapped in the spte could have
* been freed.
*/
kvm->mmu_notifier_seq++;
/*
* The above sequence increase must be visible before the
* below count decrease but both values are read by the kvm
* page fault under mmu_lock spinlock so we don't need to add
* a smb_wmb() here in between the two.
*/
kvm->mmu_notifier_count--;
spin_unlock(&kvm->mmu_lock);
BUG_ON(kvm->mmu_notifier_count < 0);
}
static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long address)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int young, idx;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
young = kvm_age_hva(kvm, address);
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
if (young)
kvm_flush_remote_tlbs(kvm);
return young;
}
static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long address)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int young, idx;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
young = kvm_test_age_hva(kvm, address);
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
return young;
}
static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
struct mm_struct *mm)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int idx;
idx = srcu_read_lock(&kvm->srcu);
kvm_arch_flush_shadow(kvm);
srcu_read_unlock(&kvm->srcu, idx);
}
static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
.invalidate_page = kvm_mmu_notifier_invalidate_page,
.invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
.invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
.clear_flush_young = kvm_mmu_notifier_clear_flush_young,
.test_young = kvm_mmu_notifier_test_young,
.change_pte = kvm_mmu_notifier_change_pte,
.release = kvm_mmu_notifier_release,
};
static int kvm_init_mmu_notifier(struct kvm *kvm)
{
kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
}
#else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
static int kvm_init_mmu_notifier(struct kvm *kvm)
{
return 0;
}
#endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
static struct kvm *kvm_create_vm(void)
{
int r, i;
struct kvm *kvm = kvm_arch_alloc_vm();
if (!kvm)
return ERR_PTR(-ENOMEM);
r = kvm_arch_init_vm(kvm);
if (r)
goto out_err_nodisable;
r = hardware_enable_all();
if (r)
goto out_err_nodisable;
#ifdef CONFIG_HAVE_KVM_IRQCHIP
INIT_HLIST_HEAD(&kvm->mask_notifier_list);
INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
#endif
r = -ENOMEM;
kvm->memslots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
if (!kvm->memslots)
goto out_err_nosrcu;
if (init_srcu_struct(&kvm->srcu))
goto out_err_nosrcu;
for (i = 0; i < KVM_NR_BUSES; i++) {
kvm->buses[i] = kzalloc(sizeof(struct kvm_io_bus),
GFP_KERNEL);
if (!kvm->buses[i])
goto out_err;
}
r = kvm_init_mmu_notifier(kvm);
if (r)
goto out_err;
kvm->mm = current->mm;
atomic_inc(&kvm->mm->mm_count);
spin_lock_init(&kvm->mmu_lock);
kvm_eventfd_init(kvm);
mutex_init(&kvm->lock);
mutex_init(&kvm->irq_lock);
mutex_init(&kvm->slots_lock);
atomic_set(&kvm->users_count, 1);
raw_spin_lock(&kvm_lock);
list_add(&kvm->vm_list, &vm_list);
raw_spin_unlock(&kvm_lock);
return kvm;
out_err:
cleanup_srcu_struct(&kvm->srcu);
out_err_nosrcu:
hardware_disable_all();
out_err_nodisable:
for (i = 0; i < KVM_NR_BUSES; i++)
kfree(kvm->buses[i]);
kfree(kvm->memslots);
kvm_arch_free_vm(kvm);
return ERR_PTR(r);
}
static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
{
if (!memslot->dirty_bitmap)
return;
if (2 * kvm_dirty_bitmap_bytes(memslot) > PAGE_SIZE)
vfree(memslot->dirty_bitmap_head);
else
kfree(memslot->dirty_bitmap_head);
memslot->dirty_bitmap = NULL;
memslot->dirty_bitmap_head = NULL;
}
/*
* Free any memory in @free but not in @dont.
*/
static void kvm_free_physmem_slot(struct kvm_memory_slot *free,
struct kvm_memory_slot *dont)
{
int i;
if (!dont || free->rmap != dont->rmap)
vfree(free->rmap);
if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
kvm_destroy_dirty_bitmap(free);
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) {
if (!dont || free->lpage_info[i] != dont->lpage_info[i]) {
vfree(free->lpage_info[i]);
free->lpage_info[i] = NULL;
}
}
free->npages = 0;
free->rmap = NULL;
}
void kvm_free_physmem(struct kvm *kvm)
{
int i;
struct kvm_memslots *slots = kvm->memslots;
for (i = 0; i < slots->nmemslots; ++i)
kvm_free_physmem_slot(&slots->memslots[i], NULL);
kfree(kvm->memslots);
}
static void kvm_destroy_vm(struct kvm *kvm)
{
int i;
struct mm_struct *mm = kvm->mm;
kvm_arch_sync_events(kvm);
raw_spin_lock(&kvm_lock);
list_del(&kvm->vm_list);
raw_spin_unlock(&kvm_lock);
kvm_free_irq_routing(kvm);
for (i = 0; i < KVM_NR_BUSES; i++)
kvm_io_bus_destroy(kvm->buses[i]);
kvm_coalesced_mmio_free(kvm);
#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
#else
kvm_arch_flush_shadow(kvm);
#endif
kvm_arch_destroy_vm(kvm);
kvm_free_physmem(kvm);
cleanup_srcu_struct(&kvm->srcu);
kvm_arch_free_vm(kvm);
hardware_disable_all();
mmdrop(mm);
}
void kvm_get_kvm(struct kvm *kvm)
{
atomic_inc(&kvm->users_count);
}
EXPORT_SYMBOL_GPL(kvm_get_kvm);
void kvm_put_kvm(struct kvm *kvm)
{
if (atomic_dec_and_test(&kvm->users_count))
kvm_destroy_vm(kvm);
}
EXPORT_SYMBOL_GPL(kvm_put_kvm);
static int kvm_vm_release(struct inode *inode, struct file *filp)
{
struct kvm *kvm = filp->private_data;
kvm_irqfd_release(kvm);
kvm_put_kvm(kvm);
return 0;
}
#ifndef CONFIG_S390
/*
* Allocation size is twice as large as the actual dirty bitmap size.
* This makes it possible to do double buffering: see x86's
* kvm_vm_ioctl_get_dirty_log().
*/
static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
{
unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
if (dirty_bytes > PAGE_SIZE)
memslot->dirty_bitmap = vzalloc(dirty_bytes);
else
memslot->dirty_bitmap = kzalloc(dirty_bytes, GFP_KERNEL);
if (!memslot->dirty_bitmap)
return -ENOMEM;
memslot->dirty_bitmap_head = memslot->dirty_bitmap;
return 0;
}
#endif /* !CONFIG_S390 */
/*
* Allocate some memory and give it an address in the guest physical address
* space.
*
* Discontiguous memory is allowed, mostly for framebuffers.
*
* Must be called holding mmap_sem for write.
*/
int __kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem,
int user_alloc)
{
int r;
gfn_t base_gfn;
unsigned long npages;
unsigned long i;
struct kvm_memory_slot *memslot;
struct kvm_memory_slot old, new;
struct kvm_memslots *slots, *old_memslots;
r = -EINVAL;
/* General sanity checks */
if (mem->memory_size & (PAGE_SIZE - 1))
goto out;
if (mem->guest_phys_addr & (PAGE_SIZE - 1))
goto out;
if (user_alloc && (mem->userspace_addr & (PAGE_SIZE - 1)))
goto out;
if (mem->slot >= KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS)
goto out;
if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
goto out;
memslot = &kvm->memslots->memslots[mem->slot];
base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
npages = mem->memory_size >> PAGE_SHIFT;
r = -EINVAL;
if (npages > KVM_MEM_MAX_NR_PAGES)
goto out;
if (!npages)
mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
new = old = *memslot;
new.id = mem->slot;
new.base_gfn = base_gfn;
new.npages = npages;
new.flags = mem->flags;
/* Disallow changing a memory slot's size. */
r = -EINVAL;
if (npages && old.npages && npages != old.npages)
goto out_free;
/* Check for overlaps */
r = -EEXIST;
for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
struct kvm_memory_slot *s = &kvm->memslots->memslots[i];
if (s == memslot || !s->npages)
continue;
if (!((base_gfn + npages <= s->base_gfn) ||
(base_gfn >= s->base_gfn + s->npages)))
goto out_free;
}
/* Free page dirty bitmap if unneeded */
if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
new.dirty_bitmap = NULL;
r = -ENOMEM;
/* Allocate if a slot is being created */
#ifndef CONFIG_S390
if (npages && !new.rmap) {
new.rmap = vzalloc(npages * sizeof(*new.rmap));
if (!new.rmap)
goto out_free;
new.user_alloc = user_alloc;
new.userspace_addr = mem->userspace_addr;
}
if (!npages)
goto skip_lpage;
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) {
unsigned long ugfn;
unsigned long j;
int lpages;
int level = i + 2;
/* Avoid unused variable warning if no large pages */
(void)level;
if (new.lpage_info[i])
continue;
lpages = 1 + ((base_gfn + npages - 1)
>> KVM_HPAGE_GFN_SHIFT(level));
lpages -= base_gfn >> KVM_HPAGE_GFN_SHIFT(level);
new.lpage_info[i] = vzalloc(lpages * sizeof(*new.lpage_info[i]));
if (!new.lpage_info[i])
goto out_free;
if (base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
new.lpage_info[i][0].write_count = 1;
if ((base_gfn+npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
new.lpage_info[i][lpages - 1].write_count = 1;
ugfn = new.userspace_addr >> PAGE_SHIFT;
/*
* If the gfn and userspace address are not aligned wrt each
* other, or if explicitly asked to, disable large page
* support for this slot
*/
if ((base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
!largepages_enabled)
for (j = 0; j < lpages; ++j)
new.lpage_info[i][j].write_count = 1;
}
skip_lpage:
/* Allocate page dirty bitmap if needed */
if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
if (kvm_create_dirty_bitmap(&new) < 0)
goto out_free;
/* destroy any largepage mappings for dirty tracking */
}
#else /* not defined CONFIG_S390 */
new.user_alloc = user_alloc;
if (user_alloc)
new.userspace_addr = mem->userspace_addr;
#endif /* not defined CONFIG_S390 */
if (!npages) {
r = -ENOMEM;
slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
if (!slots)
goto out_free;
memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
if (mem->slot >= slots->nmemslots)
slots->nmemslots = mem->slot + 1;
slots->generation++;
slots->memslots[mem->slot].flags |= KVM_MEMSLOT_INVALID;
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
/* From this point no new shadow pages pointing to a deleted
* memslot will be created.
*
* validation of sp->gfn happens in:
* - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
* - kvm_is_visible_gfn (mmu_check_roots)
*/
kvm_arch_flush_shadow(kvm);
kfree(old_memslots);
}
r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc);
if (r)
goto out_free;
/* map the pages in iommu page table */
if (npages) {
r = kvm_iommu_map_pages(kvm, &new);
if (r)
goto out_free;
}
r = -ENOMEM;
slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
if (!slots)
goto out_free;
memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
if (mem->slot >= slots->nmemslots)
slots->nmemslots = mem->slot + 1;
slots->generation++;
/* actual memory is freed via old in kvm_free_physmem_slot below */
if (!npages) {
new.rmap = NULL;
new.dirty_bitmap = NULL;
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i)
new.lpage_info[i] = NULL;
}
slots->memslots[mem->slot] = new;
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
kvm_arch_commit_memory_region(kvm, mem, old, user_alloc);
kvm_free_physmem_slot(&old, &new);
kfree(old_memslots);
return 0;
out_free:
kvm_free_physmem_slot(&new, &old);
out:
return r;
}
EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
int kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem,
int user_alloc)
{
int r;
mutex_lock(&kvm->slots_lock);
r = __kvm_set_memory_region(kvm, mem, user_alloc);
mutex_unlock(&kvm->slots_lock);
return r;
}
EXPORT_SYMBOL_GPL(kvm_set_memory_region);
int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
struct
kvm_userspace_memory_region *mem,
int user_alloc)
{
if (mem->slot >= KVM_MEMORY_SLOTS)
return -EINVAL;
return kvm_set_memory_region(kvm, mem, user_alloc);
}
int kvm_get_dirty_log(struct kvm *kvm,
struct kvm_dirty_log *log, int *is_dirty)
{
struct kvm_memory_slot *memslot;
int r, i;
unsigned long n;
unsigned long any = 0;
r = -EINVAL;
if (log->slot >= KVM_MEMORY_SLOTS)
goto out;
memslot = &kvm->memslots->memslots[log->slot];
r = -ENOENT;
if (!memslot->dirty_bitmap)
goto out;
n = kvm_dirty_bitmap_bytes(memslot);
for (i = 0; !any && i < n/sizeof(long); ++i)
any = memslot->dirty_bitmap[i];
r = -EFAULT;
if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
goto out;
if (any)
*is_dirty = 1;
r = 0;
out:
return r;
}
void kvm_disable_largepages(void)
{
largepages_enabled = false;
}
EXPORT_SYMBOL_GPL(kvm_disable_largepages);
int is_error_page(struct page *page)
{
return page == bad_page || page == hwpoison_page || page == fault_page;
}
EXPORT_SYMBOL_GPL(is_error_page);
int is_error_pfn(pfn_t pfn)
{
return pfn == bad_pfn || pfn == hwpoison_pfn || pfn == fault_pfn;
}
EXPORT_SYMBOL_GPL(is_error_pfn);
int is_hwpoison_pfn(pfn_t pfn)
{
return pfn == hwpoison_pfn;
}
EXPORT_SYMBOL_GPL(is_hwpoison_pfn);
int is_fault_pfn(pfn_t pfn)
{
return pfn == fault_pfn;
}
EXPORT_SYMBOL_GPL(is_fault_pfn);
static inline unsigned long bad_hva(void)
{
return PAGE_OFFSET;
}
int kvm_is_error_hva(unsigned long addr)
{
return addr == bad_hva();
}
EXPORT_SYMBOL_GPL(kvm_is_error_hva);
static struct kvm_memory_slot *__gfn_to_memslot(struct kvm_memslots *slots,
gfn_t gfn)
{
int i;
for (i = 0; i < slots->nmemslots; ++i) {
struct kvm_memory_slot *memslot = &slots->memslots[i];
if (gfn >= memslot->base_gfn
&& gfn < memslot->base_gfn + memslot->npages)
return memslot;
}
return NULL;
}
struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
{
return __gfn_to_memslot(kvm_memslots(kvm), gfn);
}
EXPORT_SYMBOL_GPL(gfn_to_memslot);
int kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
{
int i;
struct kvm_memslots *slots = kvm_memslots(kvm);
for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
struct kvm_memory_slot *memslot = &slots->memslots[i];
if (memslot->flags & KVM_MEMSLOT_INVALID)
continue;
if (gfn >= memslot->base_gfn
&& gfn < memslot->base_gfn + memslot->npages)
return 1;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn)
{
struct vm_area_struct *vma;
unsigned long addr, size;
size = PAGE_SIZE;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return PAGE_SIZE;
down_read(¤t->mm->mmap_sem);
vma = find_vma(current->mm, addr);
if (!vma)
goto out;
size = vma_kernel_pagesize(vma);
out:
up_read(¤t->mm->mmap_sem);
return size;
}
static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
gfn_t *nr_pages)
{
if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
return bad_hva();
if (nr_pages)
*nr_pages = slot->npages - (gfn - slot->base_gfn);
return gfn_to_hva_memslot(slot, gfn);
}
unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
{
return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
}
EXPORT_SYMBOL_GPL(gfn_to_hva);
static pfn_t get_fault_pfn(void)
{
get_page(fault_page);
return fault_pfn;
}
int get_user_page_nowait(struct task_struct *tsk, struct mm_struct *mm,
unsigned long start, int write, struct page **page)
{
int flags = FOLL_TOUCH | FOLL_NOWAIT | FOLL_HWPOISON | FOLL_GET;
if (write)
flags |= FOLL_WRITE;
return __get_user_pages(tsk, mm, start, 1, flags, page, NULL, NULL);
}
static inline int check_user_page_hwpoison(unsigned long addr)
{
int rc, flags = FOLL_TOUCH | FOLL_HWPOISON | FOLL_WRITE;
rc = __get_user_pages(current, current->mm, addr, 1,
flags, NULL, NULL, NULL);
return rc == -EHWPOISON;
}
static pfn_t hva_to_pfn(struct kvm *kvm, unsigned long addr, bool atomic,
bool *async, bool write_fault, bool *writable)
{
struct page *page[1];
int npages = 0;
pfn_t pfn;
/* we can do it either atomically or asynchronously, not both */
BUG_ON(atomic && async);
BUG_ON(!write_fault && !writable);
if (writable)
*writable = true;
if (atomic || async)
npages = __get_user_pages_fast(addr, 1, 1, page);
if (unlikely(npages != 1) && !atomic) {
might_sleep();
if (writable)
*writable = write_fault;
if (async) {
down_read(¤t->mm->mmap_sem);
npages = get_user_page_nowait(current, current->mm,
addr, write_fault, page);
up_read(¤t->mm->mmap_sem);
} else
npages = get_user_pages_fast(addr, 1, write_fault,
page);
/* map read fault as writable if possible */
if (unlikely(!write_fault) && npages == 1) {
struct page *wpage[1];
npages = __get_user_pages_fast(addr, 1, 1, wpage);
if (npages == 1) {
*writable = true;
put_page(page[0]);
page[0] = wpage[0];
}
npages = 1;
}
}
if (unlikely(npages != 1)) {
struct vm_area_struct *vma;
if (atomic)
return get_fault_pfn();
down_read(¤t->mm->mmap_sem);
if (npages == -EHWPOISON ||
(!async && check_user_page_hwpoison(addr))) {
up_read(¤t->mm->mmap_sem);
get_page(hwpoison_page);
return page_to_pfn(hwpoison_page);
}
vma = find_vma_intersection(current->mm, addr, addr+1);
if (vma == NULL)
pfn = get_fault_pfn();
else if ((vma->vm_flags & VM_PFNMAP)) {
pfn = ((addr - vma->vm_start) >> PAGE_SHIFT) +
vma->vm_pgoff;
BUG_ON(!kvm_is_mmio_pfn(pfn));
} else {
if (async && (vma->vm_flags & VM_WRITE))
*async = true;
pfn = get_fault_pfn();
}
up_read(¤t->mm->mmap_sem);
} else
pfn = page_to_pfn(page[0]);
return pfn;
}
pfn_t hva_to_pfn_atomic(struct kvm *kvm, unsigned long addr)
{
return hva_to_pfn(kvm, addr, true, NULL, true, NULL);
}
EXPORT_SYMBOL_GPL(hva_to_pfn_atomic);
static pfn_t __gfn_to_pfn(struct kvm *kvm, gfn_t gfn, bool atomic, bool *async,
bool write_fault, bool *writable)
{
unsigned long addr;
if (async)
*async = false;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr)) {
get_page(bad_page);
return page_to_pfn(bad_page);
}
return hva_to_pfn(kvm, addr, atomic, async, write_fault, writable);
}
pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
{
return __gfn_to_pfn(kvm, gfn, true, NULL, true, NULL);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
pfn_t gfn_to_pfn_async(struct kvm *kvm, gfn_t gfn, bool *async,
bool write_fault, bool *writable)
{
return __gfn_to_pfn(kvm, gfn, false, async, write_fault, writable);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn_async);
pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
{
return __gfn_to_pfn(kvm, gfn, false, NULL, true, NULL);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn);
pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
bool *writable)
{
return __gfn_to_pfn(kvm, gfn, false, NULL, write_fault, writable);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
pfn_t gfn_to_pfn_memslot(struct kvm *kvm,
struct kvm_memory_slot *slot, gfn_t gfn)
{
unsigned long addr = gfn_to_hva_memslot(slot, gfn);
return hva_to_pfn(kvm, addr, false, NULL, true, NULL);
}
int gfn_to_page_many_atomic(struct kvm *kvm, gfn_t gfn, struct page **pages,
int nr_pages)
{
unsigned long addr;
gfn_t entry;
addr = gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, &entry);
if (kvm_is_error_hva(addr))
return -1;
if (entry < nr_pages)
return 0;
return __get_user_pages_fast(addr, nr_pages, 1, pages);
}
EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
{
pfn_t pfn;
pfn = gfn_to_pfn(kvm, gfn);
if (!kvm_is_mmio_pfn(pfn))
return pfn_to_page(pfn);
WARN_ON(kvm_is_mmio_pfn(pfn));
get_page(bad_page);
return bad_page;
}
EXPORT_SYMBOL_GPL(gfn_to_page);
void kvm_release_page_clean(struct page *page)
{
kvm_release_pfn_clean(page_to_pfn(page));
}
EXPORT_SYMBOL_GPL(kvm_release_page_clean);
void kvm_release_pfn_clean(pfn_t pfn)
{
if (!kvm_is_mmio_pfn(pfn))
put_page(pfn_to_page(pfn));
}
EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
void kvm_release_page_dirty(struct page *page)
{
kvm_release_pfn_dirty(page_to_pfn(page));
}
EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
void kvm_release_pfn_dirty(pfn_t pfn)
{
kvm_set_pfn_dirty(pfn);
kvm_release_pfn_clean(pfn);
}
EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
void kvm_set_page_dirty(struct page *page)
{
kvm_set_pfn_dirty(page_to_pfn(page));
}
EXPORT_SYMBOL_GPL(kvm_set_page_dirty);
void kvm_set_pfn_dirty(pfn_t pfn)
{
if (!kvm_is_mmio_pfn(pfn)) {
struct page *page = pfn_to_page(pfn);
if (!PageReserved(page))
SetPageDirty(page);
}
}
EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
void kvm_set_pfn_accessed(pfn_t pfn)
{
if (!kvm_is_mmio_pfn(pfn))
mark_page_accessed(pfn_to_page(pfn));
}
EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
void kvm_get_pfn(pfn_t pfn)
{
if (!kvm_is_mmio_pfn(pfn))
get_page(pfn_to_page(pfn));
}
EXPORT_SYMBOL_GPL(kvm_get_pfn);
static int next_segment(unsigned long len, int offset)
{
if (len > PAGE_SIZE - offset)
return PAGE_SIZE - offset;
else
return len;
}
int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
int len)
{
int r;
unsigned long addr;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return -EFAULT;
r = copy_from_user(data, (void __user *)addr + offset, len);
if (r)
return -EFAULT;
return 0;
}
EXPORT_SYMBOL_GPL(kvm_read_guest_page);
int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
{
gfn_t gfn = gpa >> PAGE_SHIFT;
int seg;
int offset = offset_in_page(gpa);
int ret;
while ((seg = next_segment(len, offset)) != 0) {
ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
if (ret < 0)
return ret;
offset = 0;
len -= seg;
data += seg;
++gfn;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_read_guest);
int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
unsigned long len)
{
int r;
unsigned long addr;
gfn_t gfn = gpa >> PAGE_SHIFT;
int offset = offset_in_page(gpa);
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return -EFAULT;
pagefault_disable();
r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
pagefault_enable();
if (r)
return -EFAULT;
return 0;
}
EXPORT_SYMBOL(kvm_read_guest_atomic);
int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
int offset, int len)
{
int r;
unsigned long addr;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return -EFAULT;
r = copy_to_user((void __user *)addr + offset, data, len);
if (r)
return -EFAULT;
mark_page_dirty(kvm, gfn);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_write_guest_page);
int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
unsigned long len)
{
gfn_t gfn = gpa >> PAGE_SHIFT;
int seg;
int offset = offset_in_page(gpa);
int ret;
while ((seg = next_segment(len, offset)) != 0) {
ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
if (ret < 0)
return ret;
offset = 0;
len -= seg;
data += seg;
++gfn;
}
return 0;
}
int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
gpa_t gpa)
{
struct kvm_memslots *slots = kvm_memslots(kvm);
int offset = offset_in_page(gpa);
gfn_t gfn = gpa >> PAGE_SHIFT;
ghc->gpa = gpa;
ghc->generation = slots->generation;
ghc->memslot = __gfn_to_memslot(slots, gfn);
ghc->hva = gfn_to_hva_many(ghc->memslot, gfn, NULL);
if (!kvm_is_error_hva(ghc->hva))
ghc->hva += offset;
else
return -EFAULT;
return 0;
}
EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
void *data, unsigned long len)
{
struct kvm_memslots *slots = kvm_memslots(kvm);
int r;
if (slots->generation != ghc->generation)
kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa);
if (kvm_is_error_hva(ghc->hva))
return -EFAULT;
r = copy_to_user((void __user *)ghc->hva, data, len);
if (r)
return -EFAULT;
mark_page_dirty_in_slot(kvm, ghc->memslot, ghc->gpa >> PAGE_SHIFT);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
{
return kvm_write_guest_page(kvm, gfn, (const void *) empty_zero_page,
offset, len);
}
EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
{
gfn_t gfn = gpa >> PAGE_SHIFT;
int seg;
int offset = offset_in_page(gpa);
int ret;
while ((seg = next_segment(len, offset)) != 0) {
ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
if (ret < 0)
return ret;
offset = 0;
len -= seg;
++gfn;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_clear_guest);
void mark_page_dirty_in_slot(struct kvm *kvm, struct kvm_memory_slot *memslot,
gfn_t gfn)
{
if (memslot && memslot->dirty_bitmap) {
unsigned long rel_gfn = gfn - memslot->base_gfn;
__set_bit_le(rel_gfn, memslot->dirty_bitmap);
}
}
void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
{
struct kvm_memory_slot *memslot;
memslot = gfn_to_memslot(kvm, gfn);
mark_page_dirty_in_slot(kvm, memslot, gfn);
}
/*
* The vCPU has executed a HLT instruction with in-kernel mode enabled.
*/
void kvm_vcpu_block(struct kvm_vcpu *vcpu)
{
DEFINE_WAIT(wait);
for (;;) {
prepare_to_wait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
if (kvm_arch_vcpu_runnable(vcpu)) {
kvm_make_request(KVM_REQ_UNHALT, vcpu);
break;
}
if (kvm_cpu_has_pending_timer(vcpu))
break;
if (signal_pending(current))
break;
schedule();
}
finish_wait(&vcpu->wq, &wait);
}
void kvm_resched(struct kvm_vcpu *vcpu)
{
if (!need_resched())
return;
cond_resched();
}
EXPORT_SYMBOL_GPL(kvm_resched);
void kvm_vcpu_on_spin(struct kvm_vcpu *me)
{
struct kvm *kvm = me->kvm;
struct kvm_vcpu *vcpu;
int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
int yielded = 0;
int pass;
int i;
/*
* We boost the priority of a VCPU that is runnable but not
* currently running, because it got preempted by something
* else and called schedule in __vcpu_run. Hopefully that
* VCPU is holding the lock that we need and will release it.
* We approximate round-robin by starting at the last boosted VCPU.
*/
for (pass = 0; pass < 2 && !yielded; pass++) {
kvm_for_each_vcpu(i, vcpu, kvm) {
struct task_struct *task = NULL;
struct pid *pid;
if (!pass && i < last_boosted_vcpu) {
i = last_boosted_vcpu;
continue;
} else if (pass && i > last_boosted_vcpu)
break;
if (vcpu == me)
continue;
if (waitqueue_active(&vcpu->wq))
continue;
rcu_read_lock();
pid = rcu_dereference(vcpu->pid);
if (pid)
task = get_pid_task(vcpu->pid, PIDTYPE_PID);
rcu_read_unlock();
if (!task)
continue;
if (task->flags & PF_VCPU) {
put_task_struct(task);
continue;
}
if (yield_to(task, 1)) {
put_task_struct(task);
kvm->last_boosted_vcpu = i;
yielded = 1;
break;
}
put_task_struct(task);
}
}
}
EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct kvm_vcpu *vcpu = vma->vm_file->private_data;
struct page *page;
if (vmf->pgoff == 0)
page = virt_to_page(vcpu->run);
#ifdef CONFIG_X86
else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
page = virt_to_page(vcpu->arch.pio_data);
#endif
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
#endif
else
return VM_FAULT_SIGBUS;
get_page(page);
vmf->page = page;
return 0;
}
static const struct vm_operations_struct kvm_vcpu_vm_ops = {
.fault = kvm_vcpu_fault,
};
static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
{
vma->vm_ops = &kvm_vcpu_vm_ops;
return 0;
}
static int kvm_vcpu_release(struct inode *inode, struct file *filp)
{
struct kvm_vcpu *vcpu = filp->private_data;
kvm_put_kvm(vcpu->kvm);
return 0;
}
static struct file_operations kvm_vcpu_fops = {
.release = kvm_vcpu_release,
.unlocked_ioctl = kvm_vcpu_ioctl,
.compat_ioctl = kvm_vcpu_ioctl,
.mmap = kvm_vcpu_mmap,
.llseek = noop_llseek,
};
/*
* Allocates an inode for the vcpu.
*/
static int create_vcpu_fd(struct kvm_vcpu *vcpu)
{
return anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, O_RDWR);
}
/*
* Creates some virtual cpus. Good luck creating more than one.
*/
static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
{
int r;
struct kvm_vcpu *vcpu, *v;
vcpu = kvm_arch_vcpu_create(kvm, id);
if (IS_ERR(vcpu))
return PTR_ERR(vcpu);
preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
r = kvm_arch_vcpu_setup(vcpu);
if (r)
return r;
mutex_lock(&kvm->lock);
if (atomic_read(&kvm->online_vcpus) == KVM_MAX_VCPUS) {
r = -EINVAL;
goto vcpu_destroy;
}
kvm_for_each_vcpu(r, v, kvm)
if (v->vcpu_id == id) {
r = -EEXIST;
goto vcpu_destroy;
}
BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
/* Now it's all set up, let userspace reach it */
kvm_get_kvm(kvm);
r = create_vcpu_fd(vcpu);
if (r < 0) {
kvm_put_kvm(kvm);
goto vcpu_destroy;
}
kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
smp_wmb();
atomic_inc(&kvm->online_vcpus);
#ifdef CONFIG_KVM_APIC_ARCHITECTURE
if (kvm->bsp_vcpu_id == id)
kvm->bsp_vcpu = vcpu;
#endif
mutex_unlock(&kvm->lock);
return r;
vcpu_destroy:
mutex_unlock(&kvm->lock);
kvm_arch_vcpu_destroy(vcpu);
return r;
}
static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
{
if (sigset) {
sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
vcpu->sigset_active = 1;
vcpu->sigset = *sigset;
} else
vcpu->sigset_active = 0;
return 0;
}
static long kvm_vcpu_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm_vcpu *vcpu = filp->private_data;
void __user *argp = (void __user *)arg;
int r;
struct kvm_fpu *fpu = NULL;
struct kvm_sregs *kvm_sregs = NULL;
if (vcpu->kvm->mm != current->mm)
return -EIO;
#if defined(CONFIG_S390) || defined(CONFIG_PPC)
/*
* Special cases: vcpu ioctls that are asynchronous to vcpu execution,
* so vcpu_load() would break it.
*/
if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_INTERRUPT)
return kvm_arch_vcpu_ioctl(filp, ioctl, arg);
#endif
vcpu_load(vcpu);
switch (ioctl) {
case KVM_RUN:
r = -EINVAL;
if (arg)
goto out;
r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
break;
case KVM_GET_REGS: {
struct kvm_regs *kvm_regs;
r = -ENOMEM;
kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
if (!kvm_regs)
goto out;
r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
if (r)
goto out_free1;
r = -EFAULT;
if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
goto out_free1;
r = 0;
out_free1:
kfree(kvm_regs);
break;
}
case KVM_SET_REGS: {
struct kvm_regs *kvm_regs;
r = -ENOMEM;
kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
if (!kvm_regs)
goto out;
r = -EFAULT;
if (copy_from_user(kvm_regs, argp, sizeof(struct kvm_regs)))
goto out_free2;
r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
if (r)
goto out_free2;
r = 0;
out_free2:
kfree(kvm_regs);
break;
}
case KVM_GET_SREGS: {
kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
r = -ENOMEM;
if (!kvm_sregs)
goto out;
r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
goto out;
r = 0;
break;
}
case KVM_SET_SREGS: {
kvm_sregs = kmalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
r = -ENOMEM;
if (!kvm_sregs)
goto out;
r = -EFAULT;
if (copy_from_user(kvm_sregs, argp, sizeof(struct kvm_sregs)))
goto out;
r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
if (r)
goto out;
r = 0;
break;
}
case KVM_GET_MP_STATE: {
struct kvm_mp_state mp_state;
r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &mp_state, sizeof mp_state))
goto out;
r = 0;
break;
}
case KVM_SET_MP_STATE: {
struct kvm_mp_state mp_state;
r = -EFAULT;
if (copy_from_user(&mp_state, argp, sizeof mp_state))
goto out;
r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
if (r)
goto out;
r = 0;
break;
}
case KVM_TRANSLATE: {
struct kvm_translation tr;
r = -EFAULT;
if (copy_from_user(&tr, argp, sizeof tr))
goto out;
r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &tr, sizeof tr))
goto out;
r = 0;
break;
}
case KVM_SET_GUEST_DEBUG: {
struct kvm_guest_debug dbg;
r = -EFAULT;
if (copy_from_user(&dbg, argp, sizeof dbg))
goto out;
r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
if (r)
goto out;
r = 0;
break;
}
case KVM_SET_SIGNAL_MASK: {
struct kvm_signal_mask __user *sigmask_arg = argp;
struct kvm_signal_mask kvm_sigmask;
sigset_t sigset, *p;
p = NULL;
if (argp) {
r = -EFAULT;
if (copy_from_user(&kvm_sigmask, argp,
sizeof kvm_sigmask))
goto out;
r = -EINVAL;
if (kvm_sigmask.len != sizeof sigset)
goto out;
r = -EFAULT;
if (copy_from_user(&sigset, sigmask_arg->sigset,
sizeof sigset))
goto out;
p = &sigset;
}
r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
break;
}
case KVM_GET_FPU: {
fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
r = -ENOMEM;
if (!fpu)
goto out;
r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
goto out;
r = 0;
break;
}
case KVM_SET_FPU: {
fpu = kmalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
r = -ENOMEM;
if (!fpu)
goto out;
r = -EFAULT;
if (copy_from_user(fpu, argp, sizeof(struct kvm_fpu)))
goto out;
r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
if (r)
goto out;
r = 0;
break;
}
default:
r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
}
out:
vcpu_put(vcpu);
kfree(fpu);
kfree(kvm_sregs);
return r;
}
static long kvm_vm_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm *kvm = filp->private_data;
void __user *argp = (void __user *)arg;
int r;
if (kvm->mm != current->mm)
return -EIO;
switch (ioctl) {
case KVM_CREATE_VCPU:
r = kvm_vm_ioctl_create_vcpu(kvm, arg);
if (r < 0)
goto out;
break;
case KVM_SET_USER_MEMORY_REGION: {
struct kvm_userspace_memory_region kvm_userspace_mem;
r = -EFAULT;
if (copy_from_user(&kvm_userspace_mem, argp,
sizeof kvm_userspace_mem))
goto out;
r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 1);
if (r)
goto out;
break;
}
case KVM_GET_DIRTY_LOG: {
struct kvm_dirty_log log;
r = -EFAULT;
if (copy_from_user(&log, argp, sizeof log))
goto out;
r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
if (r)
goto out;
break;
}
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
case KVM_REGISTER_COALESCED_MMIO: {
struct kvm_coalesced_mmio_zone zone;
r = -EFAULT;
if (copy_from_user(&zone, argp, sizeof zone))
goto out;
r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
if (r)
goto out;
r = 0;
break;
}
case KVM_UNREGISTER_COALESCED_MMIO: {
struct kvm_coalesced_mmio_zone zone;
r = -EFAULT;
if (copy_from_user(&zone, argp, sizeof zone))
goto out;
r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
if (r)
goto out;
r = 0;
break;
}
#endif
case KVM_IRQFD: {
struct kvm_irqfd data;
r = -EFAULT;
if (copy_from_user(&data, argp, sizeof data))
goto out;
r = kvm_irqfd(kvm, data.fd, data.gsi, data.flags);
break;
}
case KVM_IOEVENTFD: {
struct kvm_ioeventfd data;
r = -EFAULT;
if (copy_from_user(&data, argp, sizeof data))
goto out;
r = kvm_ioeventfd(kvm, &data);
break;
}
#ifdef CONFIG_KVM_APIC_ARCHITECTURE
case KVM_SET_BOOT_CPU_ID:
r = 0;
mutex_lock(&kvm->lock);
if (atomic_read(&kvm->online_vcpus) != 0)
r = -EBUSY;
else
kvm->bsp_vcpu_id = arg;
mutex_unlock(&kvm->lock);
break;
#endif
default:
r = kvm_arch_vm_ioctl(filp, ioctl, arg);
if (r == -ENOTTY)
r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
}
out:
return r;
}
#ifdef CONFIG_COMPAT
struct compat_kvm_dirty_log {
__u32 slot;
__u32 padding1;
union {
compat_uptr_t dirty_bitmap; /* one bit per page */
__u64 padding2;
};
};
static long kvm_vm_compat_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm *kvm = filp->private_data;
int r;
if (kvm->mm != current->mm)
return -EIO;
switch (ioctl) {
case KVM_GET_DIRTY_LOG: {
struct compat_kvm_dirty_log compat_log;
struct kvm_dirty_log log;
r = -EFAULT;
if (copy_from_user(&compat_log, (void __user *)arg,
sizeof(compat_log)))
goto out;
log.slot = compat_log.slot;
log.padding1 = compat_log.padding1;
log.padding2 = compat_log.padding2;
log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
if (r)
goto out;
break;
}
default:
r = kvm_vm_ioctl(filp, ioctl, arg);
}
out:
return r;
}
#endif
static int kvm_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct page *page[1];
unsigned long addr;
int npages;
gfn_t gfn = vmf->pgoff;
struct kvm *kvm = vma->vm_file->private_data;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return VM_FAULT_SIGBUS;
npages = get_user_pages(current, current->mm, addr, 1, 1, 0, page,
NULL);
if (unlikely(npages != 1))
return VM_FAULT_SIGBUS;
vmf->page = page[0];
return 0;
}
static const struct vm_operations_struct kvm_vm_vm_ops = {
.fault = kvm_vm_fault,
};
static int kvm_vm_mmap(struct file *file, struct vm_area_struct *vma)
{
vma->vm_ops = &kvm_vm_vm_ops;
return 0;
}
static struct file_operations kvm_vm_fops = {
.release = kvm_vm_release,
.unlocked_ioctl = kvm_vm_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = kvm_vm_compat_ioctl,
#endif
.mmap = kvm_vm_mmap,
.llseek = noop_llseek,
};
static int kvm_dev_ioctl_create_vm(void)
{
int r;
struct kvm *kvm;
kvm = kvm_create_vm();
if (IS_ERR(kvm))
return PTR_ERR(kvm);
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
r = kvm_coalesced_mmio_init(kvm);
if (r < 0) {
kvm_put_kvm(kvm);
return r;
}
#endif
r = anon_inode_getfd("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
if (r < 0)
kvm_put_kvm(kvm);
return r;
}
static long kvm_dev_ioctl_check_extension_generic(long arg)
{
switch (arg) {
case KVM_CAP_USER_MEMORY:
case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
#ifdef CONFIG_KVM_APIC_ARCHITECTURE
case KVM_CAP_SET_BOOT_CPU_ID:
#endif
case KVM_CAP_INTERNAL_ERROR_DATA:
return 1;
#ifdef CONFIG_HAVE_KVM_IRQCHIP
case KVM_CAP_IRQ_ROUTING:
return KVM_MAX_IRQ_ROUTES;
#endif
default:
break;
}
return kvm_dev_ioctl_check_extension(arg);
}
static long kvm_dev_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
long r = -EINVAL;
switch (ioctl) {
case KVM_GET_API_VERSION:
r = -EINVAL;
if (arg)
goto out;
r = KVM_API_VERSION;
break;
case KVM_CREATE_VM:
r = -EINVAL;
if (arg)
goto out;
r = kvm_dev_ioctl_create_vm();
break;
case KVM_CHECK_EXTENSION:
r = kvm_dev_ioctl_check_extension_generic(arg);
break;
case KVM_GET_VCPU_MMAP_SIZE:
r = -EINVAL;
if (arg)
goto out;
r = PAGE_SIZE; /* struct kvm_run */
#ifdef CONFIG_X86
r += PAGE_SIZE; /* pio data page */
#endif
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
r += PAGE_SIZE; /* coalesced mmio ring page */
#endif
break;
case KVM_TRACE_ENABLE:
case KVM_TRACE_PAUSE:
case KVM_TRACE_DISABLE:
r = -EOPNOTSUPP;
break;
default:
return kvm_arch_dev_ioctl(filp, ioctl, arg);
}
out:
return r;
}
static struct file_operations kvm_chardev_ops = {
.unlocked_ioctl = kvm_dev_ioctl,
.compat_ioctl = kvm_dev_ioctl,
.llseek = noop_llseek,
};
static struct miscdevice kvm_dev = {
KVM_MINOR,
"kvm",
&kvm_chardev_ops,
};
static void hardware_enable_nolock(void *junk)
{
int cpu = raw_smp_processor_id();
int r;
if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
return;
cpumask_set_cpu(cpu, cpus_hardware_enabled);
r = kvm_arch_hardware_enable(NULL);
if (r) {
cpumask_clear_cpu(cpu, cpus_hardware_enabled);
atomic_inc(&hardware_enable_failed);
printk(KERN_INFO "kvm: enabling virtualization on "
"CPU%d failed\n", cpu);
}
}
static void hardware_enable(void *junk)
{
raw_spin_lock(&kvm_lock);
hardware_enable_nolock(junk);
raw_spin_unlock(&kvm_lock);
}
static void hardware_disable_nolock(void *junk)
{
int cpu = raw_smp_processor_id();
if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
return;
cpumask_clear_cpu(cpu, cpus_hardware_enabled);
kvm_arch_hardware_disable(NULL);
}
static void hardware_disable(void *junk)
{
raw_spin_lock(&kvm_lock);
hardware_disable_nolock(junk);
raw_spin_unlock(&kvm_lock);
}
static void hardware_disable_all_nolock(void)
{
BUG_ON(!kvm_usage_count);
kvm_usage_count--;
if (!kvm_usage_count)
on_each_cpu(hardware_disable_nolock, NULL, 1);
}
static void hardware_disable_all(void)
{
raw_spin_lock(&kvm_lock);
hardware_disable_all_nolock();
raw_spin_unlock(&kvm_lock);
}
static int hardware_enable_all(void)
{
int r = 0;
raw_spin_lock(&kvm_lock);
kvm_usage_count++;
if (kvm_usage_count == 1) {
atomic_set(&hardware_enable_failed, 0);
on_each_cpu(hardware_enable_nolock, NULL, 1);
if (atomic_read(&hardware_enable_failed)) {
hardware_disable_all_nolock();
r = -EBUSY;
}
}
raw_spin_unlock(&kvm_lock);
return r;
}
static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
void *v)
{
int cpu = (long)v;
if (!kvm_usage_count)
return NOTIFY_OK;
val &= ~CPU_TASKS_FROZEN;
switch (val) {
case CPU_DYING:
printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
cpu);
hardware_disable(NULL);
break;
case CPU_STARTING:
printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
cpu);
hardware_enable(NULL);
break;
}
return NOTIFY_OK;
}
asmlinkage void kvm_spurious_fault(void)
{
/* Fault while not rebooting. We want the trace. */
BUG();
}
EXPORT_SYMBOL_GPL(kvm_spurious_fault);
static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
void *v)
{
/*
* Some (well, at least mine) BIOSes hang on reboot if
* in vmx root mode.
*
* And Intel TXT required VMX off for all cpu when system shutdown.
*/
printk(KERN_INFO "kvm: exiting hardware virtualization\n");
kvm_rebooting = true;
on_each_cpu(hardware_disable_nolock, NULL, 1);
return NOTIFY_OK;
}
static struct notifier_block kvm_reboot_notifier = {
.notifier_call = kvm_reboot,
.priority = 0,
};
static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
{
int i;
for (i = 0; i < bus->dev_count; i++) {
struct kvm_io_device *pos = bus->devs[i];
kvm_iodevice_destructor(pos);
}
kfree(bus);
}
/* kvm_io_bus_write - called under kvm->slots_lock */
int kvm_io_bus_write(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
int len, const void *val)
{
int i;
struct kvm_io_bus *bus;
bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
for (i = 0; i < bus->dev_count; i++)
if (!kvm_iodevice_write(bus->devs[i], addr, len, val))
return 0;
return -EOPNOTSUPP;
}
/* kvm_io_bus_read - called under kvm->slots_lock */
int kvm_io_bus_read(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
int len, void *val)
{
int i;
struct kvm_io_bus *bus;
bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
for (i = 0; i < bus->dev_count; i++)
if (!kvm_iodevice_read(bus->devs[i], addr, len, val))
return 0;
return -EOPNOTSUPP;
}
/* Caller must hold slots_lock. */
int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx,
struct kvm_io_device *dev)
{
struct kvm_io_bus *new_bus, *bus;
bus = kvm->buses[bus_idx];
if (bus->dev_count > NR_IOBUS_DEVS-1)
return -ENOSPC;
new_bus = kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL);
if (!new_bus)
return -ENOMEM;
memcpy(new_bus, bus, sizeof(struct kvm_io_bus));
new_bus->devs[new_bus->dev_count++] = dev;
rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
synchronize_srcu_expedited(&kvm->srcu);
kfree(bus);
return 0;
}
/* Caller must hold slots_lock. */
int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
struct kvm_io_device *dev)
{
int i, r;
struct kvm_io_bus *new_bus, *bus;
new_bus = kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL);
if (!new_bus)
return -ENOMEM;
bus = kvm->buses[bus_idx];
memcpy(new_bus, bus, sizeof(struct kvm_io_bus));
r = -ENOENT;
for (i = 0; i < new_bus->dev_count; i++)
if (new_bus->devs[i] == dev) {
r = 0;
new_bus->devs[i] = new_bus->devs[--new_bus->dev_count];
break;
}
if (r) {
kfree(new_bus);
return r;
}
rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
synchronize_srcu_expedited(&kvm->srcu);
kfree(bus);
return r;
}
static struct notifier_block kvm_cpu_notifier = {
.notifier_call = kvm_cpu_hotplug,
};
static int vm_stat_get(void *_offset, u64 *val)
{
unsigned offset = (long)_offset;
struct kvm *kvm;
*val = 0;
raw_spin_lock(&kvm_lock);
list_for_each_entry(kvm, &vm_list, vm_list)
*val += *(u32 *)((void *)kvm + offset);
raw_spin_unlock(&kvm_lock);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
static int vcpu_stat_get(void *_offset, u64 *val)
{
unsigned offset = (long)_offset;
struct kvm *kvm;
struct kvm_vcpu *vcpu;
int i;
*val = 0;
raw_spin_lock(&kvm_lock);
list_for_each_entry(kvm, &vm_list, vm_list)
kvm_for_each_vcpu(i, vcpu, kvm)
*val += *(u32 *)((void *)vcpu + offset);
raw_spin_unlock(&kvm_lock);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
static const struct file_operations *stat_fops[] = {
[KVM_STAT_VCPU] = &vcpu_stat_fops,
[KVM_STAT_VM] = &vm_stat_fops,
};
static void kvm_init_debug(void)
{
struct kvm_stats_debugfs_item *p;
kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
for (p = debugfs_entries; p->name; ++p)
p->dentry = debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
(void *)(long)p->offset,
stat_fops[p->kind]);
}
static void kvm_exit_debug(void)
{
struct kvm_stats_debugfs_item *p;
for (p = debugfs_entries; p->name; ++p)
debugfs_remove(p->dentry);
debugfs_remove(kvm_debugfs_dir);
}
static int kvm_suspend(void)
{
if (kvm_usage_count)
hardware_disable_nolock(NULL);
return 0;
}
static void kvm_resume(void)
{
if (kvm_usage_count) {
WARN_ON(raw_spin_is_locked(&kvm_lock));
hardware_enable_nolock(NULL);
}
}
static struct syscore_ops kvm_syscore_ops = {
.suspend = kvm_suspend,
.resume = kvm_resume,
};
struct page *bad_page;
pfn_t bad_pfn;
static inline
struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
{
return container_of(pn, struct kvm_vcpu, preempt_notifier);
}
static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
{
struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
kvm_arch_vcpu_load(vcpu, cpu);
}
static void kvm_sched_out(struct preempt_notifier *pn,
struct task_struct *next)
{
struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
kvm_arch_vcpu_put(vcpu);
}
int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
struct module *module)
{
int r;
int cpu;
r = kvm_arch_init(opaque);
if (r)
goto out_fail;
bad_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (bad_page == NULL) {
r = -ENOMEM;
goto out;
}
bad_pfn = page_to_pfn(bad_page);
hwpoison_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (hwpoison_page == NULL) {
r = -ENOMEM;
goto out_free_0;
}
hwpoison_pfn = page_to_pfn(hwpoison_page);
fault_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (fault_page == NULL) {
r = -ENOMEM;
goto out_free_0;
}
fault_pfn = page_to_pfn(fault_page);
if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
r = -ENOMEM;
goto out_free_0;
}
r = kvm_arch_hardware_setup();
if (r < 0)
goto out_free_0a;
for_each_online_cpu(cpu) {
smp_call_function_single(cpu,
kvm_arch_check_processor_compat,
&r, 1);
if (r < 0)
goto out_free_1;
}
r = register_cpu_notifier(&kvm_cpu_notifier);
if (r)
goto out_free_2;
register_reboot_notifier(&kvm_reboot_notifier);
/* A kmem cache lets us meet the alignment requirements of fx_save. */
if (!vcpu_align)
vcpu_align = __alignof__(struct kvm_vcpu);
kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size, vcpu_align,
0, NULL);
if (!kvm_vcpu_cache) {
r = -ENOMEM;
goto out_free_3;
}
r = kvm_async_pf_init();
if (r)
goto out_free;
kvm_chardev_ops.owner = module;
kvm_vm_fops.owner = module;
kvm_vcpu_fops.owner = module;
r = misc_register(&kvm_dev);
if (r) {
printk(KERN_ERR "kvm: misc device register failed\n");
goto out_unreg;
}
register_syscore_ops(&kvm_syscore_ops);
kvm_preempt_ops.sched_in = kvm_sched_in;
kvm_preempt_ops.sched_out = kvm_sched_out;
kvm_init_debug();
return 0;
out_unreg:
kvm_async_pf_deinit();
out_free:
kmem_cache_destroy(kvm_vcpu_cache);
out_free_3:
unregister_reboot_notifier(&kvm_reboot_notifier);
unregister_cpu_notifier(&kvm_cpu_notifier);
out_free_2:
out_free_1:
kvm_arch_hardware_unsetup();
out_free_0a:
free_cpumask_var(cpus_hardware_enabled);
out_free_0:
if (fault_page)
__free_page(fault_page);
if (hwpoison_page)
__free_page(hwpoison_page);
__free_page(bad_page);
out:
kvm_arch_exit();
out_fail:
return r;
}
EXPORT_SYMBOL_GPL(kvm_init);
void kvm_exit(void)
{
kvm_exit_debug();
misc_deregister(&kvm_dev);
kmem_cache_destroy(kvm_vcpu_cache);
kvm_async_pf_deinit();
unregister_syscore_ops(&kvm_syscore_ops);
unregister_reboot_notifier(&kvm_reboot_notifier);
unregister_cpu_notifier(&kvm_cpu_notifier);
on_each_cpu(hardware_disable_nolock, NULL, 1);
kvm_arch_hardware_unsetup();
kvm_arch_exit();
free_cpumask_var(cpus_hardware_enabled);
__free_page(hwpoison_page);
__free_page(bad_page);
}
EXPORT_SYMBOL_GPL(kvm_exit);
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5613_1 |
crossvul-cpp_data_good_1564_0 | /*
Copyright (C) 2010 ABRT team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "problem_api.h"
#include "libabrt.h"
/* Maximal length of backtrace. */
#define MAX_BACKTRACE_SIZE (1024*1024)
/* Amount of data received from one client for a message before reporting error. */
#define MAX_MESSAGE_SIZE (4*MAX_BACKTRACE_SIZE)
/* Maximal number of characters read from socket at once. */
#define INPUT_BUFFER_SIZE (8*1024)
/* We exit after this many seconds */
#define TIMEOUT 10
/*
Unix socket in ABRT daemon for creating new dump directories.
Why to use socket for creating dump dirs? Security. When a Python
script throws unexpected exception, ABRT handler catches it, running
as a part of that broken Python application. The application is running
with certain SELinux privileges, for example it can not execute other
programs, or to create files in /var/cache or anything else required
to properly fill a problem directory. Adding these privileges to every
application would weaken the security.
The most suitable solution is for the Python application
to open a socket where ABRT daemon is listening, write all relevant
data to that socket, and close it. ABRT daemon handles the rest.
** Protocol
Initializing new dump:
open /var/run/abrt.socket
Providing dump data (hook writes to the socket):
MANDATORY ITEMS:
-> "PID="
number 0 - PID_MAX (/proc/sys/kernel/pid_max)
\0
-> "EXECUTABLE="
string
\0
-> "BACKTRACE="
string
\0
-> "ANALYZER="
string
\0
-> "BASENAME="
string (no slashes)
\0
-> "REASON="
string
\0
You can send more messages using the same KEY=value format.
*/
static unsigned total_bytes_read = 0;
static uid_t client_uid = (uid_t)-1L;
/* Remove dump dir */
static int delete_path(const char *dump_dir_name)
{
/* If doesn't start with "g_settings_dump_location/"... */
if (!dir_is_in_dump_location(dump_dir_name))
{
/* Then refuse to operate on it (someone is attacking us??) */
error_msg("Bad problem directory name '%s', should start with: '%s'", dump_dir_name, g_settings_dump_location);
return 400; /* Bad Request */
}
if (!dir_has_correct_permissions(dump_dir_name))
{
error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dump_dir_name);
return 400; /* */
}
if (!dump_dir_accessible_by_uid(dump_dir_name, client_uid))
{
if (errno == ENOTDIR)
{
error_msg("Path '%s' isn't problem directory", dump_dir_name);
return 404; /* Not Found */
}
error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dump_dir_name, (long)client_uid);
return 403; /* Forbidden */
}
delete_dump_dir(dump_dir_name);
return 0; /* success */
}
static pid_t spawn_event_handler_child(const char *dump_dir_name, const char *event_name, int *fdp)
{
char *args[7];
args[0] = (char *) LIBEXEC_DIR"/abrt-handle-event";
/* Do not forward ASK_* messages to parent*/
args[1] = (char *) "-i";
args[2] = (char *) "-e";
args[3] = (char *) event_name;
args[4] = (char *) "--";
args[5] = (char *) dump_dir_name;
args[6] = NULL;
int pipeout[2];
int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_QUIET | EXECFLG_ERR2OUT;
VERB1 flags &= ~EXECFLG_QUIET;
char *env_vec[2];
/* Intercept ASK_* messages in Client API -> don't wait for user response */
env_vec[0] = xstrdup("REPORT_CLIENT_NONINTERACTIVE=1");
env_vec[1] = NULL;
pid_t child = fork_execv_on_steroids(flags, args, pipeout,
env_vec, /*dir:*/ NULL,
/*uid(unused):*/ 0);
if (fdp)
*fdp = pipeout[0];
return child;
}
static int run_post_create(const char *dirname)
{
/* If doesn't start with "g_settings_dump_location/"... */
if (!dir_is_in_dump_location(dirname))
{
/* Then refuse to operate on it (someone is attacking us??) */
error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location);
return 400; /* Bad Request */
}
if (!dir_has_correct_permissions(dirname))
{
error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dirname);
return 400; /* */
}
if (g_settings_privatereports)
{
struct dump_dir *dd = dd_opendir(dirname, DD_OPEN_READONLY);
const bool complete = dd && problem_dump_dir_is_complete(dd);
dd_close(dd);
if (complete)
{
error_msg("Problem directory '%s' has already been processed", dirname);
return 403;
}
}
else if (!dump_dir_accessible_by_uid(dirname, client_uid))
{
if (errno == ENOTDIR)
{
error_msg("Path '%s' isn't problem directory", dirname);
return 404; /* Not Found */
}
error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dirname, (long)client_uid);
return 403; /* Forbidden */
}
int child_stdout_fd;
int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd);
char *dup_of_dir = NULL;
struct strbuf *cmd_output = strbuf_new();
bool child_is_post_create = 1; /* else it is a notify child */
read_child_output:
//log("Reading from event fd %d", child_stdout_fd);
/* Read streamed data and split lines */
for (;;)
{
char buf[250]; /* usually we get one line, no need to have big buf */
errno = 0;
int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1);
if (r <= 0)
break;
buf[r] = '\0';
/* split lines in the current buffer */
char *raw = buf;
char *newline;
while ((newline = strchr(raw, '\n')) != NULL)
{
*newline = '\0';
strbuf_append_str(cmd_output, raw);
char *msg = cmd_output->buf;
/* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */
log("%s", msg);
if (child_is_post_create
&& prefixcmp(msg, "DUP_OF_DIR: ") == 0
) {
free(dup_of_dir);
dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: "));
}
strbuf_clear(cmd_output);
/* jump to next line */
raw = newline + 1;
}
/* beginning of next line. the line continues by next read */
strbuf_append_str(cmd_output, raw);
}
/* EOF/error */
/* Wait for child to actually exit, collect status */
int status = 0;
if (safe_waitpid(child_pid, &status, 0) <= 0)
/* should not happen */
perror_msg("waitpid(%d)", child_pid);
/* If it was a "notify[-dup]" event, then we're done */
if (!child_is_post_create)
goto ret;
/* exit 0 means "this is a good, non-dup dir" */
/* exit with 1 + "DUP_OF_DIR: dir" string => dup */
if (status != 0)
{
if (WIFSIGNALED(status))
{
log("'post-create' on '%s' killed by signal %d",
dirname, WTERMSIG(status));
goto delete_bad_dir;
}
/* else: it is WIFEXITED(status) */
if (!dup_of_dir)
{
log("'post-create' on '%s' exited with %d",
dirname, WEXITSTATUS(status));
goto delete_bad_dir;
}
}
const char *work_dir = (dup_of_dir ? dup_of_dir : dirname);
/* Load problem_data (from the *first dir* if this one is a dup) */
struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0);
if (!dd)
/* dd_opendir already emitted error msg */
goto delete_bad_dir;
/* Update count */
char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT);
unsigned long count = strtoul(count_str, NULL, 10);
/* Don't increase crash count if we are working with newly uploaded
* directory (remote crash) which already has its crash count set.
*/
if ((status != 0 && dup_of_dir) || count == 0)
{
count++;
char new_count_str[sizeof(long)*3 + 2];
sprintf(new_count_str, "%lu", count);
dd_save_text(dd, FILENAME_COUNT, new_count_str);
/* This condition can be simplified to either
* (status * != 0 && * dup_of_dir) or (count == 1). But the
* chosen form is much more reliable and safe. We must not call
* dd_opendir() to locked dd otherwise we go into a deadlock.
*/
if (strcmp(dd->dd_dirname, dirname) != 0)
{
/* Update the last occurrence file by the time file of the new problem */
struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY);
char *last_ocr = NULL;
if (new_dd)
{
/* TIME must exists in a valid dump directory but we don't want to die
* due to broken duplicated dump directory */
last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME,
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT);
dd_close(new_dd);
}
else
{ /* dd_opendir() already produced a message with good information about failure */
error_msg("Can't read the last occurrence file from the new dump directory.");
}
if (!last_ocr)
{ /* the new dump directory may lie in the dump location for some time */
log("Using current time for the last occurrence file which may be incorrect.");
time_t t = time(NULL);
last_ocr = xasprintf("%lu", (long)t);
}
dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr);
free(last_ocr);
}
}
/* Reset mode/uig/gid to correct values for all files created by event run */
dd_sanitize_mode_and_owner(dd);
dd_close(dd);
if (!dup_of_dir)
log_notice("New problem directory %s, processing", work_dir);
else
{
log_warning("Deleting problem directory %s (dup of %s)",
strrchr(dirname, '/') + 1,
strrchr(dup_of_dir, '/') + 1);
delete_dump_dir(dirname);
}
/* Run "notify[-dup]" event */
int fd;
child_pid = spawn_event_handler_child(
work_dir,
(dup_of_dir ? "notify-dup" : "notify"),
&fd
);
//log("Started notify, fd %d -> %d", fd, child_stdout_fd);
xmove_fd(fd, child_stdout_fd);
child_is_post_create = 0;
strbuf_clear(cmd_output);
free(dup_of_dir);
dup_of_dir = NULL;
goto read_child_output;
delete_bad_dir:
log_warning("Deleting problem directory '%s'", dirname);
delete_dump_dir(dirname);
ret:
strbuf_free(cmd_output);
free(dup_of_dir);
close(child_stdout_fd);
return 0;
}
/* Create a new problem directory from client session.
* Caller must ensure that all fields in struct client
* are properly filled.
*/
static int create_problem_dir(GHashTable *problem_info, unsigned pid)
{
/* Exit if free space is less than 1/4 of MaxCrashReportsSize */
if (g_settings_nMaxCrashReportsSize > 0)
{
if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location))
exit(1);
}
/* Create temp directory with the problem data.
* This directory is renamed to final directory name after
* all files have been stored into it.
*/
gchar *dir_basename = g_hash_table_lookup(problem_info, "basename");
if (!dir_basename)
dir_basename = g_hash_table_lookup(problem_info, FILENAME_TYPE);
char *path = xasprintf("%s/%s-%s-%u.new",
g_settings_dump_location,
dir_basename,
iso_date_string(NULL),
pid);
/* This item is useless, don't save it */
g_hash_table_remove(problem_info, "basename");
/* No need to check the path length, as all variables used are limited,
* and dd_create() fails if the path is too long.
*/
struct dump_dir *dd = dd_create(path, g_settings_privatereports ? 0 : client_uid, DEFAULT_DUMP_DIR_MODE);
if (!dd)
{
error_msg_and_die("Error creating problem directory '%s'", path);
}
dd_create_basic_files(dd, client_uid, NULL);
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
gpointer gpkey = g_hash_table_lookup(problem_info, FILENAME_CMDLINE);
if (!gpkey)
{
/* Obtain and save the command line. */
char *cmdline = get_cmdline(pid);
if (cmdline)
{
dd_save_text(dd, FILENAME_CMDLINE, cmdline);
free(cmdline);
}
}
/* Store id of the user whose application crashed. */
char uid_str[sizeof(long) * 3 + 2];
sprintf(uid_str, "%lu", (long)client_uid);
dd_save_text(dd, FILENAME_UID, uid_str);
GHashTableIter iter;
gpointer gpvalue;
g_hash_table_iter_init(&iter, problem_info);
while (g_hash_table_iter_next(&iter, &gpkey, &gpvalue))
{
dd_save_text(dd, (gchar *) gpkey, (gchar *) gpvalue);
}
dd_close(dd);
/* Not needing it anymore */
g_hash_table_destroy(problem_info);
/* Move the completely created problem directory
* to final directory.
*/
char *newpath = xstrndup(path, strlen(path) - strlen(".new"));
if (rename(path, newpath) == 0)
strcpy(path, newpath);
free(newpath);
log_notice("Saved problem directory of pid %u to '%s'", pid, path);
/* We let the peer know that problem dir was created successfully
* _before_ we run potentially long-running post-create.
*/
printf("HTTP/1.1 201 Created\r\n\r\n");
fflush(NULL);
close(STDOUT_FILENO);
xdup2(STDERR_FILENO, STDOUT_FILENO); /* paranoia: don't leave stdout fd closed */
/* Trim old problem directories if necessary */
if (g_settings_nMaxCrashReportsSize > 0)
{
trim_problem_dirs(g_settings_dump_location, g_settings_nMaxCrashReportsSize * (double)(1024*1024), path);
}
run_post_create(path);
/* free(path); */
exit(0);
}
static gboolean key_value_ok(gchar *key, gchar *value)
{
char *i;
/* check key, it has to be valid filename and will end up in the
* bugzilla */
for (i = key; *i != 0; i++)
{
if (!isalpha(*i) && (*i != '-') && (*i != '_') && (*i != ' '))
return FALSE;
}
/* check value of 'basename', it has to be valid non-hidden directory
* name */
if (strcmp(key, "basename") == 0
|| strcmp(key, FILENAME_TYPE) == 0
)
{
if (!str_is_correct_filename(value))
{
error_msg("Value of '%s' ('%s') is not a valid directory name",
key, value);
return FALSE;
}
}
return TRUE;
}
/* Handles a message received from client over socket. */
static void process_message(GHashTable *problem_info, char *message)
{
gchar *key, *value;
value = strchr(message, '=');
if (value)
{
key = g_ascii_strdown(message, value - message); /* result is malloced */
//TODO: is it ok? it uses g_malloc, not malloc!
value++;
if (key_value_ok(key, value))
{
if (strcmp(key, FILENAME_UID) == 0)
{
error_msg("Ignoring value of %s, will be determined later",
FILENAME_UID);
}
else
{
g_hash_table_insert(problem_info, key, xstrdup(value));
/* Compat, delete when FILENAME_ANALYZER is replaced by FILENAME_TYPE: */
if (strcmp(key, FILENAME_TYPE) == 0)
g_hash_table_insert(problem_info, xstrdup(FILENAME_ANALYZER), xstrdup(value));
/* Prevent freeing key later: */
key = NULL;
}
}
else
{
/* should use error_msg_and_die() here? */
error_msg("Invalid key or value format: %s", message);
}
free(key);
}
else
{
/* should use error_msg_and_die() here? */
error_msg("Invalid message format: '%s'", message);
}
}
static void die_if_data_is_missing(GHashTable *problem_info)
{
gboolean missing_data = FALSE;
gchar **pstring;
static const gchar *const needed[] = {
FILENAME_TYPE,
FILENAME_REASON,
/* FILENAME_BACKTRACE, - ECC errors have no such elements */
/* FILENAME_EXECUTABLE, */
NULL
};
for (pstring = (gchar**) needed; *pstring; pstring++)
{
if (!g_hash_table_lookup(problem_info, *pstring))
{
error_msg("Element '%s' is missing", *pstring);
missing_data = TRUE;
}
}
if (missing_data)
error_msg_and_die("Some data is missing, aborting");
}
/*
* Takes hash table, looks for key FILENAME_PID and tries to convert its value
* to int.
*/
unsigned convert_pid(GHashTable *problem_info)
{
long ret;
gchar *pid_str = (gchar *) g_hash_table_lookup(problem_info, FILENAME_PID);
char *err_pos;
if (!pid_str)
error_msg_and_die("PID data is missing, aborting");
errno = 0;
ret = strtol(pid_str, &err_pos, 10);
if (errno || pid_str == err_pos || *err_pos != '\0'
|| ret > UINT_MAX || ret < 1)
error_msg_and_die("Malformed or out-of-range PID number: '%s'", pid_str);
return (unsigned) ret;
}
static int perform_http_xact(void)
{
/* use free instead of g_free so that we can use xstr* functions from
* libreport/lib/xfuncs.c
*/
GHashTable *problem_info = g_hash_table_new_full(g_str_hash, g_str_equal,
free, free);
/* Read header */
char *body_start = NULL;
char *messagebuf_data = NULL;
unsigned messagebuf_len = 0;
/* Loop until EOF/error/timeout/end_of_header */
while (1)
{
messagebuf_data = xrealloc(messagebuf_data, messagebuf_len + INPUT_BUFFER_SIZE);
char *p = messagebuf_data + messagebuf_len;
int rd = read(STDIN_FILENO, p, INPUT_BUFFER_SIZE);
if (rd < 0)
{
if (errno == EINTR) /* SIGALRM? */
error_msg_and_die("Timed out");
perror_msg_and_die("read");
}
if (rd == 0)
break;
log_debug("Received %u bytes of data", rd);
messagebuf_len += rd;
total_bytes_read += rd;
if (total_bytes_read > MAX_MESSAGE_SIZE)
error_msg_and_die("Message is too long, aborting");
/* Check whether we see end of header */
/* Note: we support both [\r]\n\r\n and \n\n */
char *past_end = messagebuf_data + messagebuf_len;
if (p > messagebuf_data+1)
p -= 2; /* start search from two last bytes in last read - they might be '\n\r' */
while (p < past_end)
{
p = memchr(p, '\n', past_end - p);
if (!p)
break;
p++;
if (p >= past_end)
break;
if (*p == '\n'
|| (*p == '\r' && p+1 < past_end && p[1] == '\n')
) {
body_start = p + 1 + (*p == '\r');
*p = '\0';
goto found_end_of_header;
}
}
} /* while (read) */
found_end_of_header: ;
log_debug("Request: %s", messagebuf_data);
/* Sanitize and analyze header.
* Header now is in messagebuf_data, NUL terminated string,
* with last empty line deleted (by placement of NUL).
* \r\n are not (yet) converted to \n, multi-line headers also
* not converted.
*/
/* First line must be "op<space>[http://host]/path<space>HTTP/n.n".
* <space> is exactly one space char.
*/
if (prefixcmp(messagebuf_data, "DELETE ") == 0)
{
messagebuf_data += strlen("DELETE ");
char *space = strchr(messagebuf_data, ' ');
if (!space || prefixcmp(space+1, "HTTP/") != 0)
return 400; /* Bad Request */
*space = '\0';
//decode_url(messagebuf_data); %20 => ' '
alarm(0);
return delete_path(messagebuf_data);
}
/* We erroneously used "PUT /" to create new problems.
* POST is the correct request in this case:
* "PUT /" implies creation or replace of resource named "/"!
* Delete PUT in 2014.
*/
if (prefixcmp(messagebuf_data, "PUT ") != 0
&& prefixcmp(messagebuf_data, "POST ") != 0
) {
return 400; /* Bad Request */
}
enum {
CREATION_NOTIFICATION,
CREATION_REQUEST,
};
int url_type;
char *url = skip_non_whitespace(messagebuf_data) + 1; /* skip "POST " */
if (prefixcmp(url, "/creation_notification ") == 0)
url_type = CREATION_NOTIFICATION;
else if (prefixcmp(url, "/ ") == 0)
url_type = CREATION_REQUEST;
else
return 400; /* Bad Request */
/* Read body */
if (!body_start)
{
log_warning("Premature EOF detected, exiting");
return 400; /* Bad Request */
}
messagebuf_len -= (body_start - messagebuf_data);
memmove(messagebuf_data, body_start, messagebuf_len);
log_debug("Body so far: %u bytes, '%s'", messagebuf_len, messagebuf_data);
/* Loop until EOF/error/timeout */
while (1)
{
if (url_type == CREATION_REQUEST)
{
while (1)
{
unsigned len = strnlen(messagebuf_data, messagebuf_len);
if (len >= messagebuf_len)
break;
/* messagebuf has at least one NUL - process the line */
process_message(problem_info, messagebuf_data);
messagebuf_len -= (len + 1);
memmove(messagebuf_data, messagebuf_data + len + 1, messagebuf_len);
}
}
messagebuf_data = xrealloc(messagebuf_data, messagebuf_len + INPUT_BUFFER_SIZE + 1);
int rd = read(STDIN_FILENO, messagebuf_data + messagebuf_len, INPUT_BUFFER_SIZE);
if (rd < 0)
{
if (errno == EINTR) /* SIGALRM? */
error_msg_and_die("Timed out");
perror_msg_and_die("read");
}
if (rd == 0)
break;
log_debug("Received %u bytes of data", rd);
messagebuf_len += rd;
total_bytes_read += rd;
if (total_bytes_read > MAX_MESSAGE_SIZE)
error_msg_and_die("Message is too long, aborting");
}
/* Body received, EOF was seen. Don't let alarm to interrupt after this. */
alarm(0);
if (url_type == CREATION_NOTIFICATION)
{
messagebuf_data[messagebuf_len] = '\0';
return run_post_create(messagebuf_data);
}
/* Save problem dir */
int ret = 0;
unsigned pid = convert_pid(problem_info);
die_if_data_is_missing(problem_info);
char *executable = g_hash_table_lookup(problem_info, FILENAME_EXECUTABLE);
if (executable)
{
char *last_file = concat_path_file(g_settings_dump_location, "last-via-server");
int repeating_crash = check_recent_crash_file(last_file, executable);
free(last_file);
if (repeating_crash) /* Only pretend that we saved it */
goto out; /* ret is 0: "success" */
}
#if 0
//TODO:
/* At least it should generate local problem identifier UUID */
problem_data_add_basics(problem_info);
//...the problem being that problem_info here is not a problem_data_t!
#endif
create_problem_dir(problem_info, pid);
/* does not return */
out:
g_hash_table_destroy(problem_info);
return ret; /* Used as HTTP response code */
}
static void dummy_handler(int sig_unused) {}
int main(int argc, char **argv)
{
/* I18n */
setlocale(LC_ALL, "");
#if ENABLE_NLS
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
#endif
abrt_init(argv);
/* Can't keep these strings/structs static: _() doesn't support that */
const char *program_usage_string = _(
"& [options]"
);
enum {
OPT_v = 1 << 0,
OPT_u = 1 << 1,
OPT_s = 1 << 2,
OPT_p = 1 << 3,
};
/* Keep enum above and order of options below in sync! */
struct options program_options[] = {
OPT__VERBOSE(&g_verbose),
OPT_INTEGER('u', NULL, &client_uid, _("Use NUM as client uid")),
OPT_BOOL( 's', NULL, NULL , _("Log to syslog")),
OPT_BOOL( 'p', NULL, NULL , _("Add program names to log")),
OPT_END()
};
unsigned opts = parse_opts(argc, argv, program_options, program_usage_string);
export_abrt_envvars(opts & OPT_p);
msg_prefix = xasprintf("%s[%u]", g_progname, getpid());
if (opts & OPT_s)
{
logmode = LOGMODE_JOURNAL;
}
/* Set up timeout handling */
/* Part 1 - need this to make SIGALRM interrupt syscalls
* (as opposed to restarting them): I want read syscall to be interrupted
*/
struct sigaction sa;
/* sa.sa_flags.SA_RESTART bit is clear: make signal interrupt syscalls */
memset(&sa, 0, sizeof(sa));
sa.sa_handler = dummy_handler; /* pity, SIG_DFL won't do */
sigaction(SIGALRM, &sa, NULL);
/* Part 2 - set the timeout per se */
alarm(TIMEOUT);
if (client_uid == (uid_t)-1L)
{
/* Get uid of the connected client */
struct ucred cr;
socklen_t crlen = sizeof(cr);
if (0 != getsockopt(STDIN_FILENO, SOL_SOCKET, SO_PEERCRED, &cr, &crlen))
perror_msg_and_die("getsockopt(SO_PEERCRED)");
if (crlen != sizeof(cr))
error_msg_and_die("%s: bad crlen %d", "getsockopt(SO_PEERCRED)", (int)crlen);
client_uid = cr.uid;
}
load_abrt_conf();
int r = perform_http_xact();
if (r == 0)
r = 200;
free_abrt_conf_data();
printf("HTTP/1.1 %u \r\n\r\n", r);
return (r >= 400); /* Error if 400+ */
}
#if 0
// TODO: example of SSLed connection
#include <openssl/ssl.h>
#include <openssl/err.h>
if (flags & OPT_SSL) {
/* load key and cert files */
SSL_CTX *ctx;
SSL *ssl;
ctx = init_ssl_context();
if (SSL_CTX_use_certificate_file(ctx, cert_path, SSL_FILETYPE_PEM) <= 0
|| SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) <= 0
) {
ERR_print_errors_fp(stderr);
error_msg_and_die("SSL certificates err\n");
}
if (!SSL_CTX_check_private_key(ctx)) {
error_msg_and_die("Private key does not match public key\n");
}
(void)SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
//TODO more errors?
ssl = SSL_new(ctx);
SSL_set_fd(ssl, sockfd_in);
//SSL_set_accept_state(ssl);
if (SSL_accept(ssl) == 1) {
//while whatever serve
while (serve(ssl, flags))
continue;
//TODO errors
SSL_shutdown(ssl);
}
SSL_free(ssl);
SSL_CTX_free(ctx);
} else {
while (serve(&sockfd_in, flags))
continue;
}
err = (flags & OPT_SSL) ? SSL_read(sock, buffer, READ_BUF-1):
read(*(int*)sock, buffer, READ_BUF-1);
if ( err < 0 ) {
//TODO handle errno || SSL_get_error(ssl,err);
break;
}
if ( err == 0 ) break;
if (!head) {
buffer[err] = '\0';
clean[i%2] = delete_cr(buffer);
cut = g_strstr_len(buffer, -1, "\n\n");
if ( cut == NULL ) {
g_string_append(headers, buffer);
} else {
g_string_append_len(headers, buffer, cut-buffer);
}
}
/* end of header section? */
if ( !head && ( cut != NULL || (clean[(i+1)%2] && buffer[0]=='\n') ) ) {
parse_head(&request, headers);
head = TRUE;
c_len = has_body(&request);
if ( c_len ) {
//if we want to read body some day - this will be the right place to begin
//malloc body append rest of the (fixed) buffer at the beginning of a body
//if clean buffer[1];
} else {
break;
}
break; //because we don't support body yet
} else if ( head == TRUE ) {
/* body-reading stuff
* read body, check content-len
* save body to request
*/
break;
} else {
// count header size
len += err;
if ( len > READ_BUF-1 ) {
//TODO header is too long
break;
}
}
i++;
}
g_string_free(headers, true); //because we allocated it
rt = generate_response(&request, &response);
/* write headers */
if ( flags & OPT_SSL ) {
//TODO err
err = SSL_write(sock, response.response_line, strlen(response.response_line));
err = SSL_write(sock, response.head->str , strlen(response.head->str));
err = SSL_write(sock, "\r\n", 2);
} else {
//TODO err
err = write(*(int*)sock, response.response_line, strlen(response.response_line));
err = write(*(int*)sock, response.head->str , strlen(response.head->str));
err = write(*(int*)sock, "\r\n", 2);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_1564_0 |
crossvul-cpp_data_bad_5039_4 | /*
* Copyright (c) 2009-2014 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "jansson.h"
#include "jansson_private.h"
#include "strbuffer.h"
#include "utf.h"
#define STREAM_STATE_OK 0
#define STREAM_STATE_EOF -1
#define STREAM_STATE_ERROR -2
#define TOKEN_INVALID -1
#define TOKEN_EOF 0
#define TOKEN_STRING 256
#define TOKEN_INTEGER 257
#define TOKEN_REAL 258
#define TOKEN_TRUE 259
#define TOKEN_FALSE 260
#define TOKEN_NULL 261
/* Locale independent versions of isxxx() functions */
#define l_isupper(c) ('A' <= (c) && (c) <= 'Z')
#define l_islower(c) ('a' <= (c) && (c) <= 'z')
#define l_isalpha(c) (l_isupper(c) || l_islower(c))
#define l_isdigit(c) ('0' <= (c) && (c) <= '9')
#define l_isxdigit(c) \
(l_isdigit(c) || ('A' <= (c) && (c) <= 'F') || ('a' <= (c) && (c) <= 'f'))
/* Read one byte from stream, convert to unsigned char, then int, and
return. return EOF on end of file. This corresponds to the
behaviour of fgetc(). */
typedef int (*get_func)(void *data);
typedef struct {
get_func get;
void *data;
char buffer[5];
size_t buffer_pos;
int state;
int line;
int column, last_column;
size_t position;
} stream_t;
typedef struct {
stream_t stream;
strbuffer_t saved_text;
size_t flags;
int token;
union {
struct {
char *val;
size_t len;
} string;
json_int_t integer;
double real;
} value;
} lex_t;
#define stream_to_lex(stream) container_of(stream, lex_t, stream)
/*** error reporting ***/
static void error_set(json_error_t *error, const lex_t *lex,
const char *msg, ...)
{
va_list ap;
char msg_text[JSON_ERROR_TEXT_LENGTH];
char msg_with_context[JSON_ERROR_TEXT_LENGTH];
int line = -1, col = -1;
size_t pos = 0;
const char *result = msg_text;
if(!error)
return;
va_start(ap, msg);
vsnprintf(msg_text, JSON_ERROR_TEXT_LENGTH, msg, ap);
msg_text[JSON_ERROR_TEXT_LENGTH - 1] = '\0';
va_end(ap);
if(lex)
{
const char *saved_text = strbuffer_value(&lex->saved_text);
line = lex->stream.line;
col = lex->stream.column;
pos = lex->stream.position;
if(saved_text && saved_text[0])
{
if(lex->saved_text.length <= 20) {
snprintf(msg_with_context, JSON_ERROR_TEXT_LENGTH,
"%s near '%s'", msg_text, saved_text);
msg_with_context[JSON_ERROR_TEXT_LENGTH - 1] = '\0';
result = msg_with_context;
}
}
else
{
if(lex->stream.state == STREAM_STATE_ERROR) {
/* No context for UTF-8 decoding errors */
result = msg_text;
}
else {
snprintf(msg_with_context, JSON_ERROR_TEXT_LENGTH,
"%s near end of file", msg_text);
msg_with_context[JSON_ERROR_TEXT_LENGTH - 1] = '\0';
result = msg_with_context;
}
}
}
jsonp_error_set(error, line, col, pos, "%s", result);
}
/*** lexical analyzer ***/
static void
stream_init(stream_t *stream, get_func get, void *data)
{
stream->get = get;
stream->data = data;
stream->buffer[0] = '\0';
stream->buffer_pos = 0;
stream->state = STREAM_STATE_OK;
stream->line = 1;
stream->column = 0;
stream->position = 0;
}
static int stream_get(stream_t *stream, json_error_t *error)
{
int c;
if(stream->state != STREAM_STATE_OK)
return stream->state;
if(!stream->buffer[stream->buffer_pos])
{
c = stream->get(stream->data);
if(c == EOF) {
stream->state = STREAM_STATE_EOF;
return STREAM_STATE_EOF;
}
stream->buffer[0] = c;
stream->buffer_pos = 0;
if(0x80 <= c && c <= 0xFF)
{
/* multi-byte UTF-8 sequence */
size_t i, count;
count = utf8_check_first(c);
if(!count)
goto out;
assert(count >= 2);
for(i = 1; i < count; i++)
stream->buffer[i] = stream->get(stream->data);
if(!utf8_check_full(stream->buffer, count, NULL))
goto out;
stream->buffer[count] = '\0';
}
else
stream->buffer[1] = '\0';
}
c = stream->buffer[stream->buffer_pos++];
stream->position++;
if(c == '\n') {
stream->line++;
stream->last_column = stream->column;
stream->column = 0;
}
else if(utf8_check_first(c)) {
/* track the Unicode character column, so increment only if
this is the first character of a UTF-8 sequence */
stream->column++;
}
return c;
out:
stream->state = STREAM_STATE_ERROR;
error_set(error, stream_to_lex(stream), "unable to decode byte 0x%x", c);
return STREAM_STATE_ERROR;
}
static void stream_unget(stream_t *stream, int c)
{
if(c == STREAM_STATE_EOF || c == STREAM_STATE_ERROR)
return;
stream->position--;
if(c == '\n') {
stream->line--;
stream->column = stream->last_column;
}
else if(utf8_check_first(c))
stream->column--;
assert(stream->buffer_pos > 0);
stream->buffer_pos--;
assert(stream->buffer[stream->buffer_pos] == c);
}
static int lex_get(lex_t *lex, json_error_t *error)
{
return stream_get(&lex->stream, error);
}
static void lex_save(lex_t *lex, int c)
{
strbuffer_append_byte(&lex->saved_text, c);
}
static int lex_get_save(lex_t *lex, json_error_t *error)
{
int c = stream_get(&lex->stream, error);
if(c != STREAM_STATE_EOF && c != STREAM_STATE_ERROR)
lex_save(lex, c);
return c;
}
static void lex_unget(lex_t *lex, int c)
{
stream_unget(&lex->stream, c);
}
static void lex_unget_unsave(lex_t *lex, int c)
{
if(c != STREAM_STATE_EOF && c != STREAM_STATE_ERROR) {
/* Since we treat warnings as errors, when assertions are turned
* off the "d" variable would be set but never used. Which is
* treated as an error by GCC.
*/
#ifndef NDEBUG
char d;
#endif
stream_unget(&lex->stream, c);
#ifndef NDEBUG
d =
#endif
strbuffer_pop(&lex->saved_text);
assert(c == d);
}
}
static void lex_save_cached(lex_t *lex)
{
while(lex->stream.buffer[lex->stream.buffer_pos] != '\0')
{
lex_save(lex, lex->stream.buffer[lex->stream.buffer_pos]);
lex->stream.buffer_pos++;
lex->stream.position++;
}
}
static void lex_free_string(lex_t *lex)
{
jsonp_free(lex->value.string.val);
lex->value.string.val = NULL;
lex->value.string.len = 0;
}
/* assumes that str points to 'u' plus at least 4 valid hex digits */
static int32_t decode_unicode_escape(const char *str)
{
int i;
int32_t value = 0;
assert(str[0] == 'u');
for(i = 1; i <= 4; i++) {
char c = str[i];
value <<= 4;
if(l_isdigit(c))
value += c - '0';
else if(l_islower(c))
value += c - 'a' + 10;
else if(l_isupper(c))
value += c - 'A' + 10;
else
return -1;
}
return value;
}
static void lex_scan_string(lex_t *lex, json_error_t *error)
{
int c;
const char *p;
char *t;
int i;
lex->value.string.val = NULL;
lex->token = TOKEN_INVALID;
c = lex_get_save(lex, error);
while(c != '"') {
if(c == STREAM_STATE_ERROR)
goto out;
else if(c == STREAM_STATE_EOF) {
error_set(error, lex, "premature end of input");
goto out;
}
else if(0 <= c && c <= 0x1F) {
/* control character */
lex_unget_unsave(lex, c);
if(c == '\n')
error_set(error, lex, "unexpected newline", c);
else
error_set(error, lex, "control character 0x%x", c);
goto out;
}
else if(c == '\\') {
c = lex_get_save(lex, error);
if(c == 'u') {
c = lex_get_save(lex, error);
for(i = 0; i < 4; i++) {
if(!l_isxdigit(c)) {
error_set(error, lex, "invalid escape");
goto out;
}
c = lex_get_save(lex, error);
}
}
else if(c == '"' || c == '\\' || c == '/' || c == 'b' ||
c == 'f' || c == 'n' || c == 'r' || c == 't')
c = lex_get_save(lex, error);
else {
error_set(error, lex, "invalid escape");
goto out;
}
}
else
c = lex_get_save(lex, error);
}
/* the actual value is at most of the same length as the source
string, because:
- shortcut escapes (e.g. "\t") (length 2) are converted to 1 byte
- a single \uXXXX escape (length 6) is converted to at most 3 bytes
- two \uXXXX escapes (length 12) forming an UTF-16 surrogate pair
are converted to 4 bytes
*/
t = jsonp_malloc(lex->saved_text.length + 1);
if(!t) {
/* this is not very nice, since TOKEN_INVALID is returned */
goto out;
}
lex->value.string.val = t;
/* + 1 to skip the " */
p = strbuffer_value(&lex->saved_text) + 1;
while(*p != '"') {
if(*p == '\\') {
p++;
if(*p == 'u') {
size_t length;
int32_t value;
value = decode_unicode_escape(p);
if(value < 0) {
error_set(error, lex, "invalid Unicode escape '%.6s'", p - 1);
goto out;
}
p += 5;
if(0xD800 <= value && value <= 0xDBFF) {
/* surrogate pair */
if(*p == '\\' && *(p + 1) == 'u') {
int32_t value2 = decode_unicode_escape(++p);
if(value2 < 0) {
error_set(error, lex, "invalid Unicode escape '%.6s'", p - 1);
goto out;
}
p += 5;
if(0xDC00 <= value2 && value2 <= 0xDFFF) {
/* valid second surrogate */
value =
((value - 0xD800) << 10) +
(value2 - 0xDC00) +
0x10000;
}
else {
/* invalid second surrogate */
error_set(error, lex,
"invalid Unicode '\\u%04X\\u%04X'",
value, value2);
goto out;
}
}
else {
/* no second surrogate */
error_set(error, lex, "invalid Unicode '\\u%04X'",
value);
goto out;
}
}
else if(0xDC00 <= value && value <= 0xDFFF) {
error_set(error, lex, "invalid Unicode '\\u%04X'", value);
goto out;
}
if(utf8_encode(value, t, &length))
assert(0);
t += length;
}
else {
switch(*p) {
case '"': case '\\': case '/':
*t = *p; break;
case 'b': *t = '\b'; break;
case 'f': *t = '\f'; break;
case 'n': *t = '\n'; break;
case 'r': *t = '\r'; break;
case 't': *t = '\t'; break;
default: assert(0);
}
t++;
p++;
}
}
else
*(t++) = *(p++);
}
*t = '\0';
lex->value.string.len = t - lex->value.string.val;
lex->token = TOKEN_STRING;
return;
out:
lex_free_string(lex);
}
#ifndef JANSSON_USING_CMAKE /* disabled if using cmake */
#if JSON_INTEGER_IS_LONG_LONG
#ifdef _MSC_VER /* Microsoft Visual Studio */
#define json_strtoint _strtoi64
#else
#define json_strtoint strtoll
#endif
#else
#define json_strtoint strtol
#endif
#endif
static int lex_scan_number(lex_t *lex, int c, json_error_t *error)
{
const char *saved_text;
char *end;
double doubleval;
lex->token = TOKEN_INVALID;
if(c == '-')
c = lex_get_save(lex, error);
if(c == '0') {
c = lex_get_save(lex, error);
if(l_isdigit(c)) {
lex_unget_unsave(lex, c);
goto out;
}
}
else if(l_isdigit(c)) {
do
c = lex_get_save(lex, error);
while(l_isdigit(c));
}
else {
lex_unget_unsave(lex, c);
goto out;
}
if(!(lex->flags & JSON_DECODE_INT_AS_REAL) &&
c != '.' && c != 'E' && c != 'e')
{
json_int_t intval;
lex_unget_unsave(lex, c);
saved_text = strbuffer_value(&lex->saved_text);
errno = 0;
intval = json_strtoint(saved_text, &end, 10);
if(errno == ERANGE) {
if(intval < 0)
error_set(error, lex, "too big negative integer");
else
error_set(error, lex, "too big integer");
goto out;
}
assert(end == saved_text + lex->saved_text.length);
lex->token = TOKEN_INTEGER;
lex->value.integer = intval;
return 0;
}
if(c == '.') {
c = lex_get(lex, error);
if(!l_isdigit(c)) {
lex_unget(lex, c);
goto out;
}
lex_save(lex, c);
do
c = lex_get_save(lex, error);
while(l_isdigit(c));
}
if(c == 'E' || c == 'e') {
c = lex_get_save(lex, error);
if(c == '+' || c == '-')
c = lex_get_save(lex, error);
if(!l_isdigit(c)) {
lex_unget_unsave(lex, c);
goto out;
}
do
c = lex_get_save(lex, error);
while(l_isdigit(c));
}
lex_unget_unsave(lex, c);
if(jsonp_strtod(&lex->saved_text, &doubleval)) {
error_set(error, lex, "real number overflow");
goto out;
}
lex->token = TOKEN_REAL;
lex->value.real = doubleval;
return 0;
out:
return -1;
}
static int lex_scan(lex_t *lex, json_error_t *error)
{
int c;
strbuffer_clear(&lex->saved_text);
if(lex->token == TOKEN_STRING)
lex_free_string(lex);
do
c = lex_get(lex, error);
while(c == ' ' || c == '\t' || c == '\n' || c == '\r');
if(c == STREAM_STATE_EOF) {
lex->token = TOKEN_EOF;
goto out;
}
if(c == STREAM_STATE_ERROR) {
lex->token = TOKEN_INVALID;
goto out;
}
lex_save(lex, c);
if(c == '{' || c == '}' || c == '[' || c == ']' || c == ':' || c == ',')
lex->token = c;
else if(c == '"')
lex_scan_string(lex, error);
else if(l_isdigit(c) || c == '-') {
if(lex_scan_number(lex, c, error))
goto out;
}
else if(l_isalpha(c)) {
/* eat up the whole identifier for clearer error messages */
const char *saved_text;
do
c = lex_get_save(lex, error);
while(l_isalpha(c));
lex_unget_unsave(lex, c);
saved_text = strbuffer_value(&lex->saved_text);
if(strcmp(saved_text, "true") == 0)
lex->token = TOKEN_TRUE;
else if(strcmp(saved_text, "false") == 0)
lex->token = TOKEN_FALSE;
else if(strcmp(saved_text, "null") == 0)
lex->token = TOKEN_NULL;
else
lex->token = TOKEN_INVALID;
}
else {
/* save the rest of the input UTF-8 sequence to get an error
message of valid UTF-8 */
lex_save_cached(lex);
lex->token = TOKEN_INVALID;
}
out:
return lex->token;
}
static char *lex_steal_string(lex_t *lex, size_t *out_len)
{
char *result = NULL;
if(lex->token == TOKEN_STRING) {
result = lex->value.string.val;
*out_len = lex->value.string.len;
lex->value.string.val = NULL;
lex->value.string.len = 0;
}
return result;
}
static int lex_init(lex_t *lex, get_func get, size_t flags, void *data)
{
stream_init(&lex->stream, get, data);
if(strbuffer_init(&lex->saved_text))
return -1;
lex->flags = flags;
lex->token = TOKEN_INVALID;
return 0;
}
static void lex_close(lex_t *lex)
{
if(lex->token == TOKEN_STRING)
lex_free_string(lex);
strbuffer_close(&lex->saved_text);
}
/*** parser ***/
static json_t *parse_value(lex_t *lex, size_t flags, json_error_t *error);
static json_t *parse_object(lex_t *lex, size_t flags, json_error_t *error)
{
json_t *object = json_object();
if(!object)
return NULL;
lex_scan(lex, error);
if(lex->token == '}')
return object;
while(1) {
char *key;
size_t len;
json_t *value;
if(lex->token != TOKEN_STRING) {
error_set(error, lex, "string or '}' expected");
goto error;
}
key = lex_steal_string(lex, &len);
if(!key)
return NULL;
if (memchr(key, '\0', len)) {
jsonp_free(key);
error_set(error, lex, "NUL byte in object key not supported");
goto error;
}
if(flags & JSON_REJECT_DUPLICATES) {
if(json_object_get(object, key)) {
jsonp_free(key);
error_set(error, lex, "duplicate object key");
goto error;
}
}
lex_scan(lex, error);
if(lex->token != ':') {
jsonp_free(key);
error_set(error, lex, "':' expected");
goto error;
}
lex_scan(lex, error);
value = parse_value(lex, flags, error);
if(!value) {
jsonp_free(key);
goto error;
}
if(json_object_set_nocheck(object, key, value)) {
jsonp_free(key);
json_decref(value);
goto error;
}
json_decref(value);
jsonp_free(key);
lex_scan(lex, error);
if(lex->token != ',')
break;
lex_scan(lex, error);
}
if(lex->token != '}') {
error_set(error, lex, "'}' expected");
goto error;
}
return object;
error:
json_decref(object);
return NULL;
}
static json_t *parse_array(lex_t *lex, size_t flags, json_error_t *error)
{
json_t *array = json_array();
if(!array)
return NULL;
lex_scan(lex, error);
if(lex->token == ']')
return array;
while(lex->token) {
json_t *elem = parse_value(lex, flags, error);
if(!elem)
goto error;
if(json_array_append(array, elem)) {
json_decref(elem);
goto error;
}
json_decref(elem);
lex_scan(lex, error);
if(lex->token != ',')
break;
lex_scan(lex, error);
}
if(lex->token != ']') {
error_set(error, lex, "']' expected");
goto error;
}
return array;
error:
json_decref(array);
return NULL;
}
static json_t *parse_value(lex_t *lex, size_t flags, json_error_t *error)
{
json_t *json;
switch(lex->token) {
case TOKEN_STRING: {
const char *value = lex->value.string.val;
size_t len = lex->value.string.len;
if(!(flags & JSON_ALLOW_NUL)) {
if(memchr(value, '\0', len)) {
error_set(error, lex, "\\u0000 is not allowed without JSON_ALLOW_NUL");
return NULL;
}
}
json = jsonp_stringn_nocheck_own(value, len);
if(json) {
lex->value.string.val = NULL;
lex->value.string.len = 0;
}
break;
}
case TOKEN_INTEGER: {
json = json_integer(lex->value.integer);
break;
}
case TOKEN_REAL: {
json = json_real(lex->value.real);
break;
}
case TOKEN_TRUE:
json = json_true();
break;
case TOKEN_FALSE:
json = json_false();
break;
case TOKEN_NULL:
json = json_null();
break;
case '{':
json = parse_object(lex, flags, error);
break;
case '[':
json = parse_array(lex, flags, error);
break;
case TOKEN_INVALID:
error_set(error, lex, "invalid token");
return NULL;
default:
error_set(error, lex, "unexpected token");
return NULL;
}
if(!json)
return NULL;
return json;
}
static json_t *parse_json(lex_t *lex, size_t flags, json_error_t *error)
{
json_t *result;
lex_scan(lex, error);
if(!(flags & JSON_DECODE_ANY)) {
if(lex->token != '[' && lex->token != '{') {
error_set(error, lex, "'[' or '{' expected");
return NULL;
}
}
result = parse_value(lex, flags, error);
if(!result)
return NULL;
if(!(flags & JSON_DISABLE_EOF_CHECK)) {
lex_scan(lex, error);
if(lex->token != TOKEN_EOF) {
error_set(error, lex, "end of file expected");
json_decref(result);
return NULL;
}
}
if(error) {
/* Save the position even though there was no error */
error->position = (int)lex->stream.position;
}
return result;
}
typedef struct
{
const char *data;
int pos;
} string_data_t;
static int string_get(void *data)
{
char c;
string_data_t *stream = (string_data_t *)data;
c = stream->data[stream->pos];
if(c == '\0')
return EOF;
else
{
stream->pos++;
return (unsigned char)c;
}
}
json_t *json_loads(const char *string, size_t flags, json_error_t *error)
{
lex_t lex;
json_t *result;
string_data_t stream_data;
jsonp_error_init(error, "<string>");
if (string == NULL) {
error_set(error, NULL, "wrong arguments");
return NULL;
}
stream_data.data = string;
stream_data.pos = 0;
if(lex_init(&lex, string_get, flags, (void *)&stream_data))
return NULL;
result = parse_json(&lex, flags, error);
lex_close(&lex);
return result;
}
typedef struct
{
const char *data;
size_t len;
size_t pos;
} buffer_data_t;
static int buffer_get(void *data)
{
char c;
buffer_data_t *stream = data;
if(stream->pos >= stream->len)
return EOF;
c = stream->data[stream->pos];
stream->pos++;
return (unsigned char)c;
}
json_t *json_loadb(const char *buffer, size_t buflen, size_t flags, json_error_t *error)
{
lex_t lex;
json_t *result;
buffer_data_t stream_data;
jsonp_error_init(error, "<buffer>");
if (buffer == NULL) {
error_set(error, NULL, "wrong arguments");
return NULL;
}
stream_data.data = buffer;
stream_data.pos = 0;
stream_data.len = buflen;
if(lex_init(&lex, buffer_get, flags, (void *)&stream_data))
return NULL;
result = parse_json(&lex, flags, error);
lex_close(&lex);
return result;
}
json_t *json_loadf(FILE *input, size_t flags, json_error_t *error)
{
lex_t lex;
const char *source;
json_t *result;
if(input == stdin)
source = "<stdin>";
else
source = "<stream>";
jsonp_error_init(error, source);
if (input == NULL) {
error_set(error, NULL, "wrong arguments");
return NULL;
}
if(lex_init(&lex, (get_func)fgetc, flags, input))
return NULL;
result = parse_json(&lex, flags, error);
lex_close(&lex);
return result;
}
json_t *json_load_file(const char *path, size_t flags, json_error_t *error)
{
json_t *result;
FILE *fp;
jsonp_error_init(error, path);
if (path == NULL) {
error_set(error, NULL, "wrong arguments");
return NULL;
}
fp = fopen(path, "rb");
if(!fp)
{
error_set(error, NULL, "unable to open %s: %s",
path, strerror(errno));
return NULL;
}
result = json_loadf(fp, flags, error);
fclose(fp);
return result;
}
#define MAX_BUF_LEN 1024
typedef struct
{
char data[MAX_BUF_LEN];
size_t len;
size_t pos;
json_load_callback_t callback;
void *arg;
} callback_data_t;
static int callback_get(void *data)
{
char c;
callback_data_t *stream = data;
if(stream->pos >= stream->len) {
stream->pos = 0;
stream->len = stream->callback(stream->data, MAX_BUF_LEN, stream->arg);
if(stream->len == 0 || stream->len == (size_t)-1)
return EOF;
}
c = stream->data[stream->pos];
stream->pos++;
return (unsigned char)c;
}
json_t *json_load_callback(json_load_callback_t callback, void *arg, size_t flags, json_error_t *error)
{
lex_t lex;
json_t *result;
callback_data_t stream_data;
memset(&stream_data, 0, sizeof(stream_data));
stream_data.callback = callback;
stream_data.arg = arg;
jsonp_error_init(error, "<callback>");
if (callback == NULL) {
error_set(error, NULL, "wrong arguments");
return NULL;
}
if(lex_init(&lex, (get_func)callback_get, flags, &stream_data))
return NULL;
result = parse_json(&lex, flags, error);
lex_close(&lex);
return result;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5039_4 |
crossvul-cpp_data_good_2739_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% JJJ PPPP 222 %
% J P P 2 2 %
% J PPPP 22 %
% J J P 2 %
% JJ P 22222 %
% %
% %
% Read/Write JPEG-2000 Image Format %
% %
% Cristy %
% Nathan Brown %
% June 2001 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/semaphore.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/module.h"
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
#include <openjpeg.h>
#endif
/*
Forward declarations.
*/
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
static MagickBooleanType
WriteJP2Image(const ImageInfo *,Image *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s J 2 K %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsJ2K() returns MagickTrue if the image format type, identified by the
% magick string, is J2K.
%
% The format of the IsJ2K method is:
%
% MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\xff\x4f\xff\x51",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s J P 2 %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsJP2() returns MagickTrue if the image format type, identified by the
% magick string, is JP2.
%
% The format of the IsJP2 method is:
%
% MagickBooleanType IsJP2(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsJP2(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\x0d\x0a\x87\x0a",4) == 0)
return(MagickTrue);
if (length < 12)
return(MagickFalse);
if (memcmp(magick,"\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a",12) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d J P 2 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadJP2Image() reads a JPEG 2000 Image file (JP2) or JPEG 2000
% codestream (JPC) image file and returns it. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image or set of images.
%
% JP2 support is originally written by Nathan Brown, nathanbrown@letu.edu.
%
% The format of the ReadJP2Image method is:
%
% Image *ReadJP2Image(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
static void JP2ErrorHandler(const char *message,void *client_data)
{
ExceptionInfo
*exception;
exception=(ExceptionInfo *) client_data;
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
message,"`%s'","OpenJP2");
}
static OPJ_SIZE_T JP2ReadHandler(void *buffer,OPJ_SIZE_T length,void *context)
{
Image
*image;
ssize_t
count;
image=(Image *) context;
count=ReadBlob(image,(ssize_t) length,(unsigned char *) buffer);
if (count == 0)
return((OPJ_SIZE_T) -1);
return((OPJ_SIZE_T) count);
}
static OPJ_BOOL JP2SeekHandler(OPJ_OFF_T offset,void *context)
{
Image
*image;
image=(Image *) context;
return(SeekBlob(image,offset,SEEK_SET) < 0 ? OPJ_FALSE : OPJ_TRUE);
}
static OPJ_OFF_T JP2SkipHandler(OPJ_OFF_T offset,void *context)
{
Image
*image;
image=(Image *) context;
return(SeekBlob(image,offset,SEEK_CUR) < 0 ? -1 : offset);
}
static void JP2WarningHandler(const char *message,void *client_data)
{
ExceptionInfo
*exception;
exception=(ExceptionInfo *) client_data;
(void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
message,"`%s'","OpenJP2");
}
static OPJ_SIZE_T JP2WriteHandler(void *buffer,OPJ_SIZE_T length,void *context)
{
Image
*image;
ssize_t
count;
image=(Image *) context;
count=WriteBlob(image,(ssize_t) length,(unsigned char *) buffer);
return((OPJ_SIZE_T) count);
}
static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception)
{
const char
*option;
Image
*image;
int
jp2_status;
MagickBooleanType
status;
opj_codec_t
*jp2_codec;
opj_codestream_index_t
*codestream_index = (opj_codestream_index_t *) NULL;
opj_dparameters_t
parameters;
opj_image_t
*jp2_image;
opj_stream_t
*jp2_stream;
register ssize_t
i;
ssize_t
y;
unsigned char
sans[4];
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize JP2 codec.
*/
if (ReadBlob(image,4,sans) != 4)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) SeekBlob(image,SEEK_SET,0);
if (LocaleCompare(image_info->magick,"JPT") == 0)
jp2_codec=opj_create_decompress(OPJ_CODEC_JPT);
else
if (IsJ2K(sans,4) != MagickFalse)
jp2_codec=opj_create_decompress(OPJ_CODEC_J2K);
else
jp2_codec=opj_create_decompress(OPJ_CODEC_JP2);
opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
opj_set_default_decoder_parameters(¶meters);
option=GetImageOption(image_info,"jp2:reduce-factor");
if (option != (const char *) NULL)
parameters.cp_reduce=StringToInteger(option);
option=GetImageOption(image_info,"jp2:quality-layers");
if (option == (const char *) NULL)
option=GetImageOption(image_info,"jp2:layer-number");
if (option != (const char *) NULL)
parameters.cp_layer=StringToInteger(option);
if (opj_setup_decoder(jp2_codec,¶meters) == 0)
{
opj_destroy_codec(jp2_codec);
ThrowReaderException(DelegateError,"UnableToManageJP2Stream");
}
jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE);
opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
opj_stream_set_user_data(jp2_stream,image,NULL);
opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image));
if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
jp2_status=1;
if ((image->columns != 0) && (image->rows != 0))
{
/*
Extract an area from the image.
*/
jp2_status=opj_set_decode_area(jp2_codec,jp2_image,
(OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y,
(OPJ_INT32) image->extract_info.x+(ssize_t) image->columns,
(OPJ_INT32) image->extract_info.y+(ssize_t) image->rows);
if (jp2_status == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
}
if ((image_info->number_scenes != 0) && (image_info->scene != 0))
jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image,
(unsigned int) image_info->scene-1);
else
if (image->ping == MagickFalse)
{
jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image);
if (jp2_status != 0)
jp2_status=opj_end_decompress(jp2_codec,jp2_stream);
}
if (jp2_status == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
opj_stream_destroy(jp2_stream);
for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
{
if ((jp2_image->comps[0].dx == 0) || (jp2_image->comps[0].dy == 0) ||
(jp2_image->comps[0].dx != jp2_image->comps[i].dx) ||
(jp2_image->comps[0].dy != jp2_image->comps[i].dy) ||
(jp2_image->comps[0].prec != jp2_image->comps[i].prec) ||
(jp2_image->comps[0].sgnd != jp2_image->comps[i].sgnd))
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported")
}
}
/*
Convert JP2 image.
*/
image->columns=(size_t) jp2_image->comps[0].w;
image->rows=(size_t) jp2_image->comps[0].h;
image->depth=jp2_image->comps[0].prec;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->compression=JPEG2000Compression;
if (jp2_image->color_space == 2)
{
SetImageColorspace(image,GRAYColorspace);
if (jp2_image->numcomps > 1)
image->matte=MagickTrue;
}
else
if (jp2_image->color_space == 3)
SetImageColorspace(image,Rec601YCbCrColorspace);
if (jp2_image->numcomps > 3)
image->matte=MagickTrue;
if (jp2_image->icc_profile_buf != (unsigned char *) NULL)
{
StringInfo
*profile;
profile=BlobToStringInfo(jp2_image->icc_profile_buf,
jp2_image->icc_profile_len);
if (profile != (StringInfo *) NULL)
SetImageProfile(image,"icc",profile);
}
if (image->ping != MagickFalse)
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
opj_destroy_cstr_index(&codestream_index);
return(GetFirstImageInList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
{
double
pixel,
scale;
scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1);
pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy*
image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+
(jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0));
switch (i)
{
case 0:
{
q->red=ClampToQuantum(pixel);
q->green=q->red;
q->blue=q->red;
q->opacity=OpaqueOpacity;
break;
}
case 1:
{
if (jp2_image->numcomps == 2)
{
q->opacity=ClampToQuantum(QuantumRange-pixel);
break;
}
q->green=ClampToQuantum(pixel);
break;
}
case 2:
{
q->blue=ClampToQuantum(pixel);
break;
}
case 3:
{
q->opacity=ClampToQuantum(QuantumRange-pixel);
break;
}
}
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
/*
Free resources.
*/
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
opj_destroy_cstr_index(&codestream_index);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r J P 2 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterJP2Image() adds attributes for the JP2 image format to the list of
% supported formats. The attributes include the image format tag, a method
% method to read and/or write the format, whether the format supports the
% saving of more than one frame to the same file or blob, whether the format
% supports native in-memory I/O, and a brief description of the format.
%
% The format of the RegisterJP2Image method is:
%
% size_t RegisterJP2Image(void)
%
*/
ModuleExport size_t RegisterJP2Image(void)
{
char
version[MaxTextExtent];
MagickInfo
*entry;
*version='\0';
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
(void) FormatLocaleString(version,MaxTextExtent,"%s",opj_version());
#endif
entry=SetMagickInfo("JP2");
entry->description=ConstantString("JPEG-2000 File Format Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJP2;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("J2C");
entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJ2K;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("J2K");
entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJ2K;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JPM");
entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJP2;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JPT");
entry->description=ConstantString("JPEG-2000 File Format Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJP2;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JPC");
entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJP2;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r J P 2 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterJP2Image() removes format registrations made by the JP2 module
% from the list of supported formats.
%
% The format of the UnregisterJP2Image method is:
%
% UnregisterJP2Image(void)
%
*/
ModuleExport void UnregisterJP2Image(void)
{
(void) UnregisterMagickInfo("JPC");
(void) UnregisterMagickInfo("JPT");
(void) UnregisterMagickInfo("JPM");
(void) UnregisterMagickInfo("JP2");
(void) UnregisterMagickInfo("J2K");
}
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e J P 2 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteJP2Image() writes an image in the JPEG 2000 image format.
%
% JP2 support originally written by Nathan Brown, nathanbrown@letu.edu
%
% The format of the WriteJP2Image method is:
%
% MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static void CinemaProfileCompliance(const opj_image_t *jp2_image,
opj_cparameters_t *parameters)
{
/*
Digital Cinema 4K profile compliant codestream.
*/
parameters->tile_size_on=OPJ_FALSE;
parameters->cp_tdx=1;
parameters->cp_tdy=1;
parameters->tp_flag='C';
parameters->tp_on=1;
parameters->cp_tx0=0;
parameters->cp_ty0=0;
parameters->image_offset_x0=0;
parameters->image_offset_y0=0;
parameters->cblockw_init=32;
parameters->cblockh_init=32;
parameters->csty|=0x01;
parameters->prog_order=OPJ_CPRL;
parameters->roi_compno=(-1);
parameters->subsampling_dx=1;
parameters->subsampling_dy=1;
parameters->irreversible=1;
if ((jp2_image->comps[0].w == 2048) || (jp2_image->comps[0].h == 1080))
{
/*
Digital Cinema 2K.
*/
parameters->cp_cinema=OPJ_CINEMA2K_24;
parameters->cp_rsiz=OPJ_CINEMA2K;
parameters->max_comp_size=1041666;
if (parameters->numresolution > 6)
parameters->numresolution=6;
}
if ((jp2_image->comps[0].w == 4096) || (jp2_image->comps[0].h == 2160))
{
/*
Digital Cinema 4K.
*/
parameters->cp_cinema=OPJ_CINEMA4K_24;
parameters->cp_rsiz=OPJ_CINEMA4K;
parameters->max_comp_size=1041666;
if (parameters->numresolution < 1)
parameters->numresolution=1;
if (parameters->numresolution > 7)
parameters->numresolution=7;
parameters->numpocs=2;
parameters->POC[0].tile=1;
parameters->POC[0].resno0=0;
parameters->POC[0].compno0=0;
parameters->POC[0].layno1=1;
parameters->POC[0].resno1=parameters->numresolution-1;
parameters->POC[0].compno1=3;
parameters->POC[0].prg1=OPJ_CPRL;
parameters->POC[1].tile=1;
parameters->POC[1].resno0=parameters->numresolution-1;
parameters->POC[1].compno0=0;
parameters->POC[1].layno1=1;
parameters->POC[1].resno1=parameters->numresolution;
parameters->POC[1].compno1=3;
parameters->POC[1].prg1=OPJ_CPRL;
}
parameters->tcp_numlayers=1;
parameters->tcp_rates[0]=((float) (jp2_image->numcomps*jp2_image->comps[0].w*
jp2_image->comps[0].h*jp2_image->comps[0].prec))/(parameters->max_comp_size*
8*jp2_image->comps[0].dx*jp2_image->comps[0].dy);
parameters->cp_disto_alloc=1;
}
static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image)
{
const char
*option,
*property;
int
jp2_status;
MagickBooleanType
status;
opj_codec_t
*jp2_codec;
OPJ_COLOR_SPACE
jp2_colorspace;
opj_cparameters_t
parameters;
opj_image_cmptparm_t
jp2_info[5];
opj_image_t
*jp2_image;
opj_stream_t
*jp2_stream;
register ssize_t
i;
ssize_t
y;
unsigned int
channels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
/*
Initialize JPEG 2000 encoder parameters.
*/
opj_set_default_encoder_parameters(¶meters);
for (i=1; i < 6; i++)
if (((size_t) (1 << (i+2)) > image->columns) &&
((size_t) (1 << (i+2)) > image->rows))
break;
parameters.numresolution=i;
option=GetImageOption(image_info,"jp2:number-resolutions");
if (option != (const char *) NULL)
parameters.numresolution=StringToInteger(option);
parameters.tcp_numlayers=1;
parameters.tcp_rates[0]=0; /* lossless */
parameters.cp_disto_alloc=1;
if ((image_info->quality != 0) && (image_info->quality != 100))
{
parameters.tcp_distoratio[0]=(double) image_info->quality;
parameters.cp_fixed_quality=OPJ_TRUE;
}
if (image_info->extract != (char *) NULL)
{
RectangleInfo
geometry;
int
flags;
/*
Set tile size.
*/
flags=ParseAbsoluteGeometry(image_info->extract,&geometry);
parameters.cp_tdx=(int) geometry.width;
parameters.cp_tdy=(int) geometry.width;
if ((flags & HeightValue) != 0)
parameters.cp_tdy=(int) geometry.height;
if ((flags & XValue) != 0)
parameters.cp_tx0=geometry.x;
if ((flags & YValue) != 0)
parameters.cp_ty0=geometry.y;
parameters.tile_size_on=OPJ_TRUE;
}
option=GetImageOption(image_info,"jp2:quality");
if (option != (const char *) NULL)
{
register const char
*p;
/*
Set quality PSNR.
*/
p=option;
for (i=0; sscanf(p,"%f",¶meters.tcp_distoratio[i]) == 1; i++)
{
if (i >= 100)
break;
while ((*p != '\0') && (*p != ','))
p++;
if (*p == '\0')
break;
p++;
}
parameters.tcp_numlayers=i+1;
parameters.cp_fixed_quality=OPJ_TRUE;
}
option=GetImageOption(image_info,"jp2:progression-order");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"LRCP") == 0)
parameters.prog_order=OPJ_LRCP;
if (LocaleCompare(option,"RLCP") == 0)
parameters.prog_order=OPJ_RLCP;
if (LocaleCompare(option,"RPCL") == 0)
parameters.prog_order=OPJ_RPCL;
if (LocaleCompare(option,"PCRL") == 0)
parameters.prog_order=OPJ_PCRL;
if (LocaleCompare(option,"CPRL") == 0)
parameters.prog_order=OPJ_CPRL;
}
option=GetImageOption(image_info,"jp2:rate");
if (option != (const char *) NULL)
{
register const char
*p;
/*
Set compression rate.
*/
p=option;
for (i=0; sscanf(p,"%f",¶meters.tcp_rates[i]) == 1; i++)
{
if (i > 100)
break;
while ((*p != '\0') && (*p != ','))
p++;
if (*p == '\0')
break;
p++;
}
parameters.tcp_numlayers=i+1;
parameters.cp_disto_alloc=OPJ_TRUE;
}
if (image_info->sampling_factor != (const char *) NULL)
(void) sscanf(image_info->sampling_factor,"%d,%d",
¶meters.subsampling_dx,¶meters.subsampling_dy);
property=GetImageProperty(image,"comment");
if (property != (const char *) NULL)
parameters.cp_comment=ConstantString(property);
channels=3;
jp2_colorspace=OPJ_CLRSPC_SRGB;
if (image->colorspace == YUVColorspace)
{
jp2_colorspace=OPJ_CLRSPC_SYCC;
parameters.subsampling_dx=2;
}
else
{
if (IsGrayColorspace(image->colorspace) != MagickFalse)
{
channels=1;
jp2_colorspace=OPJ_CLRSPC_GRAY;
}
else
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->matte != MagickFalse)
channels++;
}
parameters.tcp_mct=channels == 3 ? 1 : 0;
ResetMagickMemory(jp2_info,0,sizeof(jp2_info));
for (i=0; i < (ssize_t) channels; i++)
{
jp2_info[i].prec=(unsigned int) image->depth;
jp2_info[i].bpp=(unsigned int) image->depth;
if ((image->depth == 1) &&
((LocaleCompare(image_info->magick,"JPT") == 0) ||
(LocaleCompare(image_info->magick,"JP2") == 0)))
{
jp2_info[i].prec++; /* OpenJPEG returns exception for depth @ 1 */
jp2_info[i].bpp++;
}
jp2_info[i].sgnd=0;
jp2_info[i].dx=parameters.subsampling_dx;
jp2_info[i].dy=parameters.subsampling_dy;
jp2_info[i].w=(unsigned int) image->columns;
jp2_info[i].h=(unsigned int) image->rows;
}
jp2_image=opj_image_create(channels,jp2_info,jp2_colorspace);
if (jp2_image == (opj_image_t *) NULL)
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
jp2_image->x0=parameters.image_offset_x0;
jp2_image->y0=parameters.image_offset_y0;
jp2_image->x1=(unsigned int) (2*parameters.image_offset_x0+(image->columns-1)*
parameters.subsampling_dx+1);
jp2_image->y1=(unsigned int) (2*parameters.image_offset_y0+(image->rows-1)*
parameters.subsampling_dx+1);
if ((image->depth == 12) &&
((image->columns == 2048) || (image->rows == 1080) ||
(image->columns == 4096) || (image->rows == 2160)))
CinemaProfileCompliance(jp2_image,¶meters);
if (channels == 4)
jp2_image->comps[3].alpha=1;
else
if ((channels == 2) && (jp2_colorspace == OPJ_CLRSPC_GRAY))
jp2_image->comps[1].alpha=1;
/*
Convert to JP2 pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*p;
ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) channels; i++)
{
double
scale;
register int
*q;
scale=(double) ((1UL << jp2_image->comps[i].prec)-1)/QuantumRange;
q=jp2_image->comps[i].data+(y/jp2_image->comps[i].dy*
image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx);
switch (i)
{
case 0:
{
if (jp2_colorspace == OPJ_CLRSPC_GRAY)
{
*q=(int) (scale*GetPixelLuma(image,p));
break;
}
*q=(int) (scale*p->red);
break;
}
case 1:
{
if (jp2_colorspace == OPJ_CLRSPC_GRAY)
{
*q=(int) (scale*(QuantumRange-p->opacity));
break;
}
*q=(int) (scale*p->green);
break;
}
case 2:
{
*q=(int) (scale*p->blue);
break;
}
case 3:
{
*q=(int) (scale*(QuantumRange-p->opacity));
break;
}
}
}
p++;
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (LocaleCompare(image_info->magick,"JPT") == 0)
jp2_codec=opj_create_compress(OPJ_CODEC_JPT);
else
if (LocaleCompare(image_info->magick,"J2K") == 0)
jp2_codec=opj_create_compress(OPJ_CODEC_J2K);
else
jp2_codec=opj_create_compress(OPJ_CODEC_JP2);
opj_set_warning_handler(jp2_codec,JP2WarningHandler,&image->exception);
opj_set_error_handler(jp2_codec,JP2ErrorHandler,&image->exception);
opj_setup_encoder(jp2_codec,¶meters,jp2_image);
jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_FALSE);
opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
opj_stream_set_user_data(jp2_stream,image,NULL);
if (jp2_stream == (opj_stream_t *) NULL)
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
jp2_status=opj_start_compress(jp2_codec,jp2_image,jp2_stream);
if (jp2_status == 0)
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
if ((opj_encode(jp2_codec,jp2_stream) == 0) ||
(opj_end_compress(jp2_codec,jp2_stream) == 0))
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
}
/*
Free resources.
*/
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
(void) CloseBlob(image);
return(MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2739_0 |
crossvul-cpp_data_bad_5845_1 | /*
* algif_skcipher: User-space interface for skcipher algorithms
*
* This file provides the user-space API for symmetric key ciphers.
*
* Copyright (c) 2010 Herbert Xu <herbert@gondor.apana.org.au>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
*/
#include <crypto/scatterwalk.h>
#include <crypto/skcipher.h>
#include <crypto/if_alg.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/net.h>
#include <net/sock.h>
struct skcipher_sg_list {
struct list_head list;
int cur;
struct scatterlist sg[0];
};
struct skcipher_ctx {
struct list_head tsgl;
struct af_alg_sgl rsgl;
void *iv;
struct af_alg_completion completion;
unsigned used;
unsigned int len;
bool more;
bool merge;
bool enc;
struct ablkcipher_request req;
};
#define MAX_SGL_ENTS ((PAGE_SIZE - sizeof(struct skcipher_sg_list)) / \
sizeof(struct scatterlist) - 1)
static inline int skcipher_sndbuf(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
return max_t(int, max_t(int, sk->sk_sndbuf & PAGE_MASK, PAGE_SIZE) -
ctx->used, 0);
}
static inline bool skcipher_writable(struct sock *sk)
{
return PAGE_SIZE <= skcipher_sndbuf(sk);
}
static int skcipher_alloc_sgl(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct skcipher_sg_list *sgl;
struct scatterlist *sg = NULL;
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
if (!list_empty(&ctx->tsgl))
sg = sgl->sg;
if (!sg || sgl->cur >= MAX_SGL_ENTS) {
sgl = sock_kmalloc(sk, sizeof(*sgl) +
sizeof(sgl->sg[0]) * (MAX_SGL_ENTS + 1),
GFP_KERNEL);
if (!sgl)
return -ENOMEM;
sg_init_table(sgl->sg, MAX_SGL_ENTS + 1);
sgl->cur = 0;
if (sg)
scatterwalk_sg_chain(sg, MAX_SGL_ENTS + 1, sgl->sg);
list_add_tail(&sgl->list, &ctx->tsgl);
}
return 0;
}
static void skcipher_pull_sgl(struct sock *sk, int used)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct skcipher_sg_list *sgl;
struct scatterlist *sg;
int i;
while (!list_empty(&ctx->tsgl)) {
sgl = list_first_entry(&ctx->tsgl, struct skcipher_sg_list,
list);
sg = sgl->sg;
for (i = 0; i < sgl->cur; i++) {
int plen = min_t(int, used, sg[i].length);
if (!sg_page(sg + i))
continue;
sg[i].length -= plen;
sg[i].offset += plen;
used -= plen;
ctx->used -= plen;
if (sg[i].length)
return;
put_page(sg_page(sg + i));
sg_assign_page(sg + i, NULL);
}
list_del(&sgl->list);
sock_kfree_s(sk, sgl,
sizeof(*sgl) + sizeof(sgl->sg[0]) *
(MAX_SGL_ENTS + 1));
}
if (!ctx->used)
ctx->merge = 0;
}
static void skcipher_free_sgl(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
skcipher_pull_sgl(sk, ctx->used);
}
static int skcipher_wait_for_wmem(struct sock *sk, unsigned flags)
{
long timeout;
DEFINE_WAIT(wait);
int err = -ERESTARTSYS;
if (flags & MSG_DONTWAIT)
return -EAGAIN;
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
for (;;) {
if (signal_pending(current))
break;
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
timeout = MAX_SCHEDULE_TIMEOUT;
if (sk_wait_event(sk, &timeout, skcipher_writable(sk))) {
err = 0;
break;
}
}
finish_wait(sk_sleep(sk), &wait);
return err;
}
static void skcipher_wmem_wakeup(struct sock *sk)
{
struct socket_wq *wq;
if (!skcipher_writable(sk))
return;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
POLLRDNORM |
POLLRDBAND);
sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
rcu_read_unlock();
}
static int skcipher_wait_for_data(struct sock *sk, unsigned flags)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
long timeout;
DEFINE_WAIT(wait);
int err = -ERESTARTSYS;
if (flags & MSG_DONTWAIT) {
return -EAGAIN;
}
set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
for (;;) {
if (signal_pending(current))
break;
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
timeout = MAX_SCHEDULE_TIMEOUT;
if (sk_wait_event(sk, &timeout, ctx->used)) {
err = 0;
break;
}
}
finish_wait(sk_sleep(sk), &wait);
clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
return err;
}
static void skcipher_data_wakeup(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct socket_wq *wq;
if (!ctx->used)
return;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
POLLRDNORM |
POLLRDBAND);
sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
rcu_read_unlock();
}
static int skcipher_sendmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t size)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(&ctx->req);
unsigned ivsize = crypto_ablkcipher_ivsize(tfm);
struct skcipher_sg_list *sgl;
struct af_alg_control con = {};
long copied = 0;
bool enc = 0;
int err;
int i;
if (msg->msg_controllen) {
err = af_alg_cmsg_send(msg, &con);
if (err)
return err;
switch (con.op) {
case ALG_OP_ENCRYPT:
enc = 1;
break;
case ALG_OP_DECRYPT:
enc = 0;
break;
default:
return -EINVAL;
}
if (con.iv && con.iv->ivlen != ivsize)
return -EINVAL;
}
err = -EINVAL;
lock_sock(sk);
if (!ctx->more && ctx->used)
goto unlock;
if (!ctx->used) {
ctx->enc = enc;
if (con.iv)
memcpy(ctx->iv, con.iv->iv, ivsize);
}
while (size) {
struct scatterlist *sg;
unsigned long len = size;
int plen;
if (ctx->merge) {
sgl = list_entry(ctx->tsgl.prev,
struct skcipher_sg_list, list);
sg = sgl->sg + sgl->cur - 1;
len = min_t(unsigned long, len,
PAGE_SIZE - sg->offset - sg->length);
err = memcpy_fromiovec(page_address(sg_page(sg)) +
sg->offset + sg->length,
msg->msg_iov, len);
if (err)
goto unlock;
sg->length += len;
ctx->merge = (sg->offset + sg->length) &
(PAGE_SIZE - 1);
ctx->used += len;
copied += len;
size -= len;
continue;
}
if (!skcipher_writable(sk)) {
err = skcipher_wait_for_wmem(sk, msg->msg_flags);
if (err)
goto unlock;
}
len = min_t(unsigned long, len, skcipher_sndbuf(sk));
err = skcipher_alloc_sgl(sk);
if (err)
goto unlock;
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
sg = sgl->sg;
do {
i = sgl->cur;
plen = min_t(int, len, PAGE_SIZE);
sg_assign_page(sg + i, alloc_page(GFP_KERNEL));
err = -ENOMEM;
if (!sg_page(sg + i))
goto unlock;
err = memcpy_fromiovec(page_address(sg_page(sg + i)),
msg->msg_iov, plen);
if (err) {
__free_page(sg_page(sg + i));
sg_assign_page(sg + i, NULL);
goto unlock;
}
sg[i].length = plen;
len -= plen;
ctx->used += plen;
copied += plen;
size -= plen;
sgl->cur++;
} while (len && sgl->cur < MAX_SGL_ENTS);
ctx->merge = plen & (PAGE_SIZE - 1);
}
err = 0;
ctx->more = msg->msg_flags & MSG_MORE;
if (!ctx->more && !list_empty(&ctx->tsgl))
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
unlock:
skcipher_data_wakeup(sk);
release_sock(sk);
return copied ?: err;
}
static ssize_t skcipher_sendpage(struct socket *sock, struct page *page,
int offset, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct skcipher_sg_list *sgl;
int err = -EINVAL;
lock_sock(sk);
if (!ctx->more && ctx->used)
goto unlock;
if (!size)
goto done;
if (!skcipher_writable(sk)) {
err = skcipher_wait_for_wmem(sk, flags);
if (err)
goto unlock;
}
err = skcipher_alloc_sgl(sk);
if (err)
goto unlock;
ctx->merge = 0;
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
get_page(page);
sg_set_page(sgl->sg + sgl->cur, page, size, offset);
sgl->cur++;
ctx->used += size;
done:
ctx->more = flags & MSG_MORE;
if (!ctx->more && !list_empty(&ctx->tsgl))
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
unlock:
skcipher_data_wakeup(sk);
release_sock(sk);
return err ?: size;
}
static int skcipher_recvmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t ignored, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
unsigned bs = crypto_ablkcipher_blocksize(crypto_ablkcipher_reqtfm(
&ctx->req));
struct skcipher_sg_list *sgl;
struct scatterlist *sg;
unsigned long iovlen;
struct iovec *iov;
int err = -EAGAIN;
int used;
long copied = 0;
lock_sock(sk);
msg->msg_namelen = 0;
for (iov = msg->msg_iov, iovlen = msg->msg_iovlen; iovlen > 0;
iovlen--, iov++) {
unsigned long seglen = iov->iov_len;
char __user *from = iov->iov_base;
while (seglen) {
sgl = list_first_entry(&ctx->tsgl,
struct skcipher_sg_list, list);
sg = sgl->sg;
while (!sg->length)
sg++;
used = ctx->used;
if (!used) {
err = skcipher_wait_for_data(sk, flags);
if (err)
goto unlock;
}
used = min_t(unsigned long, used, seglen);
used = af_alg_make_sg(&ctx->rsgl, from, used, 1);
err = used;
if (err < 0)
goto unlock;
if (ctx->more || used < ctx->used)
used -= used % bs;
err = -EINVAL;
if (!used)
goto free;
ablkcipher_request_set_crypt(&ctx->req, sg,
ctx->rsgl.sg, used,
ctx->iv);
err = af_alg_wait_for_completion(
ctx->enc ?
crypto_ablkcipher_encrypt(&ctx->req) :
crypto_ablkcipher_decrypt(&ctx->req),
&ctx->completion);
free:
af_alg_free_sg(&ctx->rsgl);
if (err)
goto unlock;
copied += used;
from += used;
seglen -= used;
skcipher_pull_sgl(sk, used);
}
}
err = 0;
unlock:
skcipher_wmem_wakeup(sk);
release_sock(sk);
return copied ?: err;
}
static unsigned int skcipher_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
unsigned int mask;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
if (ctx->used)
mask |= POLLIN | POLLRDNORM;
if (skcipher_writable(sk))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
return mask;
}
static struct proto_ops algif_skcipher_ops = {
.family = PF_ALG,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.getname = sock_no_getname,
.ioctl = sock_no_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.getsockopt = sock_no_getsockopt,
.mmap = sock_no_mmap,
.bind = sock_no_bind,
.accept = sock_no_accept,
.setsockopt = sock_no_setsockopt,
.release = af_alg_release,
.sendmsg = skcipher_sendmsg,
.sendpage = skcipher_sendpage,
.recvmsg = skcipher_recvmsg,
.poll = skcipher_poll,
};
static void *skcipher_bind(const char *name, u32 type, u32 mask)
{
return crypto_alloc_ablkcipher(name, type, mask);
}
static void skcipher_release(void *private)
{
crypto_free_ablkcipher(private);
}
static int skcipher_setkey(void *private, const u8 *key, unsigned int keylen)
{
return crypto_ablkcipher_setkey(private, key, keylen);
}
static void skcipher_sock_destruct(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(&ctx->req);
skcipher_free_sgl(sk);
sock_kfree_s(sk, ctx->iv, crypto_ablkcipher_ivsize(tfm));
sock_kfree_s(sk, ctx, ctx->len);
af_alg_release_parent(sk);
}
static int skcipher_accept_parent(void *private, struct sock *sk)
{
struct skcipher_ctx *ctx;
struct alg_sock *ask = alg_sk(sk);
unsigned int len = sizeof(*ctx) + crypto_ablkcipher_reqsize(private);
ctx = sock_kmalloc(sk, len, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->iv = sock_kmalloc(sk, crypto_ablkcipher_ivsize(private),
GFP_KERNEL);
if (!ctx->iv) {
sock_kfree_s(sk, ctx, len);
return -ENOMEM;
}
memset(ctx->iv, 0, crypto_ablkcipher_ivsize(private));
INIT_LIST_HEAD(&ctx->tsgl);
ctx->len = len;
ctx->used = 0;
ctx->more = 0;
ctx->merge = 0;
ctx->enc = 0;
af_alg_init_completion(&ctx->completion);
ask->private = ctx;
ablkcipher_request_set_tfm(&ctx->req, private);
ablkcipher_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG,
af_alg_complete, &ctx->completion);
sk->sk_destruct = skcipher_sock_destruct;
return 0;
}
static const struct af_alg_type algif_type_skcipher = {
.bind = skcipher_bind,
.release = skcipher_release,
.setkey = skcipher_setkey,
.accept = skcipher_accept_parent,
.ops = &algif_skcipher_ops,
.name = "skcipher",
.owner = THIS_MODULE
};
static int __init algif_skcipher_init(void)
{
return af_alg_register_type(&algif_type_skcipher);
}
static void __exit algif_skcipher_exit(void)
{
int err = af_alg_unregister_type(&algif_type_skcipher);
BUG_ON(err);
}
module_init(algif_skcipher_init);
module_exit(algif_skcipher_exit);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5845_1 |
crossvul-cpp_data_good_2891_12 | /*
* Copyright (C) 2010 IBM Corporation
*
* Author:
* David Safford <safford@us.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2 of the License.
*
* See Documentation/security/keys/trusted-encrypted.rst
*/
#include <crypto/hash_info.h>
#include <linux/uaccess.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/parser.h>
#include <linux/string.h>
#include <linux/err.h>
#include <keys/user-type.h>
#include <keys/trusted-type.h>
#include <linux/key-type.h>
#include <linux/rcupdate.h>
#include <linux/crypto.h>
#include <crypto/hash.h>
#include <crypto/sha.h>
#include <linux/capability.h>
#include <linux/tpm.h>
#include <linux/tpm_command.h>
#include "trusted.h"
static const char hmac_alg[] = "hmac(sha1)";
static const char hash_alg[] = "sha1";
struct sdesc {
struct shash_desc shash;
char ctx[];
};
static struct crypto_shash *hashalg;
static struct crypto_shash *hmacalg;
static struct sdesc *init_sdesc(struct crypto_shash *alg)
{
struct sdesc *sdesc;
int size;
size = sizeof(struct shash_desc) + crypto_shash_descsize(alg);
sdesc = kmalloc(size, GFP_KERNEL);
if (!sdesc)
return ERR_PTR(-ENOMEM);
sdesc->shash.tfm = alg;
sdesc->shash.flags = 0x0;
return sdesc;
}
static int TSS_sha1(const unsigned char *data, unsigned int datalen,
unsigned char *digest)
{
struct sdesc *sdesc;
int ret;
sdesc = init_sdesc(hashalg);
if (IS_ERR(sdesc)) {
pr_info("trusted_key: can't alloc %s\n", hash_alg);
return PTR_ERR(sdesc);
}
ret = crypto_shash_digest(&sdesc->shash, data, datalen, digest);
kzfree(sdesc);
return ret;
}
static int TSS_rawhmac(unsigned char *digest, const unsigned char *key,
unsigned int keylen, ...)
{
struct sdesc *sdesc;
va_list argp;
unsigned int dlen;
unsigned char *data;
int ret;
sdesc = init_sdesc(hmacalg);
if (IS_ERR(sdesc)) {
pr_info("trusted_key: can't alloc %s\n", hmac_alg);
return PTR_ERR(sdesc);
}
ret = crypto_shash_setkey(hmacalg, key, keylen);
if (ret < 0)
goto out;
ret = crypto_shash_init(&sdesc->shash);
if (ret < 0)
goto out;
va_start(argp, keylen);
for (;;) {
dlen = va_arg(argp, unsigned int);
if (dlen == 0)
break;
data = va_arg(argp, unsigned char *);
if (data == NULL) {
ret = -EINVAL;
break;
}
ret = crypto_shash_update(&sdesc->shash, data, dlen);
if (ret < 0)
break;
}
va_end(argp);
if (!ret)
ret = crypto_shash_final(&sdesc->shash, digest);
out:
kzfree(sdesc);
return ret;
}
/*
* calculate authorization info fields to send to TPM
*/
static int TSS_authhmac(unsigned char *digest, const unsigned char *key,
unsigned int keylen, unsigned char *h1,
unsigned char *h2, unsigned char h3, ...)
{
unsigned char paramdigest[SHA1_DIGEST_SIZE];
struct sdesc *sdesc;
unsigned int dlen;
unsigned char *data;
unsigned char c;
int ret;
va_list argp;
sdesc = init_sdesc(hashalg);
if (IS_ERR(sdesc)) {
pr_info("trusted_key: can't alloc %s\n", hash_alg);
return PTR_ERR(sdesc);
}
c = h3;
ret = crypto_shash_init(&sdesc->shash);
if (ret < 0)
goto out;
va_start(argp, h3);
for (;;) {
dlen = va_arg(argp, unsigned int);
if (dlen == 0)
break;
data = va_arg(argp, unsigned char *);
if (!data) {
ret = -EINVAL;
break;
}
ret = crypto_shash_update(&sdesc->shash, data, dlen);
if (ret < 0)
break;
}
va_end(argp);
if (!ret)
ret = crypto_shash_final(&sdesc->shash, paramdigest);
if (!ret)
ret = TSS_rawhmac(digest, key, keylen, SHA1_DIGEST_SIZE,
paramdigest, TPM_NONCE_SIZE, h1,
TPM_NONCE_SIZE, h2, 1, &c, 0, 0);
out:
kzfree(sdesc);
return ret;
}
/*
* verify the AUTH1_COMMAND (Seal) result from TPM
*/
static int TSS_checkhmac1(unsigned char *buffer,
const uint32_t command,
const unsigned char *ononce,
const unsigned char *key,
unsigned int keylen, ...)
{
uint32_t bufsize;
uint16_t tag;
uint32_t ordinal;
uint32_t result;
unsigned char *enonce;
unsigned char *continueflag;
unsigned char *authdata;
unsigned char testhmac[SHA1_DIGEST_SIZE];
unsigned char paramdigest[SHA1_DIGEST_SIZE];
struct sdesc *sdesc;
unsigned int dlen;
unsigned int dpos;
va_list argp;
int ret;
bufsize = LOAD32(buffer, TPM_SIZE_OFFSET);
tag = LOAD16(buffer, 0);
ordinal = command;
result = LOAD32N(buffer, TPM_RETURN_OFFSET);
if (tag == TPM_TAG_RSP_COMMAND)
return 0;
if (tag != TPM_TAG_RSP_AUTH1_COMMAND)
return -EINVAL;
authdata = buffer + bufsize - SHA1_DIGEST_SIZE;
continueflag = authdata - 1;
enonce = continueflag - TPM_NONCE_SIZE;
sdesc = init_sdesc(hashalg);
if (IS_ERR(sdesc)) {
pr_info("trusted_key: can't alloc %s\n", hash_alg);
return PTR_ERR(sdesc);
}
ret = crypto_shash_init(&sdesc->shash);
if (ret < 0)
goto out;
ret = crypto_shash_update(&sdesc->shash, (const u8 *)&result,
sizeof result);
if (ret < 0)
goto out;
ret = crypto_shash_update(&sdesc->shash, (const u8 *)&ordinal,
sizeof ordinal);
if (ret < 0)
goto out;
va_start(argp, keylen);
for (;;) {
dlen = va_arg(argp, unsigned int);
if (dlen == 0)
break;
dpos = va_arg(argp, unsigned int);
ret = crypto_shash_update(&sdesc->shash, buffer + dpos, dlen);
if (ret < 0)
break;
}
va_end(argp);
if (!ret)
ret = crypto_shash_final(&sdesc->shash, paramdigest);
if (ret < 0)
goto out;
ret = TSS_rawhmac(testhmac, key, keylen, SHA1_DIGEST_SIZE, paramdigest,
TPM_NONCE_SIZE, enonce, TPM_NONCE_SIZE, ononce,
1, continueflag, 0, 0);
if (ret < 0)
goto out;
if (memcmp(testhmac, authdata, SHA1_DIGEST_SIZE))
ret = -EINVAL;
out:
kzfree(sdesc);
return ret;
}
/*
* verify the AUTH2_COMMAND (unseal) result from TPM
*/
static int TSS_checkhmac2(unsigned char *buffer,
const uint32_t command,
const unsigned char *ononce,
const unsigned char *key1,
unsigned int keylen1,
const unsigned char *key2,
unsigned int keylen2, ...)
{
uint32_t bufsize;
uint16_t tag;
uint32_t ordinal;
uint32_t result;
unsigned char *enonce1;
unsigned char *continueflag1;
unsigned char *authdata1;
unsigned char *enonce2;
unsigned char *continueflag2;
unsigned char *authdata2;
unsigned char testhmac1[SHA1_DIGEST_SIZE];
unsigned char testhmac2[SHA1_DIGEST_SIZE];
unsigned char paramdigest[SHA1_DIGEST_SIZE];
struct sdesc *sdesc;
unsigned int dlen;
unsigned int dpos;
va_list argp;
int ret;
bufsize = LOAD32(buffer, TPM_SIZE_OFFSET);
tag = LOAD16(buffer, 0);
ordinal = command;
result = LOAD32N(buffer, TPM_RETURN_OFFSET);
if (tag == TPM_TAG_RSP_COMMAND)
return 0;
if (tag != TPM_TAG_RSP_AUTH2_COMMAND)
return -EINVAL;
authdata1 = buffer + bufsize - (SHA1_DIGEST_SIZE + 1
+ SHA1_DIGEST_SIZE + SHA1_DIGEST_SIZE);
authdata2 = buffer + bufsize - (SHA1_DIGEST_SIZE);
continueflag1 = authdata1 - 1;
continueflag2 = authdata2 - 1;
enonce1 = continueflag1 - TPM_NONCE_SIZE;
enonce2 = continueflag2 - TPM_NONCE_SIZE;
sdesc = init_sdesc(hashalg);
if (IS_ERR(sdesc)) {
pr_info("trusted_key: can't alloc %s\n", hash_alg);
return PTR_ERR(sdesc);
}
ret = crypto_shash_init(&sdesc->shash);
if (ret < 0)
goto out;
ret = crypto_shash_update(&sdesc->shash, (const u8 *)&result,
sizeof result);
if (ret < 0)
goto out;
ret = crypto_shash_update(&sdesc->shash, (const u8 *)&ordinal,
sizeof ordinal);
if (ret < 0)
goto out;
va_start(argp, keylen2);
for (;;) {
dlen = va_arg(argp, unsigned int);
if (dlen == 0)
break;
dpos = va_arg(argp, unsigned int);
ret = crypto_shash_update(&sdesc->shash, buffer + dpos, dlen);
if (ret < 0)
break;
}
va_end(argp);
if (!ret)
ret = crypto_shash_final(&sdesc->shash, paramdigest);
if (ret < 0)
goto out;
ret = TSS_rawhmac(testhmac1, key1, keylen1, SHA1_DIGEST_SIZE,
paramdigest, TPM_NONCE_SIZE, enonce1,
TPM_NONCE_SIZE, ononce, 1, continueflag1, 0, 0);
if (ret < 0)
goto out;
if (memcmp(testhmac1, authdata1, SHA1_DIGEST_SIZE)) {
ret = -EINVAL;
goto out;
}
ret = TSS_rawhmac(testhmac2, key2, keylen2, SHA1_DIGEST_SIZE,
paramdigest, TPM_NONCE_SIZE, enonce2,
TPM_NONCE_SIZE, ononce, 1, continueflag2, 0, 0);
if (ret < 0)
goto out;
if (memcmp(testhmac2, authdata2, SHA1_DIGEST_SIZE))
ret = -EINVAL;
out:
kzfree(sdesc);
return ret;
}
/*
* For key specific tpm requests, we will generate and send our
* own TPM command packets using the drivers send function.
*/
static int trusted_tpm_send(const u32 chip_num, unsigned char *cmd,
size_t buflen)
{
int rc;
dump_tpm_buf(cmd);
rc = tpm_send(chip_num, cmd, buflen);
dump_tpm_buf(cmd);
if (rc > 0)
/* Can't return positive return codes values to keyctl */
rc = -EPERM;
return rc;
}
/*
* Lock a trusted key, by extending a selected PCR.
*
* Prevents a trusted key that is sealed to PCRs from being accessed.
* This uses the tpm driver's extend function.
*/
static int pcrlock(const int pcrnum)
{
unsigned char hash[SHA1_DIGEST_SIZE];
int ret;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
ret = tpm_get_random(TPM_ANY_NUM, hash, SHA1_DIGEST_SIZE);
if (ret != SHA1_DIGEST_SIZE)
return ret;
return tpm_pcr_extend(TPM_ANY_NUM, pcrnum, hash) ? -EINVAL : 0;
}
/*
* Create an object specific authorisation protocol (OSAP) session
*/
static int osap(struct tpm_buf *tb, struct osapsess *s,
const unsigned char *key, uint16_t type, uint32_t handle)
{
unsigned char enonce[TPM_NONCE_SIZE];
unsigned char ononce[TPM_NONCE_SIZE];
int ret;
ret = tpm_get_random(TPM_ANY_NUM, ononce, TPM_NONCE_SIZE);
if (ret != TPM_NONCE_SIZE)
return ret;
INIT_BUF(tb);
store16(tb, TPM_TAG_RQU_COMMAND);
store32(tb, TPM_OSAP_SIZE);
store32(tb, TPM_ORD_OSAP);
store16(tb, type);
store32(tb, handle);
storebytes(tb, ononce, TPM_NONCE_SIZE);
ret = trusted_tpm_send(TPM_ANY_NUM, tb->data, MAX_BUF_SIZE);
if (ret < 0)
return ret;
s->handle = LOAD32(tb->data, TPM_DATA_OFFSET);
memcpy(s->enonce, &(tb->data[TPM_DATA_OFFSET + sizeof(uint32_t)]),
TPM_NONCE_SIZE);
memcpy(enonce, &(tb->data[TPM_DATA_OFFSET + sizeof(uint32_t) +
TPM_NONCE_SIZE]), TPM_NONCE_SIZE);
return TSS_rawhmac(s->secret, key, SHA1_DIGEST_SIZE, TPM_NONCE_SIZE,
enonce, TPM_NONCE_SIZE, ononce, 0, 0);
}
/*
* Create an object independent authorisation protocol (oiap) session
*/
static int oiap(struct tpm_buf *tb, uint32_t *handle, unsigned char *nonce)
{
int ret;
INIT_BUF(tb);
store16(tb, TPM_TAG_RQU_COMMAND);
store32(tb, TPM_OIAP_SIZE);
store32(tb, TPM_ORD_OIAP);
ret = trusted_tpm_send(TPM_ANY_NUM, tb->data, MAX_BUF_SIZE);
if (ret < 0)
return ret;
*handle = LOAD32(tb->data, TPM_DATA_OFFSET);
memcpy(nonce, &tb->data[TPM_DATA_OFFSET + sizeof(uint32_t)],
TPM_NONCE_SIZE);
return 0;
}
struct tpm_digests {
unsigned char encauth[SHA1_DIGEST_SIZE];
unsigned char pubauth[SHA1_DIGEST_SIZE];
unsigned char xorwork[SHA1_DIGEST_SIZE * 2];
unsigned char xorhash[SHA1_DIGEST_SIZE];
unsigned char nonceodd[TPM_NONCE_SIZE];
};
/*
* Have the TPM seal(encrypt) the trusted key, possibly based on
* Platform Configuration Registers (PCRs). AUTH1 for sealing key.
*/
static int tpm_seal(struct tpm_buf *tb, uint16_t keytype,
uint32_t keyhandle, const unsigned char *keyauth,
const unsigned char *data, uint32_t datalen,
unsigned char *blob, uint32_t *bloblen,
const unsigned char *blobauth,
const unsigned char *pcrinfo, uint32_t pcrinfosize)
{
struct osapsess sess;
struct tpm_digests *td;
unsigned char cont;
uint32_t ordinal;
uint32_t pcrsize;
uint32_t datsize;
int sealinfosize;
int encdatasize;
int storedsize;
int ret;
int i;
/* alloc some work space for all the hashes */
td = kmalloc(sizeof *td, GFP_KERNEL);
if (!td)
return -ENOMEM;
/* get session for sealing key */
ret = osap(tb, &sess, keyauth, keytype, keyhandle);
if (ret < 0)
goto out;
dump_sess(&sess);
/* calculate encrypted authorization value */
memcpy(td->xorwork, sess.secret, SHA1_DIGEST_SIZE);
memcpy(td->xorwork + SHA1_DIGEST_SIZE, sess.enonce, SHA1_DIGEST_SIZE);
ret = TSS_sha1(td->xorwork, SHA1_DIGEST_SIZE * 2, td->xorhash);
if (ret < 0)
goto out;
ret = tpm_get_random(TPM_ANY_NUM, td->nonceodd, TPM_NONCE_SIZE);
if (ret != TPM_NONCE_SIZE)
goto out;
ordinal = htonl(TPM_ORD_SEAL);
datsize = htonl(datalen);
pcrsize = htonl(pcrinfosize);
cont = 0;
/* encrypt data authorization key */
for (i = 0; i < SHA1_DIGEST_SIZE; ++i)
td->encauth[i] = td->xorhash[i] ^ blobauth[i];
/* calculate authorization HMAC value */
if (pcrinfosize == 0) {
/* no pcr info specified */
ret = TSS_authhmac(td->pubauth, sess.secret, SHA1_DIGEST_SIZE,
sess.enonce, td->nonceodd, cont,
sizeof(uint32_t), &ordinal, SHA1_DIGEST_SIZE,
td->encauth, sizeof(uint32_t), &pcrsize,
sizeof(uint32_t), &datsize, datalen, data, 0,
0);
} else {
/* pcr info specified */
ret = TSS_authhmac(td->pubauth, sess.secret, SHA1_DIGEST_SIZE,
sess.enonce, td->nonceodd, cont,
sizeof(uint32_t), &ordinal, SHA1_DIGEST_SIZE,
td->encauth, sizeof(uint32_t), &pcrsize,
pcrinfosize, pcrinfo, sizeof(uint32_t),
&datsize, datalen, data, 0, 0);
}
if (ret < 0)
goto out;
/* build and send the TPM request packet */
INIT_BUF(tb);
store16(tb, TPM_TAG_RQU_AUTH1_COMMAND);
store32(tb, TPM_SEAL_SIZE + pcrinfosize + datalen);
store32(tb, TPM_ORD_SEAL);
store32(tb, keyhandle);
storebytes(tb, td->encauth, SHA1_DIGEST_SIZE);
store32(tb, pcrinfosize);
storebytes(tb, pcrinfo, pcrinfosize);
store32(tb, datalen);
storebytes(tb, data, datalen);
store32(tb, sess.handle);
storebytes(tb, td->nonceodd, TPM_NONCE_SIZE);
store8(tb, cont);
storebytes(tb, td->pubauth, SHA1_DIGEST_SIZE);
ret = trusted_tpm_send(TPM_ANY_NUM, tb->data, MAX_BUF_SIZE);
if (ret < 0)
goto out;
/* calculate the size of the returned Blob */
sealinfosize = LOAD32(tb->data, TPM_DATA_OFFSET + sizeof(uint32_t));
encdatasize = LOAD32(tb->data, TPM_DATA_OFFSET + sizeof(uint32_t) +
sizeof(uint32_t) + sealinfosize);
storedsize = sizeof(uint32_t) + sizeof(uint32_t) + sealinfosize +
sizeof(uint32_t) + encdatasize;
/* check the HMAC in the response */
ret = TSS_checkhmac1(tb->data, ordinal, td->nonceodd, sess.secret,
SHA1_DIGEST_SIZE, storedsize, TPM_DATA_OFFSET, 0,
0);
/* copy the returned blob to caller */
if (!ret) {
memcpy(blob, tb->data + TPM_DATA_OFFSET, storedsize);
*bloblen = storedsize;
}
out:
kzfree(td);
return ret;
}
/*
* use the AUTH2_COMMAND form of unseal, to authorize both key and blob
*/
static int tpm_unseal(struct tpm_buf *tb,
uint32_t keyhandle, const unsigned char *keyauth,
const unsigned char *blob, int bloblen,
const unsigned char *blobauth,
unsigned char *data, unsigned int *datalen)
{
unsigned char nonceodd[TPM_NONCE_SIZE];
unsigned char enonce1[TPM_NONCE_SIZE];
unsigned char enonce2[TPM_NONCE_SIZE];
unsigned char authdata1[SHA1_DIGEST_SIZE];
unsigned char authdata2[SHA1_DIGEST_SIZE];
uint32_t authhandle1 = 0;
uint32_t authhandle2 = 0;
unsigned char cont = 0;
uint32_t ordinal;
uint32_t keyhndl;
int ret;
/* sessions for unsealing key and data */
ret = oiap(tb, &authhandle1, enonce1);
if (ret < 0) {
pr_info("trusted_key: oiap failed (%d)\n", ret);
return ret;
}
ret = oiap(tb, &authhandle2, enonce2);
if (ret < 0) {
pr_info("trusted_key: oiap failed (%d)\n", ret);
return ret;
}
ordinal = htonl(TPM_ORD_UNSEAL);
keyhndl = htonl(SRKHANDLE);
ret = tpm_get_random(TPM_ANY_NUM, nonceodd, TPM_NONCE_SIZE);
if (ret != TPM_NONCE_SIZE) {
pr_info("trusted_key: tpm_get_random failed (%d)\n", ret);
return ret;
}
ret = TSS_authhmac(authdata1, keyauth, TPM_NONCE_SIZE,
enonce1, nonceodd, cont, sizeof(uint32_t),
&ordinal, bloblen, blob, 0, 0);
if (ret < 0)
return ret;
ret = TSS_authhmac(authdata2, blobauth, TPM_NONCE_SIZE,
enonce2, nonceodd, cont, sizeof(uint32_t),
&ordinal, bloblen, blob, 0, 0);
if (ret < 0)
return ret;
/* build and send TPM request packet */
INIT_BUF(tb);
store16(tb, TPM_TAG_RQU_AUTH2_COMMAND);
store32(tb, TPM_UNSEAL_SIZE + bloblen);
store32(tb, TPM_ORD_UNSEAL);
store32(tb, keyhandle);
storebytes(tb, blob, bloblen);
store32(tb, authhandle1);
storebytes(tb, nonceodd, TPM_NONCE_SIZE);
store8(tb, cont);
storebytes(tb, authdata1, SHA1_DIGEST_SIZE);
store32(tb, authhandle2);
storebytes(tb, nonceodd, TPM_NONCE_SIZE);
store8(tb, cont);
storebytes(tb, authdata2, SHA1_DIGEST_SIZE);
ret = trusted_tpm_send(TPM_ANY_NUM, tb->data, MAX_BUF_SIZE);
if (ret < 0) {
pr_info("trusted_key: authhmac failed (%d)\n", ret);
return ret;
}
*datalen = LOAD32(tb->data, TPM_DATA_OFFSET);
ret = TSS_checkhmac2(tb->data, ordinal, nonceodd,
keyauth, SHA1_DIGEST_SIZE,
blobauth, SHA1_DIGEST_SIZE,
sizeof(uint32_t), TPM_DATA_OFFSET,
*datalen, TPM_DATA_OFFSET + sizeof(uint32_t), 0,
0);
if (ret < 0) {
pr_info("trusted_key: TSS_checkhmac2 failed (%d)\n", ret);
return ret;
}
memcpy(data, tb->data + TPM_DATA_OFFSET + sizeof(uint32_t), *datalen);
return 0;
}
/*
* Have the TPM seal(encrypt) the symmetric key
*/
static int key_seal(struct trusted_key_payload *p,
struct trusted_key_options *o)
{
struct tpm_buf *tb;
int ret;
tb = kzalloc(sizeof *tb, GFP_KERNEL);
if (!tb)
return -ENOMEM;
/* include migratable flag at end of sealed key */
p->key[p->key_len] = p->migratable;
ret = tpm_seal(tb, o->keytype, o->keyhandle, o->keyauth,
p->key, p->key_len + 1, p->blob, &p->blob_len,
o->blobauth, o->pcrinfo, o->pcrinfo_len);
if (ret < 0)
pr_info("trusted_key: srkseal failed (%d)\n", ret);
kzfree(tb);
return ret;
}
/*
* Have the TPM unseal(decrypt) the symmetric key
*/
static int key_unseal(struct trusted_key_payload *p,
struct trusted_key_options *o)
{
struct tpm_buf *tb;
int ret;
tb = kzalloc(sizeof *tb, GFP_KERNEL);
if (!tb)
return -ENOMEM;
ret = tpm_unseal(tb, o->keyhandle, o->keyauth, p->blob, p->blob_len,
o->blobauth, p->key, &p->key_len);
if (ret < 0)
pr_info("trusted_key: srkunseal failed (%d)\n", ret);
else
/* pull migratable flag out of sealed key */
p->migratable = p->key[--p->key_len];
kzfree(tb);
return ret;
}
enum {
Opt_err = -1,
Opt_new, Opt_load, Opt_update,
Opt_keyhandle, Opt_keyauth, Opt_blobauth,
Opt_pcrinfo, Opt_pcrlock, Opt_migratable,
Opt_hash,
Opt_policydigest,
Opt_policyhandle,
};
static const match_table_t key_tokens = {
{Opt_new, "new"},
{Opt_load, "load"},
{Opt_update, "update"},
{Opt_keyhandle, "keyhandle=%s"},
{Opt_keyauth, "keyauth=%s"},
{Opt_blobauth, "blobauth=%s"},
{Opt_pcrinfo, "pcrinfo=%s"},
{Opt_pcrlock, "pcrlock=%s"},
{Opt_migratable, "migratable=%s"},
{Opt_hash, "hash=%s"},
{Opt_policydigest, "policydigest=%s"},
{Opt_policyhandle, "policyhandle=%s"},
{Opt_err, NULL}
};
/* can have zero or more token= options */
static int getoptions(char *c, struct trusted_key_payload *pay,
struct trusted_key_options *opt)
{
substring_t args[MAX_OPT_ARGS];
char *p = c;
int token;
int res;
unsigned long handle;
unsigned long lock;
unsigned long token_mask = 0;
unsigned int digest_len;
int i;
int tpm2;
tpm2 = tpm_is_tpm2(TPM_ANY_NUM);
if (tpm2 < 0)
return tpm2;
opt->hash = tpm2 ? HASH_ALGO_SHA256 : HASH_ALGO_SHA1;
while ((p = strsep(&c, " \t"))) {
if (*p == '\0' || *p == ' ' || *p == '\t')
continue;
token = match_token(p, key_tokens, args);
if (test_and_set_bit(token, &token_mask))
return -EINVAL;
switch (token) {
case Opt_pcrinfo:
opt->pcrinfo_len = strlen(args[0].from) / 2;
if (opt->pcrinfo_len > MAX_PCRINFO_SIZE)
return -EINVAL;
res = hex2bin(opt->pcrinfo, args[0].from,
opt->pcrinfo_len);
if (res < 0)
return -EINVAL;
break;
case Opt_keyhandle:
res = kstrtoul(args[0].from, 16, &handle);
if (res < 0)
return -EINVAL;
opt->keytype = SEAL_keytype;
opt->keyhandle = handle;
break;
case Opt_keyauth:
if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
return -EINVAL;
res = hex2bin(opt->keyauth, args[0].from,
SHA1_DIGEST_SIZE);
if (res < 0)
return -EINVAL;
break;
case Opt_blobauth:
if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
return -EINVAL;
res = hex2bin(opt->blobauth, args[0].from,
SHA1_DIGEST_SIZE);
if (res < 0)
return -EINVAL;
break;
case Opt_migratable:
if (*args[0].from == '0')
pay->migratable = 0;
else
return -EINVAL;
break;
case Opt_pcrlock:
res = kstrtoul(args[0].from, 10, &lock);
if (res < 0)
return -EINVAL;
opt->pcrlock = lock;
break;
case Opt_hash:
if (test_bit(Opt_policydigest, &token_mask))
return -EINVAL;
for (i = 0; i < HASH_ALGO__LAST; i++) {
if (!strcmp(args[0].from, hash_algo_name[i])) {
opt->hash = i;
break;
}
}
if (i == HASH_ALGO__LAST)
return -EINVAL;
if (!tpm2 && i != HASH_ALGO_SHA1) {
pr_info("trusted_key: TPM 1.x only supports SHA-1.\n");
return -EINVAL;
}
break;
case Opt_policydigest:
digest_len = hash_digest_size[opt->hash];
if (!tpm2 || strlen(args[0].from) != (2 * digest_len))
return -EINVAL;
res = hex2bin(opt->policydigest, args[0].from,
digest_len);
if (res < 0)
return -EINVAL;
opt->policydigest_len = digest_len;
break;
case Opt_policyhandle:
if (!tpm2)
return -EINVAL;
res = kstrtoul(args[0].from, 16, &handle);
if (res < 0)
return -EINVAL;
opt->policyhandle = handle;
break;
default:
return -EINVAL;
}
}
return 0;
}
/*
* datablob_parse - parse the keyctl data and fill in the
* payload and options structures
*
* On success returns 0, otherwise -EINVAL.
*/
static int datablob_parse(char *datablob, struct trusted_key_payload *p,
struct trusted_key_options *o)
{
substring_t args[MAX_OPT_ARGS];
long keylen;
int ret = -EINVAL;
int key_cmd;
char *c;
/* main command */
c = strsep(&datablob, " \t");
if (!c)
return -EINVAL;
key_cmd = match_token(c, key_tokens, args);
switch (key_cmd) {
case Opt_new:
/* first argument is key size */
c = strsep(&datablob, " \t");
if (!c)
return -EINVAL;
ret = kstrtol(c, 10, &keylen);
if (ret < 0 || keylen < MIN_KEY_SIZE || keylen > MAX_KEY_SIZE)
return -EINVAL;
p->key_len = keylen;
ret = getoptions(datablob, p, o);
if (ret < 0)
return ret;
ret = Opt_new;
break;
case Opt_load:
/* first argument is sealed blob */
c = strsep(&datablob, " \t");
if (!c)
return -EINVAL;
p->blob_len = strlen(c) / 2;
if (p->blob_len > MAX_BLOB_SIZE)
return -EINVAL;
ret = hex2bin(p->blob, c, p->blob_len);
if (ret < 0)
return -EINVAL;
ret = getoptions(datablob, p, o);
if (ret < 0)
return ret;
ret = Opt_load;
break;
case Opt_update:
/* all arguments are options */
ret = getoptions(datablob, p, o);
if (ret < 0)
return ret;
ret = Opt_update;
break;
case Opt_err:
return -EINVAL;
break;
}
return ret;
}
static struct trusted_key_options *trusted_options_alloc(void)
{
struct trusted_key_options *options;
int tpm2;
tpm2 = tpm_is_tpm2(TPM_ANY_NUM);
if (tpm2 < 0)
return NULL;
options = kzalloc(sizeof *options, GFP_KERNEL);
if (options) {
/* set any non-zero defaults */
options->keytype = SRK_keytype;
if (!tpm2)
options->keyhandle = SRKHANDLE;
}
return options;
}
static struct trusted_key_payload *trusted_payload_alloc(struct key *key)
{
struct trusted_key_payload *p = NULL;
int ret;
ret = key_payload_reserve(key, sizeof *p);
if (ret < 0)
return p;
p = kzalloc(sizeof *p, GFP_KERNEL);
if (p)
p->migratable = 1; /* migratable by default */
return p;
}
/*
* trusted_instantiate - create a new trusted key
*
* Unseal an existing trusted blob or, for a new key, get a
* random key, then seal and create a trusted key-type key,
* adding it to the specified keyring.
*
* On success, return 0. Otherwise return errno.
*/
static int trusted_instantiate(struct key *key,
struct key_preparsed_payload *prep)
{
struct trusted_key_payload *payload = NULL;
struct trusted_key_options *options = NULL;
size_t datalen = prep->datalen;
char *datablob;
int ret = 0;
int key_cmd;
size_t key_len;
int tpm2;
tpm2 = tpm_is_tpm2(TPM_ANY_NUM);
if (tpm2 < 0)
return tpm2;
if (datalen <= 0 || datalen > 32767 || !prep->data)
return -EINVAL;
datablob = kmalloc(datalen + 1, GFP_KERNEL);
if (!datablob)
return -ENOMEM;
memcpy(datablob, prep->data, datalen);
datablob[datalen] = '\0';
options = trusted_options_alloc();
if (!options) {
ret = -ENOMEM;
goto out;
}
payload = trusted_payload_alloc(key);
if (!payload) {
ret = -ENOMEM;
goto out;
}
key_cmd = datablob_parse(datablob, payload, options);
if (key_cmd < 0) {
ret = key_cmd;
goto out;
}
if (!options->keyhandle) {
ret = -EINVAL;
goto out;
}
dump_payload(payload);
dump_options(options);
switch (key_cmd) {
case Opt_load:
if (tpm2)
ret = tpm_unseal_trusted(TPM_ANY_NUM, payload, options);
else
ret = key_unseal(payload, options);
dump_payload(payload);
dump_options(options);
if (ret < 0)
pr_info("trusted_key: key_unseal failed (%d)\n", ret);
break;
case Opt_new:
key_len = payload->key_len;
ret = tpm_get_random(TPM_ANY_NUM, payload->key, key_len);
if (ret != key_len) {
pr_info("trusted_key: key_create failed (%d)\n", ret);
goto out;
}
if (tpm2)
ret = tpm_seal_trusted(TPM_ANY_NUM, payload, options);
else
ret = key_seal(payload, options);
if (ret < 0)
pr_info("trusted_key: key_seal failed (%d)\n", ret);
break;
default:
ret = -EINVAL;
goto out;
}
if (!ret && options->pcrlock)
ret = pcrlock(options->pcrlock);
out:
kzfree(datablob);
kzfree(options);
if (!ret)
rcu_assign_keypointer(key, payload);
else
kzfree(payload);
return ret;
}
static void trusted_rcu_free(struct rcu_head *rcu)
{
struct trusted_key_payload *p;
p = container_of(rcu, struct trusted_key_payload, rcu);
kzfree(p);
}
/*
* trusted_update - reseal an existing key with new PCR values
*/
static int trusted_update(struct key *key, struct key_preparsed_payload *prep)
{
struct trusted_key_payload *p;
struct trusted_key_payload *new_p;
struct trusted_key_options *new_o;
size_t datalen = prep->datalen;
char *datablob;
int ret = 0;
if (key_is_negative(key))
return -ENOKEY;
p = key->payload.data[0];
if (!p->migratable)
return -EPERM;
if (datalen <= 0 || datalen > 32767 || !prep->data)
return -EINVAL;
datablob = kmalloc(datalen + 1, GFP_KERNEL);
if (!datablob)
return -ENOMEM;
new_o = trusted_options_alloc();
if (!new_o) {
ret = -ENOMEM;
goto out;
}
new_p = trusted_payload_alloc(key);
if (!new_p) {
ret = -ENOMEM;
goto out;
}
memcpy(datablob, prep->data, datalen);
datablob[datalen] = '\0';
ret = datablob_parse(datablob, new_p, new_o);
if (ret != Opt_update) {
ret = -EINVAL;
kzfree(new_p);
goto out;
}
if (!new_o->keyhandle) {
ret = -EINVAL;
kzfree(new_p);
goto out;
}
/* copy old key values, and reseal with new pcrs */
new_p->migratable = p->migratable;
new_p->key_len = p->key_len;
memcpy(new_p->key, p->key, p->key_len);
dump_payload(p);
dump_payload(new_p);
ret = key_seal(new_p, new_o);
if (ret < 0) {
pr_info("trusted_key: key_seal failed (%d)\n", ret);
kzfree(new_p);
goto out;
}
if (new_o->pcrlock) {
ret = pcrlock(new_o->pcrlock);
if (ret < 0) {
pr_info("trusted_key: pcrlock failed (%d)\n", ret);
kzfree(new_p);
goto out;
}
}
rcu_assign_keypointer(key, new_p);
call_rcu(&p->rcu, trusted_rcu_free);
out:
kzfree(datablob);
kzfree(new_o);
return ret;
}
/*
* trusted_read - copy the sealed blob data to userspace in hex.
* On success, return to userspace the trusted key datablob size.
*/
static long trusted_read(const struct key *key, char __user *buffer,
size_t buflen)
{
const struct trusted_key_payload *p;
char *ascii_buf;
char *bufp;
int i;
p = dereference_key_locked(key);
if (!p)
return -EINVAL;
if (!buffer || buflen <= 0)
return 2 * p->blob_len;
ascii_buf = kmalloc(2 * p->blob_len, GFP_KERNEL);
if (!ascii_buf)
return -ENOMEM;
bufp = ascii_buf;
for (i = 0; i < p->blob_len; i++)
bufp = hex_byte_pack(bufp, p->blob[i]);
if ((copy_to_user(buffer, ascii_buf, 2 * p->blob_len)) != 0) {
kzfree(ascii_buf);
return -EFAULT;
}
kzfree(ascii_buf);
return 2 * p->blob_len;
}
/*
* trusted_destroy - clear and free the key's payload
*/
static void trusted_destroy(struct key *key)
{
kzfree(key->payload.data[0]);
}
struct key_type key_type_trusted = {
.name = "trusted",
.instantiate = trusted_instantiate,
.update = trusted_update,
.destroy = trusted_destroy,
.describe = user_describe,
.read = trusted_read,
};
EXPORT_SYMBOL_GPL(key_type_trusted);
static void trusted_shash_release(void)
{
if (hashalg)
crypto_free_shash(hashalg);
if (hmacalg)
crypto_free_shash(hmacalg);
}
static int __init trusted_shash_alloc(void)
{
int ret;
hmacalg = crypto_alloc_shash(hmac_alg, 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(hmacalg)) {
pr_info("trusted_key: could not allocate crypto %s\n",
hmac_alg);
return PTR_ERR(hmacalg);
}
hashalg = crypto_alloc_shash(hash_alg, 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(hashalg)) {
pr_info("trusted_key: could not allocate crypto %s\n",
hash_alg);
ret = PTR_ERR(hashalg);
goto hashalg_fail;
}
return 0;
hashalg_fail:
crypto_free_shash(hmacalg);
return ret;
}
static int __init init_trusted(void)
{
int ret;
ret = trusted_shash_alloc();
if (ret < 0)
return ret;
ret = register_key_type(&key_type_trusted);
if (ret < 0)
trusted_shash_release();
return ret;
}
static void __exit cleanup_trusted(void)
{
trusted_shash_release();
unregister_key_type(&key_type_trusted);
}
late_initcall(init_trusted);
module_exit(cleanup_trusted);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2891_12 |
crossvul-cpp_data_good_2080_0 | /*
* Implementation of the security services.
*
* Authors : Stephen Smalley, <sds@epoch.ncsc.mil>
* James Morris <jmorris@redhat.com>
*
* Updated: Trusted Computer Solutions, Inc. <dgoeddel@trustedcs.com>
*
* Support for enhanced MLS infrastructure.
* Support for context based audit filters.
*
* Updated: Frank Mayer <mayerf@tresys.com> and Karl MacMillan <kmacmillan@tresys.com>
*
* Added conditional policy language extensions
*
* Updated: Hewlett-Packard <paul@paul-moore.com>
*
* Added support for NetLabel
* Added support for the policy capability bitmap
*
* Updated: Chad Sellers <csellers@tresys.com>
*
* Added validation of kernel classes and permissions
*
* Updated: KaiGai Kohei <kaigai@ak.jp.nec.com>
*
* Added support for bounds domain and audit messaged on masked permissions
*
* Updated: Guido Trentalancia <guido@trentalancia.com>
*
* Added support for runtime switching of the policy type
*
* Copyright (C) 2008, 2009 NEC Corporation
* Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P.
* Copyright (C) 2004-2006 Trusted Computer Solutions, Inc.
* Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC
* Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2.
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/spinlock.h>
#include <linux/rcupdate.h>
#include <linux/errno.h>
#include <linux/in.h>
#include <linux/sched.h>
#include <linux/audit.h>
#include <linux/mutex.h>
#include <linux/selinux.h>
#include <linux/flex_array.h>
#include <linux/vmalloc.h>
#include <net/netlabel.h>
#include "flask.h"
#include "avc.h"
#include "avc_ss.h"
#include "security.h"
#include "context.h"
#include "policydb.h"
#include "sidtab.h"
#include "services.h"
#include "conditional.h"
#include "mls.h"
#include "objsec.h"
#include "netlabel.h"
#include "xfrm.h"
#include "ebitmap.h"
#include "audit.h"
int selinux_policycap_netpeer;
int selinux_policycap_openperm;
int selinux_policycap_alwaysnetwork;
static DEFINE_RWLOCK(policy_rwlock);
static struct sidtab sidtab;
struct policydb policydb;
int ss_initialized;
/*
* The largest sequence number that has been used when
* providing an access decision to the access vector cache.
* The sequence number only changes when a policy change
* occurs.
*/
static u32 latest_granting;
/* Forward declaration. */
static int context_struct_to_string(struct context *context, char **scontext,
u32 *scontext_len);
static void context_struct_compute_av(struct context *scontext,
struct context *tcontext,
u16 tclass,
struct av_decision *avd);
struct selinux_mapping {
u16 value; /* policy value */
unsigned num_perms;
u32 perms[sizeof(u32) * 8];
};
static struct selinux_mapping *current_mapping;
static u16 current_mapping_size;
static int selinux_set_mapping(struct policydb *pol,
struct security_class_mapping *map,
struct selinux_mapping **out_map_p,
u16 *out_map_size)
{
struct selinux_mapping *out_map = NULL;
size_t size = sizeof(struct selinux_mapping);
u16 i, j;
unsigned k;
bool print_unknown_handle = false;
/* Find number of classes in the input mapping */
if (!map)
return -EINVAL;
i = 0;
while (map[i].name)
i++;
/* Allocate space for the class records, plus one for class zero */
out_map = kcalloc(++i, size, GFP_ATOMIC);
if (!out_map)
return -ENOMEM;
/* Store the raw class and permission values */
j = 0;
while (map[j].name) {
struct security_class_mapping *p_in = map + (j++);
struct selinux_mapping *p_out = out_map + j;
/* An empty class string skips ahead */
if (!strcmp(p_in->name, "")) {
p_out->num_perms = 0;
continue;
}
p_out->value = string_to_security_class(pol, p_in->name);
if (!p_out->value) {
printk(KERN_INFO
"SELinux: Class %s not defined in policy.\n",
p_in->name);
if (pol->reject_unknown)
goto err;
p_out->num_perms = 0;
print_unknown_handle = true;
continue;
}
k = 0;
while (p_in->perms && p_in->perms[k]) {
/* An empty permission string skips ahead */
if (!*p_in->perms[k]) {
k++;
continue;
}
p_out->perms[k] = string_to_av_perm(pol, p_out->value,
p_in->perms[k]);
if (!p_out->perms[k]) {
printk(KERN_INFO
"SELinux: Permission %s in class %s not defined in policy.\n",
p_in->perms[k], p_in->name);
if (pol->reject_unknown)
goto err;
print_unknown_handle = true;
}
k++;
}
p_out->num_perms = k;
}
if (print_unknown_handle)
printk(KERN_INFO "SELinux: the above unknown classes and permissions will be %s\n",
pol->allow_unknown ? "allowed" : "denied");
*out_map_p = out_map;
*out_map_size = i;
return 0;
err:
kfree(out_map);
return -EINVAL;
}
/*
* Get real, policy values from mapped values
*/
static u16 unmap_class(u16 tclass)
{
if (tclass < current_mapping_size)
return current_mapping[tclass].value;
return tclass;
}
/*
* Get kernel value for class from its policy value
*/
static u16 map_class(u16 pol_value)
{
u16 i;
for (i = 1; i < current_mapping_size; i++) {
if (current_mapping[i].value == pol_value)
return i;
}
return SECCLASS_NULL;
}
static void map_decision(u16 tclass, struct av_decision *avd,
int allow_unknown)
{
if (tclass < current_mapping_size) {
unsigned i, n = current_mapping[tclass].num_perms;
u32 result;
for (i = 0, result = 0; i < n; i++) {
if (avd->allowed & current_mapping[tclass].perms[i])
result |= 1<<i;
if (allow_unknown && !current_mapping[tclass].perms[i])
result |= 1<<i;
}
avd->allowed = result;
for (i = 0, result = 0; i < n; i++)
if (avd->auditallow & current_mapping[tclass].perms[i])
result |= 1<<i;
avd->auditallow = result;
for (i = 0, result = 0; i < n; i++) {
if (avd->auditdeny & current_mapping[tclass].perms[i])
result |= 1<<i;
if (!allow_unknown && !current_mapping[tclass].perms[i])
result |= 1<<i;
}
/*
* In case the kernel has a bug and requests a permission
* between num_perms and the maximum permission number, we
* should audit that denial
*/
for (; i < (sizeof(u32)*8); i++)
result |= 1<<i;
avd->auditdeny = result;
}
}
int security_mls_enabled(void)
{
return policydb.mls_enabled;
}
/*
* Return the boolean value of a constraint expression
* when it is applied to the specified source and target
* security contexts.
*
* xcontext is a special beast... It is used by the validatetrans rules
* only. For these rules, scontext is the context before the transition,
* tcontext is the context after the transition, and xcontext is the context
* of the process performing the transition. All other callers of
* constraint_expr_eval should pass in NULL for xcontext.
*/
static int constraint_expr_eval(struct context *scontext,
struct context *tcontext,
struct context *xcontext,
struct constraint_expr *cexpr)
{
u32 val1, val2;
struct context *c;
struct role_datum *r1, *r2;
struct mls_level *l1, *l2;
struct constraint_expr *e;
int s[CEXPR_MAXDEPTH];
int sp = -1;
for (e = cexpr; e; e = e->next) {
switch (e->expr_type) {
case CEXPR_NOT:
BUG_ON(sp < 0);
s[sp] = !s[sp];
break;
case CEXPR_AND:
BUG_ON(sp < 1);
sp--;
s[sp] &= s[sp + 1];
break;
case CEXPR_OR:
BUG_ON(sp < 1);
sp--;
s[sp] |= s[sp + 1];
break;
case CEXPR_ATTR:
if (sp == (CEXPR_MAXDEPTH - 1))
return 0;
switch (e->attr) {
case CEXPR_USER:
val1 = scontext->user;
val2 = tcontext->user;
break;
case CEXPR_TYPE:
val1 = scontext->type;
val2 = tcontext->type;
break;
case CEXPR_ROLE:
val1 = scontext->role;
val2 = tcontext->role;
r1 = policydb.role_val_to_struct[val1 - 1];
r2 = policydb.role_val_to_struct[val2 - 1];
switch (e->op) {
case CEXPR_DOM:
s[++sp] = ebitmap_get_bit(&r1->dominates,
val2 - 1);
continue;
case CEXPR_DOMBY:
s[++sp] = ebitmap_get_bit(&r2->dominates,
val1 - 1);
continue;
case CEXPR_INCOMP:
s[++sp] = (!ebitmap_get_bit(&r1->dominates,
val2 - 1) &&
!ebitmap_get_bit(&r2->dominates,
val1 - 1));
continue;
default:
break;
}
break;
case CEXPR_L1L2:
l1 = &(scontext->range.level[0]);
l2 = &(tcontext->range.level[0]);
goto mls_ops;
case CEXPR_L1H2:
l1 = &(scontext->range.level[0]);
l2 = &(tcontext->range.level[1]);
goto mls_ops;
case CEXPR_H1L2:
l1 = &(scontext->range.level[1]);
l2 = &(tcontext->range.level[0]);
goto mls_ops;
case CEXPR_H1H2:
l1 = &(scontext->range.level[1]);
l2 = &(tcontext->range.level[1]);
goto mls_ops;
case CEXPR_L1H1:
l1 = &(scontext->range.level[0]);
l2 = &(scontext->range.level[1]);
goto mls_ops;
case CEXPR_L2H2:
l1 = &(tcontext->range.level[0]);
l2 = &(tcontext->range.level[1]);
goto mls_ops;
mls_ops:
switch (e->op) {
case CEXPR_EQ:
s[++sp] = mls_level_eq(l1, l2);
continue;
case CEXPR_NEQ:
s[++sp] = !mls_level_eq(l1, l2);
continue;
case CEXPR_DOM:
s[++sp] = mls_level_dom(l1, l2);
continue;
case CEXPR_DOMBY:
s[++sp] = mls_level_dom(l2, l1);
continue;
case CEXPR_INCOMP:
s[++sp] = mls_level_incomp(l2, l1);
continue;
default:
BUG();
return 0;
}
break;
default:
BUG();
return 0;
}
switch (e->op) {
case CEXPR_EQ:
s[++sp] = (val1 == val2);
break;
case CEXPR_NEQ:
s[++sp] = (val1 != val2);
break;
default:
BUG();
return 0;
}
break;
case CEXPR_NAMES:
if (sp == (CEXPR_MAXDEPTH-1))
return 0;
c = scontext;
if (e->attr & CEXPR_TARGET)
c = tcontext;
else if (e->attr & CEXPR_XTARGET) {
c = xcontext;
if (!c) {
BUG();
return 0;
}
}
if (e->attr & CEXPR_USER)
val1 = c->user;
else if (e->attr & CEXPR_ROLE)
val1 = c->role;
else if (e->attr & CEXPR_TYPE)
val1 = c->type;
else {
BUG();
return 0;
}
switch (e->op) {
case CEXPR_EQ:
s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
break;
case CEXPR_NEQ:
s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
break;
default:
BUG();
return 0;
}
break;
default:
BUG();
return 0;
}
}
BUG_ON(sp != 0);
return s[0];
}
/*
* security_dump_masked_av - dumps masked permissions during
* security_compute_av due to RBAC, MLS/Constraint and Type bounds.
*/
static int dump_masked_av_helper(void *k, void *d, void *args)
{
struct perm_datum *pdatum = d;
char **permission_names = args;
BUG_ON(pdatum->value < 1 || pdatum->value > 32);
permission_names[pdatum->value - 1] = (char *)k;
return 0;
}
static void security_dump_masked_av(struct context *scontext,
struct context *tcontext,
u16 tclass,
u32 permissions,
const char *reason)
{
struct common_datum *common_dat;
struct class_datum *tclass_dat;
struct audit_buffer *ab;
char *tclass_name;
char *scontext_name = NULL;
char *tcontext_name = NULL;
char *permission_names[32];
int index;
u32 length;
bool need_comma = false;
if (!permissions)
return;
tclass_name = sym_name(&policydb, SYM_CLASSES, tclass - 1);
tclass_dat = policydb.class_val_to_struct[tclass - 1];
common_dat = tclass_dat->comdatum;
/* init permission_names */
if (common_dat &&
hashtab_map(common_dat->permissions.table,
dump_masked_av_helper, permission_names) < 0)
goto out;
if (hashtab_map(tclass_dat->permissions.table,
dump_masked_av_helper, permission_names) < 0)
goto out;
/* get scontext/tcontext in text form */
if (context_struct_to_string(scontext,
&scontext_name, &length) < 0)
goto out;
if (context_struct_to_string(tcontext,
&tcontext_name, &length) < 0)
goto out;
/* audit a message */
ab = audit_log_start(current->audit_context,
GFP_ATOMIC, AUDIT_SELINUX_ERR);
if (!ab)
goto out;
audit_log_format(ab, "op=security_compute_av reason=%s "
"scontext=%s tcontext=%s tclass=%s perms=",
reason, scontext_name, tcontext_name, tclass_name);
for (index = 0; index < 32; index++) {
u32 mask = (1 << index);
if ((mask & permissions) == 0)
continue;
audit_log_format(ab, "%s%s",
need_comma ? "," : "",
permission_names[index]
? permission_names[index] : "????");
need_comma = true;
}
audit_log_end(ab);
out:
/* release scontext/tcontext */
kfree(tcontext_name);
kfree(scontext_name);
return;
}
/*
* security_boundary_permission - drops violated permissions
* on boundary constraint.
*/
static void type_attribute_bounds_av(struct context *scontext,
struct context *tcontext,
u16 tclass,
struct av_decision *avd)
{
struct context lo_scontext;
struct context lo_tcontext;
struct av_decision lo_avd;
struct type_datum *source;
struct type_datum *target;
u32 masked = 0;
source = flex_array_get_ptr(policydb.type_val_to_struct_array,
scontext->type - 1);
BUG_ON(!source);
target = flex_array_get_ptr(policydb.type_val_to_struct_array,
tcontext->type - 1);
BUG_ON(!target);
if (source->bounds) {
memset(&lo_avd, 0, sizeof(lo_avd));
memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
lo_scontext.type = source->bounds;
context_struct_compute_av(&lo_scontext,
tcontext,
tclass,
&lo_avd);
if ((lo_avd.allowed & avd->allowed) == avd->allowed)
return; /* no masked permission */
masked = ~lo_avd.allowed & avd->allowed;
}
if (target->bounds) {
memset(&lo_avd, 0, sizeof(lo_avd));
memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
lo_tcontext.type = target->bounds;
context_struct_compute_av(scontext,
&lo_tcontext,
tclass,
&lo_avd);
if ((lo_avd.allowed & avd->allowed) == avd->allowed)
return; /* no masked permission */
masked = ~lo_avd.allowed & avd->allowed;
}
if (source->bounds && target->bounds) {
memset(&lo_avd, 0, sizeof(lo_avd));
/*
* lo_scontext and lo_tcontext are already
* set up.
*/
context_struct_compute_av(&lo_scontext,
&lo_tcontext,
tclass,
&lo_avd);
if ((lo_avd.allowed & avd->allowed) == avd->allowed)
return; /* no masked permission */
masked = ~lo_avd.allowed & avd->allowed;
}
if (masked) {
/* mask violated permissions */
avd->allowed &= ~masked;
/* audit masked permissions */
security_dump_masked_av(scontext, tcontext,
tclass, masked, "bounds");
}
}
/*
* Compute access vectors based on a context structure pair for
* the permissions in a particular class.
*/
static void context_struct_compute_av(struct context *scontext,
struct context *tcontext,
u16 tclass,
struct av_decision *avd)
{
struct constraint_node *constraint;
struct role_allow *ra;
struct avtab_key avkey;
struct avtab_node *node;
struct class_datum *tclass_datum;
struct ebitmap *sattr, *tattr;
struct ebitmap_node *snode, *tnode;
unsigned int i, j;
avd->allowed = 0;
avd->auditallow = 0;
avd->auditdeny = 0xffffffff;
if (unlikely(!tclass || tclass > policydb.p_classes.nprim)) {
if (printk_ratelimit())
printk(KERN_WARNING "SELinux: Invalid class %hu\n", tclass);
return;
}
tclass_datum = policydb.class_val_to_struct[tclass - 1];
/*
* If a specific type enforcement rule was defined for
* this permission check, then use it.
*/
avkey.target_class = tclass;
avkey.specified = AVTAB_AV;
sattr = flex_array_get(policydb.type_attr_map_array, scontext->type - 1);
BUG_ON(!sattr);
tattr = flex_array_get(policydb.type_attr_map_array, tcontext->type - 1);
BUG_ON(!tattr);
ebitmap_for_each_positive_bit(sattr, snode, i) {
ebitmap_for_each_positive_bit(tattr, tnode, j) {
avkey.source_type = i + 1;
avkey.target_type = j + 1;
for (node = avtab_search_node(&policydb.te_avtab, &avkey);
node;
node = avtab_search_node_next(node, avkey.specified)) {
if (node->key.specified == AVTAB_ALLOWED)
avd->allowed |= node->datum.data;
else if (node->key.specified == AVTAB_AUDITALLOW)
avd->auditallow |= node->datum.data;
else if (node->key.specified == AVTAB_AUDITDENY)
avd->auditdeny &= node->datum.data;
}
/* Check conditional av table for additional permissions */
cond_compute_av(&policydb.te_cond_avtab, &avkey, avd);
}
}
/*
* Remove any permissions prohibited by a constraint (this includes
* the MLS policy).
*/
constraint = tclass_datum->constraints;
while (constraint) {
if ((constraint->permissions & (avd->allowed)) &&
!constraint_expr_eval(scontext, tcontext, NULL,
constraint->expr)) {
avd->allowed &= ~(constraint->permissions);
}
constraint = constraint->next;
}
/*
* If checking process transition permission and the
* role is changing, then check the (current_role, new_role)
* pair.
*/
if (tclass == policydb.process_class &&
(avd->allowed & policydb.process_trans_perms) &&
scontext->role != tcontext->role) {
for (ra = policydb.role_allow; ra; ra = ra->next) {
if (scontext->role == ra->role &&
tcontext->role == ra->new_role)
break;
}
if (!ra)
avd->allowed &= ~policydb.process_trans_perms;
}
/*
* If the given source and target types have boundary
* constraint, lazy checks have to mask any violated
* permission and notice it to userspace via audit.
*/
type_attribute_bounds_av(scontext, tcontext,
tclass, avd);
}
static int security_validtrans_handle_fail(struct context *ocontext,
struct context *ncontext,
struct context *tcontext,
u16 tclass)
{
char *o = NULL, *n = NULL, *t = NULL;
u32 olen, nlen, tlen;
if (context_struct_to_string(ocontext, &o, &olen))
goto out;
if (context_struct_to_string(ncontext, &n, &nlen))
goto out;
if (context_struct_to_string(tcontext, &t, &tlen))
goto out;
audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
"security_validate_transition: denied for"
" oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
o, n, t, sym_name(&policydb, SYM_CLASSES, tclass-1));
out:
kfree(o);
kfree(n);
kfree(t);
if (!selinux_enforcing)
return 0;
return -EPERM;
}
int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid,
u16 orig_tclass)
{
struct context *ocontext;
struct context *ncontext;
struct context *tcontext;
struct class_datum *tclass_datum;
struct constraint_node *constraint;
u16 tclass;
int rc = 0;
if (!ss_initialized)
return 0;
read_lock(&policy_rwlock);
tclass = unmap_class(orig_tclass);
if (!tclass || tclass > policydb.p_classes.nprim) {
printk(KERN_ERR "SELinux: %s: unrecognized class %d\n",
__func__, tclass);
rc = -EINVAL;
goto out;
}
tclass_datum = policydb.class_val_to_struct[tclass - 1];
ocontext = sidtab_search(&sidtab, oldsid);
if (!ocontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, oldsid);
rc = -EINVAL;
goto out;
}
ncontext = sidtab_search(&sidtab, newsid);
if (!ncontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, newsid);
rc = -EINVAL;
goto out;
}
tcontext = sidtab_search(&sidtab, tasksid);
if (!tcontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, tasksid);
rc = -EINVAL;
goto out;
}
constraint = tclass_datum->validatetrans;
while (constraint) {
if (!constraint_expr_eval(ocontext, ncontext, tcontext,
constraint->expr)) {
rc = security_validtrans_handle_fail(ocontext, ncontext,
tcontext, tclass);
goto out;
}
constraint = constraint->next;
}
out:
read_unlock(&policy_rwlock);
return rc;
}
/*
* security_bounded_transition - check whether the given
* transition is directed to bounded, or not.
* It returns 0, if @newsid is bounded by @oldsid.
* Otherwise, it returns error code.
*
* @oldsid : current security identifier
* @newsid : destinated security identifier
*/
int security_bounded_transition(u32 old_sid, u32 new_sid)
{
struct context *old_context, *new_context;
struct type_datum *type;
int index;
int rc;
read_lock(&policy_rwlock);
rc = -EINVAL;
old_context = sidtab_search(&sidtab, old_sid);
if (!old_context) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
__func__, old_sid);
goto out;
}
rc = -EINVAL;
new_context = sidtab_search(&sidtab, new_sid);
if (!new_context) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
__func__, new_sid);
goto out;
}
rc = 0;
/* type/domain unchanged */
if (old_context->type == new_context->type)
goto out;
index = new_context->type;
while (true) {
type = flex_array_get_ptr(policydb.type_val_to_struct_array,
index - 1);
BUG_ON(!type);
/* not bounded anymore */
rc = -EPERM;
if (!type->bounds)
break;
/* @newsid is bounded by @oldsid */
rc = 0;
if (type->bounds == old_context->type)
break;
index = type->bounds;
}
if (rc) {
char *old_name = NULL;
char *new_name = NULL;
u32 length;
if (!context_struct_to_string(old_context,
&old_name, &length) &&
!context_struct_to_string(new_context,
&new_name, &length)) {
audit_log(current->audit_context,
GFP_ATOMIC, AUDIT_SELINUX_ERR,
"op=security_bounded_transition "
"result=denied "
"oldcontext=%s newcontext=%s",
old_name, new_name);
}
kfree(new_name);
kfree(old_name);
}
out:
read_unlock(&policy_rwlock);
return rc;
}
static void avd_init(struct av_decision *avd)
{
avd->allowed = 0;
avd->auditallow = 0;
avd->auditdeny = 0xffffffff;
avd->seqno = latest_granting;
avd->flags = 0;
}
/**
* security_compute_av - Compute access vector decisions.
* @ssid: source security identifier
* @tsid: target security identifier
* @tclass: target security class
* @avd: access vector decisions
*
* Compute a set of access vector decisions based on the
* SID pair (@ssid, @tsid) for the permissions in @tclass.
*/
void security_compute_av(u32 ssid,
u32 tsid,
u16 orig_tclass,
struct av_decision *avd)
{
u16 tclass;
struct context *scontext = NULL, *tcontext = NULL;
read_lock(&policy_rwlock);
avd_init(avd);
if (!ss_initialized)
goto allow;
scontext = sidtab_search(&sidtab, ssid);
if (!scontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, ssid);
goto out;
}
/* permissive domain? */
if (ebitmap_get_bit(&policydb.permissive_map, scontext->type))
avd->flags |= AVD_FLAGS_PERMISSIVE;
tcontext = sidtab_search(&sidtab, tsid);
if (!tcontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, tsid);
goto out;
}
tclass = unmap_class(orig_tclass);
if (unlikely(orig_tclass && !tclass)) {
if (policydb.allow_unknown)
goto allow;
goto out;
}
context_struct_compute_av(scontext, tcontext, tclass, avd);
map_decision(orig_tclass, avd, policydb.allow_unknown);
out:
read_unlock(&policy_rwlock);
return;
allow:
avd->allowed = 0xffffffff;
goto out;
}
void security_compute_av_user(u32 ssid,
u32 tsid,
u16 tclass,
struct av_decision *avd)
{
struct context *scontext = NULL, *tcontext = NULL;
read_lock(&policy_rwlock);
avd_init(avd);
if (!ss_initialized)
goto allow;
scontext = sidtab_search(&sidtab, ssid);
if (!scontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, ssid);
goto out;
}
/* permissive domain? */
if (ebitmap_get_bit(&policydb.permissive_map, scontext->type))
avd->flags |= AVD_FLAGS_PERMISSIVE;
tcontext = sidtab_search(&sidtab, tsid);
if (!tcontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, tsid);
goto out;
}
if (unlikely(!tclass)) {
if (policydb.allow_unknown)
goto allow;
goto out;
}
context_struct_compute_av(scontext, tcontext, tclass, avd);
out:
read_unlock(&policy_rwlock);
return;
allow:
avd->allowed = 0xffffffff;
goto out;
}
/*
* Write the security context string representation of
* the context structure `context' into a dynamically
* allocated string of the correct size. Set `*scontext'
* to point to this string and set `*scontext_len' to
* the length of the string.
*/
static int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len)
{
char *scontextp;
if (scontext)
*scontext = NULL;
*scontext_len = 0;
if (context->len) {
*scontext_len = context->len;
if (scontext) {
*scontext = kstrdup(context->str, GFP_ATOMIC);
if (!(*scontext))
return -ENOMEM;
}
return 0;
}
/* Compute the size of the context. */
*scontext_len += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) + 1;
*scontext_len += strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) + 1;
*scontext_len += strlen(sym_name(&policydb, SYM_TYPES, context->type - 1)) + 1;
*scontext_len += mls_compute_context_len(context);
if (!scontext)
return 0;
/* Allocate space for the context; caller must free this space. */
scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
if (!scontextp)
return -ENOMEM;
*scontext = scontextp;
/*
* Copy the user name, role name and type name into the context.
*/
sprintf(scontextp, "%s:%s:%s",
sym_name(&policydb, SYM_USERS, context->user - 1),
sym_name(&policydb, SYM_ROLES, context->role - 1),
sym_name(&policydb, SYM_TYPES, context->type - 1));
scontextp += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) +
1 + strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) +
1 + strlen(sym_name(&policydb, SYM_TYPES, context->type - 1));
mls_sid_to_context(context, &scontextp);
*scontextp = 0;
return 0;
}
#include "initial_sid_to_string.h"
const char *security_get_initial_sid_context(u32 sid)
{
if (unlikely(sid > SECINITSID_NUM))
return NULL;
return initial_sid_to_string[sid];
}
static int security_sid_to_context_core(u32 sid, char **scontext,
u32 *scontext_len, int force)
{
struct context *context;
int rc = 0;
if (scontext)
*scontext = NULL;
*scontext_len = 0;
if (!ss_initialized) {
if (sid <= SECINITSID_NUM) {
char *scontextp;
*scontext_len = strlen(initial_sid_to_string[sid]) + 1;
if (!scontext)
goto out;
scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
if (!scontextp) {
rc = -ENOMEM;
goto out;
}
strcpy(scontextp, initial_sid_to_string[sid]);
*scontext = scontextp;
goto out;
}
printk(KERN_ERR "SELinux: %s: called before initial "
"load_policy on unknown SID %d\n", __func__, sid);
rc = -EINVAL;
goto out;
}
read_lock(&policy_rwlock);
if (force)
context = sidtab_search_force(&sidtab, sid);
else
context = sidtab_search(&sidtab, sid);
if (!context) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, sid);
rc = -EINVAL;
goto out_unlock;
}
rc = context_struct_to_string(context, scontext, scontext_len);
out_unlock:
read_unlock(&policy_rwlock);
out:
return rc;
}
/**
* security_sid_to_context - Obtain a context for a given SID.
* @sid: security identifier, SID
* @scontext: security context
* @scontext_len: length in bytes
*
* Write the string representation of the context associated with @sid
* into a dynamically allocated string of the correct size. Set @scontext
* to point to this string and set @scontext_len to the length of the string.
*/
int security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len)
{
return security_sid_to_context_core(sid, scontext, scontext_len, 0);
}
int security_sid_to_context_force(u32 sid, char **scontext, u32 *scontext_len)
{
return security_sid_to_context_core(sid, scontext, scontext_len, 1);
}
/*
* Caveat: Mutates scontext.
*/
static int string_to_context_struct(struct policydb *pol,
struct sidtab *sidtabp,
char *scontext,
u32 scontext_len,
struct context *ctx,
u32 def_sid)
{
struct role_datum *role;
struct type_datum *typdatum;
struct user_datum *usrdatum;
char *scontextp, *p, oldc;
int rc = 0;
context_init(ctx);
/* Parse the security context. */
rc = -EINVAL;
scontextp = (char *) scontext;
/* Extract the user. */
p = scontextp;
while (*p && *p != ':')
p++;
if (*p == 0)
goto out;
*p++ = 0;
usrdatum = hashtab_search(pol->p_users.table, scontextp);
if (!usrdatum)
goto out;
ctx->user = usrdatum->value;
/* Extract role. */
scontextp = p;
while (*p && *p != ':')
p++;
if (*p == 0)
goto out;
*p++ = 0;
role = hashtab_search(pol->p_roles.table, scontextp);
if (!role)
goto out;
ctx->role = role->value;
/* Extract type. */
scontextp = p;
while (*p && *p != ':')
p++;
oldc = *p;
*p++ = 0;
typdatum = hashtab_search(pol->p_types.table, scontextp);
if (!typdatum || typdatum->attribute)
goto out;
ctx->type = typdatum->value;
rc = mls_context_to_sid(pol, oldc, &p, ctx, sidtabp, def_sid);
if (rc)
goto out;
rc = -EINVAL;
if ((p - scontext) < scontext_len)
goto out;
/* Check the validity of the new context. */
if (!policydb_context_isvalid(pol, ctx))
goto out;
rc = 0;
out:
if (rc)
context_destroy(ctx);
return rc;
}
static int security_context_to_sid_core(const char *scontext, u32 scontext_len,
u32 *sid, u32 def_sid, gfp_t gfp_flags,
int force)
{
char *scontext2, *str = NULL;
struct context context;
int rc = 0;
/* An empty security context is never valid. */
if (!scontext_len)
return -EINVAL;
if (!ss_initialized) {
int i;
for (i = 1; i < SECINITSID_NUM; i++) {
if (!strcmp(initial_sid_to_string[i], scontext)) {
*sid = i;
return 0;
}
}
*sid = SECINITSID_KERNEL;
return 0;
}
*sid = SECSID_NULL;
/* Copy the string so that we can modify the copy as we parse it. */
scontext2 = kmalloc(scontext_len + 1, gfp_flags);
if (!scontext2)
return -ENOMEM;
memcpy(scontext2, scontext, scontext_len);
scontext2[scontext_len] = 0;
if (force) {
/* Save another copy for storing in uninterpreted form */
rc = -ENOMEM;
str = kstrdup(scontext2, gfp_flags);
if (!str)
goto out;
}
read_lock(&policy_rwlock);
rc = string_to_context_struct(&policydb, &sidtab, scontext2,
scontext_len, &context, def_sid);
if (rc == -EINVAL && force) {
context.str = str;
context.len = scontext_len;
str = NULL;
} else if (rc)
goto out_unlock;
rc = sidtab_context_to_sid(&sidtab, &context, sid);
context_destroy(&context);
out_unlock:
read_unlock(&policy_rwlock);
out:
kfree(scontext2);
kfree(str);
return rc;
}
/**
* security_context_to_sid - Obtain a SID for a given security context.
* @scontext: security context
* @scontext_len: length in bytes
* @sid: security identifier, SID
*
* Obtains a SID associated with the security context that
* has the string representation specified by @scontext.
* Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
* memory is available, or 0 on success.
*/
int security_context_to_sid(const char *scontext, u32 scontext_len, u32 *sid)
{
return security_context_to_sid_core(scontext, scontext_len,
sid, SECSID_NULL, GFP_KERNEL, 0);
}
/**
* security_context_to_sid_default - Obtain a SID for a given security context,
* falling back to specified default if needed.
*
* @scontext: security context
* @scontext_len: length in bytes
* @sid: security identifier, SID
* @def_sid: default SID to assign on error
*
* Obtains a SID associated with the security context that
* has the string representation specified by @scontext.
* The default SID is passed to the MLS layer to be used to allow
* kernel labeling of the MLS field if the MLS field is not present
* (for upgrading to MLS without full relabel).
* Implicitly forces adding of the context even if it cannot be mapped yet.
* Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
* memory is available, or 0 on success.
*/
int security_context_to_sid_default(const char *scontext, u32 scontext_len,
u32 *sid, u32 def_sid, gfp_t gfp_flags)
{
return security_context_to_sid_core(scontext, scontext_len,
sid, def_sid, gfp_flags, 1);
}
int security_context_to_sid_force(const char *scontext, u32 scontext_len,
u32 *sid)
{
return security_context_to_sid_core(scontext, scontext_len,
sid, SECSID_NULL, GFP_KERNEL, 1);
}
static int compute_sid_handle_invalid_context(
struct context *scontext,
struct context *tcontext,
u16 tclass,
struct context *newcontext)
{
char *s = NULL, *t = NULL, *n = NULL;
u32 slen, tlen, nlen;
if (context_struct_to_string(scontext, &s, &slen))
goto out;
if (context_struct_to_string(tcontext, &t, &tlen))
goto out;
if (context_struct_to_string(newcontext, &n, &nlen))
goto out;
audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
"security_compute_sid: invalid context %s"
" for scontext=%s"
" tcontext=%s"
" tclass=%s",
n, s, t, sym_name(&policydb, SYM_CLASSES, tclass-1));
out:
kfree(s);
kfree(t);
kfree(n);
if (!selinux_enforcing)
return 0;
return -EACCES;
}
static void filename_compute_type(struct policydb *p, struct context *newcontext,
u32 stype, u32 ttype, u16 tclass,
const char *objname)
{
struct filename_trans ft;
struct filename_trans_datum *otype;
/*
* Most filename trans rules are going to live in specific directories
* like /dev or /var/run. This bitmap will quickly skip rule searches
* if the ttype does not contain any rules.
*/
if (!ebitmap_get_bit(&p->filename_trans_ttypes, ttype))
return;
ft.stype = stype;
ft.ttype = ttype;
ft.tclass = tclass;
ft.name = objname;
otype = hashtab_search(p->filename_trans, &ft);
if (otype)
newcontext->type = otype->otype;
}
static int security_compute_sid(u32 ssid,
u32 tsid,
u16 orig_tclass,
u32 specified,
const char *objname,
u32 *out_sid,
bool kern)
{
struct class_datum *cladatum = NULL;
struct context *scontext = NULL, *tcontext = NULL, newcontext;
struct role_trans *roletr = NULL;
struct avtab_key avkey;
struct avtab_datum *avdatum;
struct avtab_node *node;
u16 tclass;
int rc = 0;
bool sock;
if (!ss_initialized) {
switch (orig_tclass) {
case SECCLASS_PROCESS: /* kernel value */
*out_sid = ssid;
break;
default:
*out_sid = tsid;
break;
}
goto out;
}
context_init(&newcontext);
read_lock(&policy_rwlock);
if (kern) {
tclass = unmap_class(orig_tclass);
sock = security_is_socket_class(orig_tclass);
} else {
tclass = orig_tclass;
sock = security_is_socket_class(map_class(tclass));
}
scontext = sidtab_search(&sidtab, ssid);
if (!scontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, ssid);
rc = -EINVAL;
goto out_unlock;
}
tcontext = sidtab_search(&sidtab, tsid);
if (!tcontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, tsid);
rc = -EINVAL;
goto out_unlock;
}
if (tclass && tclass <= policydb.p_classes.nprim)
cladatum = policydb.class_val_to_struct[tclass - 1];
/* Set the user identity. */
switch (specified) {
case AVTAB_TRANSITION:
case AVTAB_CHANGE:
if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
newcontext.user = tcontext->user;
} else {
/* notice this gets both DEFAULT_SOURCE and unset */
/* Use the process user identity. */
newcontext.user = scontext->user;
}
break;
case AVTAB_MEMBER:
/* Use the related object owner. */
newcontext.user = tcontext->user;
break;
}
/* Set the role to default values. */
if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
newcontext.role = scontext->role;
} else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
newcontext.role = tcontext->role;
} else {
if ((tclass == policydb.process_class) || (sock == true))
newcontext.role = scontext->role;
else
newcontext.role = OBJECT_R_VAL;
}
/* Set the type to default values. */
if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
newcontext.type = scontext->type;
} else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
newcontext.type = tcontext->type;
} else {
if ((tclass == policydb.process_class) || (sock == true)) {
/* Use the type of process. */
newcontext.type = scontext->type;
} else {
/* Use the type of the related object. */
newcontext.type = tcontext->type;
}
}
/* Look for a type transition/member/change rule. */
avkey.source_type = scontext->type;
avkey.target_type = tcontext->type;
avkey.target_class = tclass;
avkey.specified = specified;
avdatum = avtab_search(&policydb.te_avtab, &avkey);
/* If no permanent rule, also check for enabled conditional rules */
if (!avdatum) {
node = avtab_search_node(&policydb.te_cond_avtab, &avkey);
for (; node; node = avtab_search_node_next(node, specified)) {
if (node->key.specified & AVTAB_ENABLED) {
avdatum = &node->datum;
break;
}
}
}
if (avdatum) {
/* Use the type from the type transition/member/change rule. */
newcontext.type = avdatum->data;
}
/* if we have a objname this is a file trans check so check those rules */
if (objname)
filename_compute_type(&policydb, &newcontext, scontext->type,
tcontext->type, tclass, objname);
/* Check for class-specific changes. */
if (specified & AVTAB_TRANSITION) {
/* Look for a role transition rule. */
for (roletr = policydb.role_tr; roletr; roletr = roletr->next) {
if ((roletr->role == scontext->role) &&
(roletr->type == tcontext->type) &&
(roletr->tclass == tclass)) {
/* Use the role transition rule. */
newcontext.role = roletr->new_role;
break;
}
}
}
/* Set the MLS attributes.
This is done last because it may allocate memory. */
rc = mls_compute_sid(scontext, tcontext, tclass, specified,
&newcontext, sock);
if (rc)
goto out_unlock;
/* Check the validity of the context. */
if (!policydb_context_isvalid(&policydb, &newcontext)) {
rc = compute_sid_handle_invalid_context(scontext,
tcontext,
tclass,
&newcontext);
if (rc)
goto out_unlock;
}
/* Obtain the sid for the context. */
rc = sidtab_context_to_sid(&sidtab, &newcontext, out_sid);
out_unlock:
read_unlock(&policy_rwlock);
context_destroy(&newcontext);
out:
return rc;
}
/**
* security_transition_sid - Compute the SID for a new subject/object.
* @ssid: source security identifier
* @tsid: target security identifier
* @tclass: target security class
* @out_sid: security identifier for new subject/object
*
* Compute a SID to use for labeling a new subject or object in the
* class @tclass based on a SID pair (@ssid, @tsid).
* Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
* if insufficient memory is available, or %0 if the new SID was
* computed successfully.
*/
int security_transition_sid(u32 ssid, u32 tsid, u16 tclass,
const struct qstr *qstr, u32 *out_sid)
{
return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,
qstr ? qstr->name : NULL, out_sid, true);
}
int security_transition_sid_user(u32 ssid, u32 tsid, u16 tclass,
const char *objname, u32 *out_sid)
{
return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,
objname, out_sid, false);
}
/**
* security_member_sid - Compute the SID for member selection.
* @ssid: source security identifier
* @tsid: target security identifier
* @tclass: target security class
* @out_sid: security identifier for selected member
*
* Compute a SID to use when selecting a member of a polyinstantiated
* object of class @tclass based on a SID pair (@ssid, @tsid).
* Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
* if insufficient memory is available, or %0 if the SID was
* computed successfully.
*/
int security_member_sid(u32 ssid,
u32 tsid,
u16 tclass,
u32 *out_sid)
{
return security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, NULL,
out_sid, false);
}
/**
* security_change_sid - Compute the SID for object relabeling.
* @ssid: source security identifier
* @tsid: target security identifier
* @tclass: target security class
* @out_sid: security identifier for selected member
*
* Compute a SID to use for relabeling an object of class @tclass
* based on a SID pair (@ssid, @tsid).
* Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
* if insufficient memory is available, or %0 if the SID was
* computed successfully.
*/
int security_change_sid(u32 ssid,
u32 tsid,
u16 tclass,
u32 *out_sid)
{
return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, NULL,
out_sid, false);
}
/* Clone the SID into the new SID table. */
static int clone_sid(u32 sid,
struct context *context,
void *arg)
{
struct sidtab *s = arg;
if (sid > SECINITSID_NUM)
return sidtab_insert(s, sid, context);
else
return 0;
}
static inline int convert_context_handle_invalid_context(struct context *context)
{
char *s;
u32 len;
if (selinux_enforcing)
return -EINVAL;
if (!context_struct_to_string(context, &s, &len)) {
printk(KERN_WARNING "SELinux: Context %s would be invalid if enforcing\n", s);
kfree(s);
}
return 0;
}
struct convert_context_args {
struct policydb *oldp;
struct policydb *newp;
};
/*
* Convert the values in the security context
* structure `c' from the values specified
* in the policy `p->oldp' to the values specified
* in the policy `p->newp'. Verify that the
* context is valid under the new policy.
*/
static int convert_context(u32 key,
struct context *c,
void *p)
{
struct convert_context_args *args;
struct context oldc;
struct ocontext *oc;
struct mls_range *range;
struct role_datum *role;
struct type_datum *typdatum;
struct user_datum *usrdatum;
char *s;
u32 len;
int rc = 0;
if (key <= SECINITSID_NUM)
goto out;
args = p;
if (c->str) {
struct context ctx;
rc = -ENOMEM;
s = kstrdup(c->str, GFP_KERNEL);
if (!s)
goto out;
rc = string_to_context_struct(args->newp, NULL, s,
c->len, &ctx, SECSID_NULL);
kfree(s);
if (!rc) {
printk(KERN_INFO "SELinux: Context %s became valid (mapped).\n",
c->str);
/* Replace string with mapped representation. */
kfree(c->str);
memcpy(c, &ctx, sizeof(*c));
goto out;
} else if (rc == -EINVAL) {
/* Retain string representation for later mapping. */
rc = 0;
goto out;
} else {
/* Other error condition, e.g. ENOMEM. */
printk(KERN_ERR "SELinux: Unable to map context %s, rc = %d.\n",
c->str, -rc);
goto out;
}
}
rc = context_cpy(&oldc, c);
if (rc)
goto out;
/* Convert the user. */
rc = -EINVAL;
usrdatum = hashtab_search(args->newp->p_users.table,
sym_name(args->oldp, SYM_USERS, c->user - 1));
if (!usrdatum)
goto bad;
c->user = usrdatum->value;
/* Convert the role. */
rc = -EINVAL;
role = hashtab_search(args->newp->p_roles.table,
sym_name(args->oldp, SYM_ROLES, c->role - 1));
if (!role)
goto bad;
c->role = role->value;
/* Convert the type. */
rc = -EINVAL;
typdatum = hashtab_search(args->newp->p_types.table,
sym_name(args->oldp, SYM_TYPES, c->type - 1));
if (!typdatum)
goto bad;
c->type = typdatum->value;
/* Convert the MLS fields if dealing with MLS policies */
if (args->oldp->mls_enabled && args->newp->mls_enabled) {
rc = mls_convert_context(args->oldp, args->newp, c);
if (rc)
goto bad;
} else if (args->oldp->mls_enabled && !args->newp->mls_enabled) {
/*
* Switching between MLS and non-MLS policy:
* free any storage used by the MLS fields in the
* context for all existing entries in the sidtab.
*/
mls_context_destroy(c);
} else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
/*
* Switching between non-MLS and MLS policy:
* ensure that the MLS fields of the context for all
* existing entries in the sidtab are filled in with a
* suitable default value, likely taken from one of the
* initial SIDs.
*/
oc = args->newp->ocontexts[OCON_ISID];
while (oc && oc->sid[0] != SECINITSID_UNLABELED)
oc = oc->next;
rc = -EINVAL;
if (!oc) {
printk(KERN_ERR "SELinux: unable to look up"
" the initial SIDs list\n");
goto bad;
}
range = &oc->context[0].range;
rc = mls_range_set(c, range);
if (rc)
goto bad;
}
/* Check the validity of the new context. */
if (!policydb_context_isvalid(args->newp, c)) {
rc = convert_context_handle_invalid_context(&oldc);
if (rc)
goto bad;
}
context_destroy(&oldc);
rc = 0;
out:
return rc;
bad:
/* Map old representation to string and save it. */
rc = context_struct_to_string(&oldc, &s, &len);
if (rc)
return rc;
context_destroy(&oldc);
context_destroy(c);
c->str = s;
c->len = len;
printk(KERN_INFO "SELinux: Context %s became invalid (unmapped).\n",
c->str);
rc = 0;
goto out;
}
static void security_load_policycaps(void)
{
selinux_policycap_netpeer = ebitmap_get_bit(&policydb.policycaps,
POLICYDB_CAPABILITY_NETPEER);
selinux_policycap_openperm = ebitmap_get_bit(&policydb.policycaps,
POLICYDB_CAPABILITY_OPENPERM);
selinux_policycap_alwaysnetwork = ebitmap_get_bit(&policydb.policycaps,
POLICYDB_CAPABILITY_ALWAYSNETWORK);
}
static int security_preserve_bools(struct policydb *p);
/**
* security_load_policy - Load a security policy configuration.
* @data: binary policy data
* @len: length of data in bytes
*
* Load a new set of security policy configuration data,
* validate it and convert the SID table as necessary.
* This function will flush the access vector cache after
* loading the new policy.
*/
int security_load_policy(void *data, size_t len)
{
struct policydb *oldpolicydb, *newpolicydb;
struct sidtab oldsidtab, newsidtab;
struct selinux_mapping *oldmap, *map = NULL;
struct convert_context_args args;
u32 seqno;
u16 map_size;
int rc = 0;
struct policy_file file = { data, len }, *fp = &file;
oldpolicydb = kzalloc(2 * sizeof(*oldpolicydb), GFP_KERNEL);
if (!oldpolicydb) {
rc = -ENOMEM;
goto out;
}
newpolicydb = oldpolicydb + 1;
if (!ss_initialized) {
avtab_cache_init();
rc = policydb_read(&policydb, fp);
if (rc) {
avtab_cache_destroy();
goto out;
}
policydb.len = len;
rc = selinux_set_mapping(&policydb, secclass_map,
¤t_mapping,
¤t_mapping_size);
if (rc) {
policydb_destroy(&policydb);
avtab_cache_destroy();
goto out;
}
rc = policydb_load_isids(&policydb, &sidtab);
if (rc) {
policydb_destroy(&policydb);
avtab_cache_destroy();
goto out;
}
security_load_policycaps();
ss_initialized = 1;
seqno = ++latest_granting;
selinux_complete_init();
avc_ss_reset(seqno);
selnl_notify_policyload(seqno);
selinux_status_update_policyload(seqno);
selinux_netlbl_cache_invalidate();
selinux_xfrm_notify_policyload();
goto out;
}
#if 0
sidtab_hash_eval(&sidtab, "sids");
#endif
rc = policydb_read(newpolicydb, fp);
if (rc)
goto out;
newpolicydb->len = len;
/* If switching between different policy types, log MLS status */
if (policydb.mls_enabled && !newpolicydb->mls_enabled)
printk(KERN_INFO "SELinux: Disabling MLS support...\n");
else if (!policydb.mls_enabled && newpolicydb->mls_enabled)
printk(KERN_INFO "SELinux: Enabling MLS support...\n");
rc = policydb_load_isids(newpolicydb, &newsidtab);
if (rc) {
printk(KERN_ERR "SELinux: unable to load the initial SIDs\n");
policydb_destroy(newpolicydb);
goto out;
}
rc = selinux_set_mapping(newpolicydb, secclass_map, &map, &map_size);
if (rc)
goto err;
rc = security_preserve_bools(newpolicydb);
if (rc) {
printk(KERN_ERR "SELinux: unable to preserve booleans\n");
goto err;
}
/* Clone the SID table. */
sidtab_shutdown(&sidtab);
rc = sidtab_map(&sidtab, clone_sid, &newsidtab);
if (rc)
goto err;
/*
* Convert the internal representations of contexts
* in the new SID table.
*/
args.oldp = &policydb;
args.newp = newpolicydb;
rc = sidtab_map(&newsidtab, convert_context, &args);
if (rc) {
printk(KERN_ERR "SELinux: unable to convert the internal"
" representation of contexts in the new SID"
" table\n");
goto err;
}
/* Save the old policydb and SID table to free later. */
memcpy(oldpolicydb, &policydb, sizeof(policydb));
sidtab_set(&oldsidtab, &sidtab);
/* Install the new policydb and SID table. */
write_lock_irq(&policy_rwlock);
memcpy(&policydb, newpolicydb, sizeof(policydb));
sidtab_set(&sidtab, &newsidtab);
security_load_policycaps();
oldmap = current_mapping;
current_mapping = map;
current_mapping_size = map_size;
seqno = ++latest_granting;
write_unlock_irq(&policy_rwlock);
/* Free the old policydb and SID table. */
policydb_destroy(oldpolicydb);
sidtab_destroy(&oldsidtab);
kfree(oldmap);
avc_ss_reset(seqno);
selnl_notify_policyload(seqno);
selinux_status_update_policyload(seqno);
selinux_netlbl_cache_invalidate();
selinux_xfrm_notify_policyload();
rc = 0;
goto out;
err:
kfree(map);
sidtab_destroy(&newsidtab);
policydb_destroy(newpolicydb);
out:
kfree(oldpolicydb);
return rc;
}
size_t security_policydb_len(void)
{
size_t len;
read_lock(&policy_rwlock);
len = policydb.len;
read_unlock(&policy_rwlock);
return len;
}
/**
* security_port_sid - Obtain the SID for a port.
* @protocol: protocol number
* @port: port number
* @out_sid: security identifier
*/
int security_port_sid(u8 protocol, u16 port, u32 *out_sid)
{
struct ocontext *c;
int rc = 0;
read_lock(&policy_rwlock);
c = policydb.ocontexts[OCON_PORT];
while (c) {
if (c->u.port.protocol == protocol &&
c->u.port.low_port <= port &&
c->u.port.high_port >= port)
break;
c = c->next;
}
if (c) {
if (!c->sid[0]) {
rc = sidtab_context_to_sid(&sidtab,
&c->context[0],
&c->sid[0]);
if (rc)
goto out;
}
*out_sid = c->sid[0];
} else {
*out_sid = SECINITSID_PORT;
}
out:
read_unlock(&policy_rwlock);
return rc;
}
/**
* security_netif_sid - Obtain the SID for a network interface.
* @name: interface name
* @if_sid: interface SID
*/
int security_netif_sid(char *name, u32 *if_sid)
{
int rc = 0;
struct ocontext *c;
read_lock(&policy_rwlock);
c = policydb.ocontexts[OCON_NETIF];
while (c) {
if (strcmp(name, c->u.name) == 0)
break;
c = c->next;
}
if (c) {
if (!c->sid[0] || !c->sid[1]) {
rc = sidtab_context_to_sid(&sidtab,
&c->context[0],
&c->sid[0]);
if (rc)
goto out;
rc = sidtab_context_to_sid(&sidtab,
&c->context[1],
&c->sid[1]);
if (rc)
goto out;
}
*if_sid = c->sid[0];
} else
*if_sid = SECINITSID_NETIF;
out:
read_unlock(&policy_rwlock);
return rc;
}
static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
{
int i, fail = 0;
for (i = 0; i < 4; i++)
if (addr[i] != (input[i] & mask[i])) {
fail = 1;
break;
}
return !fail;
}
/**
* security_node_sid - Obtain the SID for a node (host).
* @domain: communication domain aka address family
* @addrp: address
* @addrlen: address length in bytes
* @out_sid: security identifier
*/
int security_node_sid(u16 domain,
void *addrp,
u32 addrlen,
u32 *out_sid)
{
int rc;
struct ocontext *c;
read_lock(&policy_rwlock);
switch (domain) {
case AF_INET: {
u32 addr;
rc = -EINVAL;
if (addrlen != sizeof(u32))
goto out;
addr = *((u32 *)addrp);
c = policydb.ocontexts[OCON_NODE];
while (c) {
if (c->u.node.addr == (addr & c->u.node.mask))
break;
c = c->next;
}
break;
}
case AF_INET6:
rc = -EINVAL;
if (addrlen != sizeof(u64) * 2)
goto out;
c = policydb.ocontexts[OCON_NODE6];
while (c) {
if (match_ipv6_addrmask(addrp, c->u.node6.addr,
c->u.node6.mask))
break;
c = c->next;
}
break;
default:
rc = 0;
*out_sid = SECINITSID_NODE;
goto out;
}
if (c) {
if (!c->sid[0]) {
rc = sidtab_context_to_sid(&sidtab,
&c->context[0],
&c->sid[0]);
if (rc)
goto out;
}
*out_sid = c->sid[0];
} else {
*out_sid = SECINITSID_NODE;
}
rc = 0;
out:
read_unlock(&policy_rwlock);
return rc;
}
#define SIDS_NEL 25
/**
* security_get_user_sids - Obtain reachable SIDs for a user.
* @fromsid: starting SID
* @username: username
* @sids: array of reachable SIDs for user
* @nel: number of elements in @sids
*
* Generate the set of SIDs for legal security contexts
* for a given user that can be reached by @fromsid.
* Set *@sids to point to a dynamically allocated
* array containing the set of SIDs. Set *@nel to the
* number of elements in the array.
*/
int security_get_user_sids(u32 fromsid,
char *username,
u32 **sids,
u32 *nel)
{
struct context *fromcon, usercon;
u32 *mysids = NULL, *mysids2, sid;
u32 mynel = 0, maxnel = SIDS_NEL;
struct user_datum *user;
struct role_datum *role;
struct ebitmap_node *rnode, *tnode;
int rc = 0, i, j;
*sids = NULL;
*nel = 0;
if (!ss_initialized)
goto out;
read_lock(&policy_rwlock);
context_init(&usercon);
rc = -EINVAL;
fromcon = sidtab_search(&sidtab, fromsid);
if (!fromcon)
goto out_unlock;
rc = -EINVAL;
user = hashtab_search(policydb.p_users.table, username);
if (!user)
goto out_unlock;
usercon.user = user->value;
rc = -ENOMEM;
mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
if (!mysids)
goto out_unlock;
ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
role = policydb.role_val_to_struct[i];
usercon.role = i + 1;
ebitmap_for_each_positive_bit(&role->types, tnode, j) {
usercon.type = j + 1;
if (mls_setup_user_range(fromcon, user, &usercon))
continue;
rc = sidtab_context_to_sid(&sidtab, &usercon, &sid);
if (rc)
goto out_unlock;
if (mynel < maxnel) {
mysids[mynel++] = sid;
} else {
rc = -ENOMEM;
maxnel += SIDS_NEL;
mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
if (!mysids2)
goto out_unlock;
memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
kfree(mysids);
mysids = mysids2;
mysids[mynel++] = sid;
}
}
}
rc = 0;
out_unlock:
read_unlock(&policy_rwlock);
if (rc || !mynel) {
kfree(mysids);
goto out;
}
rc = -ENOMEM;
mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
if (!mysids2) {
kfree(mysids);
goto out;
}
for (i = 0, j = 0; i < mynel; i++) {
struct av_decision dummy_avd;
rc = avc_has_perm_noaudit(fromsid, mysids[i],
SECCLASS_PROCESS, /* kernel value */
PROCESS__TRANSITION, AVC_STRICT,
&dummy_avd);
if (!rc)
mysids2[j++] = mysids[i];
cond_resched();
}
rc = 0;
kfree(mysids);
*sids = mysids2;
*nel = j;
out:
return rc;
}
/**
* security_genfs_sid - Obtain a SID for a file in a filesystem
* @fstype: filesystem type
* @path: path from root of mount
* @sclass: file security class
* @sid: SID for path
*
* Obtain a SID to use for a file in a filesystem that
* cannot support xattr or use a fixed labeling behavior like
* transition SIDs or task SIDs.
*/
int security_genfs_sid(const char *fstype,
char *path,
u16 orig_sclass,
u32 *sid)
{
int len;
u16 sclass;
struct genfs *genfs;
struct ocontext *c;
int rc, cmp = 0;
while (path[0] == '/' && path[1] == '/')
path++;
read_lock(&policy_rwlock);
sclass = unmap_class(orig_sclass);
*sid = SECINITSID_UNLABELED;
for (genfs = policydb.genfs; genfs; genfs = genfs->next) {
cmp = strcmp(fstype, genfs->fstype);
if (cmp <= 0)
break;
}
rc = -ENOENT;
if (!genfs || cmp)
goto out;
for (c = genfs->head; c; c = c->next) {
len = strlen(c->u.name);
if ((!c->v.sclass || sclass == c->v.sclass) &&
(strncmp(c->u.name, path, len) == 0))
break;
}
rc = -ENOENT;
if (!c)
goto out;
if (!c->sid[0]) {
rc = sidtab_context_to_sid(&sidtab, &c->context[0], &c->sid[0]);
if (rc)
goto out;
}
*sid = c->sid[0];
rc = 0;
out:
read_unlock(&policy_rwlock);
return rc;
}
/**
* security_fs_use - Determine how to handle labeling for a filesystem.
* @sb: superblock in question
*/
int security_fs_use(struct super_block *sb)
{
int rc = 0;
struct ocontext *c;
struct superblock_security_struct *sbsec = sb->s_security;
const char *fstype = sb->s_type->name;
read_lock(&policy_rwlock);
c = policydb.ocontexts[OCON_FSUSE];
while (c) {
if (strcmp(fstype, c->u.name) == 0)
break;
c = c->next;
}
if (c) {
sbsec->behavior = c->v.behavior;
if (!c->sid[0]) {
rc = sidtab_context_to_sid(&sidtab, &c->context[0],
&c->sid[0]);
if (rc)
goto out;
}
sbsec->sid = c->sid[0];
} else {
rc = security_genfs_sid(fstype, "/", SECCLASS_DIR, &sbsec->sid);
if (rc) {
sbsec->behavior = SECURITY_FS_USE_NONE;
rc = 0;
} else {
sbsec->behavior = SECURITY_FS_USE_GENFS;
}
}
out:
read_unlock(&policy_rwlock);
return rc;
}
int security_get_bools(int *len, char ***names, int **values)
{
int i, rc;
read_lock(&policy_rwlock);
*names = NULL;
*values = NULL;
rc = 0;
*len = policydb.p_bools.nprim;
if (!*len)
goto out;
rc = -ENOMEM;
*names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
if (!*names)
goto err;
rc = -ENOMEM;
*values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
if (!*values)
goto err;
for (i = 0; i < *len; i++) {
size_t name_len;
(*values)[i] = policydb.bool_val_to_struct[i]->state;
name_len = strlen(sym_name(&policydb, SYM_BOOLS, i)) + 1;
rc = -ENOMEM;
(*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC);
if (!(*names)[i])
goto err;
strncpy((*names)[i], sym_name(&policydb, SYM_BOOLS, i), name_len);
(*names)[i][name_len - 1] = 0;
}
rc = 0;
out:
read_unlock(&policy_rwlock);
return rc;
err:
if (*names) {
for (i = 0; i < *len; i++)
kfree((*names)[i]);
}
kfree(*values);
goto out;
}
int security_set_bools(int len, int *values)
{
int i, rc;
int lenp, seqno = 0;
struct cond_node *cur;
write_lock_irq(&policy_rwlock);
rc = -EFAULT;
lenp = policydb.p_bools.nprim;
if (len != lenp)
goto out;
for (i = 0; i < len; i++) {
if (!!values[i] != policydb.bool_val_to_struct[i]->state) {
audit_log(current->audit_context, GFP_ATOMIC,
AUDIT_MAC_CONFIG_CHANGE,
"bool=%s val=%d old_val=%d auid=%u ses=%u",
sym_name(&policydb, SYM_BOOLS, i),
!!values[i],
policydb.bool_val_to_struct[i]->state,
from_kuid(&init_user_ns, audit_get_loginuid(current)),
audit_get_sessionid(current));
}
if (values[i])
policydb.bool_val_to_struct[i]->state = 1;
else
policydb.bool_val_to_struct[i]->state = 0;
}
for (cur = policydb.cond_list; cur; cur = cur->next) {
rc = evaluate_cond_node(&policydb, cur);
if (rc)
goto out;
}
seqno = ++latest_granting;
rc = 0;
out:
write_unlock_irq(&policy_rwlock);
if (!rc) {
avc_ss_reset(seqno);
selnl_notify_policyload(seqno);
selinux_status_update_policyload(seqno);
selinux_xfrm_notify_policyload();
}
return rc;
}
int security_get_bool_value(int bool)
{
int rc;
int len;
read_lock(&policy_rwlock);
rc = -EFAULT;
len = policydb.p_bools.nprim;
if (bool >= len)
goto out;
rc = policydb.bool_val_to_struct[bool]->state;
out:
read_unlock(&policy_rwlock);
return rc;
}
static int security_preserve_bools(struct policydb *p)
{
int rc, nbools = 0, *bvalues = NULL, i;
char **bnames = NULL;
struct cond_bool_datum *booldatum;
struct cond_node *cur;
rc = security_get_bools(&nbools, &bnames, &bvalues);
if (rc)
goto out;
for (i = 0; i < nbools; i++) {
booldatum = hashtab_search(p->p_bools.table, bnames[i]);
if (booldatum)
booldatum->state = bvalues[i];
}
for (cur = p->cond_list; cur; cur = cur->next) {
rc = evaluate_cond_node(p, cur);
if (rc)
goto out;
}
out:
if (bnames) {
for (i = 0; i < nbools; i++)
kfree(bnames[i]);
}
kfree(bnames);
kfree(bvalues);
return rc;
}
/*
* security_sid_mls_copy() - computes a new sid based on the given
* sid and the mls portion of mls_sid.
*/
int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
{
struct context *context1;
struct context *context2;
struct context newcon;
char *s;
u32 len;
int rc;
rc = 0;
if (!ss_initialized || !policydb.mls_enabled) {
*new_sid = sid;
goto out;
}
context_init(&newcon);
read_lock(&policy_rwlock);
rc = -EINVAL;
context1 = sidtab_search(&sidtab, sid);
if (!context1) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, sid);
goto out_unlock;
}
rc = -EINVAL;
context2 = sidtab_search(&sidtab, mls_sid);
if (!context2) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, mls_sid);
goto out_unlock;
}
newcon.user = context1->user;
newcon.role = context1->role;
newcon.type = context1->type;
rc = mls_context_cpy(&newcon, context2);
if (rc)
goto out_unlock;
/* Check the validity of the new context. */
if (!policydb_context_isvalid(&policydb, &newcon)) {
rc = convert_context_handle_invalid_context(&newcon);
if (rc) {
if (!context_struct_to_string(&newcon, &s, &len)) {
audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
"security_sid_mls_copy: invalid context %s", s);
kfree(s);
}
goto out_unlock;
}
}
rc = sidtab_context_to_sid(&sidtab, &newcon, new_sid);
out_unlock:
read_unlock(&policy_rwlock);
context_destroy(&newcon);
out:
return rc;
}
/**
* security_net_peersid_resolve - Compare and resolve two network peer SIDs
* @nlbl_sid: NetLabel SID
* @nlbl_type: NetLabel labeling protocol type
* @xfrm_sid: XFRM SID
*
* Description:
* Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
* resolved into a single SID it is returned via @peer_sid and the function
* returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function
* returns a negative value. A table summarizing the behavior is below:
*
* | function return | @sid
* ------------------------------+-----------------+-----------------
* no peer labels | 0 | SECSID_NULL
* single peer label | 0 | <peer_label>
* multiple, consistent labels | 0 | <peer_label>
* multiple, inconsistent labels | -<errno> | SECSID_NULL
*
*/
int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,
u32 xfrm_sid,
u32 *peer_sid)
{
int rc;
struct context *nlbl_ctx;
struct context *xfrm_ctx;
*peer_sid = SECSID_NULL;
/* handle the common (which also happens to be the set of easy) cases
* right away, these two if statements catch everything involving a
* single or absent peer SID/label */
if (xfrm_sid == SECSID_NULL) {
*peer_sid = nlbl_sid;
return 0;
}
/* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
* and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
* is present */
if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
*peer_sid = xfrm_sid;
return 0;
}
/* we don't need to check ss_initialized here since the only way both
* nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
* security server was initialized and ss_initialized was true */
if (!policydb.mls_enabled)
return 0;
read_lock(&policy_rwlock);
rc = -EINVAL;
nlbl_ctx = sidtab_search(&sidtab, nlbl_sid);
if (!nlbl_ctx) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, nlbl_sid);
goto out;
}
rc = -EINVAL;
xfrm_ctx = sidtab_search(&sidtab, xfrm_sid);
if (!xfrm_ctx) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, xfrm_sid);
goto out;
}
rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
if (rc)
goto out;
/* at present NetLabel SIDs/labels really only carry MLS
* information so if the MLS portion of the NetLabel SID
* matches the MLS portion of the labeled XFRM SID/label
* then pass along the XFRM SID as it is the most
* expressive */
*peer_sid = xfrm_sid;
out:
read_unlock(&policy_rwlock);
return rc;
}
static int get_classes_callback(void *k, void *d, void *args)
{
struct class_datum *datum = d;
char *name = k, **classes = args;
int value = datum->value - 1;
classes[value] = kstrdup(name, GFP_ATOMIC);
if (!classes[value])
return -ENOMEM;
return 0;
}
int security_get_classes(char ***classes, int *nclasses)
{
int rc;
read_lock(&policy_rwlock);
rc = -ENOMEM;
*nclasses = policydb.p_classes.nprim;
*classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
if (!*classes)
goto out;
rc = hashtab_map(policydb.p_classes.table, get_classes_callback,
*classes);
if (rc) {
int i;
for (i = 0; i < *nclasses; i++)
kfree((*classes)[i]);
kfree(*classes);
}
out:
read_unlock(&policy_rwlock);
return rc;
}
static int get_permissions_callback(void *k, void *d, void *args)
{
struct perm_datum *datum = d;
char *name = k, **perms = args;
int value = datum->value - 1;
perms[value] = kstrdup(name, GFP_ATOMIC);
if (!perms[value])
return -ENOMEM;
return 0;
}
int security_get_permissions(char *class, char ***perms, int *nperms)
{
int rc, i;
struct class_datum *match;
read_lock(&policy_rwlock);
rc = -EINVAL;
match = hashtab_search(policydb.p_classes.table, class);
if (!match) {
printk(KERN_ERR "SELinux: %s: unrecognized class %s\n",
__func__, class);
goto out;
}
rc = -ENOMEM;
*nperms = match->permissions.nprim;
*perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
if (!*perms)
goto out;
if (match->comdatum) {
rc = hashtab_map(match->comdatum->permissions.table,
get_permissions_callback, *perms);
if (rc)
goto err;
}
rc = hashtab_map(match->permissions.table, get_permissions_callback,
*perms);
if (rc)
goto err;
out:
read_unlock(&policy_rwlock);
return rc;
err:
read_unlock(&policy_rwlock);
for (i = 0; i < *nperms; i++)
kfree((*perms)[i]);
kfree(*perms);
return rc;
}
int security_get_reject_unknown(void)
{
return policydb.reject_unknown;
}
int security_get_allow_unknown(void)
{
return policydb.allow_unknown;
}
/**
* security_policycap_supported - Check for a specific policy capability
* @req_cap: capability
*
* Description:
* This function queries the currently loaded policy to see if it supports the
* capability specified by @req_cap. Returns true (1) if the capability is
* supported, false (0) if it isn't supported.
*
*/
int security_policycap_supported(unsigned int req_cap)
{
int rc;
read_lock(&policy_rwlock);
rc = ebitmap_get_bit(&policydb.policycaps, req_cap);
read_unlock(&policy_rwlock);
return rc;
}
struct selinux_audit_rule {
u32 au_seqno;
struct context au_ctxt;
};
void selinux_audit_rule_free(void *vrule)
{
struct selinux_audit_rule *rule = vrule;
if (rule) {
context_destroy(&rule->au_ctxt);
kfree(rule);
}
}
int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
{
struct selinux_audit_rule *tmprule;
struct role_datum *roledatum;
struct type_datum *typedatum;
struct user_datum *userdatum;
struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
int rc = 0;
*rule = NULL;
if (!ss_initialized)
return -EOPNOTSUPP;
switch (field) {
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
/* only 'equals' and 'not equals' fit user, role, and type */
if (op != Audit_equal && op != Audit_not_equal)
return -EINVAL;
break;
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
/* we do not allow a range, indicated by the presence of '-' */
if (strchr(rulestr, '-'))
return -EINVAL;
break;
default:
/* only the above fields are valid */
return -EINVAL;
}
tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
if (!tmprule)
return -ENOMEM;
context_init(&tmprule->au_ctxt);
read_lock(&policy_rwlock);
tmprule->au_seqno = latest_granting;
switch (field) {
case AUDIT_SUBJ_USER:
case AUDIT_OBJ_USER:
rc = -EINVAL;
userdatum = hashtab_search(policydb.p_users.table, rulestr);
if (!userdatum)
goto out;
tmprule->au_ctxt.user = userdatum->value;
break;
case AUDIT_SUBJ_ROLE:
case AUDIT_OBJ_ROLE:
rc = -EINVAL;
roledatum = hashtab_search(policydb.p_roles.table, rulestr);
if (!roledatum)
goto out;
tmprule->au_ctxt.role = roledatum->value;
break;
case AUDIT_SUBJ_TYPE:
case AUDIT_OBJ_TYPE:
rc = -EINVAL;
typedatum = hashtab_search(policydb.p_types.table, rulestr);
if (!typedatum)
goto out;
tmprule->au_ctxt.type = typedatum->value;
break;
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
rc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC);
if (rc)
goto out;
break;
}
rc = 0;
out:
read_unlock(&policy_rwlock);
if (rc) {
selinux_audit_rule_free(tmprule);
tmprule = NULL;
}
*rule = tmprule;
return rc;
}
/* Check to see if the rule contains any selinux fields */
int selinux_audit_rule_known(struct audit_krule *rule)
{
int i;
for (i = 0; i < rule->field_count; i++) {
struct audit_field *f = &rule->fields[i];
switch (f->type) {
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
return 1;
}
}
return 0;
}
int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule,
struct audit_context *actx)
{
struct context *ctxt;
struct mls_level *level;
struct selinux_audit_rule *rule = vrule;
int match = 0;
if (!rule) {
audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
"selinux_audit_rule_match: missing rule\n");
return -ENOENT;
}
read_lock(&policy_rwlock);
if (rule->au_seqno < latest_granting) {
audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
"selinux_audit_rule_match: stale rule\n");
match = -ESTALE;
goto out;
}
ctxt = sidtab_search(&sidtab, sid);
if (!ctxt) {
audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
"selinux_audit_rule_match: unrecognized SID %d\n",
sid);
match = -ENOENT;
goto out;
}
/* a field/op pair that is not caught here will simply fall through
without a match */
switch (field) {
case AUDIT_SUBJ_USER:
case AUDIT_OBJ_USER:
switch (op) {
case Audit_equal:
match = (ctxt->user == rule->au_ctxt.user);
break;
case Audit_not_equal:
match = (ctxt->user != rule->au_ctxt.user);
break;
}
break;
case AUDIT_SUBJ_ROLE:
case AUDIT_OBJ_ROLE:
switch (op) {
case Audit_equal:
match = (ctxt->role == rule->au_ctxt.role);
break;
case Audit_not_equal:
match = (ctxt->role != rule->au_ctxt.role);
break;
}
break;
case AUDIT_SUBJ_TYPE:
case AUDIT_OBJ_TYPE:
switch (op) {
case Audit_equal:
match = (ctxt->type == rule->au_ctxt.type);
break;
case Audit_not_equal:
match = (ctxt->type != rule->au_ctxt.type);
break;
}
break;
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
level = ((field == AUDIT_SUBJ_SEN ||
field == AUDIT_OBJ_LEV_LOW) ?
&ctxt->range.level[0] : &ctxt->range.level[1]);
switch (op) {
case Audit_equal:
match = mls_level_eq(&rule->au_ctxt.range.level[0],
level);
break;
case Audit_not_equal:
match = !mls_level_eq(&rule->au_ctxt.range.level[0],
level);
break;
case Audit_lt:
match = (mls_level_dom(&rule->au_ctxt.range.level[0],
level) &&
!mls_level_eq(&rule->au_ctxt.range.level[0],
level));
break;
case Audit_le:
match = mls_level_dom(&rule->au_ctxt.range.level[0],
level);
break;
case Audit_gt:
match = (mls_level_dom(level,
&rule->au_ctxt.range.level[0]) &&
!mls_level_eq(level,
&rule->au_ctxt.range.level[0]));
break;
case Audit_ge:
match = mls_level_dom(level,
&rule->au_ctxt.range.level[0]);
break;
}
}
out:
read_unlock(&policy_rwlock);
return match;
}
static int (*aurule_callback)(void) = audit_update_lsm_rules;
static int aurule_avc_callback(u32 event)
{
int err = 0;
if (event == AVC_CALLBACK_RESET && aurule_callback)
err = aurule_callback();
return err;
}
static int __init aurule_init(void)
{
int err;
err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);
if (err)
panic("avc_add_callback() failed, error %d\n", err);
return err;
}
__initcall(aurule_init);
#ifdef CONFIG_NETLABEL
/**
* security_netlbl_cache_add - Add an entry to the NetLabel cache
* @secattr: the NetLabel packet security attributes
* @sid: the SELinux SID
*
* Description:
* Attempt to cache the context in @ctx, which was derived from the packet in
* @skb, in the NetLabel subsystem cache. This function assumes @secattr has
* already been initialized.
*
*/
static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
u32 sid)
{
u32 *sid_cache;
sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
if (sid_cache == NULL)
return;
secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
if (secattr->cache == NULL) {
kfree(sid_cache);
return;
}
*sid_cache = sid;
secattr->cache->free = kfree;
secattr->cache->data = sid_cache;
secattr->flags |= NETLBL_SECATTR_CACHE;
}
/**
* security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
* @secattr: the NetLabel packet security attributes
* @sid: the SELinux SID
*
* Description:
* Convert the given NetLabel security attributes in @secattr into a
* SELinux SID. If the @secattr field does not contain a full SELinux
* SID/context then use SECINITSID_NETMSG as the foundation. If possible the
* 'cache' field of @secattr is set and the CACHE flag is set; this is to
* allow the @secattr to be used by NetLabel to cache the secattr to SID
* conversion for future lookups. Returns zero on success, negative values on
* failure.
*
*/
int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,
u32 *sid)
{
int rc;
struct context *ctx;
struct context ctx_new;
if (!ss_initialized) {
*sid = SECSID_NULL;
return 0;
}
read_lock(&policy_rwlock);
if (secattr->flags & NETLBL_SECATTR_CACHE)
*sid = *(u32 *)secattr->cache->data;
else if (secattr->flags & NETLBL_SECATTR_SECID)
*sid = secattr->attr.secid;
else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
rc = -EIDRM;
ctx = sidtab_search(&sidtab, SECINITSID_NETMSG);
if (ctx == NULL)
goto out;
context_init(&ctx_new);
ctx_new.user = ctx->user;
ctx_new.role = ctx->role;
ctx_new.type = ctx->type;
mls_import_netlbl_lvl(&ctx_new, secattr);
if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
rc = ebitmap_netlbl_import(&ctx_new.range.level[0].cat,
secattr->attr.mls.cat);
if (rc)
goto out;
memcpy(&ctx_new.range.level[1].cat,
&ctx_new.range.level[0].cat,
sizeof(ctx_new.range.level[0].cat));
}
rc = -EIDRM;
if (!mls_context_isvalid(&policydb, &ctx_new))
goto out_free;
rc = sidtab_context_to_sid(&sidtab, &ctx_new, sid);
if (rc)
goto out_free;
security_netlbl_cache_add(secattr, *sid);
ebitmap_destroy(&ctx_new.range.level[0].cat);
} else
*sid = SECSID_NULL;
read_unlock(&policy_rwlock);
return 0;
out_free:
ebitmap_destroy(&ctx_new.range.level[0].cat);
out:
read_unlock(&policy_rwlock);
return rc;
}
/**
* security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
* @sid: the SELinux SID
* @secattr: the NetLabel packet security attributes
*
* Description:
* Convert the given SELinux SID in @sid into a NetLabel security attribute.
* Returns zero on success, negative values on failure.
*
*/
int security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr)
{
int rc;
struct context *ctx;
if (!ss_initialized)
return 0;
read_lock(&policy_rwlock);
rc = -ENOENT;
ctx = sidtab_search(&sidtab, sid);
if (ctx == NULL)
goto out;
rc = -ENOMEM;
secattr->domain = kstrdup(sym_name(&policydb, SYM_TYPES, ctx->type - 1),
GFP_ATOMIC);
if (secattr->domain == NULL)
goto out;
secattr->attr.secid = sid;
secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
mls_export_netlbl_lvl(ctx, secattr);
rc = mls_export_netlbl_cat(ctx, secattr);
out:
read_unlock(&policy_rwlock);
return rc;
}
#endif /* CONFIG_NETLABEL */
/**
* security_read_policy - read the policy.
* @data: binary policy data
* @len: length of data in bytes
*
*/
int security_read_policy(void **data, size_t *len)
{
int rc;
struct policy_file fp;
if (!ss_initialized)
return -EINVAL;
*len = security_policydb_len();
*data = vmalloc_user(*len);
if (!*data)
return -ENOMEM;
fp.data = *data;
fp.len = *len;
read_lock(&policy_rwlock);
rc = policydb_write(&policydb, &fp);
read_unlock(&policy_rwlock);
if (rc)
return rc;
*len = (unsigned long)fp.data - (unsigned long)*data;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2080_0 |
crossvul-cpp_data_good_3379_0 | /*
* IPv6 output functions
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
*
* Based on linux/net/ipv4/ip_output.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Changes:
* A.N.Kuznetsov : airthmetics in fragmentation.
* extension headers are implemented.
* route changes now work.
* ip6_forward does not confuse sniffers.
* etc.
*
* H. von Brand : Added missing #include <linux/string.h>
* Imran Patel : frag id should be in NBO
* Kazunori MIYAZAWA @USAGI
* : add ip6_append_data and related functions
* for datagram xmit
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/socket.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/in6.h>
#include <linux/tcp.h>
#include <linux/route.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/bpf-cgroup.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv6.h>
#include <net/sock.h>
#include <net/snmp.h>
#include <net/ipv6.h>
#include <net/ndisc.h>
#include <net/protocol.h>
#include <net/ip6_route.h>
#include <net/addrconf.h>
#include <net/rawv6.h>
#include <net/icmp.h>
#include <net/xfrm.h>
#include <net/checksum.h>
#include <linux/mroute6.h>
#include <net/l3mdev.h>
#include <net/lwtunnel.h>
static int ip6_finish_output2(struct net *net, struct sock *sk, struct sk_buff *skb)
{
struct dst_entry *dst = skb_dst(skb);
struct net_device *dev = dst->dev;
struct neighbour *neigh;
struct in6_addr *nexthop;
int ret;
skb->protocol = htons(ETH_P_IPV6);
skb->dev = dev;
if (ipv6_addr_is_multicast(&ipv6_hdr(skb)->daddr)) {
struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
if (!(dev->flags & IFF_LOOPBACK) && sk_mc_loop(sk) &&
((mroute6_socket(net, skb) &&
!(IP6CB(skb)->flags & IP6SKB_FORWARDED)) ||
ipv6_chk_mcast_addr(dev, &ipv6_hdr(skb)->daddr,
&ipv6_hdr(skb)->saddr))) {
struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC);
/* Do not check for IFF_ALLMULTI; multicast routing
is not supported in any case.
*/
if (newskb)
NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING,
net, sk, newskb, NULL, newskb->dev,
dev_loopback_xmit);
if (ipv6_hdr(skb)->hop_limit == 0) {
IP6_INC_STATS(net, idev,
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return 0;
}
}
IP6_UPD_PO_STATS(net, idev, IPSTATS_MIB_OUTMCAST, skb->len);
if (IPV6_ADDR_MC_SCOPE(&ipv6_hdr(skb)->daddr) <=
IPV6_ADDR_SCOPE_NODELOCAL &&
!(dev->flags & IFF_LOOPBACK)) {
kfree_skb(skb);
return 0;
}
}
if (lwtunnel_xmit_redirect(dst->lwtstate)) {
int res = lwtunnel_xmit(skb);
if (res < 0 || res == LWTUNNEL_XMIT_DONE)
return res;
}
rcu_read_lock_bh();
nexthop = rt6_nexthop((struct rt6_info *)dst, &ipv6_hdr(skb)->daddr);
neigh = __ipv6_neigh_lookup_noref(dst->dev, nexthop);
if (unlikely(!neigh))
neigh = __neigh_create(&nd_tbl, nexthop, dst->dev, false);
if (!IS_ERR(neigh)) {
sock_confirm_neigh(skb, neigh);
ret = neigh_output(neigh, skb);
rcu_read_unlock_bh();
return ret;
}
rcu_read_unlock_bh();
IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES);
kfree_skb(skb);
return -EINVAL;
}
static int ip6_finish_output(struct net *net, struct sock *sk, struct sk_buff *skb)
{
int ret;
ret = BPF_CGROUP_RUN_PROG_INET_EGRESS(sk, skb);
if (ret) {
kfree_skb(skb);
return ret;
}
if ((skb->len > ip6_skb_dst_mtu(skb) && !skb_is_gso(skb)) ||
dst_allfrag(skb_dst(skb)) ||
(IP6CB(skb)->frag_max_size && skb->len > IP6CB(skb)->frag_max_size))
return ip6_fragment(net, sk, skb, ip6_finish_output2);
else
return ip6_finish_output2(net, sk, skb);
}
int ip6_output(struct net *net, struct sock *sk, struct sk_buff *skb)
{
struct net_device *dev = skb_dst(skb)->dev;
struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
if (unlikely(idev->cnf.disable_ipv6)) {
IP6_INC_STATS(net, idev, IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return 0;
}
return NF_HOOK_COND(NFPROTO_IPV6, NF_INET_POST_ROUTING,
net, sk, skb, NULL, dev,
ip6_finish_output,
!(IP6CB(skb)->flags & IP6SKB_REROUTED));
}
/*
* xmit an sk_buff (used by TCP, SCTP and DCCP)
* Note : socket lock is not held for SYNACK packets, but might be modified
* by calls to skb_set_owner_w() and ipv6_local_error(),
* which are using proper atomic operations or spinlocks.
*/
int ip6_xmit(const struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6,
__u32 mark, struct ipv6_txoptions *opt, int tclass)
{
struct net *net = sock_net(sk);
const struct ipv6_pinfo *np = inet6_sk(sk);
struct in6_addr *first_hop = &fl6->daddr;
struct dst_entry *dst = skb_dst(skb);
struct ipv6hdr *hdr;
u8 proto = fl6->flowi6_proto;
int seg_len = skb->len;
int hlimit = -1;
u32 mtu;
if (opt) {
unsigned int head_room;
/* First: exthdrs may take lots of space (~8K for now)
MAX_HEADER is not enough.
*/
head_room = opt->opt_nflen + opt->opt_flen;
seg_len += head_room;
head_room += sizeof(struct ipv6hdr) + LL_RESERVED_SPACE(dst->dev);
if (skb_headroom(skb) < head_room) {
struct sk_buff *skb2 = skb_realloc_headroom(skb, head_room);
if (!skb2) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return -ENOBUFS;
}
consume_skb(skb);
skb = skb2;
/* skb_set_owner_w() changes sk->sk_wmem_alloc atomically,
* it is safe to call in our context (socket lock not held)
*/
skb_set_owner_w(skb, (struct sock *)sk);
}
if (opt->opt_flen)
ipv6_push_frag_opts(skb, opt, &proto);
if (opt->opt_nflen)
ipv6_push_nfrag_opts(skb, opt, &proto, &first_hop,
&fl6->saddr);
}
skb_push(skb, sizeof(struct ipv6hdr));
skb_reset_network_header(skb);
hdr = ipv6_hdr(skb);
/*
* Fill in the IPv6 header
*/
if (np)
hlimit = np->hop_limit;
if (hlimit < 0)
hlimit = ip6_dst_hoplimit(dst);
ip6_flow_hdr(hdr, tclass, ip6_make_flowlabel(net, skb, fl6->flowlabel,
np->autoflowlabel, fl6));
hdr->payload_len = htons(seg_len);
hdr->nexthdr = proto;
hdr->hop_limit = hlimit;
hdr->saddr = fl6->saddr;
hdr->daddr = *first_hop;
skb->protocol = htons(ETH_P_IPV6);
skb->priority = sk->sk_priority;
skb->mark = mark;
mtu = dst_mtu(dst);
if ((skb->len <= mtu) || skb->ignore_df || skb_is_gso(skb)) {
IP6_UPD_PO_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUT, skb->len);
/* if egress device is enslaved to an L3 master device pass the
* skb to its handler for processing
*/
skb = l3mdev_ip6_out((struct sock *)sk, skb);
if (unlikely(!skb))
return 0;
/* hooks should never assume socket lock is held.
* we promote our socket to non const
*/
return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT,
net, (struct sock *)sk, skb, NULL, dst->dev,
dst_output);
}
skb->dev = dst->dev;
/* ipv6_local_error() does not require socket lock,
* we promote our socket to non const
*/
ipv6_local_error((struct sock *)sk, EMSGSIZE, fl6, mtu);
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
EXPORT_SYMBOL(ip6_xmit);
static int ip6_call_ra_chain(struct sk_buff *skb, int sel)
{
struct ip6_ra_chain *ra;
struct sock *last = NULL;
read_lock(&ip6_ra_lock);
for (ra = ip6_ra_chain; ra; ra = ra->next) {
struct sock *sk = ra->sk;
if (sk && ra->sel == sel &&
(!sk->sk_bound_dev_if ||
sk->sk_bound_dev_if == skb->dev->ifindex)) {
if (last) {
struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
if (skb2)
rawv6_rcv(last, skb2);
}
last = sk;
}
}
if (last) {
rawv6_rcv(last, skb);
read_unlock(&ip6_ra_lock);
return 1;
}
read_unlock(&ip6_ra_lock);
return 0;
}
static int ip6_forward_proxy_check(struct sk_buff *skb)
{
struct ipv6hdr *hdr = ipv6_hdr(skb);
u8 nexthdr = hdr->nexthdr;
__be16 frag_off;
int offset;
if (ipv6_ext_hdr(nexthdr)) {
offset = ipv6_skip_exthdr(skb, sizeof(*hdr), &nexthdr, &frag_off);
if (offset < 0)
return 0;
} else
offset = sizeof(struct ipv6hdr);
if (nexthdr == IPPROTO_ICMPV6) {
struct icmp6hdr *icmp6;
if (!pskb_may_pull(skb, (skb_network_header(skb) +
offset + 1 - skb->data)))
return 0;
icmp6 = (struct icmp6hdr *)(skb_network_header(skb) + offset);
switch (icmp6->icmp6_type) {
case NDISC_ROUTER_SOLICITATION:
case NDISC_ROUTER_ADVERTISEMENT:
case NDISC_NEIGHBOUR_SOLICITATION:
case NDISC_NEIGHBOUR_ADVERTISEMENT:
case NDISC_REDIRECT:
/* For reaction involving unicast neighbor discovery
* message destined to the proxied address, pass it to
* input function.
*/
return 1;
default:
break;
}
}
/*
* The proxying router can't forward traffic sent to a link-local
* address, so signal the sender and discard the packet. This
* behavior is clarified by the MIPv6 specification.
*/
if (ipv6_addr_type(&hdr->daddr) & IPV6_ADDR_LINKLOCAL) {
dst_link_failure(skb);
return -1;
}
return 0;
}
static inline int ip6_forward_finish(struct net *net, struct sock *sk,
struct sk_buff *skb)
{
return dst_output(net, sk, skb);
}
static unsigned int ip6_dst_mtu_forward(const struct dst_entry *dst)
{
unsigned int mtu;
struct inet6_dev *idev;
if (dst_metric_locked(dst, RTAX_MTU)) {
mtu = dst_metric_raw(dst, RTAX_MTU);
if (mtu)
return mtu;
}
mtu = IPV6_MIN_MTU;
rcu_read_lock();
idev = __in6_dev_get(dst->dev);
if (idev)
mtu = idev->cnf.mtu6;
rcu_read_unlock();
return mtu;
}
static bool ip6_pkt_too_big(const struct sk_buff *skb, unsigned int mtu)
{
if (skb->len <= mtu)
return false;
/* ipv6 conntrack defrag sets max_frag_size + ignore_df */
if (IP6CB(skb)->frag_max_size && IP6CB(skb)->frag_max_size > mtu)
return true;
if (skb->ignore_df)
return false;
if (skb_is_gso(skb) && skb_gso_validate_mtu(skb, mtu))
return false;
return true;
}
int ip6_forward(struct sk_buff *skb)
{
struct dst_entry *dst = skb_dst(skb);
struct ipv6hdr *hdr = ipv6_hdr(skb);
struct inet6_skb_parm *opt = IP6CB(skb);
struct net *net = dev_net(dst->dev);
u32 mtu;
if (net->ipv6.devconf_all->forwarding == 0)
goto error;
if (skb->pkt_type != PACKET_HOST)
goto drop;
if (unlikely(skb->sk))
goto drop;
if (skb_warn_if_lro(skb))
goto drop;
if (!xfrm6_policy_check(NULL, XFRM_POLICY_FWD, skb)) {
__IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_INDISCARDS);
goto drop;
}
skb_forward_csum(skb);
/*
* We DO NOT make any processing on
* RA packets, pushing them to user level AS IS
* without ane WARRANTY that application will be able
* to interpret them. The reason is that we
* cannot make anything clever here.
*
* We are not end-node, so that if packet contains
* AH/ESP, we cannot make anything.
* Defragmentation also would be mistake, RA packets
* cannot be fragmented, because there is no warranty
* that different fragments will go along one path. --ANK
*/
if (unlikely(opt->flags & IP6SKB_ROUTERALERT)) {
if (ip6_call_ra_chain(skb, ntohs(opt->ra)))
return 0;
}
/*
* check and decrement ttl
*/
if (hdr->hop_limit <= 1) {
/* Force OUTPUT device used as source address */
skb->dev = dst->dev;
icmpv6_send(skb, ICMPV6_TIME_EXCEED, ICMPV6_EXC_HOPLIMIT, 0);
__IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_INHDRERRORS);
kfree_skb(skb);
return -ETIMEDOUT;
}
/* XXX: idev->cnf.proxy_ndp? */
if (net->ipv6.devconf_all->proxy_ndp &&
pneigh_lookup(&nd_tbl, net, &hdr->daddr, skb->dev, 0)) {
int proxied = ip6_forward_proxy_check(skb);
if (proxied > 0)
return ip6_input(skb);
else if (proxied < 0) {
__IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_INDISCARDS);
goto drop;
}
}
if (!xfrm6_route_forward(skb)) {
__IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_INDISCARDS);
goto drop;
}
dst = skb_dst(skb);
/* IPv6 specs say nothing about it, but it is clear that we cannot
send redirects to source routed frames.
We don't send redirects to frames decapsulated from IPsec.
*/
if (skb->dev == dst->dev && opt->srcrt == 0 && !skb_sec_path(skb)) {
struct in6_addr *target = NULL;
struct inet_peer *peer;
struct rt6_info *rt;
/*
* incoming and outgoing devices are the same
* send a redirect.
*/
rt = (struct rt6_info *) dst;
if (rt->rt6i_flags & RTF_GATEWAY)
target = &rt->rt6i_gateway;
else
target = &hdr->daddr;
peer = inet_getpeer_v6(net->ipv6.peers, &hdr->daddr, 1);
/* Limit redirects both by destination (here)
and by source (inside ndisc_send_redirect)
*/
if (inet_peer_xrlim_allow(peer, 1*HZ))
ndisc_send_redirect(skb, target);
if (peer)
inet_putpeer(peer);
} else {
int addrtype = ipv6_addr_type(&hdr->saddr);
/* This check is security critical. */
if (addrtype == IPV6_ADDR_ANY ||
addrtype & (IPV6_ADDR_MULTICAST | IPV6_ADDR_LOOPBACK))
goto error;
if (addrtype & IPV6_ADDR_LINKLOCAL) {
icmpv6_send(skb, ICMPV6_DEST_UNREACH,
ICMPV6_NOT_NEIGHBOUR, 0);
goto error;
}
}
mtu = ip6_dst_mtu_forward(dst);
if (mtu < IPV6_MIN_MTU)
mtu = IPV6_MIN_MTU;
if (ip6_pkt_too_big(skb, mtu)) {
/* Again, force OUTPUT device used as source address */
skb->dev = dst->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
__IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_INTOOBIGERRORS);
__IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
if (skb_cow(skb, dst->dev->hard_header_len)) {
__IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_OUTDISCARDS);
goto drop;
}
hdr = ipv6_hdr(skb);
/* Mangling hops number delayed to point after skb COW */
hdr->hop_limit--;
__IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTFORWDATAGRAMS);
__IP6_ADD_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTOCTETS, skb->len);
return NF_HOOK(NFPROTO_IPV6, NF_INET_FORWARD,
net, NULL, skb, skb->dev, dst->dev,
ip6_forward_finish);
error:
__IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INADDRERRORS);
drop:
kfree_skb(skb);
return -EINVAL;
}
static void ip6_copy_metadata(struct sk_buff *to, struct sk_buff *from)
{
to->pkt_type = from->pkt_type;
to->priority = from->priority;
to->protocol = from->protocol;
skb_dst_drop(to);
skb_dst_set(to, dst_clone(skb_dst(from)));
to->dev = from->dev;
to->mark = from->mark;
#ifdef CONFIG_NET_SCHED
to->tc_index = from->tc_index;
#endif
nf_copy(to, from);
skb_copy_secmark(to, from);
}
int ip6_fragment(struct net *net, struct sock *sk, struct sk_buff *skb,
int (*output)(struct net *, struct sock *, struct sk_buff *))
{
struct sk_buff *frag;
struct rt6_info *rt = (struct rt6_info *)skb_dst(skb);
struct ipv6_pinfo *np = skb->sk && !dev_recursion_level() ?
inet6_sk(skb->sk) : NULL;
struct ipv6hdr *tmp_hdr;
struct frag_hdr *fh;
unsigned int mtu, hlen, left, len;
int hroom, troom;
__be32 frag_id;
int ptr, offset = 0, err = 0;
u8 *prevhdr, nexthdr = 0;
err = ip6_find_1stfragopt(skb, &prevhdr);
if (err < 0)
goto fail;
hlen = err;
nexthdr = *prevhdr;
mtu = ip6_skb_dst_mtu(skb);
/* We must not fragment if the socket is set to force MTU discovery
* or if the skb it not generated by a local socket.
*/
if (unlikely(!skb->ignore_df && skb->len > mtu))
goto fail_toobig;
if (IP6CB(skb)->frag_max_size) {
if (IP6CB(skb)->frag_max_size > mtu)
goto fail_toobig;
/* don't send fragments larger than what we received */
mtu = IP6CB(skb)->frag_max_size;
if (mtu < IPV6_MIN_MTU)
mtu = IPV6_MIN_MTU;
}
if (np && np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
if (mtu < hlen + sizeof(struct frag_hdr) + 8)
goto fail_toobig;
mtu -= hlen + sizeof(struct frag_hdr);
frag_id = ipv6_select_ident(net, &ipv6_hdr(skb)->daddr,
&ipv6_hdr(skb)->saddr);
if (skb->ip_summed == CHECKSUM_PARTIAL &&
(err = skb_checksum_help(skb)))
goto fail;
hroom = LL_RESERVED_SPACE(rt->dst.dev);
if (skb_has_frag_list(skb)) {
unsigned int first_len = skb_pagelen(skb);
struct sk_buff *frag2;
if (first_len - hlen > mtu ||
((first_len - hlen) & 7) ||
skb_cloned(skb) ||
skb_headroom(skb) < (hroom + sizeof(struct frag_hdr)))
goto slow_path;
skb_walk_frags(skb, frag) {
/* Correct geometry. */
if (frag->len > mtu ||
((frag->len & 7) && frag->next) ||
skb_headroom(frag) < (hlen + hroom + sizeof(struct frag_hdr)))
goto slow_path_clean;
/* Partially cloned skb? */
if (skb_shared(frag))
goto slow_path_clean;
BUG_ON(frag->sk);
if (skb->sk) {
frag->sk = skb->sk;
frag->destructor = sock_wfree;
}
skb->truesize -= frag->truesize;
}
err = 0;
offset = 0;
/* BUILD HEADER */
*prevhdr = NEXTHDR_FRAGMENT;
tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC);
if (!tmp_hdr) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
err = -ENOMEM;
goto fail;
}
frag = skb_shinfo(skb)->frag_list;
skb_frag_list_init(skb);
__skb_pull(skb, hlen);
fh = (struct frag_hdr *)__skb_push(skb, sizeof(struct frag_hdr));
__skb_push(skb, hlen);
skb_reset_network_header(skb);
memcpy(skb_network_header(skb), tmp_hdr, hlen);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(IP6_MF);
fh->identification = frag_id;
first_len = skb_pagelen(skb);
skb->data_len = first_len - skb_headlen(skb);
skb->len = first_len;
ipv6_hdr(skb)->payload_len = htons(first_len -
sizeof(struct ipv6hdr));
dst_hold(&rt->dst);
for (;;) {
/* Prepare header of the next frame,
* before previous one went down. */
if (frag) {
frag->ip_summed = CHECKSUM_NONE;
skb_reset_transport_header(frag);
fh = (struct frag_hdr *)__skb_push(frag, sizeof(struct frag_hdr));
__skb_push(frag, hlen);
skb_reset_network_header(frag);
memcpy(skb_network_header(frag), tmp_hdr,
hlen);
offset += skb->len - hlen - sizeof(struct frag_hdr);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(offset);
if (frag->next)
fh->frag_off |= htons(IP6_MF);
fh->identification = frag_id;
ipv6_hdr(frag)->payload_len =
htons(frag->len -
sizeof(struct ipv6hdr));
ip6_copy_metadata(frag, skb);
}
err = output(net, sk, skb);
if (!err)
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGCREATES);
if (err || !frag)
break;
skb = frag;
frag = skb->next;
skb->next = NULL;
}
kfree(tmp_hdr);
if (err == 0) {
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGOKS);
ip6_rt_put(rt);
return 0;
}
kfree_skb_list(frag);
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGFAILS);
ip6_rt_put(rt);
return err;
slow_path_clean:
skb_walk_frags(skb, frag2) {
if (frag2 == frag)
break;
frag2->sk = NULL;
frag2->destructor = NULL;
skb->truesize += frag2->truesize;
}
}
slow_path:
left = skb->len - hlen; /* Space per frame */
ptr = hlen; /* Where to start from */
/*
* Fragment the datagram.
*/
troom = rt->dst.dev->needed_tailroom;
/*
* Keep copying data until we run out.
*/
while (left > 0) {
u8 *fragnexthdr_offset;
len = left;
/* IF: it doesn't fit, use 'mtu' - the data space left */
if (len > mtu)
len = mtu;
/* IF: we are not sending up to and including the packet end
then align the next start on an eight byte boundary */
if (len < left) {
len &= ~7;
}
/* Allocate buffer */
frag = alloc_skb(len + hlen + sizeof(struct frag_hdr) +
hroom + troom, GFP_ATOMIC);
if (!frag) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
err = -ENOMEM;
goto fail;
}
/*
* Set up data on packet
*/
ip6_copy_metadata(frag, skb);
skb_reserve(frag, hroom);
skb_put(frag, len + hlen + sizeof(struct frag_hdr));
skb_reset_network_header(frag);
fh = (struct frag_hdr *)(skb_network_header(frag) + hlen);
frag->transport_header = (frag->network_header + hlen +
sizeof(struct frag_hdr));
/*
* Charge the memory for the fragment to any owner
* it might possess
*/
if (skb->sk)
skb_set_owner_w(frag, skb->sk);
/*
* Copy the packet header into the new buffer.
*/
skb_copy_from_linear_data(skb, skb_network_header(frag), hlen);
fragnexthdr_offset = skb_network_header(frag);
fragnexthdr_offset += prevhdr - skb_network_header(skb);
*fragnexthdr_offset = NEXTHDR_FRAGMENT;
/*
* Build fragment header.
*/
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->identification = frag_id;
/*
* Copy a block of the IP datagram.
*/
BUG_ON(skb_copy_bits(skb, ptr, skb_transport_header(frag),
len));
left -= len;
fh->frag_off = htons(offset);
if (left > 0)
fh->frag_off |= htons(IP6_MF);
ipv6_hdr(frag)->payload_len = htons(frag->len -
sizeof(struct ipv6hdr));
ptr += len;
offset += len;
/*
* Put this fragment into the sending queue.
*/
err = output(net, sk, frag);
if (err)
goto fail;
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGCREATES);
}
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGOKS);
consume_skb(skb);
return err;
fail_toobig:
if (skb->sk && dst_allfrag(skb_dst(skb)))
sk_nocaps_add(skb->sk, NETIF_F_GSO_MASK);
skb->dev = skb_dst(skb)->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
err = -EMSGSIZE;
fail:
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return err;
}
static inline int ip6_rt_check(const struct rt6key *rt_key,
const struct in6_addr *fl_addr,
const struct in6_addr *addr_cache)
{
return (rt_key->plen != 128 || !ipv6_addr_equal(fl_addr, &rt_key->addr)) &&
(!addr_cache || !ipv6_addr_equal(fl_addr, addr_cache));
}
static struct dst_entry *ip6_sk_dst_check(struct sock *sk,
struct dst_entry *dst,
const struct flowi6 *fl6)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct rt6_info *rt;
if (!dst)
goto out;
if (dst->ops->family != AF_INET6) {
dst_release(dst);
return NULL;
}
rt = (struct rt6_info *)dst;
/* Yes, checking route validity in not connected
* case is not very simple. Take into account,
* that we do not support routing by source, TOS,
* and MSG_DONTROUTE --ANK (980726)
*
* 1. ip6_rt_check(): If route was host route,
* check that cached destination is current.
* If it is network route, we still may
* check its validity using saved pointer
* to the last used address: daddr_cache.
* We do not want to save whole address now,
* (because main consumer of this service
* is tcp, which has not this problem),
* so that the last trick works only on connected
* sockets.
* 2. oif also should be the same.
*/
if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) ||
#ifdef CONFIG_IPV6_SUBTREES
ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) ||
#endif
(!(fl6->flowi6_flags & FLOWI_FLAG_SKIP_NH_OIF) &&
(fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex))) {
dst_release(dst);
dst = NULL;
}
out:
return dst;
}
static int ip6_dst_lookup_tail(struct net *net, const struct sock *sk,
struct dst_entry **dst, struct flowi6 *fl6)
{
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
struct neighbour *n;
struct rt6_info *rt;
#endif
int err;
int flags = 0;
/* The correct way to handle this would be to do
* ip6_route_get_saddr, and then ip6_route_output; however,
* the route-specific preferred source forces the
* ip6_route_output call _before_ ip6_route_get_saddr.
*
* In source specific routing (no src=any default route),
* ip6_route_output will fail given src=any saddr, though, so
* that's why we try it again later.
*/
if (ipv6_addr_any(&fl6->saddr) && (!*dst || !(*dst)->error)) {
struct rt6_info *rt;
bool had_dst = *dst != NULL;
if (!had_dst)
*dst = ip6_route_output(net, sk, fl6);
rt = (*dst)->error ? NULL : (struct rt6_info *)*dst;
err = ip6_route_get_saddr(net, rt, &fl6->daddr,
sk ? inet6_sk(sk)->srcprefs : 0,
&fl6->saddr);
if (err)
goto out_err_release;
/* If we had an erroneous initial result, pretend it
* never existed and let the SA-enabled version take
* over.
*/
if (!had_dst && (*dst)->error) {
dst_release(*dst);
*dst = NULL;
}
if (fl6->flowi6_oif)
flags |= RT6_LOOKUP_F_IFACE;
}
if (!*dst)
*dst = ip6_route_output_flags(net, sk, fl6, flags);
err = (*dst)->error;
if (err)
goto out_err_release;
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
/*
* Here if the dst entry we've looked up
* has a neighbour entry that is in the INCOMPLETE
* state and the src address from the flow is
* marked as OPTIMISTIC, we release the found
* dst entry and replace it instead with the
* dst entry of the nexthop router
*/
rt = (struct rt6_info *) *dst;
rcu_read_lock_bh();
n = __ipv6_neigh_lookup_noref(rt->dst.dev,
rt6_nexthop(rt, &fl6->daddr));
err = n && !(n->nud_state & NUD_VALID) ? -EINVAL : 0;
rcu_read_unlock_bh();
if (err) {
struct inet6_ifaddr *ifp;
struct flowi6 fl_gw6;
int redirect;
ifp = ipv6_get_ifaddr(net, &fl6->saddr,
(*dst)->dev, 1);
redirect = (ifp && ifp->flags & IFA_F_OPTIMISTIC);
if (ifp)
in6_ifa_put(ifp);
if (redirect) {
/*
* We need to get the dst entry for the
* default router instead
*/
dst_release(*dst);
memcpy(&fl_gw6, fl6, sizeof(struct flowi6));
memset(&fl_gw6.daddr, 0, sizeof(struct in6_addr));
*dst = ip6_route_output(net, sk, &fl_gw6);
err = (*dst)->error;
if (err)
goto out_err_release;
}
}
#endif
if (ipv6_addr_v4mapped(&fl6->saddr) &&
!(ipv6_addr_v4mapped(&fl6->daddr) || ipv6_addr_any(&fl6->daddr))) {
err = -EAFNOSUPPORT;
goto out_err_release;
}
return 0;
out_err_release:
dst_release(*dst);
*dst = NULL;
if (err == -ENETUNREACH)
IP6_INC_STATS(net, NULL, IPSTATS_MIB_OUTNOROUTES);
return err;
}
/**
* ip6_dst_lookup - perform route lookup on flow
* @sk: socket which provides route info
* @dst: pointer to dst_entry * for result
* @fl6: flow to lookup
*
* This function performs a route lookup on the given flow.
*
* It returns zero on success, or a standard errno code on error.
*/
int ip6_dst_lookup(struct net *net, struct sock *sk, struct dst_entry **dst,
struct flowi6 *fl6)
{
*dst = NULL;
return ip6_dst_lookup_tail(net, sk, dst, fl6);
}
EXPORT_SYMBOL_GPL(ip6_dst_lookup);
/**
* ip6_dst_lookup_flow - perform route lookup on flow with ipsec
* @sk: socket which provides route info
* @fl6: flow to lookup
* @final_dst: final destination address for ipsec lookup
*
* This function performs a route lookup on the given flow.
*
* It returns a valid dst pointer on success, or a pointer encoded
* error code.
*/
struct dst_entry *ip6_dst_lookup_flow(const struct sock *sk, struct flowi6 *fl6,
const struct in6_addr *final_dst)
{
struct dst_entry *dst = NULL;
int err;
err = ip6_dst_lookup_tail(sock_net(sk), sk, &dst, fl6);
if (err)
return ERR_PTR(err);
if (final_dst)
fl6->daddr = *final_dst;
return xfrm_lookup_route(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0);
}
EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow);
/**
* ip6_sk_dst_lookup_flow - perform socket cached route lookup on flow
* @sk: socket which provides the dst cache and route info
* @fl6: flow to lookup
* @final_dst: final destination address for ipsec lookup
*
* This function performs a route lookup on the given flow with the
* possibility of using the cached route in the socket if it is valid.
* It will take the socket dst lock when operating on the dst cache.
* As a result, this function can only be used in process context.
*
* It returns a valid dst pointer on success, or a pointer encoded
* error code.
*/
struct dst_entry *ip6_sk_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6,
const struct in6_addr *final_dst)
{
struct dst_entry *dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie);
dst = ip6_sk_dst_check(sk, dst, fl6);
if (!dst)
dst = ip6_dst_lookup_flow(sk, fl6, final_dst);
return dst;
}
EXPORT_SYMBOL_GPL(ip6_sk_dst_lookup_flow);
static inline int ip6_ufo_append_data(struct sock *sk,
struct sk_buff_head *queue,
int getfrag(void *from, char *to, int offset, int len,
int odd, struct sk_buff *skb),
void *from, int length, int hh_len, int fragheaderlen,
int exthdrlen, int transhdrlen, int mtu,
unsigned int flags, const struct flowi6 *fl6)
{
struct sk_buff *skb;
int err;
/* There is support for UDP large send offload by network
* device, so create one single skb packet containing complete
* udp datagram
*/
skb = skb_peek_tail(queue);
if (!skb) {
skb = sock_alloc_send_skb(sk,
hh_len + fragheaderlen + transhdrlen + 20,
(flags & MSG_DONTWAIT), &err);
if (!skb)
return err;
/* reserve space for Hardware header */
skb_reserve(skb, hh_len);
/* create space for UDP/IP header */
skb_put(skb, fragheaderlen + transhdrlen);
/* initialize network header pointer */
skb_set_network_header(skb, exthdrlen);
/* initialize protocol header pointer */
skb->transport_header = skb->network_header + fragheaderlen;
skb->protocol = htons(ETH_P_IPV6);
skb->csum = 0;
if (flags & MSG_CONFIRM)
skb_set_dst_pending_confirm(skb, 1);
__skb_queue_tail(queue, skb);
} else if (skb_is_gso(skb)) {
goto append;
}
skb->ip_summed = CHECKSUM_PARTIAL;
/* Specify the length of each IPv6 datagram fragment.
* It has to be a multiple of 8.
*/
skb_shinfo(skb)->gso_size = (mtu - fragheaderlen -
sizeof(struct frag_hdr)) & ~7;
skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
skb_shinfo(skb)->ip6_frag_id = ipv6_select_ident(sock_net(sk),
&fl6->daddr,
&fl6->saddr);
append:
return skb_append_datato_frags(sk, skb, getfrag, from,
(length - transhdrlen));
}
static inline struct ipv6_opt_hdr *ip6_opt_dup(struct ipv6_opt_hdr *src,
gfp_t gfp)
{
return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL;
}
static inline struct ipv6_rt_hdr *ip6_rthdr_dup(struct ipv6_rt_hdr *src,
gfp_t gfp)
{
return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL;
}
static void ip6_append_data_mtu(unsigned int *mtu,
int *maxfraglen,
unsigned int fragheaderlen,
struct sk_buff *skb,
struct rt6_info *rt,
unsigned int orig_mtu)
{
if (!(rt->dst.flags & DST_XFRM_TUNNEL)) {
if (!skb) {
/* first fragment, reserve header_len */
*mtu = orig_mtu - rt->dst.header_len;
} else {
/*
* this fragment is not first, the headers
* space is regarded as data space.
*/
*mtu = orig_mtu;
}
*maxfraglen = ((*mtu - fragheaderlen) & ~7)
+ fragheaderlen - sizeof(struct frag_hdr);
}
}
static int ip6_setup_cork(struct sock *sk, struct inet_cork_full *cork,
struct inet6_cork *v6_cork, struct ipcm6_cookie *ipc6,
struct rt6_info *rt, struct flowi6 *fl6)
{
struct ipv6_pinfo *np = inet6_sk(sk);
unsigned int mtu;
struct ipv6_txoptions *opt = ipc6->opt;
/*
* setup for corking
*/
if (opt) {
if (WARN_ON(v6_cork->opt))
return -EINVAL;
v6_cork->opt = kzalloc(opt->tot_len, sk->sk_allocation);
if (unlikely(!v6_cork->opt))
return -ENOBUFS;
v6_cork->opt->tot_len = opt->tot_len;
v6_cork->opt->opt_flen = opt->opt_flen;
v6_cork->opt->opt_nflen = opt->opt_nflen;
v6_cork->opt->dst0opt = ip6_opt_dup(opt->dst0opt,
sk->sk_allocation);
if (opt->dst0opt && !v6_cork->opt->dst0opt)
return -ENOBUFS;
v6_cork->opt->dst1opt = ip6_opt_dup(opt->dst1opt,
sk->sk_allocation);
if (opt->dst1opt && !v6_cork->opt->dst1opt)
return -ENOBUFS;
v6_cork->opt->hopopt = ip6_opt_dup(opt->hopopt,
sk->sk_allocation);
if (opt->hopopt && !v6_cork->opt->hopopt)
return -ENOBUFS;
v6_cork->opt->srcrt = ip6_rthdr_dup(opt->srcrt,
sk->sk_allocation);
if (opt->srcrt && !v6_cork->opt->srcrt)
return -ENOBUFS;
/* need source address above miyazawa*/
}
dst_hold(&rt->dst);
cork->base.dst = &rt->dst;
cork->fl.u.ip6 = *fl6;
v6_cork->hop_limit = ipc6->hlimit;
v6_cork->tclass = ipc6->tclass;
if (rt->dst.flags & DST_XFRM_TUNNEL)
mtu = np->pmtudisc >= IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(&rt->dst);
else
mtu = np->pmtudisc >= IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(rt->dst.path);
if (np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
cork->base.fragsize = mtu;
if (dst_allfrag(rt->dst.path))
cork->base.flags |= IPCORK_ALLFRAG;
cork->base.length = 0;
return 0;
}
static int __ip6_append_data(struct sock *sk,
struct flowi6 *fl6,
struct sk_buff_head *queue,
struct inet_cork *cork,
struct inet6_cork *v6_cork,
struct page_frag *pfrag,
int getfrag(void *from, char *to, int offset,
int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
unsigned int flags, struct ipcm6_cookie *ipc6,
const struct sockcm_cookie *sockc)
{
struct sk_buff *skb, *skb_prev = NULL;
unsigned int maxfraglen, fragheaderlen, mtu, orig_mtu;
int exthdrlen = 0;
int dst_exthdrlen = 0;
int hh_len;
int copy;
int err;
int offset = 0;
__u8 tx_flags = 0;
u32 tskey = 0;
struct rt6_info *rt = (struct rt6_info *)cork->dst;
struct ipv6_txoptions *opt = v6_cork->opt;
int csummode = CHECKSUM_NONE;
unsigned int maxnonfragsize, headersize;
skb = skb_peek_tail(queue);
if (!skb) {
exthdrlen = opt ? opt->opt_flen : 0;
dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len;
}
mtu = cork->fragsize;
orig_mtu = mtu;
hh_len = LL_RESERVED_SPACE(rt->dst.dev);
fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len +
(opt ? opt->opt_nflen : 0);
maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen -
sizeof(struct frag_hdr);
headersize = sizeof(struct ipv6hdr) +
(opt ? opt->opt_flen + opt->opt_nflen : 0) +
(dst_allfrag(&rt->dst) ?
sizeof(struct frag_hdr) : 0) +
rt->rt6i_nfheader_len;
if (cork->length + length > mtu - headersize && ipc6->dontfrag &&
(sk->sk_protocol == IPPROTO_UDP ||
sk->sk_protocol == IPPROTO_RAW)) {
ipv6_local_rxpmtu(sk, fl6, mtu - headersize +
sizeof(struct ipv6hdr));
goto emsgsize;
}
if (ip6_sk_ignore_df(sk))
maxnonfragsize = sizeof(struct ipv6hdr) + IPV6_MAXPLEN;
else
maxnonfragsize = mtu;
if (cork->length + length > maxnonfragsize - headersize) {
emsgsize:
ipv6_local_error(sk, EMSGSIZE, fl6,
mtu - headersize +
sizeof(struct ipv6hdr));
return -EMSGSIZE;
}
/* CHECKSUM_PARTIAL only with no extension headers and when
* we are not going to fragment
*/
if (transhdrlen && sk->sk_protocol == IPPROTO_UDP &&
headersize == sizeof(struct ipv6hdr) &&
length <= mtu - headersize &&
!(flags & MSG_MORE) &&
rt->dst.dev->features & (NETIF_F_IPV6_CSUM | NETIF_F_HW_CSUM))
csummode = CHECKSUM_PARTIAL;
if (sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) {
sock_tx_timestamp(sk, sockc->tsflags, &tx_flags);
if (tx_flags & SKBTX_ANY_SW_TSTAMP &&
sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)
tskey = sk->sk_tskey++;
}
/*
* Let's try using as much space as possible.
* Use MTU if total length of the message fits into the MTU.
* Otherwise, we need to reserve fragment header and
* fragment alignment (= 8-15 octects, in total).
*
* Note that we may need to "move" the data from the tail of
* of the buffer to the new fragment when we split
* the message.
*
* FIXME: It may be fragmented into multiple chunks
* at once if non-fragmentable extension headers
* are too large.
* --yoshfuji
*/
cork->length += length;
if ((((length + fragheaderlen) > mtu) ||
(skb && skb_is_gso(skb))) &&
(sk->sk_protocol == IPPROTO_UDP) &&
(rt->dst.dev->features & NETIF_F_UFO) && !dst_xfrm(&rt->dst) &&
(sk->sk_type == SOCK_DGRAM) && !udp_get_no_check6_tx(sk)) {
err = ip6_ufo_append_data(sk, queue, getfrag, from, length,
hh_len, fragheaderlen, exthdrlen,
transhdrlen, mtu, flags, fl6);
if (err)
goto error;
return 0;
}
if (!skb)
goto alloc_new_skb;
while (length > 0) {
/* Check if the remaining data fits into current packet. */
copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len;
if (copy < length)
copy = maxfraglen - skb->len;
if (copy <= 0) {
char *data;
unsigned int datalen;
unsigned int fraglen;
unsigned int fraggap;
unsigned int alloclen;
alloc_new_skb:
/* There's no room in the current skb */
if (skb)
fraggap = skb->len - maxfraglen;
else
fraggap = 0;
/* update mtu and maxfraglen if necessary */
if (!skb || !skb_prev)
ip6_append_data_mtu(&mtu, &maxfraglen,
fragheaderlen, skb, rt,
orig_mtu);
skb_prev = skb;
/*
* If remaining data exceeds the mtu,
* we know we need more fragment(s).
*/
datalen = length + fraggap;
if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen)
datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len;
if ((flags & MSG_MORE) &&
!(rt->dst.dev->features&NETIF_F_SG))
alloclen = mtu;
else
alloclen = datalen + fragheaderlen;
alloclen += dst_exthdrlen;
if (datalen != length + fraggap) {
/*
* this is not the last fragment, the trailer
* space is regarded as data space.
*/
datalen += rt->dst.trailer_len;
}
alloclen += rt->dst.trailer_len;
fraglen = datalen + fragheaderlen;
/*
* We just reserve space for fragment header.
* Note: this may be overallocation if the message
* (without MSG_MORE) fits into the MTU.
*/
alloclen += sizeof(struct frag_hdr);
copy = datalen - transhdrlen - fraggap;
if (copy < 0) {
err = -EINVAL;
goto error;
}
if (transhdrlen) {
skb = sock_alloc_send_skb(sk,
alloclen + hh_len,
(flags & MSG_DONTWAIT), &err);
} else {
skb = NULL;
if (atomic_read(&sk->sk_wmem_alloc) <=
2 * sk->sk_sndbuf)
skb = sock_wmalloc(sk,
alloclen + hh_len, 1,
sk->sk_allocation);
if (unlikely(!skb))
err = -ENOBUFS;
}
if (!skb)
goto error;
/*
* Fill in the control structures
*/
skb->protocol = htons(ETH_P_IPV6);
skb->ip_summed = csummode;
skb->csum = 0;
/* reserve for fragmentation and ipsec header */
skb_reserve(skb, hh_len + sizeof(struct frag_hdr) +
dst_exthdrlen);
/* Only the initial fragment is time stamped */
skb_shinfo(skb)->tx_flags = tx_flags;
tx_flags = 0;
skb_shinfo(skb)->tskey = tskey;
tskey = 0;
/*
* Find where to start putting bytes
*/
data = skb_put(skb, fraglen);
skb_set_network_header(skb, exthdrlen);
data += fragheaderlen;
skb->transport_header = (skb->network_header +
fragheaderlen);
if (fraggap) {
skb->csum = skb_copy_and_csum_bits(
skb_prev, maxfraglen,
data + transhdrlen, fraggap, 0);
skb_prev->csum = csum_sub(skb_prev->csum,
skb->csum);
data += fraggap;
pskb_trim_unique(skb_prev, maxfraglen);
}
if (copy > 0 &&
getfrag(from, data + transhdrlen, offset,
copy, fraggap, skb) < 0) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}
offset += copy;
length -= datalen - fraggap;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
if ((flags & MSG_CONFIRM) && !skb_prev)
skb_set_dst_pending_confirm(skb, 1);
/*
* Put the packet on the pending queue
*/
__skb_queue_tail(queue, skb);
continue;
}
if (copy > length)
copy = length;
if (!(rt->dst.dev->features&NETIF_F_SG)) {
unsigned int off;
off = skb->len;
if (getfrag(from, skb_put(skb, copy),
offset, copy, off, skb) < 0) {
__skb_trim(skb, off);
err = -EFAULT;
goto error;
}
} else {
int i = skb_shinfo(skb)->nr_frags;
err = -ENOMEM;
if (!sk_page_frag_refill(sk, pfrag))
goto error;
if (!skb_can_coalesce(skb, i, pfrag->page,
pfrag->offset)) {
err = -EMSGSIZE;
if (i == MAX_SKB_FRAGS)
goto error;
__skb_fill_page_desc(skb, i, pfrag->page,
pfrag->offset, 0);
skb_shinfo(skb)->nr_frags = ++i;
get_page(pfrag->page);
}
copy = min_t(int, copy, pfrag->size - pfrag->offset);
if (getfrag(from,
page_address(pfrag->page) + pfrag->offset,
offset, copy, skb->len, skb) < 0)
goto error_efault;
pfrag->offset += copy;
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
atomic_add(copy, &sk->sk_wmem_alloc);
}
offset += copy;
length -= copy;
}
return 0;
error_efault:
err = -EFAULT;
error:
cork->length -= length;
IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
return err;
}
int ip6_append_data(struct sock *sk,
int getfrag(void *from, char *to, int offset, int len,
int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
struct ipcm6_cookie *ipc6, struct flowi6 *fl6,
struct rt6_info *rt, unsigned int flags,
const struct sockcm_cookie *sockc)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
int exthdrlen;
int err;
if (flags&MSG_PROBE)
return 0;
if (skb_queue_empty(&sk->sk_write_queue)) {
/*
* setup for corking
*/
err = ip6_setup_cork(sk, &inet->cork, &np->cork,
ipc6, rt, fl6);
if (err)
return err;
exthdrlen = (ipc6->opt ? ipc6->opt->opt_flen : 0);
length += exthdrlen;
transhdrlen += exthdrlen;
} else {
fl6 = &inet->cork.fl.u.ip6;
transhdrlen = 0;
}
return __ip6_append_data(sk, fl6, &sk->sk_write_queue, &inet->cork.base,
&np->cork, sk_page_frag(sk), getfrag,
from, length, transhdrlen, flags, ipc6, sockc);
}
EXPORT_SYMBOL_GPL(ip6_append_data);
static void ip6_cork_release(struct inet_cork_full *cork,
struct inet6_cork *v6_cork)
{
if (v6_cork->opt) {
kfree(v6_cork->opt->dst0opt);
kfree(v6_cork->opt->dst1opt);
kfree(v6_cork->opt->hopopt);
kfree(v6_cork->opt->srcrt);
kfree(v6_cork->opt);
v6_cork->opt = NULL;
}
if (cork->base.dst) {
dst_release(cork->base.dst);
cork->base.dst = NULL;
cork->base.flags &= ~IPCORK_ALLFRAG;
}
memset(&cork->fl, 0, sizeof(cork->fl));
}
struct sk_buff *__ip6_make_skb(struct sock *sk,
struct sk_buff_head *queue,
struct inet_cork_full *cork,
struct inet6_cork *v6_cork)
{
struct sk_buff *skb, *tmp_skb;
struct sk_buff **tail_skb;
struct in6_addr final_dst_buf, *final_dst = &final_dst_buf;
struct ipv6_pinfo *np = inet6_sk(sk);
struct net *net = sock_net(sk);
struct ipv6hdr *hdr;
struct ipv6_txoptions *opt = v6_cork->opt;
struct rt6_info *rt = (struct rt6_info *)cork->base.dst;
struct flowi6 *fl6 = &cork->fl.u.ip6;
unsigned char proto = fl6->flowi6_proto;
skb = __skb_dequeue(queue);
if (!skb)
goto out;
tail_skb = &(skb_shinfo(skb)->frag_list);
/* move skb->data to ip header from ext header */
if (skb->data < skb_network_header(skb))
__skb_pull(skb, skb_network_offset(skb));
while ((tmp_skb = __skb_dequeue(queue)) != NULL) {
__skb_pull(tmp_skb, skb_network_header_len(skb));
*tail_skb = tmp_skb;
tail_skb = &(tmp_skb->next);
skb->len += tmp_skb->len;
skb->data_len += tmp_skb->len;
skb->truesize += tmp_skb->truesize;
tmp_skb->destructor = NULL;
tmp_skb->sk = NULL;
}
/* Allow local fragmentation. */
skb->ignore_df = ip6_sk_ignore_df(sk);
*final_dst = fl6->daddr;
__skb_pull(skb, skb_network_header_len(skb));
if (opt && opt->opt_flen)
ipv6_push_frag_opts(skb, opt, &proto);
if (opt && opt->opt_nflen)
ipv6_push_nfrag_opts(skb, opt, &proto, &final_dst, &fl6->saddr);
skb_push(skb, sizeof(struct ipv6hdr));
skb_reset_network_header(skb);
hdr = ipv6_hdr(skb);
ip6_flow_hdr(hdr, v6_cork->tclass,
ip6_make_flowlabel(net, skb, fl6->flowlabel,
np->autoflowlabel, fl6));
hdr->hop_limit = v6_cork->hop_limit;
hdr->nexthdr = proto;
hdr->saddr = fl6->saddr;
hdr->daddr = *final_dst;
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
skb_dst_set(skb, dst_clone(&rt->dst));
IP6_UPD_PO_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUT, skb->len);
if (proto == IPPROTO_ICMPV6) {
struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
ICMP6MSGOUT_INC_STATS(net, idev, icmp6_hdr(skb)->icmp6_type);
ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTMSGS);
}
ip6_cork_release(cork, v6_cork);
out:
return skb;
}
int ip6_send_skb(struct sk_buff *skb)
{
struct net *net = sock_net(skb->sk);
struct rt6_info *rt = (struct rt6_info *)skb_dst(skb);
int err;
err = ip6_local_out(net, skb->sk, skb);
if (err) {
if (err > 0)
err = net_xmit_errno(err);
if (err)
IP6_INC_STATS(net, rt->rt6i_idev,
IPSTATS_MIB_OUTDISCARDS);
}
return err;
}
int ip6_push_pending_frames(struct sock *sk)
{
struct sk_buff *skb;
skb = ip6_finish_skb(sk);
if (!skb)
return 0;
return ip6_send_skb(skb);
}
EXPORT_SYMBOL_GPL(ip6_push_pending_frames);
static void __ip6_flush_pending_frames(struct sock *sk,
struct sk_buff_head *queue,
struct inet_cork_full *cork,
struct inet6_cork *v6_cork)
{
struct sk_buff *skb;
while ((skb = __skb_dequeue_tail(queue)) != NULL) {
if (skb_dst(skb))
IP6_INC_STATS(sock_net(sk), ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
}
ip6_cork_release(cork, v6_cork);
}
void ip6_flush_pending_frames(struct sock *sk)
{
__ip6_flush_pending_frames(sk, &sk->sk_write_queue,
&inet_sk(sk)->cork, &inet6_sk(sk)->cork);
}
EXPORT_SYMBOL_GPL(ip6_flush_pending_frames);
struct sk_buff *ip6_make_skb(struct sock *sk,
int getfrag(void *from, char *to, int offset,
int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
struct ipcm6_cookie *ipc6, struct flowi6 *fl6,
struct rt6_info *rt, unsigned int flags,
const struct sockcm_cookie *sockc)
{
struct inet_cork_full cork;
struct inet6_cork v6_cork;
struct sk_buff_head queue;
int exthdrlen = (ipc6->opt ? ipc6->opt->opt_flen : 0);
int err;
if (flags & MSG_PROBE)
return NULL;
__skb_queue_head_init(&queue);
cork.base.flags = 0;
cork.base.addr = 0;
cork.base.opt = NULL;
v6_cork.opt = NULL;
err = ip6_setup_cork(sk, &cork, &v6_cork, ipc6, rt, fl6);
if (err)
return ERR_PTR(err);
if (ipc6->dontfrag < 0)
ipc6->dontfrag = inet6_sk(sk)->dontfrag;
err = __ip6_append_data(sk, fl6, &queue, &cork.base, &v6_cork,
¤t->task_frag, getfrag, from,
length + exthdrlen, transhdrlen + exthdrlen,
flags, ipc6, sockc);
if (err) {
__ip6_flush_pending_frames(sk, &queue, &cork, &v6_cork);
return ERR_PTR(err);
}
return __ip6_make_skb(sk, &queue, &cork, &v6_cork);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3379_0 |
crossvul-cpp_data_bad_4718_0 | /*
* reflection.c: Routines for creating an image at runtime.
*
* Author:
* Paolo Molaro (lupus@ximian.com)
*
* Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2009 Novell, Inc (http://www.novell.com)
*
*/
#include <config.h>
#include "mono/utils/mono-digest.h"
#include "mono/utils/mono-membar.h"
#include "mono/metadata/reflection.h"
#include "mono/metadata/tabledefs.h"
#include "mono/metadata/metadata-internals.h"
#include <mono/metadata/profiler-private.h>
#include "mono/metadata/class-internals.h"
#include "mono/metadata/gc-internal.h"
#include "mono/metadata/tokentype.h"
#include "mono/metadata/domain-internals.h"
#include "mono/metadata/opcodes.h"
#include "mono/metadata/assembly.h"
#include "mono/metadata/object-internals.h"
#include <mono/metadata/exception.h>
#include <mono/metadata/marshal.h>
#include <mono/metadata/security-manager.h>
#include <stdio.h>
#include <glib.h>
#include <errno.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
#include "image.h"
#include "cil-coff.h"
#include "mono-endian.h"
#include <mono/metadata/gc-internal.h>
#include <mono/metadata/mempool-internals.h>
#include <mono/metadata/security-core-clr.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/verify-internals.h>
#include <mono/metadata/mono-ptr-array.h>
#include <mono/utils/mono-string.h>
#include <mono/utils/mono-error-internals.h>
#if HAVE_SGEN_GC
static void* reflection_info_desc = NULL;
#define MOVING_GC_REGISTER(addr) do { \
if (!reflection_info_desc) { \
gsize bmap = 1; \
reflection_info_desc = mono_gc_make_descr_from_bitmap (&bmap, 1); \
} \
mono_gc_register_root ((char*)(addr), sizeof (gpointer), reflection_info_desc); \
} while (0)
#else
#define MOVING_GC_REGISTER(addr)
#endif
static gboolean is_usertype (MonoReflectionType *ref);
static MonoReflectionType *mono_reflection_type_resolve_user_types (MonoReflectionType *type);
typedef struct {
char *p;
char *buf;
char *end;
} SigBuffer;
#define TEXT_OFFSET 512
#define CLI_H_SIZE 136
#define FILE_ALIGN 512
#define VIRT_ALIGN 8192
#define START_TEXT_RVA 0x00002000
typedef struct {
MonoReflectionILGen *ilgen;
MonoReflectionType *rtype;
MonoArray *parameters;
MonoArray *generic_params;
MonoGenericContainer *generic_container;
MonoArray *pinfo;
MonoArray *opt_types;
guint32 attrs;
guint32 iattrs;
guint32 call_conv;
guint32 *table_idx; /* note: it's a pointer */
MonoArray *code;
MonoObject *type;
MonoString *name;
MonoBoolean init_locals;
MonoBoolean skip_visibility;
MonoArray *return_modreq;
MonoArray *return_modopt;
MonoArray *param_modreq;
MonoArray *param_modopt;
MonoArray *permissions;
MonoMethod *mhandle;
guint32 nrefs;
gpointer *refs;
/* for PInvoke */
int charset, extra_flags, native_cc;
MonoString *dll, *dllentry;
} ReflectionMethodBuilder;
typedef struct {
guint32 owner;
MonoReflectionGenericParam *gparam;
} GenericParamTableEntry;
const unsigned char table_sizes [MONO_TABLE_NUM] = {
MONO_MODULE_SIZE,
MONO_TYPEREF_SIZE,
MONO_TYPEDEF_SIZE,
0,
MONO_FIELD_SIZE,
0,
MONO_METHOD_SIZE,
0,
MONO_PARAM_SIZE,
MONO_INTERFACEIMPL_SIZE,
MONO_MEMBERREF_SIZE, /* 0x0A */
MONO_CONSTANT_SIZE,
MONO_CUSTOM_ATTR_SIZE,
MONO_FIELD_MARSHAL_SIZE,
MONO_DECL_SECURITY_SIZE,
MONO_CLASS_LAYOUT_SIZE,
MONO_FIELD_LAYOUT_SIZE, /* 0x10 */
MONO_STAND_ALONE_SIGNATURE_SIZE,
MONO_EVENT_MAP_SIZE,
0,
MONO_EVENT_SIZE,
MONO_PROPERTY_MAP_SIZE,
0,
MONO_PROPERTY_SIZE,
MONO_METHOD_SEMA_SIZE,
MONO_METHODIMPL_SIZE,
MONO_MODULEREF_SIZE, /* 0x1A */
MONO_TYPESPEC_SIZE,
MONO_IMPLMAP_SIZE,
MONO_FIELD_RVA_SIZE,
0,
0,
MONO_ASSEMBLY_SIZE, /* 0x20 */
MONO_ASSEMBLY_PROCESSOR_SIZE,
MONO_ASSEMBLYOS_SIZE,
MONO_ASSEMBLYREF_SIZE,
MONO_ASSEMBLYREFPROC_SIZE,
MONO_ASSEMBLYREFOS_SIZE,
MONO_FILE_SIZE,
MONO_EXP_TYPE_SIZE,
MONO_MANIFEST_SIZE,
MONO_NESTED_CLASS_SIZE,
MONO_GENERICPARAM_SIZE, /* 0x2A */
MONO_METHODSPEC_SIZE,
MONO_GENPARCONSTRAINT_SIZE
};
#ifndef DISABLE_REFLECTION_EMIT
static guint32 mono_image_get_methodref_token (MonoDynamicImage *assembly, MonoMethod *method, gboolean create_typespec);
static guint32 mono_image_get_methodbuilder_token (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb, gboolean create_open_instance);
static guint32 mono_image_get_ctorbuilder_token (MonoDynamicImage *assembly, MonoReflectionCtorBuilder *cb);
static guint32 mono_image_get_sighelper_token (MonoDynamicImage *assembly, MonoReflectionSigHelper *helper);
static void ensure_runtime_vtable (MonoClass *klass);
static gpointer resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, MonoGenericContext *context);
static guint32 mono_image_get_methodref_token_for_methodbuilder (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *method);
static guint32 encode_generic_method_sig (MonoDynamicImage *assembly, MonoGenericContext *context);
static gpointer register_assembly (MonoDomain *domain, MonoReflectionAssembly *res, MonoAssembly *assembly);
static void reflection_methodbuilder_from_method_builder (ReflectionMethodBuilder *rmb, MonoReflectionMethodBuilder *mb);
static void reflection_methodbuilder_from_ctor_builder (ReflectionMethodBuilder *rmb, MonoReflectionCtorBuilder *mb);
static guint32 create_generic_typespec (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *tb);
#endif
static guint32 mono_image_typedef_or_ref (MonoDynamicImage *assembly, MonoType *type);
static guint32 mono_image_typedef_or_ref_full (MonoDynamicImage *assembly, MonoType *type, gboolean try_typespec);
static void mono_image_get_generic_param_info (MonoReflectionGenericParam *gparam, guint32 owner, MonoDynamicImage *assembly);
static guint32 encode_marshal_blob (MonoDynamicImage *assembly, MonoReflectionMarshal *minfo);
static guint32 encode_constant (MonoDynamicImage *assembly, MonoObject *val, guint32 *ret_type);
static char* type_get_qualified_name (MonoType *type, MonoAssembly *ass);
static void encode_type (MonoDynamicImage *assembly, MonoType *type, SigBuffer *buf);
static void get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types);
static MonoReflectionType *mono_reflection_type_get_underlying_system_type (MonoReflectionType* t);
static MonoType* mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve);
static MonoReflectionType* mono_reflection_type_resolve_user_types (MonoReflectionType *type);
static gboolean is_sre_array (MonoClass *class);
static gboolean is_sre_byref (MonoClass *class);
static gboolean is_sre_pointer (MonoClass *class);
static gboolean is_sre_type_builder (MonoClass *class);
static gboolean is_sre_method_builder (MonoClass *class);
static gboolean is_sre_ctor_builder (MonoClass *class);
static gboolean is_sre_field_builder (MonoClass *class);
static gboolean is_sr_mono_method (MonoClass *class);
static gboolean is_sr_mono_cmethod (MonoClass *class);
static gboolean is_sr_mono_generic_method (MonoClass *class);
static gboolean is_sr_mono_generic_cmethod (MonoClass *class);
static gboolean is_sr_mono_field (MonoClass *class);
static gboolean is_sr_mono_property (MonoClass *class);
static gboolean is_sre_method_on_tb_inst (MonoClass *class);
static gboolean is_sre_ctor_on_tb_inst (MonoClass *class);
static guint32 mono_image_get_methodspec_token (MonoDynamicImage *assembly, MonoMethod *method);
static guint32 mono_image_get_inflated_method_token (MonoDynamicImage *assembly, MonoMethod *m);
static MonoMethod * inflate_method (MonoReflectionType *type, MonoObject *obj);
static guint32 create_typespec (MonoDynamicImage *assembly, MonoType *type);
static void init_type_builder_generics (MonoObject *type);
#define RESOLVE_TYPE(type) do { type = (void*)mono_reflection_type_resolve_user_types ((MonoReflectionType*)type); } while (0)
#define RESOLVE_ARRAY_TYPE_ELEMENT(array, index) do { \
MonoReflectionType *__type = mono_array_get (array, MonoReflectionType*, index); \
__type = mono_reflection_type_resolve_user_types (__type); \
mono_array_set (arr, MonoReflectionType*, index, __type); \
} while (0)
#define mono_type_array_get_and_resolve(array, index) mono_reflection_type_get_handle ((MonoReflectionType*)mono_array_get (array, gpointer, index))
void
mono_reflection_init (void)
{
}
static void
sigbuffer_init (SigBuffer *buf, int size)
{
buf->buf = g_malloc (size);
buf->p = buf->buf;
buf->end = buf->buf + size;
}
static void
sigbuffer_make_room (SigBuffer *buf, int size)
{
if (buf->end - buf->p < size) {
int new_size = buf->end - buf->buf + size + 32;
char *p = g_realloc (buf->buf, new_size);
size = buf->p - buf->buf;
buf->buf = p;
buf->p = p + size;
buf->end = buf->buf + new_size;
}
}
static void
sigbuffer_add_value (SigBuffer *buf, guint32 val)
{
sigbuffer_make_room (buf, 6);
mono_metadata_encode_value (val, buf->p, &buf->p);
}
static void
sigbuffer_add_byte (SigBuffer *buf, guint8 val)
{
sigbuffer_make_room (buf, 1);
buf->p [0] = val;
buf->p++;
}
static void
sigbuffer_add_mem (SigBuffer *buf, char *p, guint32 size)
{
sigbuffer_make_room (buf, size);
memcpy (buf->p, p, size);
buf->p += size;
}
static void
sigbuffer_free (SigBuffer *buf)
{
g_free (buf->buf);
}
#ifndef DISABLE_REFLECTION_EMIT
/**
* mp_g_alloc:
*
* Allocate memory from the @image mempool if it is non-NULL. Otherwise, allocate memory
* from the C heap.
*/
static gpointer
image_g_malloc (MonoImage *image, guint size)
{
if (image)
return mono_image_alloc (image, size);
else
return g_malloc (size);
}
#endif /* !DISABLE_REFLECTION_EMIT */
/**
* image_g_alloc0:
*
* Allocate memory from the @image mempool if it is non-NULL. Otherwise, allocate memory
* from the C heap.
*/
static gpointer
image_g_malloc0 (MonoImage *image, guint size)
{
if (image)
return mono_image_alloc0 (image, size);
else
return g_malloc0 (size);
}
#ifndef DISABLE_REFLECTION_EMIT
static char*
image_strdup (MonoImage *image, const char *s)
{
if (image)
return mono_image_strdup (image, s);
else
return g_strdup (s);
}
#endif
#define image_g_new(image,struct_type, n_structs) \
((struct_type *) image_g_malloc (image, ((gsize) sizeof (struct_type)) * ((gsize) (n_structs))))
#define image_g_new0(image,struct_type, n_structs) \
((struct_type *) image_g_malloc0 (image, ((gsize) sizeof (struct_type)) * ((gsize) (n_structs))))
static void
alloc_table (MonoDynamicTable *table, guint nrows)
{
table->rows = nrows;
g_assert (table->columns);
if (nrows + 1 >= table->alloc_rows) {
while (nrows + 1 >= table->alloc_rows) {
if (table->alloc_rows == 0)
table->alloc_rows = 16;
else
table->alloc_rows *= 2;
}
table->values = g_renew (guint32, table->values, (table->alloc_rows) * table->columns);
}
}
static void
make_room_in_stream (MonoDynamicStream *stream, int size)
{
if (size <= stream->alloc_size)
return;
while (stream->alloc_size <= size) {
if (stream->alloc_size < 4096)
stream->alloc_size = 4096;
else
stream->alloc_size *= 2;
}
stream->data = g_realloc (stream->data, stream->alloc_size);
}
static guint32
string_heap_insert (MonoDynamicStream *sh, const char *str)
{
guint32 idx;
guint32 len;
gpointer oldkey, oldval;
if (g_hash_table_lookup_extended (sh->hash, str, &oldkey, &oldval))
return GPOINTER_TO_UINT (oldval);
len = strlen (str) + 1;
idx = sh->index;
make_room_in_stream (sh, idx + len);
/*
* We strdup the string even if we already copy them in sh->data
* so that the string pointers in the hash remain valid even if
* we need to realloc sh->data. We may want to avoid that later.
*/
g_hash_table_insert (sh->hash, g_strdup (str), GUINT_TO_POINTER (idx));
memcpy (sh->data + idx, str, len);
sh->index += len;
return idx;
}
static guint32
string_heap_insert_mstring (MonoDynamicStream *sh, MonoString *str)
{
char *name = mono_string_to_utf8 (str);
guint32 idx;
idx = string_heap_insert (sh, name);
g_free (name);
return idx;
}
#ifndef DISABLE_REFLECTION_EMIT
static void
string_heap_init (MonoDynamicStream *sh)
{
sh->index = 0;
sh->alloc_size = 4096;
sh->data = g_malloc (4096);
sh->hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
string_heap_insert (sh, "");
}
#endif
static guint32
mono_image_add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
{
guint32 idx;
make_room_in_stream (stream, stream->index + len);
memcpy (stream->data + stream->index, data, len);
idx = stream->index;
stream->index += len;
/*
* align index? Not without adding an additional param that controls it since
* we may store a blob value in pieces.
*/
return idx;
}
static guint32
mono_image_add_stream_zero (MonoDynamicStream *stream, guint32 len)
{
guint32 idx;
make_room_in_stream (stream, stream->index + len);
memset (stream->data + stream->index, 0, len);
idx = stream->index;
stream->index += len;
return idx;
}
static void
stream_data_align (MonoDynamicStream *stream)
{
char buf [4] = {0};
guint32 count = stream->index % 4;
/* we assume the stream data will be aligned */
if (count)
mono_image_add_stream_data (stream, buf, 4 - count);
}
#ifndef DISABLE_REFLECTION_EMIT
static int
mono_blob_entry_hash (const char* str)
{
guint len, h;
const char *end;
len = mono_metadata_decode_blob_size (str, &str);
if (len > 0) {
end = str + len;
h = *str;
for (str += 1; str < end; str++)
h = (h << 5) - h + *str;
return h;
} else {
return 0;
}
}
static gboolean
mono_blob_entry_equal (const char *str1, const char *str2) {
int len, len2;
const char *end1;
const char *end2;
len = mono_metadata_decode_blob_size (str1, &end1);
len2 = mono_metadata_decode_blob_size (str2, &end2);
if (len != len2)
return 0;
return memcmp (end1, end2, len) == 0;
}
#endif
static guint32
add_to_blob_cached (MonoDynamicImage *assembly, char *b1, int s1, char *b2, int s2)
{
guint32 idx;
char *copy;
gpointer oldkey, oldval;
copy = g_malloc (s1+s2);
memcpy (copy, b1, s1);
memcpy (copy + s1, b2, s2);
if (g_hash_table_lookup_extended (assembly->blob_cache, copy, &oldkey, &oldval)) {
g_free (copy);
idx = GPOINTER_TO_UINT (oldval);
} else {
idx = mono_image_add_stream_data (&assembly->blob, b1, s1);
mono_image_add_stream_data (&assembly->blob, b2, s2);
g_hash_table_insert (assembly->blob_cache, copy, GUINT_TO_POINTER (idx));
}
return idx;
}
static guint32
sigbuffer_add_to_blob_cached (MonoDynamicImage *assembly, SigBuffer *buf)
{
char blob_size [8];
char *b = blob_size;
guint32 size = buf->p - buf->buf;
/* store length */
g_assert (size <= (buf->end - buf->buf));
mono_metadata_encode_value (size, b, &b);
return add_to_blob_cached (assembly, blob_size, b-blob_size, buf->buf, size);
}
/*
* Copy len * nelem bytes from val to dest, swapping bytes to LE if necessary.
* dest may be misaligned.
*/
static void
swap_with_size (char *dest, const char* val, int len, int nelem) {
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
int elem;
for (elem = 0; elem < nelem; ++elem) {
switch (len) {
case 1:
*dest = *val;
break;
case 2:
dest [0] = val [1];
dest [1] = val [0];
break;
case 4:
dest [0] = val [3];
dest [1] = val [2];
dest [2] = val [1];
dest [3] = val [0];
break;
case 8:
dest [0] = val [7];
dest [1] = val [6];
dest [2] = val [5];
dest [3] = val [4];
dest [4] = val [3];
dest [5] = val [2];
dest [6] = val [1];
dest [7] = val [0];
break;
default:
g_assert_not_reached ();
}
dest += len;
val += len;
}
#else
memcpy (dest, val, len * nelem);
#endif
}
static guint32
add_mono_string_to_blob_cached (MonoDynamicImage *assembly, MonoString *str)
{
char blob_size [64];
char *b = blob_size;
guint32 idx = 0, len;
len = str->length * 2;
mono_metadata_encode_value (len, b, &b);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
{
char *swapped = g_malloc (2 * mono_string_length (str));
const char *p = (const char*)mono_string_chars (str);
swap_with_size (swapped, p, 2, mono_string_length (str));
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, swapped, len);
g_free (swapped);
}
#else
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, (char*)mono_string_chars (str), len);
#endif
return idx;
}
#ifndef DISABLE_REFLECTION_EMIT
static MonoClass *
default_class_from_mono_type (MonoType *type)
{
switch (type->type) {
case MONO_TYPE_OBJECT:
return mono_defaults.object_class;
case MONO_TYPE_VOID:
return mono_defaults.void_class;
case MONO_TYPE_BOOLEAN:
return mono_defaults.boolean_class;
case MONO_TYPE_CHAR:
return mono_defaults.char_class;
case MONO_TYPE_I1:
return mono_defaults.sbyte_class;
case MONO_TYPE_U1:
return mono_defaults.byte_class;
case MONO_TYPE_I2:
return mono_defaults.int16_class;
case MONO_TYPE_U2:
return mono_defaults.uint16_class;
case MONO_TYPE_I4:
return mono_defaults.int32_class;
case MONO_TYPE_U4:
return mono_defaults.uint32_class;
case MONO_TYPE_I:
return mono_defaults.int_class;
case MONO_TYPE_U:
return mono_defaults.uint_class;
case MONO_TYPE_I8:
return mono_defaults.int64_class;
case MONO_TYPE_U8:
return mono_defaults.uint64_class;
case MONO_TYPE_R4:
return mono_defaults.single_class;
case MONO_TYPE_R8:
return mono_defaults.double_class;
case MONO_TYPE_STRING:
return mono_defaults.string_class;
default:
g_warning ("default_class_from_mono_type: implement me 0x%02x\n", type->type);
g_assert_not_reached ();
}
return NULL;
}
#endif
/*
* mono_class_get_ref_info:
*
* Return the type builder/generic param builder corresponding to KLASS, if it exists.
*/
gpointer
mono_class_get_ref_info (MonoClass *klass)
{
if (klass->ref_info_handle == 0)
return NULL;
else
return mono_gchandle_get_target (klass->ref_info_handle);
}
void
mono_class_set_ref_info (MonoClass *klass, gpointer obj)
{
klass->ref_info_handle = mono_gchandle_new ((MonoObject*)obj, FALSE);
g_assert (klass->ref_info_handle != 0);
}
void
mono_class_free_ref_info (MonoClass *klass)
{
if (klass->ref_info_handle) {
mono_gchandle_free (klass->ref_info_handle);
klass->ref_info_handle = 0;
}
}
static void
encode_generic_class (MonoDynamicImage *assembly, MonoGenericClass *gclass, SigBuffer *buf)
{
int i;
MonoGenericInst *class_inst;
MonoClass *klass;
g_assert (gclass);
class_inst = gclass->context.class_inst;
sigbuffer_add_value (buf, MONO_TYPE_GENERICINST);
klass = gclass->container_class;
sigbuffer_add_value (buf, klass->byval_arg.type);
sigbuffer_add_value (buf, mono_image_typedef_or_ref_full (assembly, &klass->byval_arg, FALSE));
sigbuffer_add_value (buf, class_inst->type_argc);
for (i = 0; i < class_inst->type_argc; ++i)
encode_type (assembly, class_inst->type_argv [i], buf);
}
static void
encode_type (MonoDynamicImage *assembly, MonoType *type, SigBuffer *buf)
{
if (!type) {
g_assert_not_reached ();
return;
}
if (type->byref)
sigbuffer_add_value (buf, MONO_TYPE_BYREF);
switch (type->type){
case MONO_TYPE_VOID:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_CHAR:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_TYPEDBYREF:
sigbuffer_add_value (buf, type->type);
break;
case MONO_TYPE_PTR:
sigbuffer_add_value (buf, type->type);
encode_type (assembly, type->data.type, buf);
break;
case MONO_TYPE_SZARRAY:
sigbuffer_add_value (buf, type->type);
encode_type (assembly, &type->data.klass->byval_arg, buf);
break;
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_CLASS: {
MonoClass *k = mono_class_from_mono_type (type);
if (k->generic_container) {
MonoGenericClass *gclass = mono_metadata_lookup_generic_class (k, k->generic_container->context.class_inst, TRUE);
encode_generic_class (assembly, gclass, buf);
} else {
/*
* Make sure we use the correct type.
*/
sigbuffer_add_value (buf, k->byval_arg.type);
/*
* ensure only non-byref gets passed to mono_image_typedef_or_ref(),
* otherwise two typerefs could point to the same type, leading to
* verification errors.
*/
sigbuffer_add_value (buf, mono_image_typedef_or_ref (assembly, &k->byval_arg));
}
break;
}
case MONO_TYPE_ARRAY:
sigbuffer_add_value (buf, type->type);
encode_type (assembly, &type->data.array->eklass->byval_arg, buf);
sigbuffer_add_value (buf, type->data.array->rank);
sigbuffer_add_value (buf, 0); /* FIXME: set to 0 for now */
sigbuffer_add_value (buf, 0);
break;
case MONO_TYPE_GENERICINST:
encode_generic_class (assembly, type->data.generic_class, buf);
break;
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
sigbuffer_add_value (buf, type->type);
sigbuffer_add_value (buf, mono_type_get_generic_param_num (type));
break;
default:
g_error ("need to encode type %x", type->type);
}
}
static void
encode_reflection_type (MonoDynamicImage *assembly, MonoReflectionType *type, SigBuffer *buf)
{
if (!type) {
sigbuffer_add_value (buf, MONO_TYPE_VOID);
return;
}
encode_type (assembly, mono_reflection_type_get_handle (type), buf);
}
static void
encode_custom_modifiers (MonoDynamicImage *assembly, MonoArray *modreq, MonoArray *modopt, SigBuffer *buf)
{
int i;
if (modreq) {
for (i = 0; i < mono_array_length (modreq); ++i) {
MonoType *mod = mono_type_array_get_and_resolve (modreq, i);
sigbuffer_add_byte (buf, MONO_TYPE_CMOD_REQD);
sigbuffer_add_value (buf, mono_image_typedef_or_ref (assembly, mod));
}
}
if (modopt) {
for (i = 0; i < mono_array_length (modopt); ++i) {
MonoType *mod = mono_type_array_get_and_resolve (modopt, i);
sigbuffer_add_byte (buf, MONO_TYPE_CMOD_OPT);
sigbuffer_add_value (buf, mono_image_typedef_or_ref (assembly, mod));
}
}
}
#ifndef DISABLE_REFLECTION_EMIT
static guint32
method_encode_signature (MonoDynamicImage *assembly, MonoMethodSignature *sig)
{
SigBuffer buf;
int i;
guint32 nparams = sig->param_count;
guint32 idx;
if (!assembly->save)
return 0;
sigbuffer_init (&buf, 32);
/*
* FIXME: vararg, explicit_this, differenc call_conv values...
*/
idx = sig->call_convention;
if (sig->hasthis)
idx |= 0x20; /* hasthis */
if (sig->generic_param_count)
idx |= 0x10; /* generic */
sigbuffer_add_byte (&buf, idx);
if (sig->generic_param_count)
sigbuffer_add_value (&buf, sig->generic_param_count);
sigbuffer_add_value (&buf, nparams);
encode_type (assembly, sig->ret, &buf);
for (i = 0; i < nparams; ++i) {
if (i == sig->sentinelpos)
sigbuffer_add_byte (&buf, MONO_TYPE_SENTINEL);
encode_type (assembly, sig->params [i], &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
#endif
static guint32
method_builder_encode_signature (MonoDynamicImage *assembly, ReflectionMethodBuilder *mb)
{
/*
* FIXME: reuse code from method_encode_signature().
*/
SigBuffer buf;
int i;
guint32 nparams = mb->parameters ? mono_array_length (mb->parameters): 0;
guint32 ngparams = mb->generic_params ? mono_array_length (mb->generic_params): 0;
guint32 notypes = mb->opt_types ? mono_array_length (mb->opt_types): 0;
guint32 idx;
sigbuffer_init (&buf, 32);
/* LAMESPEC: all the call conv spec is foobared */
idx = mb->call_conv & 0x60; /* has-this, explicit-this */
if (mb->call_conv & 2)
idx |= 0x5; /* vararg */
if (!(mb->attrs & METHOD_ATTRIBUTE_STATIC))
idx |= 0x20; /* hasthis */
if (ngparams)
idx |= 0x10; /* generic */
sigbuffer_add_byte (&buf, idx);
if (ngparams)
sigbuffer_add_value (&buf, ngparams);
sigbuffer_add_value (&buf, nparams + notypes);
encode_custom_modifiers (assembly, mb->return_modreq, mb->return_modopt, &buf);
encode_reflection_type (assembly, mb->rtype, &buf);
for (i = 0; i < nparams; ++i) {
MonoArray *modreq = NULL;
MonoArray *modopt = NULL;
MonoReflectionType *pt;
if (mb->param_modreq && (i < mono_array_length (mb->param_modreq)))
modreq = mono_array_get (mb->param_modreq, MonoArray*, i);
if (mb->param_modopt && (i < mono_array_length (mb->param_modopt)))
modopt = mono_array_get (mb->param_modopt, MonoArray*, i);
encode_custom_modifiers (assembly, modreq, modopt, &buf);
pt = mono_array_get (mb->parameters, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
if (notypes)
sigbuffer_add_byte (&buf, MONO_TYPE_SENTINEL);
for (i = 0; i < notypes; ++i) {
MonoReflectionType *pt;
pt = mono_array_get (mb->opt_types, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
encode_locals (MonoDynamicImage *assembly, MonoReflectionILGen *ilgen)
{
MonoDynamicTable *table;
guint32 *values;
guint32 idx, sig_idx;
guint nl = mono_array_length (ilgen->locals);
SigBuffer buf;
int i;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x07);
sigbuffer_add_value (&buf, nl);
for (i = 0; i < nl; ++i) {
MonoReflectionLocalBuilder *lb = mono_array_get (ilgen->locals, MonoReflectionLocalBuilder*, i);
if (lb->is_pinned)
sigbuffer_add_value (&buf, MONO_TYPE_PINNED);
encode_reflection_type (assembly, (MonoReflectionType*)lb->type, &buf);
}
sig_idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
if (assembly->standalonesig_cache == NULL)
assembly->standalonesig_cache = g_hash_table_new (NULL, NULL);
idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->standalonesig_cache, GUINT_TO_POINTER (sig_idx)));
if (idx)
return idx;
table = &assembly->tables [MONO_TABLE_STANDALONESIG];
idx = table->next_idx ++;
table->rows ++;
alloc_table (table, table->rows);
values = table->values + idx * MONO_STAND_ALONE_SIGNATURE_SIZE;
values [MONO_STAND_ALONE_SIGNATURE] = sig_idx;
g_hash_table_insert (assembly->standalonesig_cache, GUINT_TO_POINTER (sig_idx), GUINT_TO_POINTER (idx));
return idx;
}
static guint32
method_count_clauses (MonoReflectionILGen *ilgen)
{
guint32 num_clauses = 0;
int i;
MonoILExceptionInfo *ex_info;
for (i = 0; i < mono_array_length (ilgen->ex_handlers); ++i) {
ex_info = (MonoILExceptionInfo*)mono_array_addr (ilgen->ex_handlers, MonoILExceptionInfo, i);
if (ex_info->handlers)
num_clauses += mono_array_length (ex_info->handlers);
else
num_clauses++;
}
return num_clauses;
}
#ifndef DISABLE_REFLECTION_EMIT
static MonoExceptionClause*
method_encode_clauses (MonoImage *image, MonoDynamicImage *assembly, MonoReflectionILGen *ilgen, guint32 num_clauses)
{
MonoExceptionClause *clauses;
MonoExceptionClause *clause;
MonoILExceptionInfo *ex_info;
MonoILExceptionBlock *ex_block;
guint32 finally_start;
int i, j, clause_index;;
clauses = image_g_new0 (image, MonoExceptionClause, num_clauses);
clause_index = 0;
for (i = mono_array_length (ilgen->ex_handlers) - 1; i >= 0; --i) {
ex_info = (MonoILExceptionInfo*)mono_array_addr (ilgen->ex_handlers, MonoILExceptionInfo, i);
finally_start = ex_info->start + ex_info->len;
if (!ex_info->handlers)
continue;
for (j = 0; j < mono_array_length (ex_info->handlers); ++j) {
ex_block = (MonoILExceptionBlock*)mono_array_addr (ex_info->handlers, MonoILExceptionBlock, j);
clause = &(clauses [clause_index]);
clause->flags = ex_block->type;
clause->try_offset = ex_info->start;
if (ex_block->type == MONO_EXCEPTION_CLAUSE_FINALLY)
clause->try_len = finally_start - ex_info->start;
else
clause->try_len = ex_info->len;
clause->handler_offset = ex_block->start;
clause->handler_len = ex_block->len;
if (ex_block->extype) {
clause->data.catch_class = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)ex_block->extype));
} else {
if (ex_block->type == MONO_EXCEPTION_CLAUSE_FILTER)
clause->data.filter_offset = ex_block->filter_offset;
else
clause->data.filter_offset = 0;
}
finally_start = ex_block->start + ex_block->len;
clause_index ++;
}
}
return clauses;
}
#endif /* !DISABLE_REFLECTION_EMIT */
static guint32
method_encode_code (MonoDynamicImage *assembly, ReflectionMethodBuilder *mb)
{
char flags = 0;
guint32 idx;
guint32 code_size;
gint32 max_stack, i;
gint32 num_locals = 0;
gint32 num_exception = 0;
gint maybe_small;
guint32 fat_flags;
char fat_header [12];
guint32 int_value;
guint16 short_value;
guint32 local_sig = 0;
guint32 header_size = 12;
MonoArray *code;
if ((mb->attrs & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT)) ||
(mb->iattrs & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)))
return 0;
/*if (mb->name)
g_print ("Encode method %s\n", mono_string_to_utf8 (mb->name));*/
if (mb->ilgen) {
code = mb->ilgen->code;
code_size = mb->ilgen->code_len;
max_stack = mb->ilgen->max_stack;
num_locals = mb->ilgen->locals ? mono_array_length (mb->ilgen->locals) : 0;
if (mb->ilgen->ex_handlers)
num_exception = method_count_clauses (mb->ilgen);
} else {
code = mb->code;
if (code == NULL){
char *name = mono_string_to_utf8 (mb->name);
char *str = g_strdup_printf ("Method %s does not have any IL associated", name);
MonoException *exception = mono_get_exception_argument (NULL, "a method does not have any IL associated");
g_free (str);
g_free (name);
mono_raise_exception (exception);
}
code_size = mono_array_length (code);
max_stack = 8; /* we probably need to run a verifier on the code... */
}
stream_data_align (&assembly->code);
/* check for exceptions, maxstack, locals */
maybe_small = (max_stack <= 8) && (!num_locals) && (!num_exception);
if (maybe_small) {
if (code_size < 64 && !(code_size & 1)) {
flags = (code_size << 2) | 0x2;
} else if (code_size < 32 && (code_size & 1)) {
flags = (code_size << 2) | 0x6; /* LAMESPEC: see metadata.c */
} else {
goto fat_header;
}
idx = mono_image_add_stream_data (&assembly->code, &flags, 1);
/* add to the fixup todo list */
if (mb->ilgen && mb->ilgen->num_token_fixups)
mono_g_hash_table_insert (assembly->token_fixups, mb->ilgen, GUINT_TO_POINTER (idx + 1));
mono_image_add_stream_data (&assembly->code, mono_array_addr (code, char, 0), code_size);
return assembly->text_rva + idx;
}
fat_header:
if (num_locals)
local_sig = MONO_TOKEN_SIGNATURE | encode_locals (assembly, mb->ilgen);
/*
* FIXME: need to set also the header size in fat_flags.
* (and more sects and init locals flags)
*/
fat_flags = 0x03;
if (num_exception)
fat_flags |= METHOD_HEADER_MORE_SECTS;
if (mb->init_locals)
fat_flags |= METHOD_HEADER_INIT_LOCALS;
fat_header [0] = fat_flags;
fat_header [1] = (header_size / 4 ) << 4;
short_value = GUINT16_TO_LE (max_stack);
memcpy (fat_header + 2, &short_value, 2);
int_value = GUINT32_TO_LE (code_size);
memcpy (fat_header + 4, &int_value, 4);
int_value = GUINT32_TO_LE (local_sig);
memcpy (fat_header + 8, &int_value, 4);
idx = mono_image_add_stream_data (&assembly->code, fat_header, 12);
/* add to the fixup todo list */
if (mb->ilgen && mb->ilgen->num_token_fixups)
mono_g_hash_table_insert (assembly->token_fixups, mb->ilgen, GUINT_TO_POINTER (idx + 12));
mono_image_add_stream_data (&assembly->code, mono_array_addr (code, char, 0), code_size);
if (num_exception) {
unsigned char sheader [4];
MonoILExceptionInfo * ex_info;
MonoILExceptionBlock * ex_block;
int j;
stream_data_align (&assembly->code);
/* always use fat format for now */
sheader [0] = METHOD_HEADER_SECTION_FAT_FORMAT | METHOD_HEADER_SECTION_EHTABLE;
num_exception *= 6 * sizeof (guint32);
num_exception += 4; /* include the size of the header */
sheader [1] = num_exception & 0xff;
sheader [2] = (num_exception >> 8) & 0xff;
sheader [3] = (num_exception >> 16) & 0xff;
mono_image_add_stream_data (&assembly->code, (char*)sheader, 4);
/* fat header, so we are already aligned */
/* reverse order */
for (i = mono_array_length (mb->ilgen->ex_handlers) - 1; i >= 0; --i) {
ex_info = (MonoILExceptionInfo *)mono_array_addr (mb->ilgen->ex_handlers, MonoILExceptionInfo, i);
if (ex_info->handlers) {
int finally_start = ex_info->start + ex_info->len;
for (j = 0; j < mono_array_length (ex_info->handlers); ++j) {
guint32 val;
ex_block = (MonoILExceptionBlock*)mono_array_addr (ex_info->handlers, MonoILExceptionBlock, j);
/* the flags */
val = GUINT32_TO_LE (ex_block->type);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/* try offset */
val = GUINT32_TO_LE (ex_info->start);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/* need fault, too, probably */
if (ex_block->type == MONO_EXCEPTION_CLAUSE_FINALLY)
val = GUINT32_TO_LE (finally_start - ex_info->start);
else
val = GUINT32_TO_LE (ex_info->len);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/* handler offset */
val = GUINT32_TO_LE (ex_block->start);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/* handler len */
val = GUINT32_TO_LE (ex_block->len);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
finally_start = ex_block->start + ex_block->len;
if (ex_block->extype) {
val = mono_metadata_token_from_dor (mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)ex_block->extype)));
} else {
if (ex_block->type == MONO_EXCEPTION_CLAUSE_FILTER)
val = ex_block->filter_offset;
else
val = 0;
}
val = GUINT32_TO_LE (val);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/*g_print ("out clause %d: from %d len=%d, handler at %d, %d, finally_start=%d, ex_info->start=%d, ex_info->len=%d, ex_block->type=%d, j=%d, i=%d\n",
clause.flags, clause.try_offset, clause.try_len, clause.handler_offset, clause.handler_len, finally_start, ex_info->start, ex_info->len, ex_block->type, j, i);*/
}
} else {
g_error ("No clauses for ex info block %d", i);
}
}
}
return assembly->text_rva + idx;
}
static guint32
find_index_in_table (MonoDynamicImage *assembly, int table_idx, int col, guint32 token)
{
int i;
MonoDynamicTable *table;
guint32 *values;
table = &assembly->tables [table_idx];
g_assert (col < table->columns);
values = table->values + table->columns;
for (i = 1; i <= table->rows; ++i) {
if (values [col] == token)
return i;
values += table->columns;
}
return 0;
}
/*
* LOCKING: Acquires the loader lock.
*/
static MonoCustomAttrInfo*
lookup_custom_attr (MonoImage *image, gpointer member)
{
MonoCustomAttrInfo* res;
res = mono_image_property_lookup (image, member, MONO_PROP_DYNAMIC_CATTR);
if (!res)
return NULL;
return g_memdup (res, MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * res->num_attrs);
}
static gboolean
custom_attr_visible (MonoImage *image, MonoReflectionCustomAttr *cattr)
{
/* FIXME: Need to do more checks */
if (cattr->ctor->method && (cattr->ctor->method->klass->image != image)) {
int visibility = cattr->ctor->method->klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
if ((visibility != TYPE_ATTRIBUTE_PUBLIC) && (visibility != TYPE_ATTRIBUTE_NESTED_PUBLIC))
return FALSE;
}
return TRUE;
}
static MonoCustomAttrInfo*
mono_custom_attrs_from_builders (MonoImage *alloc_img, MonoImage *image, MonoArray *cattrs)
{
int i, index, count, not_visible;
MonoCustomAttrInfo *ainfo;
MonoReflectionCustomAttr *cattr;
if (!cattrs)
return NULL;
/* FIXME: check in assembly the Run flag is set */
count = mono_array_length (cattrs);
/* Skip nonpublic attributes since MS.NET seems to do the same */
/* FIXME: This needs to be done more globally */
not_visible = 0;
for (i = 0; i < count; ++i) {
cattr = (MonoReflectionCustomAttr*)mono_array_get (cattrs, gpointer, i);
if (!custom_attr_visible (image, cattr))
not_visible ++;
}
count -= not_visible;
ainfo = image_g_malloc0 (alloc_img, MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * count);
ainfo->image = image;
ainfo->num_attrs = count;
ainfo->cached = alloc_img != NULL;
index = 0;
for (i = 0; i < count; ++i) {
cattr = (MonoReflectionCustomAttr*)mono_array_get (cattrs, gpointer, i);
if (custom_attr_visible (image, cattr)) {
unsigned char *saved = mono_image_alloc (image, mono_array_length (cattr->data));
memcpy (saved, mono_array_addr (cattr->data, char, 0), mono_array_length (cattr->data));
ainfo->attrs [index].ctor = cattr->ctor->method;
ainfo->attrs [index].data = saved;
ainfo->attrs [index].data_size = mono_array_length (cattr->data);
index ++;
}
}
return ainfo;
}
#ifndef DISABLE_REFLECTION_EMIT
/*
* LOCKING: Acquires the loader lock.
*/
static void
mono_save_custom_attrs (MonoImage *image, void *obj, MonoArray *cattrs)
{
MonoCustomAttrInfo *ainfo, *tmp;
if (!cattrs || !mono_array_length (cattrs))
return;
ainfo = mono_custom_attrs_from_builders (image, image, cattrs);
mono_loader_lock ();
tmp = mono_image_property_lookup (image, obj, MONO_PROP_DYNAMIC_CATTR);
if (tmp)
mono_custom_attrs_free (tmp);
mono_image_property_insert (image, obj, MONO_PROP_DYNAMIC_CATTR, ainfo);
mono_loader_unlock ();
}
#endif
void
mono_custom_attrs_free (MonoCustomAttrInfo *ainfo)
{
if (!ainfo->cached)
g_free (ainfo);
}
/*
* idx is the table index of the object
* type is one of MONO_CUSTOM_ATTR_*
*/
static void
mono_image_add_cattrs (MonoDynamicImage *assembly, guint32 idx, guint32 type, MonoArray *cattrs)
{
MonoDynamicTable *table;
MonoReflectionCustomAttr *cattr;
guint32 *values;
guint32 count, i, token;
char blob_size [6];
char *p = blob_size;
/* it is legal to pass a NULL cattrs: we avoid to use the if in a lot of places */
if (!cattrs)
return;
count = mono_array_length (cattrs);
table = &assembly->tables [MONO_TABLE_CUSTOMATTRIBUTE];
table->rows += count;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_CUSTOM_ATTR_SIZE;
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= type;
for (i = 0; i < count; ++i) {
cattr = (MonoReflectionCustomAttr*)mono_array_get (cattrs, gpointer, i);
values [MONO_CUSTOM_ATTR_PARENT] = idx;
token = mono_image_create_token (assembly, (MonoObject*)cattr->ctor, FALSE, FALSE);
type = mono_metadata_token_index (token);
type <<= MONO_CUSTOM_ATTR_TYPE_BITS;
switch (mono_metadata_token_table (token)) {
case MONO_TABLE_METHOD:
type |= MONO_CUSTOM_ATTR_TYPE_METHODDEF;
break;
case MONO_TABLE_MEMBERREF:
type |= MONO_CUSTOM_ATTR_TYPE_MEMBERREF;
break;
default:
g_warning ("got wrong token in custom attr");
continue;
}
values [MONO_CUSTOM_ATTR_TYPE] = type;
p = blob_size;
mono_metadata_encode_value (mono_array_length (cattr->data), p, &p);
values [MONO_CUSTOM_ATTR_VALUE] = add_to_blob_cached (assembly, blob_size, p - blob_size,
mono_array_addr (cattr->data, char, 0), mono_array_length (cattr->data));
values += MONO_CUSTOM_ATTR_SIZE;
++table->next_idx;
}
}
static void
mono_image_add_decl_security (MonoDynamicImage *assembly, guint32 parent_token, MonoArray *permissions)
{
MonoDynamicTable *table;
guint32 *values;
guint32 count, i, idx;
MonoReflectionPermissionSet *perm;
if (!permissions)
return;
count = mono_array_length (permissions);
table = &assembly->tables [MONO_TABLE_DECLSECURITY];
table->rows += count;
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (permissions); ++i) {
perm = (MonoReflectionPermissionSet*)mono_array_addr (permissions, MonoReflectionPermissionSet, i);
values = table->values + table->next_idx * MONO_DECL_SECURITY_SIZE;
idx = mono_metadata_token_index (parent_token);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
switch (mono_metadata_token_table (parent_token)) {
case MONO_TABLE_TYPEDEF:
idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
break;
case MONO_TABLE_METHOD:
idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
break;
case MONO_TABLE_ASSEMBLY:
idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY;
break;
default:
g_assert_not_reached ();
}
values [MONO_DECL_SECURITY_ACTION] = perm->action;
values [MONO_DECL_SECURITY_PARENT] = idx;
values [MONO_DECL_SECURITY_PERMISSIONSET] = add_mono_string_to_blob_cached (assembly, perm->pset);
++table->next_idx;
}
}
/*
* Fill in the MethodDef and ParamDef tables for a method.
* This is used for both normal methods and constructors.
*/
static void
mono_image_basic_method (ReflectionMethodBuilder *mb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint i, count;
/* room in this table is already allocated */
table = &assembly->tables [MONO_TABLE_METHOD];
*mb->table_idx = table->next_idx ++;
g_hash_table_insert (assembly->method_to_table_idx, mb->mhandle, GUINT_TO_POINTER ((*mb->table_idx)));
values = table->values + *mb->table_idx * MONO_METHOD_SIZE;
values [MONO_METHOD_NAME] = string_heap_insert_mstring (&assembly->sheap, mb->name);
values [MONO_METHOD_FLAGS] = mb->attrs;
values [MONO_METHOD_IMPLFLAGS] = mb->iattrs;
values [MONO_METHOD_SIGNATURE] = method_builder_encode_signature (assembly, mb);
values [MONO_METHOD_RVA] = method_encode_code (assembly, mb);
table = &assembly->tables [MONO_TABLE_PARAM];
values [MONO_METHOD_PARAMLIST] = table->next_idx;
mono_image_add_decl_security (assembly,
mono_metadata_make_token (MONO_TABLE_METHOD, *mb->table_idx), mb->permissions);
if (mb->pinfo) {
MonoDynamicTable *mtable;
guint32 *mvalues;
mtable = &assembly->tables [MONO_TABLE_FIELDMARSHAL];
mvalues = mtable->values + mtable->next_idx * MONO_FIELD_MARSHAL_SIZE;
count = 0;
for (i = 0; i < mono_array_length (mb->pinfo); ++i) {
if (mono_array_get (mb->pinfo, gpointer, i))
count++;
}
table->rows += count;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_PARAM_SIZE;
for (i = 0; i < mono_array_length (mb->pinfo); ++i) {
MonoReflectionParamBuilder *pb;
if ((pb = mono_array_get (mb->pinfo, MonoReflectionParamBuilder*, i))) {
values [MONO_PARAM_FLAGS] = pb->attrs;
values [MONO_PARAM_SEQUENCE] = i;
if (pb->name != NULL) {
values [MONO_PARAM_NAME] = string_heap_insert_mstring (&assembly->sheap, pb->name);
} else {
values [MONO_PARAM_NAME] = 0;
}
values += MONO_PARAM_SIZE;
if (pb->marshal_info) {
mtable->rows++;
alloc_table (mtable, mtable->rows);
mvalues = mtable->values + mtable->rows * MONO_FIELD_MARSHAL_SIZE;
mvalues [MONO_FIELD_MARSHAL_PARENT] = (table->next_idx << MONO_HAS_FIELD_MARSHAL_BITS) | MONO_HAS_FIELD_MARSHAL_PARAMDEF;
mvalues [MONO_FIELD_MARSHAL_NATIVE_TYPE] = encode_marshal_blob (assembly, pb->marshal_info);
}
pb->table_idx = table->next_idx++;
if (pb->attrs & PARAM_ATTRIBUTE_HAS_DEFAULT) {
guint32 field_type = 0;
mtable = &assembly->tables [MONO_TABLE_CONSTANT];
mtable->rows ++;
alloc_table (mtable, mtable->rows);
mvalues = mtable->values + mtable->rows * MONO_CONSTANT_SIZE;
mvalues [MONO_CONSTANT_PARENT] = MONO_HASCONSTANT_PARAM | (pb->table_idx << MONO_HASCONSTANT_BITS);
mvalues [MONO_CONSTANT_VALUE] = encode_constant (assembly, pb->def_value, &field_type);
mvalues [MONO_CONSTANT_TYPE] = field_type;
mvalues [MONO_CONSTANT_PADDING] = 0;
}
}
}
}
}
#ifndef DISABLE_REFLECTION_EMIT
static void
reflection_methodbuilder_from_method_builder (ReflectionMethodBuilder *rmb, MonoReflectionMethodBuilder *mb)
{
memset (rmb, 0, sizeof (ReflectionMethodBuilder));
rmb->ilgen = mb->ilgen;
rmb->rtype = mono_reflection_type_resolve_user_types ((MonoReflectionType*)mb->rtype);
rmb->parameters = mb->parameters;
rmb->generic_params = mb->generic_params;
rmb->generic_container = mb->generic_container;
rmb->opt_types = NULL;
rmb->pinfo = mb->pinfo;
rmb->attrs = mb->attrs;
rmb->iattrs = mb->iattrs;
rmb->call_conv = mb->call_conv;
rmb->code = mb->code;
rmb->type = mb->type;
rmb->name = mb->name;
rmb->table_idx = &mb->table_idx;
rmb->init_locals = mb->init_locals;
rmb->skip_visibility = FALSE;
rmb->return_modreq = mb->return_modreq;
rmb->return_modopt = mb->return_modopt;
rmb->param_modreq = mb->param_modreq;
rmb->param_modopt = mb->param_modopt;
rmb->permissions = mb->permissions;
rmb->mhandle = mb->mhandle;
rmb->nrefs = 0;
rmb->refs = NULL;
if (mb->dll) {
rmb->charset = mb->charset;
rmb->extra_flags = mb->extra_flags;
rmb->native_cc = mb->native_cc;
rmb->dllentry = mb->dllentry;
rmb->dll = mb->dll;
}
}
static void
reflection_methodbuilder_from_ctor_builder (ReflectionMethodBuilder *rmb, MonoReflectionCtorBuilder *mb)
{
const char *name = mb->attrs & METHOD_ATTRIBUTE_STATIC ? ".cctor": ".ctor";
memset (rmb, 0, sizeof (ReflectionMethodBuilder));
rmb->ilgen = mb->ilgen;
rmb->rtype = mono_type_get_object (mono_domain_get (), &mono_defaults.void_class->byval_arg);
rmb->parameters = mb->parameters;
rmb->generic_params = NULL;
rmb->generic_container = NULL;
rmb->opt_types = NULL;
rmb->pinfo = mb->pinfo;
rmb->attrs = mb->attrs;
rmb->iattrs = mb->iattrs;
rmb->call_conv = mb->call_conv;
rmb->code = NULL;
rmb->type = mb->type;
rmb->name = mono_string_new (mono_domain_get (), name);
rmb->table_idx = &mb->table_idx;
rmb->init_locals = mb->init_locals;
rmb->skip_visibility = FALSE;
rmb->return_modreq = NULL;
rmb->return_modopt = NULL;
rmb->param_modreq = mb->param_modreq;
rmb->param_modopt = mb->param_modopt;
rmb->permissions = mb->permissions;
rmb->mhandle = mb->mhandle;
rmb->nrefs = 0;
rmb->refs = NULL;
}
static void
reflection_methodbuilder_from_dynamic_method (ReflectionMethodBuilder *rmb, MonoReflectionDynamicMethod *mb)
{
memset (rmb, 0, sizeof (ReflectionMethodBuilder));
rmb->ilgen = mb->ilgen;
rmb->rtype = mb->rtype;
rmb->parameters = mb->parameters;
rmb->generic_params = NULL;
rmb->generic_container = NULL;
rmb->opt_types = NULL;
rmb->pinfo = NULL;
rmb->attrs = mb->attrs;
rmb->iattrs = 0;
rmb->call_conv = mb->call_conv;
rmb->code = NULL;
rmb->type = (MonoObject *) mb->owner;
rmb->name = mb->name;
rmb->table_idx = NULL;
rmb->init_locals = mb->init_locals;
rmb->skip_visibility = mb->skip_visibility;
rmb->return_modreq = NULL;
rmb->return_modopt = NULL;
rmb->param_modreq = NULL;
rmb->param_modopt = NULL;
rmb->permissions = NULL;
rmb->mhandle = mb->mhandle;
rmb->nrefs = 0;
rmb->refs = NULL;
}
#endif
static void
mono_image_add_methodimpl (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb)
{
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)mb->type;
MonoDynamicTable *table;
guint32 *values;
guint32 tok;
if (!mb->override_method)
return;
table = &assembly->tables [MONO_TABLE_METHODIMPL];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_METHODIMPL_SIZE;
values [MONO_METHODIMPL_CLASS] = tb->table_idx;
values [MONO_METHODIMPL_BODY] = MONO_METHODDEFORREF_METHODDEF | (mb->table_idx << MONO_METHODDEFORREF_BITS);
tok = mono_image_create_token (assembly, (MonoObject*)mb->override_method, FALSE, FALSE);
switch (mono_metadata_token_table (tok)) {
case MONO_TABLE_MEMBERREF:
tok = (mono_metadata_token_index (tok) << MONO_METHODDEFORREF_BITS ) | MONO_METHODDEFORREF_METHODREF;
break;
case MONO_TABLE_METHOD:
tok = (mono_metadata_token_index (tok) << MONO_METHODDEFORREF_BITS ) | MONO_METHODDEFORREF_METHODDEF;
break;
default:
g_assert_not_reached ();
}
values [MONO_METHODIMPL_DECLARATION] = tok;
}
#ifndef DISABLE_REFLECTION_EMIT
static void
mono_image_get_method_info (MonoReflectionMethodBuilder *mb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
ReflectionMethodBuilder rmb;
int i;
reflection_methodbuilder_from_method_builder (&rmb, mb);
mono_image_basic_method (&rmb, assembly);
mb->table_idx = *rmb.table_idx;
if (mb->dll) { /* It's a P/Invoke method */
guint32 moduleref;
/* map CharSet values to on-disk values */
int ncharset = (mb->charset ? (mb->charset - 1) * 2 : 0);
int extra_flags = mb->extra_flags;
table = &assembly->tables [MONO_TABLE_IMPLMAP];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_IMPLMAP_SIZE;
values [MONO_IMPLMAP_FLAGS] = (mb->native_cc << 8) | ncharset | extra_flags;
values [MONO_IMPLMAP_MEMBER] = (mb->table_idx << 1) | 1; /* memberforwarded: method */
if (mb->dllentry)
values [MONO_IMPLMAP_NAME] = string_heap_insert_mstring (&assembly->sheap, mb->dllentry);
else
values [MONO_IMPLMAP_NAME] = string_heap_insert_mstring (&assembly->sheap, mb->name);
moduleref = string_heap_insert_mstring (&assembly->sheap, mb->dll);
if (!(values [MONO_IMPLMAP_SCOPE] = find_index_in_table (assembly, MONO_TABLE_MODULEREF, MONO_MODULEREF_NAME, moduleref))) {
table = &assembly->tables [MONO_TABLE_MODULEREF];
table->rows ++;
alloc_table (table, table->rows);
table->values [table->rows * MONO_MODULEREF_SIZE + MONO_MODULEREF_NAME] = moduleref;
values [MONO_IMPLMAP_SCOPE] = table->rows;
}
}
if (mb->generic_params) {
table = &assembly->tables [MONO_TABLE_GENERICPARAM];
table->rows += mono_array_length (mb->generic_params);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (mb->generic_params); ++i) {
guint32 owner = MONO_TYPEORMETHOD_METHOD | (mb->table_idx << MONO_TYPEORMETHOD_BITS);
mono_image_get_generic_param_info (
mono_array_get (mb->generic_params, gpointer, i), owner, assembly);
}
}
}
static void
mono_image_get_ctor_info (MonoDomain *domain, MonoReflectionCtorBuilder *mb, MonoDynamicImage *assembly)
{
ReflectionMethodBuilder rmb;
reflection_methodbuilder_from_ctor_builder (&rmb, mb);
mono_image_basic_method (&rmb, assembly);
mb->table_idx = *rmb.table_idx;
}
#endif
static char*
type_get_fully_qualified_name (MonoType *type)
{
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED);
}
static char*
type_get_qualified_name (MonoType *type, MonoAssembly *ass) {
MonoClass *klass;
MonoAssembly *ta;
klass = mono_class_from_mono_type (type);
if (!klass)
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_REFLECTION);
ta = klass->image->assembly;
if (ta->dynamic || (ta == ass)) {
if (klass->generic_class || klass->generic_container)
/* For generic type definitions, we want T, while REFLECTION returns T<K> */
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_FULL_NAME);
else
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_REFLECTION);
}
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED);
}
#ifndef DISABLE_REFLECTION_EMIT
/*field_image is the image to which the eventual custom mods have been encoded against*/
static guint32
fieldref_encode_signature (MonoDynamicImage *assembly, MonoImage *field_image, MonoType *type)
{
SigBuffer buf;
guint32 idx, i, token;
if (!assembly->save)
return 0;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x06);
/* encode custom attributes before the type */
if (type->num_mods) {
for (i = 0; i < type->num_mods; ++i) {
if (field_image) {
MonoClass *class = mono_class_get (field_image, type->modifiers [i].token);
g_assert (class);
token = mono_image_typedef_or_ref (assembly, &class->byval_arg);
} else {
token = type->modifiers [i].token;
}
if (type->modifiers [i].required)
sigbuffer_add_byte (&buf, MONO_TYPE_CMOD_REQD);
else
sigbuffer_add_byte (&buf, MONO_TYPE_CMOD_OPT);
sigbuffer_add_value (&buf, token);
}
}
encode_type (assembly, type, &buf);
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
#endif
static guint32
field_encode_signature (MonoDynamicImage *assembly, MonoReflectionFieldBuilder *fb)
{
SigBuffer buf;
guint32 idx;
guint32 typespec = 0;
MonoType *type;
MonoClass *class;
init_type_builder_generics (fb->type);
type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
class = mono_class_from_mono_type (type);
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x06);
encode_custom_modifiers (assembly, fb->modreq, fb->modopt, &buf);
/* encode custom attributes before the type */
if (class->generic_container)
typespec = create_typespec (assembly, type);
if (typespec) {
MonoGenericClass *gclass;
gclass = mono_metadata_lookup_generic_class (class, class->generic_container->context.class_inst, TRUE);
encode_generic_class (assembly, gclass, &buf);
} else {
encode_type (assembly, type, &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
encode_constant (MonoDynamicImage *assembly, MonoObject *val, guint32 *ret_type) {
char blob_size [64];
char *b = blob_size;
char *p, *box_val;
char* buf;
guint32 idx = 0, len = 0, dummy = 0;
#ifdef ARM_FPU_FPA
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
guint32 fpa_double [2];
guint32 *fpa_p;
#endif
#endif
p = buf = g_malloc (64);
if (!val) {
*ret_type = MONO_TYPE_CLASS;
len = 4;
box_val = (char*)&dummy;
} else {
box_val = ((char*)val) + sizeof (MonoObject);
*ret_type = val->vtable->klass->byval_arg.type;
}
handle_enum:
switch (*ret_type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_U1:
case MONO_TYPE_I1:
len = 1;
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
len = 2;
break;
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_R4:
len = 4;
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
len = 8;
break;
case MONO_TYPE_R8:
len = 8;
#ifdef ARM_FPU_FPA
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
fpa_p = (guint32*)box_val;
fpa_double [0] = fpa_p [1];
fpa_double [1] = fpa_p [0];
box_val = (char*)fpa_double;
#endif
#endif
break;
case MONO_TYPE_VALUETYPE: {
MonoClass *klass = val->vtable->klass;
if (klass->enumtype) {
*ret_type = mono_class_enum_basetype (klass)->type;
goto handle_enum;
} else if (mono_is_corlib_image (klass->image) && strcmp (klass->name_space, "System") == 0 && strcmp (klass->name, "DateTime") == 0) {
len = 8;
} else
g_error ("we can't encode valuetypes, we should have never reached this line");
break;
}
case MONO_TYPE_CLASS:
break;
case MONO_TYPE_STRING: {
MonoString *str = (MonoString*)val;
/* there is no signature */
len = str->length * 2;
mono_metadata_encode_value (len, b, &b);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
{
char *swapped = g_malloc (2 * mono_string_length (str));
const char *p = (const char*)mono_string_chars (str);
swap_with_size (swapped, p, 2, mono_string_length (str));
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, swapped, len);
g_free (swapped);
}
#else
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, (char*)mono_string_chars (str), len);
#endif
g_free (buf);
return idx;
}
case MONO_TYPE_GENERICINST:
*ret_type = val->vtable->klass->generic_class->container_class->byval_arg.type;
goto handle_enum;
default:
g_error ("we don't encode constant type 0x%02x yet", *ret_type);
}
/* there is no signature */
mono_metadata_encode_value (len, b, &b);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
idx = mono_image_add_stream_data (&assembly->blob, blob_size, b-blob_size);
swap_with_size (blob_size, box_val, len, 1);
mono_image_add_stream_data (&assembly->blob, blob_size, len);
#else
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, box_val, len);
#endif
g_free (buf);
return idx;
}
static guint32
encode_marshal_blob (MonoDynamicImage *assembly, MonoReflectionMarshal *minfo) {
char *str;
SigBuffer buf;
guint32 idx, len;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, minfo->type);
switch (minfo->type) {
case MONO_NATIVE_BYVALTSTR:
case MONO_NATIVE_BYVALARRAY:
sigbuffer_add_value (&buf, minfo->count);
break;
case MONO_NATIVE_LPARRAY:
if (minfo->eltype || minfo->has_size) {
sigbuffer_add_value (&buf, minfo->eltype);
if (minfo->has_size) {
sigbuffer_add_value (&buf, minfo->param_num != -1? minfo->param_num: 0);
sigbuffer_add_value (&buf, minfo->count != -1? minfo->count: 0);
/* LAMESPEC: ElemMult is undocumented */
sigbuffer_add_value (&buf, minfo->param_num != -1? 1: 0);
}
}
break;
case MONO_NATIVE_SAFEARRAY:
if (minfo->eltype)
sigbuffer_add_value (&buf, minfo->eltype);
break;
case MONO_NATIVE_CUSTOM:
if (minfo->guid) {
str = mono_string_to_utf8 (minfo->guid);
len = strlen (str);
sigbuffer_add_value (&buf, len);
sigbuffer_add_mem (&buf, str, len);
g_free (str);
} else {
sigbuffer_add_value (&buf, 0);
}
/* native type name */
sigbuffer_add_value (&buf, 0);
/* custom marshaler type name */
if (minfo->marshaltype || minfo->marshaltyperef) {
if (minfo->marshaltyperef)
str = type_get_fully_qualified_name (mono_reflection_type_get_handle ((MonoReflectionType*)minfo->marshaltyperef));
else
str = mono_string_to_utf8 (minfo->marshaltype);
len = strlen (str);
sigbuffer_add_value (&buf, len);
sigbuffer_add_mem (&buf, str, len);
g_free (str);
} else {
/* FIXME: Actually a bug, since this field is required. Punting for now ... */
sigbuffer_add_value (&buf, 0);
}
if (minfo->mcookie) {
str = mono_string_to_utf8 (minfo->mcookie);
len = strlen (str);
sigbuffer_add_value (&buf, len);
sigbuffer_add_mem (&buf, str, len);
g_free (str);
} else {
sigbuffer_add_value (&buf, 0);
}
break;
default:
break;
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static void
mono_image_get_field_info (MonoReflectionFieldBuilder *fb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
/* maybe this fixup should be done in the C# code */
if (fb->attrs & FIELD_ATTRIBUTE_LITERAL)
fb->attrs |= FIELD_ATTRIBUTE_HAS_DEFAULT;
table = &assembly->tables [MONO_TABLE_FIELD];
fb->table_idx = table->next_idx ++;
g_hash_table_insert (assembly->field_to_table_idx, fb->handle, GUINT_TO_POINTER (fb->table_idx));
values = table->values + fb->table_idx * MONO_FIELD_SIZE;
values [MONO_FIELD_NAME] = string_heap_insert_mstring (&assembly->sheap, fb->name);
values [MONO_FIELD_FLAGS] = fb->attrs;
values [MONO_FIELD_SIGNATURE] = field_encode_signature (assembly, fb);
if (fb->offset != -1) {
table = &assembly->tables [MONO_TABLE_FIELDLAYOUT];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_FIELD_LAYOUT_SIZE;
values [MONO_FIELD_LAYOUT_FIELD] = fb->table_idx;
values [MONO_FIELD_LAYOUT_OFFSET] = fb->offset;
}
if (fb->attrs & FIELD_ATTRIBUTE_LITERAL) {
guint32 field_type = 0;
table = &assembly->tables [MONO_TABLE_CONSTANT];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_CONSTANT_SIZE;
values [MONO_CONSTANT_PARENT] = MONO_HASCONSTANT_FIEDDEF | (fb->table_idx << MONO_HASCONSTANT_BITS);
values [MONO_CONSTANT_VALUE] = encode_constant (assembly, fb->def_value, &field_type);
values [MONO_CONSTANT_TYPE] = field_type;
values [MONO_CONSTANT_PADDING] = 0;
}
if (fb->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
guint32 rva_idx;
table = &assembly->tables [MONO_TABLE_FIELDRVA];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_FIELD_RVA_SIZE;
values [MONO_FIELD_RVA_FIELD] = fb->table_idx;
/*
* We store it in the code section because it's simpler for now.
*/
if (fb->rva_data) {
if (mono_array_length (fb->rva_data) >= 10)
stream_data_align (&assembly->code);
rva_idx = mono_image_add_stream_data (&assembly->code, mono_array_addr (fb->rva_data, char, 0), mono_array_length (fb->rva_data));
} else
rva_idx = mono_image_add_stream_zero (&assembly->code, mono_class_value_size (fb->handle->parent, NULL));
values [MONO_FIELD_RVA_RVA] = rva_idx + assembly->text_rva;
}
if (fb->marshal_info) {
table = &assembly->tables [MONO_TABLE_FIELDMARSHAL];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_FIELD_MARSHAL_SIZE;
values [MONO_FIELD_MARSHAL_PARENT] = (fb->table_idx << MONO_HAS_FIELD_MARSHAL_BITS) | MONO_HAS_FIELD_MARSHAL_FIELDSREF;
values [MONO_FIELD_MARSHAL_NATIVE_TYPE] = encode_marshal_blob (assembly, fb->marshal_info);
}
}
static guint32
property_encode_signature (MonoDynamicImage *assembly, MonoReflectionPropertyBuilder *fb)
{
SigBuffer buf;
guint32 nparams = 0;
MonoReflectionMethodBuilder *mb = fb->get_method;
MonoReflectionMethodBuilder *smb = fb->set_method;
guint32 idx, i;
if (mb && mb->parameters)
nparams = mono_array_length (mb->parameters);
if (!mb && smb && smb->parameters)
nparams = mono_array_length (smb->parameters) - 1;
sigbuffer_init (&buf, 32);
if (fb->call_conv & 0x20)
sigbuffer_add_byte (&buf, 0x28);
else
sigbuffer_add_byte (&buf, 0x08);
sigbuffer_add_value (&buf, nparams);
if (mb) {
encode_reflection_type (assembly, (MonoReflectionType*)mb->rtype, &buf);
for (i = 0; i < nparams; ++i) {
MonoReflectionType *pt = mono_array_get (mb->parameters, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
} else if (smb && smb->parameters) {
/* the property type is the last param */
encode_reflection_type (assembly, mono_array_get (smb->parameters, MonoReflectionType*, nparams), &buf);
for (i = 0; i < nparams; ++i) {
MonoReflectionType *pt = mono_array_get (smb->parameters, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
} else {
encode_reflection_type (assembly, (MonoReflectionType*)fb->type, &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static void
mono_image_get_property_info (MonoReflectionPropertyBuilder *pb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint num_methods = 0;
guint32 semaidx;
/*
* we need to set things in the following tables:
* PROPERTYMAP (info already filled in _get_type_info ())
* PROPERTY (rows already preallocated in _get_type_info ())
* METHOD (method info already done with the generic method code)
* METHODSEMANTICS
* CONSTANT
*/
table = &assembly->tables [MONO_TABLE_PROPERTY];
pb->table_idx = table->next_idx ++;
values = table->values + pb->table_idx * MONO_PROPERTY_SIZE;
values [MONO_PROPERTY_NAME] = string_heap_insert_mstring (&assembly->sheap, pb->name);
values [MONO_PROPERTY_FLAGS] = pb->attrs;
values [MONO_PROPERTY_TYPE] = property_encode_signature (assembly, pb);
/* FIXME: we still don't handle 'other' methods */
if (pb->get_method) num_methods ++;
if (pb->set_method) num_methods ++;
table = &assembly->tables [MONO_TABLE_METHODSEMANTICS];
table->rows += num_methods;
alloc_table (table, table->rows);
if (pb->get_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_GETTER;
values [MONO_METHOD_SEMA_METHOD] = pb->get_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (pb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_PROPERTY;
}
if (pb->set_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_SETTER;
values [MONO_METHOD_SEMA_METHOD] = pb->set_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (pb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_PROPERTY;
}
if (pb->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT) {
guint32 field_type = 0;
table = &assembly->tables [MONO_TABLE_CONSTANT];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_CONSTANT_SIZE;
values [MONO_CONSTANT_PARENT] = MONO_HASCONSTANT_PROPERTY | (pb->table_idx << MONO_HASCONSTANT_BITS);
values [MONO_CONSTANT_VALUE] = encode_constant (assembly, pb->def_value, &field_type);
values [MONO_CONSTANT_TYPE] = field_type;
values [MONO_CONSTANT_PADDING] = 0;
}
}
static void
mono_image_get_event_info (MonoReflectionEventBuilder *eb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint num_methods = 0;
guint32 semaidx;
/*
* we need to set things in the following tables:
* EVENTMAP (info already filled in _get_type_info ())
* EVENT (rows already preallocated in _get_type_info ())
* METHOD (method info already done with the generic method code)
* METHODSEMANTICS
*/
table = &assembly->tables [MONO_TABLE_EVENT];
eb->table_idx = table->next_idx ++;
values = table->values + eb->table_idx * MONO_EVENT_SIZE;
values [MONO_EVENT_NAME] = string_heap_insert_mstring (&assembly->sheap, eb->name);
values [MONO_EVENT_FLAGS] = eb->attrs;
values [MONO_EVENT_TYPE] = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (eb->type));
/*
* FIXME: we still don't handle 'other' methods
*/
if (eb->add_method) num_methods ++;
if (eb->remove_method) num_methods ++;
if (eb->raise_method) num_methods ++;
table = &assembly->tables [MONO_TABLE_METHODSEMANTICS];
table->rows += num_methods;
alloc_table (table, table->rows);
if (eb->add_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_ADD_ON;
values [MONO_METHOD_SEMA_METHOD] = eb->add_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (eb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT;
}
if (eb->remove_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_REMOVE_ON;
values [MONO_METHOD_SEMA_METHOD] = eb->remove_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (eb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT;
}
if (eb->raise_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_FIRE;
values [MONO_METHOD_SEMA_METHOD] = eb->raise_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (eb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT;
}
}
static void
encode_constraints (MonoReflectionGenericParam *gparam, guint32 owner, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 num_constraints, i;
guint32 *values;
guint32 table_idx;
table = &assembly->tables [MONO_TABLE_GENERICPARAMCONSTRAINT];
num_constraints = gparam->iface_constraints ?
mono_array_length (gparam->iface_constraints) : 0;
table->rows += num_constraints;
if (gparam->base_type)
table->rows++;
alloc_table (table, table->rows);
if (gparam->base_type) {
table_idx = table->next_idx ++;
values = table->values + table_idx * MONO_GENPARCONSTRAINT_SIZE;
values [MONO_GENPARCONSTRAINT_GENERICPAR] = owner;
values [MONO_GENPARCONSTRAINT_CONSTRAINT] = mono_image_typedef_or_ref (
assembly, mono_reflection_type_get_handle (gparam->base_type));
}
for (i = 0; i < num_constraints; i++) {
MonoReflectionType *constraint = mono_array_get (
gparam->iface_constraints, gpointer, i);
table_idx = table->next_idx ++;
values = table->values + table_idx * MONO_GENPARCONSTRAINT_SIZE;
values [MONO_GENPARCONSTRAINT_GENERICPAR] = owner;
values [MONO_GENPARCONSTRAINT_CONSTRAINT] = mono_image_typedef_or_ref (
assembly, mono_reflection_type_get_handle (constraint));
}
}
static void
mono_image_get_generic_param_info (MonoReflectionGenericParam *gparam, guint32 owner, MonoDynamicImage *assembly)
{
GenericParamTableEntry *entry;
/*
* The GenericParam table must be sorted according to the `owner' field.
* We need to do this sorting prior to writing the GenericParamConstraint
* table, since we have to use the final GenericParam table indices there
* and they must also be sorted.
*/
entry = g_new0 (GenericParamTableEntry, 1);
entry->owner = owner;
/* FIXME: track where gen_params should be freed and remove the GC root as well */
MOVING_GC_REGISTER (&entry->gparam);
entry->gparam = gparam;
g_ptr_array_add (assembly->gen_params, entry);
}
static void
write_generic_param_entry (MonoDynamicImage *assembly, GenericParamTableEntry *entry)
{
MonoDynamicTable *table;
MonoGenericParam *param;
guint32 *values;
guint32 table_idx;
table = &assembly->tables [MONO_TABLE_GENERICPARAM];
table_idx = table->next_idx ++;
values = table->values + table_idx * MONO_GENERICPARAM_SIZE;
param = mono_reflection_type_get_handle ((MonoReflectionType*)entry->gparam)->data.generic_param;
values [MONO_GENERICPARAM_OWNER] = entry->owner;
values [MONO_GENERICPARAM_FLAGS] = entry->gparam->attrs;
values [MONO_GENERICPARAM_NUMBER] = mono_generic_param_num (param);
values [MONO_GENERICPARAM_NAME] = string_heap_insert (&assembly->sheap, mono_generic_param_info (param)->name);
mono_image_add_cattrs (assembly, table_idx, MONO_CUSTOM_ATTR_GENERICPAR, entry->gparam->cattrs);
encode_constraints (entry->gparam, table_idx, assembly);
}
static guint32
resolution_scope_from_image (MonoDynamicImage *assembly, MonoImage *image)
{
MonoDynamicTable *table;
guint32 token;
guint32 *values;
guint32 cols [MONO_ASSEMBLY_SIZE];
const char *pubkey;
guint32 publen;
if ((token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, image))))
return token;
if (image->assembly->dynamic && (image->assembly == assembly->image.assembly)) {
table = &assembly->tables [MONO_TABLE_MODULEREF];
token = table->next_idx ++;
table->rows ++;
alloc_table (table, table->rows);
values = table->values + token * MONO_MODULEREF_SIZE;
values [MONO_MODULEREF_NAME] = string_heap_insert (&assembly->sheap, image->module_name);
token <<= MONO_RESOLTION_SCOPE_BITS;
token |= MONO_RESOLTION_SCOPE_MODULEREF;
g_hash_table_insert (assembly->handleref, image, GUINT_TO_POINTER (token));
return token;
}
if (image->assembly->dynamic)
/* FIXME: */
memset (cols, 0, sizeof (cols));
else {
/* image->assembly->image is the manifest module */
image = image->assembly->image;
mono_metadata_decode_row (&image->tables [MONO_TABLE_ASSEMBLY], 0, cols, MONO_ASSEMBLY_SIZE);
}
table = &assembly->tables [MONO_TABLE_ASSEMBLYREF];
token = table->next_idx ++;
table->rows ++;
alloc_table (table, table->rows);
values = table->values + token * MONO_ASSEMBLYREF_SIZE;
values [MONO_ASSEMBLYREF_NAME] = string_heap_insert (&assembly->sheap, image->assembly_name);
values [MONO_ASSEMBLYREF_MAJOR_VERSION] = cols [MONO_ASSEMBLY_MAJOR_VERSION];
values [MONO_ASSEMBLYREF_MINOR_VERSION] = cols [MONO_ASSEMBLY_MINOR_VERSION];
values [MONO_ASSEMBLYREF_BUILD_NUMBER] = cols [MONO_ASSEMBLY_BUILD_NUMBER];
values [MONO_ASSEMBLYREF_REV_NUMBER] = cols [MONO_ASSEMBLY_REV_NUMBER];
values [MONO_ASSEMBLYREF_FLAGS] = 0;
values [MONO_ASSEMBLYREF_CULTURE] = 0;
values [MONO_ASSEMBLYREF_HASH_VALUE] = 0;
if (strcmp ("", image->assembly->aname.culture)) {
values [MONO_ASSEMBLYREF_CULTURE] = string_heap_insert (&assembly->sheap,
image->assembly->aname.culture);
}
if ((pubkey = mono_image_get_public_key (image, &publen))) {
guchar pubtoken [9];
pubtoken [0] = 8;
mono_digest_get_public_token (pubtoken + 1, (guchar*)pubkey, publen);
values [MONO_ASSEMBLYREF_PUBLIC_KEY] = mono_image_add_stream_data (&assembly->blob, (char*)pubtoken, 9);
} else {
values [MONO_ASSEMBLYREF_PUBLIC_KEY] = 0;
}
token <<= MONO_RESOLTION_SCOPE_BITS;
token |= MONO_RESOLTION_SCOPE_ASSEMBLYREF;
g_hash_table_insert (assembly->handleref, image, GUINT_TO_POINTER (token));
return token;
}
static guint32
create_typespec (MonoDynamicImage *assembly, MonoType *type)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token;
SigBuffer buf;
if ((token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->typespec, type))))
return token;
sigbuffer_init (&buf, 32);
switch (type->type) {
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
case MONO_TYPE_GENERICINST:
encode_type (assembly, type, &buf);
break;
case MONO_TYPE_CLASS:
case MONO_TYPE_VALUETYPE: {
MonoClass *k = mono_class_from_mono_type (type);
if (!k || !k->generic_container) {
sigbuffer_free (&buf);
return 0;
}
encode_type (assembly, type, &buf);
break;
}
default:
sigbuffer_free (&buf);
return 0;
}
table = &assembly->tables [MONO_TABLE_TYPESPEC];
if (assembly->save) {
token = sigbuffer_add_to_blob_cached (assembly, &buf);
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_TYPESPEC_SIZE;
values [MONO_TYPESPEC_SIGNATURE] = token;
}
sigbuffer_free (&buf);
token = MONO_TYPEDEFORREF_TYPESPEC | (table->next_idx << MONO_TYPEDEFORREF_BITS);
g_hash_table_insert (assembly->typespec, type, GUINT_TO_POINTER(token));
table->next_idx ++;
return token;
}
static guint32
mono_image_typedef_or_ref_full (MonoDynamicImage *assembly, MonoType *type, gboolean try_typespec)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token, scope, enclosing;
MonoClass *klass;
/* if the type requires a typespec, we must try that first*/
if (try_typespec && (token = create_typespec (assembly, type)))
return token;
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->typeref, type));
if (token)
return token;
klass = mono_class_from_mono_type (type);
if (!klass)
klass = mono_class_from_mono_type (type);
/*
* If it's in the same module and not a generic type parameter:
*/
if ((klass->image == &assembly->image) && (type->type != MONO_TYPE_VAR) &&
(type->type != MONO_TYPE_MVAR)) {
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
token = MONO_TYPEDEFORREF_TYPEDEF | (tb->table_idx << MONO_TYPEDEFORREF_BITS);
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), mono_class_get_ref_info (klass));
return token;
}
if (klass->nested_in) {
enclosing = mono_image_typedef_or_ref_full (assembly, &klass->nested_in->byval_arg, FALSE);
/* get the typeref idx of the enclosing type */
enclosing >>= MONO_TYPEDEFORREF_BITS;
scope = (enclosing << MONO_RESOLTION_SCOPE_BITS) | MONO_RESOLTION_SCOPE_TYPEREF;
} else {
scope = resolution_scope_from_image (assembly, klass->image);
}
table = &assembly->tables [MONO_TABLE_TYPEREF];
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_TYPEREF_SIZE;
values [MONO_TYPEREF_SCOPE] = scope;
values [MONO_TYPEREF_NAME] = string_heap_insert (&assembly->sheap, klass->name);
values [MONO_TYPEREF_NAMESPACE] = string_heap_insert (&assembly->sheap, klass->name_space);
}
token = MONO_TYPEDEFORREF_TYPEREF | (table->next_idx << MONO_TYPEDEFORREF_BITS); /* typeref */
g_hash_table_insert (assembly->typeref, type, GUINT_TO_POINTER(token));
table->next_idx ++;
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), mono_class_get_ref_info (klass));
return token;
}
/*
* Despite the name, we handle also TypeSpec (with the above helper).
*/
static guint32
mono_image_typedef_or_ref (MonoDynamicImage *assembly, MonoType *type)
{
return mono_image_typedef_or_ref_full (assembly, type, TRUE);
}
#ifndef DISABLE_REFLECTION_EMIT
static guint32
mono_image_add_memberef_row (MonoDynamicImage *assembly, guint32 parent, const char *name, guint32 sig)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token, pclass;
switch (parent & MONO_TYPEDEFORREF_MASK) {
case MONO_TYPEDEFORREF_TYPEREF:
pclass = MONO_MEMBERREF_PARENT_TYPEREF;
break;
case MONO_TYPEDEFORREF_TYPESPEC:
pclass = MONO_MEMBERREF_PARENT_TYPESPEC;
break;
case MONO_TYPEDEFORREF_TYPEDEF:
pclass = MONO_MEMBERREF_PARENT_TYPEDEF;
break;
default:
g_warning ("unknown typeref or def token 0x%08x for %s", parent, name);
return 0;
}
/* extract the index */
parent >>= MONO_TYPEDEFORREF_BITS;
table = &assembly->tables [MONO_TABLE_MEMBERREF];
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_MEMBERREF_SIZE;
values [MONO_MEMBERREF_CLASS] = pclass | (parent << MONO_MEMBERREF_PARENT_BITS);
values [MONO_MEMBERREF_NAME] = string_heap_insert (&assembly->sheap, name);
values [MONO_MEMBERREF_SIGNATURE] = sig;
}
token = MONO_TOKEN_MEMBER_REF | table->next_idx;
table->next_idx ++;
return token;
}
/*
* Insert a memberef row into the metadata: the token that point to the memberref
* is returned. Caching is done in the caller (mono_image_get_methodref_token() or
* mono_image_get_fieldref_token()).
* The sig param is an index to an already built signature.
*/
static guint32
mono_image_get_memberref_token (MonoDynamicImage *assembly, MonoType *type, const char *name, guint32 sig)
{
guint32 parent = mono_image_typedef_or_ref (assembly, type);
return mono_image_add_memberef_row (assembly, parent, name, sig);
}
static guint32
mono_image_get_methodref_token (MonoDynamicImage *assembly, MonoMethod *method, gboolean create_typespec)
{
guint32 token;
MonoMethodSignature *sig;
create_typespec = create_typespec && method->is_generic && method->klass->image != &assembly->image;
if (create_typespec) {
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, GUINT_TO_POINTER (GPOINTER_TO_UINT (method) + 1)));
if (token)
return token;
}
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, method));
if (token && !create_typespec)
return token;
g_assert (!method->is_inflated);
if (!token) {
/*
* A methodref signature can't contain an unmanaged calling convention.
*/
sig = mono_metadata_signature_dup (mono_method_signature (method));
if ((sig->call_convention != MONO_CALL_DEFAULT) && (sig->call_convention != MONO_CALL_VARARG))
sig->call_convention = MONO_CALL_DEFAULT;
token = mono_image_get_memberref_token (assembly, &method->klass->byval_arg,
method->name, method_encode_signature (assembly, sig));
g_free (sig);
g_hash_table_insert (assembly->handleref, method, GUINT_TO_POINTER(token));
}
if (create_typespec) {
MonoDynamicTable *table = &assembly->tables [MONO_TABLE_METHODSPEC];
g_assert (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF);
token = (mono_metadata_token_index (token) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODREF;
if (assembly->save) {
guint32 *values;
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_METHODSPEC_SIZE;
values [MONO_METHODSPEC_METHOD] = token;
values [MONO_METHODSPEC_SIGNATURE] = encode_generic_method_sig (assembly, &mono_method_get_generic_container (method)->context);
}
token = MONO_TOKEN_METHOD_SPEC | table->next_idx;
table->next_idx ++;
/*methodspec and memberef tokens are diferent, */
g_hash_table_insert (assembly->handleref, GUINT_TO_POINTER (GPOINTER_TO_UINT (method) + 1), GUINT_TO_POINTER (token));
return token;
}
return token;
}
static guint32
mono_image_get_methodref_token_for_methodbuilder (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *method)
{
guint32 token, parent, sig;
ReflectionMethodBuilder rmb;
char *name;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)method->type;
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, method));
if (token)
return token;
name = mono_string_to_utf8 (method->name);
reflection_methodbuilder_from_method_builder (&rmb, method);
/*
* A methodref signature can't contain an unmanaged calling convention.
* Since some flags are encoded as part of call_conv, we need to check against it.
*/
if ((rmb.call_conv & ~0x60) != MONO_CALL_DEFAULT && (rmb.call_conv & ~0x60) != MONO_CALL_VARARG)
rmb.call_conv = (rmb.call_conv & 0x60) | MONO_CALL_DEFAULT;
sig = method_builder_encode_signature (assembly, &rmb);
if (tb->generic_params)
parent = create_generic_typespec (assembly, tb);
else
parent = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)rmb.type));
token = mono_image_add_memberef_row (assembly, parent, name, sig);
g_free (name);
g_hash_table_insert (assembly->handleref, method, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_varargs_method_token (MonoDynamicImage *assembly, guint32 original,
const gchar *name, guint32 sig)
{
MonoDynamicTable *table;
guint32 token;
guint32 *values;
table = &assembly->tables [MONO_TABLE_MEMBERREF];
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_MEMBERREF_SIZE;
values [MONO_MEMBERREF_CLASS] = original;
values [MONO_MEMBERREF_NAME] = string_heap_insert (&assembly->sheap, name);
values [MONO_MEMBERREF_SIGNATURE] = sig;
}
token = MONO_TOKEN_MEMBER_REF | table->next_idx;
table->next_idx ++;
return token;
}
static guint32
encode_generic_method_definition_sig (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb)
{
SigBuffer buf;
int i;
guint32 nparams = mono_array_length (mb->generic_params);
guint32 idx;
if (!assembly->save)
return 0;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0xa);
sigbuffer_add_value (&buf, nparams);
for (i = 0; i < nparams; i++) {
sigbuffer_add_value (&buf, MONO_TYPE_MVAR);
sigbuffer_add_value (&buf, i);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
mono_image_get_methodspec_token_for_generic_method_definition (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token, mtoken = 0;
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->methodspec, mb));
if (token)
return token;
table = &assembly->tables [MONO_TABLE_METHODSPEC];
mtoken = mono_image_get_methodref_token_for_methodbuilder (assembly, mb);
switch (mono_metadata_token_table (mtoken)) {
case MONO_TABLE_MEMBERREF:
mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODREF;
break;
case MONO_TABLE_METHOD:
mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODDEF;
break;
default:
g_assert_not_reached ();
}
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_METHODSPEC_SIZE;
values [MONO_METHODSPEC_METHOD] = mtoken;
values [MONO_METHODSPEC_SIGNATURE] = encode_generic_method_definition_sig (assembly, mb);
}
token = MONO_TOKEN_METHOD_SPEC | table->next_idx;
table->next_idx ++;
mono_g_hash_table_insert (assembly->methodspec, mb, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_methodbuilder_token (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb, gboolean create_methodspec)
{
guint32 token;
if (mb->generic_params && create_methodspec)
return mono_image_get_methodspec_token_for_generic_method_definition (assembly, mb);
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, mb));
if (token)
return token;
token = mono_image_get_methodref_token_for_methodbuilder (assembly, mb);
mono_g_hash_table_insert (assembly->handleref_managed, mb, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_ctorbuilder_token (MonoDynamicImage *assembly, MonoReflectionCtorBuilder *mb)
{
guint32 token, parent, sig;
ReflectionMethodBuilder rmb;
char *name;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)mb->type;
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, mb));
if (token)
return token;
g_assert (tb->generic_params);
reflection_methodbuilder_from_ctor_builder (&rmb, mb);
parent = create_generic_typespec (assembly, tb);
name = mono_string_to_utf8 (rmb.name);
sig = method_builder_encode_signature (assembly, &rmb);
token = mono_image_add_memberef_row (assembly, parent, name, sig);
g_free (name);
mono_g_hash_table_insert (assembly->handleref_managed, mb, GUINT_TO_POINTER(token));
return token;
}
#endif
static gboolean
is_field_on_inst (MonoClassField *field)
{
return (field->parent->generic_class && field->parent->generic_class->is_dynamic && ((MonoDynamicGenericClass*)field->parent->generic_class)->fields);
}
/*
* If FIELD is a field of a MonoDynamicGenericClass, return its non-inflated type.
*/
static MonoType*
get_field_on_inst_generic_type (MonoClassField *field)
{
MonoClass *class, *gtd;
MonoDynamicGenericClass *dgclass;
int field_index;
g_assert (is_field_on_inst (field));
dgclass = (MonoDynamicGenericClass*)field->parent->generic_class;
if (field >= dgclass->fields && field - dgclass->fields < dgclass->count_fields) {
field_index = field - dgclass->fields;
return dgclass->field_generic_types [field_index];
}
class = field->parent;
gtd = class->generic_class->container_class;
if (field >= class->fields && field - class->fields < class->field.count) {
field_index = field - class->fields;
return gtd->fields [field_index].type;
}
g_assert_not_reached ();
return 0;
}
#ifndef DISABLE_REFLECTION_EMIT
static guint32
mono_image_get_fieldref_token (MonoDynamicImage *assembly, MonoObject *f, MonoClassField *field)
{
MonoType *type;
guint32 token;
g_assert (field);
g_assert (field->parent);
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, f));
if (token)
return token;
if (field->parent->generic_class && field->parent->generic_class->container_class && field->parent->generic_class->container_class->fields) {
int index = field - field->parent->fields;
type = field->parent->generic_class->container_class->fields [index].type;
} else {
if (is_field_on_inst (field))
type = get_field_on_inst_generic_type (field);
else
type = field->type;
}
token = mono_image_get_memberref_token (assembly, &field->parent->byval_arg,
mono_field_get_name (field),
fieldref_encode_signature (assembly, field->parent->image, type));
mono_g_hash_table_insert (assembly->handleref_managed, f, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_field_on_inst_token (MonoDynamicImage *assembly, MonoReflectionFieldOnTypeBuilderInst *f)
{
guint32 token;
MonoClass *klass;
MonoGenericClass *gclass;
MonoDynamicGenericClass *dgclass;
MonoType *type;
char *name;
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, f));
if (token)
return token;
if (is_sre_field_builder (mono_object_class (f->fb))) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)f->fb;
type = mono_reflection_type_get_handle ((MonoReflectionType*)f->inst);
klass = mono_class_from_mono_type (type);
gclass = type->data.generic_class;
g_assert (gclass->is_dynamic);
dgclass = (MonoDynamicGenericClass *) gclass;
name = mono_string_to_utf8 (fb->name);
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, name,
field_encode_signature (assembly, fb));
g_free (name);
} else if (is_sr_mono_field (mono_object_class (f->fb))) {
guint32 sig;
MonoClassField *field = ((MonoReflectionField *)f->fb)->field;
type = mono_reflection_type_get_handle ((MonoReflectionType*)f->inst);
klass = mono_class_from_mono_type (type);
sig = fieldref_encode_signature (assembly, field->parent->image, field->type);
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, field->name, sig);
} else {
char *name = mono_type_get_full_name (mono_object_class (f->fb));
g_error ("mono_image_get_field_on_inst_token: don't know how to handle %s", name);
}
mono_g_hash_table_insert (assembly->handleref_managed, f, GUINT_TO_POINTER (token));
return token;
}
static guint32
mono_image_get_ctor_on_inst_token (MonoDynamicImage *assembly, MonoReflectionCtorOnTypeBuilderInst *c, gboolean create_methodspec)
{
guint32 sig, token;
MonoClass *klass;
MonoGenericClass *gclass;
MonoType *type;
/* A ctor cannot be a generic method, so we can ignore create_methodspec */
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, c));
if (token)
return token;
if (is_sre_ctor_builder (mono_object_class (c->cb))) {
MonoReflectionCtorBuilder *cb = (MonoReflectionCtorBuilder *)c->cb;
MonoDynamicGenericClass *dgclass;
ReflectionMethodBuilder rmb;
char *name;
type = mono_reflection_type_get_handle ((MonoReflectionType*)c->inst);
klass = mono_class_from_mono_type (type);
gclass = type->data.generic_class;
g_assert (gclass->is_dynamic);
dgclass = (MonoDynamicGenericClass *) gclass;
reflection_methodbuilder_from_ctor_builder (&rmb, cb);
name = mono_string_to_utf8 (rmb.name);
sig = method_builder_encode_signature (assembly, &rmb);
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, name, sig);
g_free (name);
} else if (is_sr_mono_cmethod (mono_object_class (c->cb))) {
MonoMethod *mm = ((MonoReflectionMethod *)c->cb)->method;
type = mono_reflection_type_get_handle ((MonoReflectionType*)c->inst);
klass = mono_class_from_mono_type (type);
sig = method_encode_signature (assembly, mono_method_signature (mm));
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, mm->name, sig);
} else {
char *name = mono_type_get_full_name (mono_object_class (c->cb));
g_error ("mono_image_get_method_on_inst_token: don't know how to handle %s", name);
}
mono_g_hash_table_insert (assembly->handleref_managed, c, GUINT_TO_POINTER (token));
return token;
}
static MonoMethod*
mono_reflection_method_on_tb_inst_get_handle (MonoReflectionMethodOnTypeBuilderInst *m)
{
MonoClass *klass;
MonoGenericContext tmp_context;
MonoType **type_argv;
MonoGenericInst *ginst;
MonoMethod *method, *inflated;
int count, i;
init_type_builder_generics ((MonoObject*)m->inst);
method = inflate_method (m->inst, (MonoObject*)m->mb);
klass = method->klass;
if (m->method_args == NULL)
return method;
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
count = mono_array_length (m->method_args);
type_argv = g_new0 (MonoType *, count);
for (i = 0; i < count; i++) {
MonoReflectionType *garg = mono_array_get (m->method_args, gpointer, i);
type_argv [i] = mono_reflection_type_get_handle (garg);
}
ginst = mono_metadata_get_generic_inst (count, type_argv);
g_free (type_argv);
tmp_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
tmp_context.method_inst = ginst;
inflated = mono_class_inflate_generic_method (method, &tmp_context);
return inflated;
}
static guint32
mono_image_get_method_on_inst_token (MonoDynamicImage *assembly, MonoReflectionMethodOnTypeBuilderInst *m, gboolean create_methodspec)
{
guint32 sig, token = 0;
MonoType *type;
MonoClass *klass;
if (m->method_args) {
MonoMethod *inflated;
inflated = mono_reflection_method_on_tb_inst_get_handle (m);
if (create_methodspec)
token = mono_image_get_methodspec_token (assembly, inflated);
else
token = mono_image_get_inflated_method_token (assembly, inflated);
return token;
}
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, m));
if (token)
return token;
if (is_sre_method_builder (mono_object_class (m->mb))) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)m->mb;
MonoGenericClass *gclass;
ReflectionMethodBuilder rmb;
char *name;
type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst);
klass = mono_class_from_mono_type (type);
gclass = type->data.generic_class;
g_assert (gclass->is_dynamic);
reflection_methodbuilder_from_method_builder (&rmb, mb);
name = mono_string_to_utf8 (rmb.name);
sig = method_builder_encode_signature (assembly, &rmb);
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, name, sig);
g_free (name);
} else if (is_sr_mono_method (mono_object_class (m->mb))) {
MonoMethod *mm = ((MonoReflectionMethod *)m->mb)->method;
type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst);
klass = mono_class_from_mono_type (type);
sig = method_encode_signature (assembly, mono_method_signature (mm));
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, mm->name, sig);
} else {
char *name = mono_type_get_full_name (mono_object_class (m->mb));
g_error ("mono_image_get_method_on_inst_token: don't know how to handle %s", name);
}
mono_g_hash_table_insert (assembly->handleref_managed, m, GUINT_TO_POINTER (token));
return token;
}
static guint32
encode_generic_method_sig (MonoDynamicImage *assembly, MonoGenericContext *context)
{
SigBuffer buf;
int i;
guint32 nparams = context->method_inst->type_argc;
guint32 idx;
if (!assembly->save)
return 0;
sigbuffer_init (&buf, 32);
/*
* FIXME: vararg, explicit_this, differenc call_conv values...
*/
sigbuffer_add_value (&buf, 0xa); /* FIXME FIXME FIXME */
sigbuffer_add_value (&buf, nparams);
for (i = 0; i < nparams; i++)
encode_type (assembly, context->method_inst->type_argv [i], &buf);
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
method_encode_methodspec (MonoDynamicImage *assembly, MonoMethod *method)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token, mtoken = 0, sig;
MonoMethodInflated *imethod;
MonoMethod *declaring;
table = &assembly->tables [MONO_TABLE_METHODSPEC];
g_assert (method->is_inflated);
imethod = (MonoMethodInflated *) method;
declaring = imethod->declaring;
sig = method_encode_signature (assembly, mono_method_signature (declaring));
mtoken = mono_image_get_memberref_token (assembly, &method->klass->byval_arg, declaring->name, sig);
if (!mono_method_signature (declaring)->generic_param_count)
return mtoken;
switch (mono_metadata_token_table (mtoken)) {
case MONO_TABLE_MEMBERREF:
mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODREF;
break;
case MONO_TABLE_METHOD:
mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODDEF;
break;
default:
g_assert_not_reached ();
}
sig = encode_generic_method_sig (assembly, mono_method_get_context (method));
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_METHODSPEC_SIZE;
values [MONO_METHODSPEC_METHOD] = mtoken;
values [MONO_METHODSPEC_SIGNATURE] = sig;
}
token = MONO_TOKEN_METHOD_SPEC | table->next_idx;
table->next_idx ++;
return token;
}
static guint32
mono_image_get_methodspec_token (MonoDynamicImage *assembly, MonoMethod *method)
{
MonoMethodInflated *imethod;
guint32 token;
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, method));
if (token)
return token;
g_assert (method->is_inflated);
imethod = (MonoMethodInflated *) method;
if (mono_method_signature (imethod->declaring)->generic_param_count) {
token = method_encode_methodspec (assembly, method);
} else {
guint32 sig = method_encode_signature (
assembly, mono_method_signature (imethod->declaring));
token = mono_image_get_memberref_token (
assembly, &method->klass->byval_arg, method->name, sig);
}
g_hash_table_insert (assembly->handleref, method, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_inflated_method_token (MonoDynamicImage *assembly, MonoMethod *m)
{
MonoMethodInflated *imethod = (MonoMethodInflated *) m;
guint32 sig, token;
sig = method_encode_signature (assembly, mono_method_signature (imethod->declaring));
token = mono_image_get_memberref_token (
assembly, &m->klass->byval_arg, m->name, sig);
return token;
}
static guint32
create_generic_typespec (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *tb)
{
MonoDynamicTable *table;
MonoClass *klass;
MonoType *type;
guint32 *values;
guint32 token;
SigBuffer buf;
int count, i;
/*
* We're creating a TypeSpec for the TypeBuilder of a generic type declaration,
* ie. what we'd normally use as the generic type in a TypeSpec signature.
* Because of this, we must not insert it into the `typeref' hash table.
*/
type = mono_reflection_type_get_handle ((MonoReflectionType*)tb);
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->typespec, type));
if (token)
return token;
sigbuffer_init (&buf, 32);
g_assert (tb->generic_params);
klass = mono_class_from_mono_type (type);
if (tb->generic_container)
mono_reflection_create_generic_class (tb);
sigbuffer_add_value (&buf, MONO_TYPE_GENERICINST);
g_assert (klass->generic_container);
sigbuffer_add_value (&buf, klass->byval_arg.type);
sigbuffer_add_value (&buf, mono_image_typedef_or_ref_full (assembly, &klass->byval_arg, FALSE));
count = mono_array_length (tb->generic_params);
sigbuffer_add_value (&buf, count);
for (i = 0; i < count; i++) {
MonoReflectionGenericParam *gparam;
gparam = mono_array_get (tb->generic_params, MonoReflectionGenericParam *, i);
encode_type (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)gparam), &buf);
}
table = &assembly->tables [MONO_TABLE_TYPESPEC];
if (assembly->save) {
token = sigbuffer_add_to_blob_cached (assembly, &buf);
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_TYPESPEC_SIZE;
values [MONO_TYPESPEC_SIGNATURE] = token;
}
sigbuffer_free (&buf);
token = MONO_TYPEDEFORREF_TYPESPEC | (table->next_idx << MONO_TYPEDEFORREF_BITS);
g_hash_table_insert (assembly->typespec, type, GUINT_TO_POINTER(token));
table->next_idx ++;
return token;
}
/*
* Return a copy of TYPE, adding the custom modifiers in MODREQ and MODOPT.
*/
static MonoType*
add_custom_modifiers (MonoDynamicImage *assembly, MonoType *type, MonoArray *modreq, MonoArray *modopt)
{
int i, count, len, pos;
MonoType *t;
count = 0;
if (modreq)
count += mono_array_length (modreq);
if (modopt)
count += mono_array_length (modopt);
if (count == 0)
return mono_metadata_type_dup (NULL, type);
len = MONO_SIZEOF_TYPE + ((gint32)count) * sizeof (MonoCustomMod);
t = g_malloc (len);
memcpy (t, type, MONO_SIZEOF_TYPE);
t->num_mods = count;
pos = 0;
if (modreq) {
for (i = 0; i < mono_array_length (modreq); ++i) {
MonoType *mod = mono_type_array_get_and_resolve (modreq, i);
t->modifiers [pos].required = 1;
t->modifiers [pos].token = mono_image_typedef_or_ref (assembly, mod);
pos ++;
}
}
if (modopt) {
for (i = 0; i < mono_array_length (modopt); ++i) {
MonoType *mod = mono_type_array_get_and_resolve (modopt, i);
t->modifiers [pos].required = 0;
t->modifiers [pos].token = mono_image_typedef_or_ref (assembly, mod);
pos ++;
}
}
return t;
}
static void
init_type_builder_generics (MonoObject *type)
{
MonoReflectionTypeBuilder *tb;
if (!is_sre_type_builder(mono_object_class (type)))
return;
tb = (MonoReflectionTypeBuilder *)type;
if (tb && tb->generic_container)
mono_reflection_create_generic_class (tb);
}
static guint32
mono_image_get_generic_field_token (MonoDynamicImage *assembly, MonoReflectionFieldBuilder *fb)
{
MonoDynamicTable *table;
MonoClass *klass;
MonoType *custom = NULL, *type;
guint32 *values;
guint32 token, pclass, parent, sig;
gchar *name;
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, fb));
if (token)
return token;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle (fb->typeb));
name = mono_string_to_utf8 (fb->name);
/*FIXME this is one more layer of ugliness due how types are created.*/
init_type_builder_generics (fb->type);
/* fb->type does not include the custom modifiers */
/* FIXME: We should do this in one place when a fieldbuilder is created */
type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
if (fb->modreq || fb->modopt)
type = custom = add_custom_modifiers (assembly, type, fb->modreq, fb->modopt);
sig = fieldref_encode_signature (assembly, NULL, type);
g_free (custom);
parent = create_generic_typespec (assembly, (MonoReflectionTypeBuilder *) fb->typeb);
g_assert ((parent & MONO_TYPEDEFORREF_MASK) == MONO_TYPEDEFORREF_TYPESPEC);
pclass = MONO_MEMBERREF_PARENT_TYPESPEC;
parent >>= MONO_TYPEDEFORREF_BITS;
table = &assembly->tables [MONO_TABLE_MEMBERREF];
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_MEMBERREF_SIZE;
values [MONO_MEMBERREF_CLASS] = pclass | (parent << MONO_MEMBERREF_PARENT_BITS);
values [MONO_MEMBERREF_NAME] = string_heap_insert (&assembly->sheap, name);
values [MONO_MEMBERREF_SIGNATURE] = sig;
}
token = MONO_TOKEN_MEMBER_REF | table->next_idx;
table->next_idx ++;
mono_g_hash_table_insert (assembly->handleref_managed, fb, GUINT_TO_POINTER(token));
g_free (name);
return token;
}
static guint32
mono_reflection_encode_sighelper (MonoDynamicImage *assembly, MonoReflectionSigHelper *helper)
{
SigBuffer buf;
guint32 nargs;
guint32 size;
guint32 i, idx;
if (!assembly->save)
return 0;
/* FIXME: this means SignatureHelper.SignatureHelpType.HELPER_METHOD */
g_assert (helper->type == 2);
if (helper->arguments)
nargs = mono_array_length (helper->arguments);
else
nargs = 0;
size = 10 + (nargs * 10);
sigbuffer_init (&buf, 32);
/* Encode calling convention */
/* Change Any to Standard */
if ((helper->call_conv & 0x03) == 0x03)
helper->call_conv = 0x01;
/* explicit_this implies has_this */
if (helper->call_conv & 0x40)
helper->call_conv &= 0x20;
if (helper->call_conv == 0) { /* Unmanaged */
idx = helper->unmanaged_call_conv - 1;
} else {
/* Managed */
idx = helper->call_conv & 0x60; /* has_this + explicit_this */
if (helper->call_conv & 0x02) /* varargs */
idx += 0x05;
}
sigbuffer_add_byte (&buf, idx);
sigbuffer_add_value (&buf, nargs);
encode_reflection_type (assembly, helper->return_type, &buf);
for (i = 0; i < nargs; ++i) {
MonoArray *modreqs = NULL;
MonoArray *modopts = NULL;
MonoReflectionType *pt;
if (helper->modreqs && (i < mono_array_length (helper->modreqs)))
modreqs = mono_array_get (helper->modreqs, MonoArray*, i);
if (helper->modopts && (i < mono_array_length (helper->modopts)))
modopts = mono_array_get (helper->modopts, MonoArray*, i);
encode_custom_modifiers (assembly, modreqs, modopts, &buf);
pt = mono_array_get (helper->arguments, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
mono_image_get_sighelper_token (MonoDynamicImage *assembly, MonoReflectionSigHelper *helper)
{
guint32 idx;
MonoDynamicTable *table;
guint32 *values;
table = &assembly->tables [MONO_TABLE_STANDALONESIG];
idx = table->next_idx ++;
table->rows ++;
alloc_table (table, table->rows);
values = table->values + idx * MONO_STAND_ALONE_SIGNATURE_SIZE;
values [MONO_STAND_ALONE_SIGNATURE] =
mono_reflection_encode_sighelper (assembly, helper);
return idx;
}
static int
reflection_cc_to_file (int call_conv) {
switch (call_conv & 0x3) {
case 0:
case 1: return MONO_CALL_DEFAULT;
case 2: return MONO_CALL_VARARG;
default:
g_assert_not_reached ();
}
return 0;
}
#endif /* !DISABLE_REFLECTION_EMIT */
typedef struct {
MonoType *parent;
MonoMethodSignature *sig;
char *name;
guint32 token;
} ArrayMethod;
#ifndef DISABLE_REFLECTION_EMIT
static guint32
mono_image_get_array_token (MonoDynamicImage *assembly, MonoReflectionArrayMethod *m)
{
guint32 nparams, i;
GList *tmp;
char *name;
MonoMethodSignature *sig;
ArrayMethod *am;
MonoType *mtype;
name = mono_string_to_utf8 (m->name);
nparams = mono_array_length (m->parameters);
sig = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + sizeof (MonoType*) * nparams);
sig->hasthis = 1;
sig->sentinelpos = -1;
sig->call_convention = reflection_cc_to_file (m->call_conv);
sig->param_count = nparams;
sig->ret = m->ret ? mono_reflection_type_get_handle (m->ret): &mono_defaults.void_class->byval_arg;
mtype = mono_reflection_type_get_handle (m->parent);
for (i = 0; i < nparams; ++i)
sig->params [i] = mono_type_array_get_and_resolve (m->parameters, i);
for (tmp = assembly->array_methods; tmp; tmp = tmp->next) {
am = tmp->data;
if (strcmp (name, am->name) == 0 &&
mono_metadata_type_equal (am->parent, mtype) &&
mono_metadata_signature_equal (am->sig, sig)) {
g_free (name);
g_free (sig);
m->table_idx = am->token & 0xffffff;
return am->token;
}
}
am = g_new0 (ArrayMethod, 1);
am->name = name;
am->sig = sig;
am->parent = mtype;
am->token = mono_image_get_memberref_token (assembly, am->parent, name,
method_encode_signature (assembly, sig));
assembly->array_methods = g_list_prepend (assembly->array_methods, am);
m->table_idx = am->token & 0xffffff;
return am->token;
}
/*
* Insert into the metadata tables all the info about the TypeBuilder tb.
* Data in the tables is inserted in a predefined order, since some tables need to be sorted.
*/
static void
mono_image_get_type_info (MonoDomain *domain, MonoReflectionTypeBuilder *tb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint *values;
int i, is_object = 0, is_system = 0;
char *n;
table = &assembly->tables [MONO_TABLE_TYPEDEF];
values = table->values + tb->table_idx * MONO_TYPEDEF_SIZE;
values [MONO_TYPEDEF_FLAGS] = tb->attrs;
n = mono_string_to_utf8 (tb->name);
if (strcmp (n, "Object") == 0)
is_object++;
values [MONO_TYPEDEF_NAME] = string_heap_insert (&assembly->sheap, n);
g_free (n);
n = mono_string_to_utf8 (tb->nspace);
if (strcmp (n, "System") == 0)
is_system++;
values [MONO_TYPEDEF_NAMESPACE] = string_heap_insert (&assembly->sheap, n);
g_free (n);
if (tb->parent && !(is_system && is_object) &&
!(tb->attrs & TYPE_ATTRIBUTE_INTERFACE)) { /* interfaces don't have a parent */
values [MONO_TYPEDEF_EXTENDS] = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)tb->parent));
} else {
values [MONO_TYPEDEF_EXTENDS] = 0;
}
values [MONO_TYPEDEF_FIELD_LIST] = assembly->tables [MONO_TABLE_FIELD].next_idx;
values [MONO_TYPEDEF_METHOD_LIST] = assembly->tables [MONO_TABLE_METHOD].next_idx;
/*
* if we have explicitlayout or sequentiallayouts, output data in the
* ClassLayout table.
*/
if (((tb->attrs & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT) &&
((tb->class_size > 0) || (tb->packing_size > 0))) {
table = &assembly->tables [MONO_TABLE_CLASSLAYOUT];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_CLASS_LAYOUT_SIZE;
values [MONO_CLASS_LAYOUT_PARENT] = tb->table_idx;
values [MONO_CLASS_LAYOUT_CLASS_SIZE] = tb->class_size;
values [MONO_CLASS_LAYOUT_PACKING_SIZE] = tb->packing_size;
}
/* handle interfaces */
if (tb->interfaces) {
table = &assembly->tables [MONO_TABLE_INTERFACEIMPL];
i = table->rows;
table->rows += mono_array_length (tb->interfaces);
alloc_table (table, table->rows);
values = table->values + (i + 1) * MONO_INTERFACEIMPL_SIZE;
for (i = 0; i < mono_array_length (tb->interfaces); ++i) {
MonoReflectionType* iface = (MonoReflectionType*) mono_array_get (tb->interfaces, gpointer, i);
values [MONO_INTERFACEIMPL_CLASS] = tb->table_idx;
values [MONO_INTERFACEIMPL_INTERFACE] = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (iface));
values += MONO_INTERFACEIMPL_SIZE;
}
}
/* handle fields */
if (tb->fields) {
table = &assembly->tables [MONO_TABLE_FIELD];
table->rows += tb->num_fields;
alloc_table (table, table->rows);
for (i = 0; i < tb->num_fields; ++i)
mono_image_get_field_info (
mono_array_get (tb->fields, MonoReflectionFieldBuilder*, i), assembly);
}
/* handle constructors */
if (tb->ctors) {
table = &assembly->tables [MONO_TABLE_METHOD];
table->rows += mono_array_length (tb->ctors);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (tb->ctors); ++i)
mono_image_get_ctor_info (domain,
mono_array_get (tb->ctors, MonoReflectionCtorBuilder*, i), assembly);
}
/* handle methods */
if (tb->methods) {
table = &assembly->tables [MONO_TABLE_METHOD];
table->rows += tb->num_methods;
alloc_table (table, table->rows);
for (i = 0; i < tb->num_methods; ++i)
mono_image_get_method_info (
mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i), assembly);
}
/* Do the same with properties etc.. */
if (tb->events && mono_array_length (tb->events)) {
table = &assembly->tables [MONO_TABLE_EVENT];
table->rows += mono_array_length (tb->events);
alloc_table (table, table->rows);
table = &assembly->tables [MONO_TABLE_EVENTMAP];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_EVENT_MAP_SIZE;
values [MONO_EVENT_MAP_PARENT] = tb->table_idx;
values [MONO_EVENT_MAP_EVENTLIST] = assembly->tables [MONO_TABLE_EVENT].next_idx;
for (i = 0; i < mono_array_length (tb->events); ++i)
mono_image_get_event_info (
mono_array_get (tb->events, MonoReflectionEventBuilder*, i), assembly);
}
if (tb->properties && mono_array_length (tb->properties)) {
table = &assembly->tables [MONO_TABLE_PROPERTY];
table->rows += mono_array_length (tb->properties);
alloc_table (table, table->rows);
table = &assembly->tables [MONO_TABLE_PROPERTYMAP];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_PROPERTY_MAP_SIZE;
values [MONO_PROPERTY_MAP_PARENT] = tb->table_idx;
values [MONO_PROPERTY_MAP_PROPERTY_LIST] = assembly->tables [MONO_TABLE_PROPERTY].next_idx;
for (i = 0; i < mono_array_length (tb->properties); ++i)
mono_image_get_property_info (
mono_array_get (tb->properties, MonoReflectionPropertyBuilder*, i), assembly);
}
/* handle generic parameters */
if (tb->generic_params) {
table = &assembly->tables [MONO_TABLE_GENERICPARAM];
table->rows += mono_array_length (tb->generic_params);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (tb->generic_params); ++i) {
guint32 owner = MONO_TYPEORMETHOD_TYPE | (tb->table_idx << MONO_TYPEORMETHOD_BITS);
mono_image_get_generic_param_info (
mono_array_get (tb->generic_params, MonoReflectionGenericParam*, i), owner, assembly);
}
}
mono_image_add_decl_security (assembly,
mono_metadata_make_token (MONO_TABLE_TYPEDEF, tb->table_idx), tb->permissions);
if (tb->subtypes) {
MonoDynamicTable *ntable;
ntable = &assembly->tables [MONO_TABLE_NESTEDCLASS];
ntable->rows += mono_array_length (tb->subtypes);
alloc_table (ntable, ntable->rows);
values = ntable->values + ntable->next_idx * MONO_NESTED_CLASS_SIZE;
for (i = 0; i < mono_array_length (tb->subtypes); ++i) {
MonoReflectionTypeBuilder *subtype = mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i);
values [MONO_NESTED_CLASS_NESTED] = subtype->table_idx;
values [MONO_NESTED_CLASS_ENCLOSING] = tb->table_idx;
/*g_print ("nesting %s (%d) in %s (%d) (rows %d/%d)\n",
mono_string_to_utf8 (subtype->name), subtype->table_idx,
mono_string_to_utf8 (tb->name), tb->table_idx,
ntable->next_idx, ntable->rows);*/
values += MONO_NESTED_CLASS_SIZE;
ntable->next_idx++;
}
}
}
#endif
static void
collect_types (MonoPtrArray *types, MonoReflectionTypeBuilder *type)
{
int i;
mono_ptr_array_append (*types, type);
if (!type->subtypes)
return;
for (i = 0; i < mono_array_length (type->subtypes); ++i) {
MonoReflectionTypeBuilder *subtype = mono_array_get (type->subtypes, MonoReflectionTypeBuilder*, i);
collect_types (types, subtype);
}
}
static gint
compare_types_by_table_idx (MonoReflectionTypeBuilder **type1, MonoReflectionTypeBuilder **type2)
{
if ((*type1)->table_idx < (*type2)->table_idx)
return -1;
else
if ((*type1)->table_idx > (*type2)->table_idx)
return 1;
else
return 0;
}
static void
params_add_cattrs (MonoDynamicImage *assembly, MonoArray *pinfo) {
int i;
if (!pinfo)
return;
for (i = 0; i < mono_array_length (pinfo); ++i) {
MonoReflectionParamBuilder *pb;
pb = mono_array_get (pinfo, MonoReflectionParamBuilder *, i);
if (!pb)
continue;
mono_image_add_cattrs (assembly, pb->table_idx, MONO_CUSTOM_ATTR_PARAMDEF, pb->cattrs);
}
}
static void
type_add_cattrs (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *tb) {
int i;
mono_image_add_cattrs (assembly, tb->table_idx, MONO_CUSTOM_ATTR_TYPEDEF, tb->cattrs);
if (tb->fields) {
for (i = 0; i < tb->num_fields; ++i) {
MonoReflectionFieldBuilder* fb;
fb = mono_array_get (tb->fields, MonoReflectionFieldBuilder*, i);
mono_image_add_cattrs (assembly, fb->table_idx, MONO_CUSTOM_ATTR_FIELDDEF, fb->cattrs);
}
}
if (tb->events) {
for (i = 0; i < mono_array_length (tb->events); ++i) {
MonoReflectionEventBuilder* eb;
eb = mono_array_get (tb->events, MonoReflectionEventBuilder*, i);
mono_image_add_cattrs (assembly, eb->table_idx, MONO_CUSTOM_ATTR_EVENT, eb->cattrs);
}
}
if (tb->properties) {
for (i = 0; i < mono_array_length (tb->properties); ++i) {
MonoReflectionPropertyBuilder* pb;
pb = mono_array_get (tb->properties, MonoReflectionPropertyBuilder*, i);
mono_image_add_cattrs (assembly, pb->table_idx, MONO_CUSTOM_ATTR_PROPERTY, pb->cattrs);
}
}
if (tb->ctors) {
for (i = 0; i < mono_array_length (tb->ctors); ++i) {
MonoReflectionCtorBuilder* cb;
cb = mono_array_get (tb->ctors, MonoReflectionCtorBuilder*, i);
mono_image_add_cattrs (assembly, cb->table_idx, MONO_CUSTOM_ATTR_METHODDEF, cb->cattrs);
params_add_cattrs (assembly, cb->pinfo);
}
}
if (tb->methods) {
for (i = 0; i < tb->num_methods; ++i) {
MonoReflectionMethodBuilder* mb;
mb = mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i);
mono_image_add_cattrs (assembly, mb->table_idx, MONO_CUSTOM_ATTR_METHODDEF, mb->cattrs);
params_add_cattrs (assembly, mb->pinfo);
}
}
if (tb->subtypes) {
for (i = 0; i < mono_array_length (tb->subtypes); ++i)
type_add_cattrs (assembly, mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i));
}
}
static void
module_add_cattrs (MonoDynamicImage *assembly, MonoReflectionModuleBuilder *moduleb)
{
int i;
mono_image_add_cattrs (assembly, moduleb->table_idx, MONO_CUSTOM_ATTR_MODULE, moduleb->cattrs);
if (moduleb->global_methods) {
for (i = 0; i < mono_array_length (moduleb->global_methods); ++i) {
MonoReflectionMethodBuilder* mb = mono_array_get (moduleb->global_methods, MonoReflectionMethodBuilder*, i);
mono_image_add_cattrs (assembly, mb->table_idx, MONO_CUSTOM_ATTR_METHODDEF, mb->cattrs);
params_add_cattrs (assembly, mb->pinfo);
}
}
if (moduleb->global_fields) {
for (i = 0; i < mono_array_length (moduleb->global_fields); ++i) {
MonoReflectionFieldBuilder *fb = mono_array_get (moduleb->global_fields, MonoReflectionFieldBuilder*, i);
mono_image_add_cattrs (assembly, fb->table_idx, MONO_CUSTOM_ATTR_FIELDDEF, fb->cattrs);
}
}
if (moduleb->types) {
for (i = 0; i < moduleb->num_types; ++i)
type_add_cattrs (assembly, mono_array_get (moduleb->types, MonoReflectionTypeBuilder*, i));
}
}
static void
mono_image_fill_file_table (MonoDomain *domain, MonoReflectionModule *module, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
char blob_size [6];
guchar hash [20];
char *b = blob_size;
char *dir, *path;
table = &assembly->tables [MONO_TABLE_FILE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_FILE_SIZE;
values [MONO_FILE_FLAGS] = FILE_CONTAINS_METADATA;
values [MONO_FILE_NAME] = string_heap_insert (&assembly->sheap, module->image->module_name);
if (module->image->dynamic) {
/* This depends on the fact that the main module is emitted last */
dir = mono_string_to_utf8 (((MonoReflectionModuleBuilder*)module)->assemblyb->dir);
path = g_strdup_printf ("%s%c%s", dir, G_DIR_SEPARATOR, module->image->module_name);
} else {
dir = NULL;
path = g_strdup (module->image->name);
}
mono_sha1_get_digest_from_file (path, hash);
g_free (dir);
g_free (path);
mono_metadata_encode_value (20, b, &b);
values [MONO_FILE_HASH_VALUE] = mono_image_add_stream_data (&assembly->blob, blob_size, b-blob_size);
mono_image_add_stream_data (&assembly->blob, (char*)hash, 20);
table->next_idx ++;
}
static void
mono_image_fill_module_table (MonoDomain *domain, MonoReflectionModuleBuilder *mb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
int i;
table = &assembly->tables [MONO_TABLE_MODULE];
mb->table_idx = table->next_idx ++;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_NAME] = string_heap_insert_mstring (&assembly->sheap, mb->module.name);
i = mono_image_add_stream_data (&assembly->guid, mono_array_addr (mb->guid, char, 0), 16);
i /= 16;
++i;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_GENERATION] = 0;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_MVID] = i;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_ENC] = 0;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_ENCBASE] = 0;
}
static guint32
mono_image_fill_export_table_from_class (MonoDomain *domain, MonoClass *klass,
guint32 module_index, guint32 parent_index, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint32 visib, res;
visib = klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
if (! ((visib & TYPE_ATTRIBUTE_PUBLIC) || (visib & TYPE_ATTRIBUTE_NESTED_PUBLIC)))
return 0;
table = &assembly->tables [MONO_TABLE_EXPORTEDTYPE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_EXP_TYPE_SIZE;
values [MONO_EXP_TYPE_FLAGS] = klass->flags;
values [MONO_EXP_TYPE_TYPEDEF] = klass->type_token;
if (klass->nested_in)
values [MONO_EXP_TYPE_IMPLEMENTATION] = (parent_index << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_EXP_TYPE;
else
values [MONO_EXP_TYPE_IMPLEMENTATION] = (module_index << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_FILE;
values [MONO_EXP_TYPE_NAME] = string_heap_insert (&assembly->sheap, klass->name);
values [MONO_EXP_TYPE_NAMESPACE] = string_heap_insert (&assembly->sheap, klass->name_space);
res = table->next_idx;
table->next_idx ++;
/* Emit nested types */
if (klass->ext && klass->ext->nested_classes) {
GList *tmp;
for (tmp = klass->ext->nested_classes; tmp; tmp = tmp->next)
mono_image_fill_export_table_from_class (domain, tmp->data, module_index, table->next_idx - 1, assembly);
}
return res;
}
static void
mono_image_fill_export_table (MonoDomain *domain, MonoReflectionTypeBuilder *tb,
guint32 module_index, guint32 parent_index, MonoDynamicImage *assembly)
{
MonoClass *klass;
guint32 idx, i;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
klass->type_token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, tb->table_idx);
idx = mono_image_fill_export_table_from_class (domain, klass, module_index,
parent_index, assembly);
/*
* Emit nested types
* We need to do this ourselves since klass->nested_classes is not set up.
*/
if (tb->subtypes) {
for (i = 0; i < mono_array_length (tb->subtypes); ++i)
mono_image_fill_export_table (domain, mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i), module_index, idx, assembly);
}
}
static void
mono_image_fill_export_table_from_module (MonoDomain *domain, MonoReflectionModule *module,
guint32 module_index, MonoDynamicImage *assembly)
{
MonoImage *image = module->image;
MonoTableInfo *t;
guint32 i;
t = &image->tables [MONO_TABLE_TYPEDEF];
for (i = 0; i < t->rows; ++i) {
MonoClass *klass = mono_class_get (image, mono_metadata_make_token (MONO_TABLE_TYPEDEF, i + 1));
if (klass->flags & TYPE_ATTRIBUTE_PUBLIC)
mono_image_fill_export_table_from_class (domain, klass, module_index, 0, assembly);
}
}
static void
add_exported_type (MonoReflectionAssemblyBuilder *assemblyb, MonoDynamicImage *assembly, MonoClass *klass, guint32 parent_index)
{
MonoDynamicTable *table;
guint32 *values;
guint32 scope, scope_idx, impl, current_idx;
gboolean forwarder = TRUE;
gpointer iter = NULL;
MonoClass *nested;
if (klass->nested_in) {
impl = (parent_index << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_EXP_TYPE;
forwarder = FALSE;
} else {
scope = resolution_scope_from_image (assembly, klass->image);
g_assert ((scope & MONO_RESOLTION_SCOPE_MASK) == MONO_RESOLTION_SCOPE_ASSEMBLYREF);
scope_idx = scope >> MONO_RESOLTION_SCOPE_BITS;
impl = (scope_idx << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_ASSEMBLYREF;
}
table = &assembly->tables [MONO_TABLE_EXPORTEDTYPE];
table->rows++;
alloc_table (table, table->rows);
current_idx = table->next_idx;
values = table->values + current_idx * MONO_EXP_TYPE_SIZE;
values [MONO_EXP_TYPE_FLAGS] = forwarder ? TYPE_ATTRIBUTE_FORWARDER : 0;
values [MONO_EXP_TYPE_TYPEDEF] = 0;
values [MONO_EXP_TYPE_IMPLEMENTATION] = impl;
values [MONO_EXP_TYPE_NAME] = string_heap_insert (&assembly->sheap, klass->name);
values [MONO_EXP_TYPE_NAMESPACE] = string_heap_insert (&assembly->sheap, klass->name_space);
table->next_idx++;
while ((nested = mono_class_get_nested_types (klass, &iter)))
add_exported_type (assemblyb, assembly, nested, current_idx);
}
static void
mono_image_fill_export_table_from_type_forwarders (MonoReflectionAssemblyBuilder *assemblyb, MonoDynamicImage *assembly)
{
MonoClass *klass;
int i;
if (!assemblyb->type_forwarders)
return;
for (i = 0; i < mono_array_length (assemblyb->type_forwarders); ++i) {
MonoReflectionType *t = mono_array_get (assemblyb->type_forwarders, MonoReflectionType *, i);
MonoType *type;
if (!t)
continue;
type = mono_reflection_type_get_handle (t);
g_assert (type);
klass = mono_class_from_mono_type (type);
add_exported_type (assemblyb, assembly, klass, 0);
}
}
#define align_pointer(base,p)\
do {\
guint32 __diff = (unsigned char*)(p)-(unsigned char*)(base);\
if (__diff & 3)\
(p) += 4 - (__diff & 3);\
} while (0)
static int
compare_constants (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_CONSTANT_PARENT] - b_values [MONO_CONSTANT_PARENT];
}
static int
compare_semantics (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
int assoc = a_values [MONO_METHOD_SEMA_ASSOCIATION] - b_values [MONO_METHOD_SEMA_ASSOCIATION];
if (assoc)
return assoc;
return a_values [MONO_METHOD_SEMA_SEMANTICS] - b_values [MONO_METHOD_SEMA_SEMANTICS];
}
static int
compare_custom_attrs (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_CUSTOM_ATTR_PARENT] - b_values [MONO_CUSTOM_ATTR_PARENT];
}
static int
compare_field_marshal (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_FIELD_MARSHAL_PARENT] - b_values [MONO_FIELD_MARSHAL_PARENT];
}
static int
compare_nested (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_NESTED_CLASS_NESTED] - b_values [MONO_NESTED_CLASS_NESTED];
}
static int
compare_genericparam (const void *a, const void *b)
{
const GenericParamTableEntry **a_entry = (const GenericParamTableEntry **) a;
const GenericParamTableEntry **b_entry = (const GenericParamTableEntry **) b;
if ((*b_entry)->owner == (*a_entry)->owner)
return
mono_type_get_generic_param_num (mono_reflection_type_get_handle ((MonoReflectionType*)(*a_entry)->gparam)) -
mono_type_get_generic_param_num (mono_reflection_type_get_handle ((MonoReflectionType*)(*b_entry)->gparam));
else
return (*a_entry)->owner - (*b_entry)->owner;
}
static int
compare_declsecurity_attrs (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_DECL_SECURITY_PARENT] - b_values [MONO_DECL_SECURITY_PARENT];
}
static int
compare_interface_impl (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
int klass = a_values [MONO_INTERFACEIMPL_CLASS] - b_values [MONO_INTERFACEIMPL_CLASS];
if (klass)
return klass;
return a_values [MONO_INTERFACEIMPL_INTERFACE] - b_values [MONO_INTERFACEIMPL_INTERFACE];
}
static void
pad_heap (MonoDynamicStream *sh)
{
if (sh->index & 3) {
int sz = 4 - (sh->index & 3);
memset (sh->data + sh->index, 0, sz);
sh->index += sz;
}
}
struct StreamDesc {
const char *name;
MonoDynamicStream *stream;
};
/*
* build_compressed_metadata() fills in the blob of data that represents the
* raw metadata as it will be saved in the PE file. The five streams are output
* and the metadata tables are comnpressed from the guint32 array representation,
* to the compressed on-disk format.
*/
static void
build_compressed_metadata (MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
int i;
guint64 valid_mask = 0;
guint64 sorted_mask;
guint32 heapt_size = 0;
guint32 meta_size = 256; /* allow for header and other stuff */
guint32 table_offset;
guint32 ntables = 0;
guint64 *int64val;
guint32 *int32val;
guint16 *int16val;
MonoImage *meta;
unsigned char *p;
struct StreamDesc stream_desc [5];
qsort (assembly->gen_params->pdata, assembly->gen_params->len, sizeof (gpointer), compare_genericparam);
for (i = 0; i < assembly->gen_params->len; i++){
GenericParamTableEntry *entry = g_ptr_array_index (assembly->gen_params, i);
write_generic_param_entry (assembly, entry);
}
stream_desc [0].name = "#~";
stream_desc [0].stream = &assembly->tstream;
stream_desc [1].name = "#Strings";
stream_desc [1].stream = &assembly->sheap;
stream_desc [2].name = "#US";
stream_desc [2].stream = &assembly->us;
stream_desc [3].name = "#Blob";
stream_desc [3].stream = &assembly->blob;
stream_desc [4].name = "#GUID";
stream_desc [4].stream = &assembly->guid;
/* tables that are sorted */
sorted_mask = ((guint64)1 << MONO_TABLE_CONSTANT) | ((guint64)1 << MONO_TABLE_FIELDMARSHAL)
| ((guint64)1 << MONO_TABLE_METHODSEMANTICS) | ((guint64)1 << MONO_TABLE_CLASSLAYOUT)
| ((guint64)1 << MONO_TABLE_FIELDLAYOUT) | ((guint64)1 << MONO_TABLE_FIELDRVA)
| ((guint64)1 << MONO_TABLE_IMPLMAP) | ((guint64)1 << MONO_TABLE_NESTEDCLASS)
| ((guint64)1 << MONO_TABLE_METHODIMPL) | ((guint64)1 << MONO_TABLE_CUSTOMATTRIBUTE)
| ((guint64)1 << MONO_TABLE_DECLSECURITY) | ((guint64)1 << MONO_TABLE_GENERICPARAM)
| ((guint64)1 << MONO_TABLE_INTERFACEIMPL);
/* Compute table sizes */
/* the MonoImage has already been created in mono_image_basic_init() */
meta = &assembly->image;
/* sizes should be multiple of 4 */
pad_heap (&assembly->blob);
pad_heap (&assembly->guid);
pad_heap (&assembly->sheap);
pad_heap (&assembly->us);
/* Setup the info used by compute_sizes () */
meta->idx_blob_wide = assembly->blob.index >= 65536 ? 1 : 0;
meta->idx_guid_wide = assembly->guid.index >= 65536 ? 1 : 0;
meta->idx_string_wide = assembly->sheap.index >= 65536 ? 1 : 0;
meta_size += assembly->blob.index;
meta_size += assembly->guid.index;
meta_size += assembly->sheap.index;
meta_size += assembly->us.index;
for (i=0; i < MONO_TABLE_NUM; ++i)
meta->tables [i].rows = assembly->tables [i].rows;
for (i = 0; i < MONO_TABLE_NUM; i++){
if (meta->tables [i].rows == 0)
continue;
valid_mask |= (guint64)1 << i;
ntables ++;
meta->tables [i].row_size = mono_metadata_compute_size (
meta, i, &meta->tables [i].size_bitfield);
heapt_size += meta->tables [i].row_size * meta->tables [i].rows;
}
heapt_size += 24; /* #~ header size */
heapt_size += ntables * 4;
/* make multiple of 4 */
heapt_size += 3;
heapt_size &= ~3;
meta_size += heapt_size;
meta->raw_metadata = g_malloc0 (meta_size);
p = (unsigned char*)meta->raw_metadata;
/* the metadata signature */
*p++ = 'B'; *p++ = 'S'; *p++ = 'J'; *p++ = 'B';
/* version numbers and 4 bytes reserved */
int16val = (guint16*)p;
*int16val++ = GUINT16_TO_LE (meta->md_version_major);
*int16val = GUINT16_TO_LE (meta->md_version_minor);
p += 8;
/* version string */
int32val = (guint32*)p;
*int32val = GUINT32_TO_LE ((strlen (meta->version) + 3) & (~3)); /* needs to be multiple of 4 */
p += 4;
memcpy (p, meta->version, strlen (meta->version));
p += GUINT32_FROM_LE (*int32val);
align_pointer (meta->raw_metadata, p);
int16val = (guint16*)p;
*int16val++ = GUINT16_TO_LE (0); /* flags must be 0 */
*int16val = GUINT16_TO_LE (5); /* number of streams */
p += 4;
/*
* write the stream info.
*/
table_offset = (p - (unsigned char*)meta->raw_metadata) + 5 * 8 + 40; /* room needed for stream headers */
table_offset += 3; table_offset &= ~3;
assembly->tstream.index = heapt_size;
for (i = 0; i < 5; ++i) {
int32val = (guint32*)p;
stream_desc [i].stream->offset = table_offset;
*int32val++ = GUINT32_TO_LE (table_offset);
*int32val = GUINT32_TO_LE (stream_desc [i].stream->index);
table_offset += GUINT32_FROM_LE (*int32val);
table_offset += 3; table_offset &= ~3;
p += 8;
strcpy ((char*)p, stream_desc [i].name);
p += strlen (stream_desc [i].name) + 1;
align_pointer (meta->raw_metadata, p);
}
/*
* now copy the data, the table stream header and contents goes first.
*/
g_assert ((p - (unsigned char*)meta->raw_metadata) < assembly->tstream.offset);
p = (guchar*)meta->raw_metadata + assembly->tstream.offset;
int32val = (guint32*)p;
*int32val = GUINT32_TO_LE (0); /* reserved */
p += 4;
*p++ = 2; /* version */
*p++ = 0;
if (meta->idx_string_wide)
*p |= 0x01;
if (meta->idx_guid_wide)
*p |= 0x02;
if (meta->idx_blob_wide)
*p |= 0x04;
++p;
*p++ = 1; /* reserved */
int64val = (guint64*)p;
*int64val++ = GUINT64_TO_LE (valid_mask);
*int64val++ = GUINT64_TO_LE (valid_mask & sorted_mask); /* bitvector of sorted tables */
p += 16;
int32val = (guint32*)p;
for (i = 0; i < MONO_TABLE_NUM; i++){
if (meta->tables [i].rows == 0)
continue;
*int32val++ = GUINT32_TO_LE (meta->tables [i].rows);
}
p = (unsigned char*)int32val;
/* sort the tables that still need sorting */
table = &assembly->tables [MONO_TABLE_CONSTANT];
if (table->rows)
qsort (table->values + MONO_CONSTANT_SIZE, table->rows, sizeof (guint32) * MONO_CONSTANT_SIZE, compare_constants);
table = &assembly->tables [MONO_TABLE_METHODSEMANTICS];
if (table->rows)
qsort (table->values + MONO_METHOD_SEMA_SIZE, table->rows, sizeof (guint32) * MONO_METHOD_SEMA_SIZE, compare_semantics);
table = &assembly->tables [MONO_TABLE_CUSTOMATTRIBUTE];
if (table->rows)
qsort (table->values + MONO_CUSTOM_ATTR_SIZE, table->rows, sizeof (guint32) * MONO_CUSTOM_ATTR_SIZE, compare_custom_attrs);
table = &assembly->tables [MONO_TABLE_FIELDMARSHAL];
if (table->rows)
qsort (table->values + MONO_FIELD_MARSHAL_SIZE, table->rows, sizeof (guint32) * MONO_FIELD_MARSHAL_SIZE, compare_field_marshal);
table = &assembly->tables [MONO_TABLE_NESTEDCLASS];
if (table->rows)
qsort (table->values + MONO_NESTED_CLASS_SIZE, table->rows, sizeof (guint32) * MONO_NESTED_CLASS_SIZE, compare_nested);
/* Section 21.11 DeclSecurity in Partition II doesn't specify this to be sorted by MS implementation requires it */
table = &assembly->tables [MONO_TABLE_DECLSECURITY];
if (table->rows)
qsort (table->values + MONO_DECL_SECURITY_SIZE, table->rows, sizeof (guint32) * MONO_DECL_SECURITY_SIZE, compare_declsecurity_attrs);
table = &assembly->tables [MONO_TABLE_INTERFACEIMPL];
if (table->rows)
qsort (table->values + MONO_INTERFACEIMPL_SIZE, table->rows, sizeof (guint32) * MONO_INTERFACEIMPL_SIZE, compare_interface_impl);
/* compress the tables */
for (i = 0; i < MONO_TABLE_NUM; i++){
int row, col;
guint32 *values;
guint32 bitfield = meta->tables [i].size_bitfield;
if (!meta->tables [i].rows)
continue;
if (assembly->tables [i].columns != mono_metadata_table_count (bitfield))
g_error ("col count mismatch in %d: %d %d", i, assembly->tables [i].columns, mono_metadata_table_count (bitfield));
meta->tables [i].base = (char*)p;
for (row = 1; row <= meta->tables [i].rows; ++row) {
values = assembly->tables [i].values + row * assembly->tables [i].columns;
for (col = 0; col < assembly->tables [i].columns; ++col) {
switch (mono_metadata_table_size (bitfield, col)) {
case 1:
*p++ = values [col];
break;
case 2:
*p++ = values [col] & 0xff;
*p++ = (values [col] >> 8) & 0xff;
break;
case 4:
*p++ = values [col] & 0xff;
*p++ = (values [col] >> 8) & 0xff;
*p++ = (values [col] >> 16) & 0xff;
*p++ = (values [col] >> 24) & 0xff;
break;
default:
g_assert_not_reached ();
}
}
}
g_assert ((p - (const unsigned char*)meta->tables [i].base) == (meta->tables [i].rows * meta->tables [i].row_size));
}
g_assert (assembly->guid.offset + assembly->guid.index < meta_size);
memcpy (meta->raw_metadata + assembly->sheap.offset, assembly->sheap.data, assembly->sheap.index);
memcpy (meta->raw_metadata + assembly->us.offset, assembly->us.data, assembly->us.index);
memcpy (meta->raw_metadata + assembly->blob.offset, assembly->blob.data, assembly->blob.index);
memcpy (meta->raw_metadata + assembly->guid.offset, assembly->guid.data, assembly->guid.index);
assembly->meta_size = assembly->guid.offset + assembly->guid.index;
}
/*
* Some tables in metadata need to be sorted according to some criteria, but
* when methods and fields are first created with reflection, they may be assigned a token
* that doesn't correspond to the final token they will get assigned after the sorting.
* ILGenerator.cs keeps a fixup table that maps the position of tokens in the IL code stream
* with the reflection objects that represent them. Once all the tables are set up, the
* reflection objects will contains the correct table index. fixup_method() will fixup the
* tokens for the method with ILGenerator @ilgen.
*/
static void
fixup_method (MonoReflectionILGen *ilgen, gpointer value, MonoDynamicImage *assembly)
{
guint32 code_idx = GPOINTER_TO_UINT (value);
MonoReflectionILTokenInfo *iltoken;
MonoReflectionFieldBuilder *field;
MonoReflectionCtorBuilder *ctor;
MonoReflectionMethodBuilder *method;
MonoReflectionTypeBuilder *tb;
MonoReflectionArrayMethod *am;
guint32 i, idx = 0;
unsigned char *target;
for (i = 0; i < ilgen->num_token_fixups; ++i) {
iltoken = (MonoReflectionILTokenInfo *)mono_array_addr_with_size (ilgen->token_fixups, sizeof (MonoReflectionILTokenInfo), i);
target = (guchar*)assembly->code.data + code_idx + iltoken->code_pos;
switch (target [3]) {
case MONO_TABLE_FIELD:
if (!strcmp (iltoken->member->vtable->klass->name, "FieldBuilder")) {
field = (MonoReflectionFieldBuilder *)iltoken->member;
idx = field->table_idx;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MonoField")) {
MonoClassField *f = ((MonoReflectionField*)iltoken->member)->field;
idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->field_to_table_idx, f));
} else {
g_assert_not_reached ();
}
break;
case MONO_TABLE_METHOD:
if (!strcmp (iltoken->member->vtable->klass->name, "MethodBuilder")) {
method = (MonoReflectionMethodBuilder *)iltoken->member;
idx = method->table_idx;
} else if (!strcmp (iltoken->member->vtable->klass->name, "ConstructorBuilder")) {
ctor = (MonoReflectionCtorBuilder *)iltoken->member;
idx = ctor->table_idx;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MonoMethod") ||
!strcmp (iltoken->member->vtable->klass->name, "MonoCMethod")) {
MonoMethod *m = ((MonoReflectionMethod*)iltoken->member)->method;
idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->method_to_table_idx, m));
} else {
g_assert_not_reached ();
}
break;
case MONO_TABLE_TYPEDEF:
if (strcmp (iltoken->member->vtable->klass->name, "TypeBuilder"))
g_assert_not_reached ();
tb = (MonoReflectionTypeBuilder *)iltoken->member;
idx = tb->table_idx;
break;
case MONO_TABLE_MEMBERREF:
if (!strcmp (iltoken->member->vtable->klass->name, "MonoArrayMethod")) {
am = (MonoReflectionArrayMethod*)iltoken->member;
idx = am->table_idx;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MonoMethod") ||
!strcmp (iltoken->member->vtable->klass->name, "MonoCMethod") ||
!strcmp (iltoken->member->vtable->klass->name, "MonoGenericMethod") ||
!strcmp (iltoken->member->vtable->klass->name, "MonoGenericCMethod")) {
MonoMethod *m = ((MonoReflectionMethod*)iltoken->member)->method;
g_assert (m->klass->generic_class || m->klass->generic_container);
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "FieldBuilder")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MonoField")) {
MonoClassField *f = ((MonoReflectionField*)iltoken->member)->field;
g_assert (is_field_on_inst (f));
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MethodBuilder") ||
!strcmp (iltoken->member->vtable->klass->name, "ConstructorBuilder")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "FieldOnTypeBuilderInst")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MethodOnTypeBuilderInst")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "ConstructorOnTypeBuilderInst")) {
continue;
} else {
g_assert_not_reached ();
}
break;
case MONO_TABLE_METHODSPEC:
if (!strcmp (iltoken->member->vtable->klass->name, "MonoGenericMethod")) {
MonoMethod *m = ((MonoReflectionMethod*)iltoken->member)->method;
g_assert (mono_method_signature (m)->generic_param_count);
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MethodBuilder")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MethodOnTypeBuilderInst")) {
continue;
} else {
g_assert_not_reached ();
}
break;
default:
g_error ("got unexpected table 0x%02x in fixup", target [3]);
}
target [0] = idx & 0xff;
target [1] = (idx >> 8) & 0xff;
target [2] = (idx >> 16) & 0xff;
}
}
/*
* fixup_cattrs:
*
* The CUSTOM_ATTRIBUTE table might contain METHODDEF tokens whose final
* value is not known when the table is emitted.
*/
static void
fixup_cattrs (MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint32 type, i, idx, token;
MonoObject *ctor;
table = &assembly->tables [MONO_TABLE_CUSTOMATTRIBUTE];
for (i = 0; i < table->rows; ++i) {
values = table->values + ((i + 1) * MONO_CUSTOM_ATTR_SIZE);
type = values [MONO_CUSTOM_ATTR_TYPE];
if ((type & MONO_CUSTOM_ATTR_TYPE_MASK) == MONO_CUSTOM_ATTR_TYPE_METHODDEF) {
idx = type >> MONO_CUSTOM_ATTR_TYPE_BITS;
token = mono_metadata_make_token (MONO_TABLE_METHOD, idx);
ctor = mono_g_hash_table_lookup (assembly->tokens, GUINT_TO_POINTER (token));
g_assert (ctor);
if (!strcmp (ctor->vtable->klass->name, "MonoCMethod")) {
MonoMethod *m = ((MonoReflectionMethod*)ctor)->method;
idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->method_to_table_idx, m));
values [MONO_CUSTOM_ATTR_TYPE] = (idx << MONO_CUSTOM_ATTR_TYPE_BITS) | MONO_CUSTOM_ATTR_TYPE_METHODDEF;
}
}
}
}
static void
assembly_add_resource_manifest (MonoReflectionModuleBuilder *mb, MonoDynamicImage *assembly, MonoReflectionResource *rsrc, guint32 implementation)
{
MonoDynamicTable *table;
guint32 *values;
table = &assembly->tables [MONO_TABLE_MANIFESTRESOURCE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_MANIFEST_SIZE;
values [MONO_MANIFEST_OFFSET] = rsrc->offset;
values [MONO_MANIFEST_FLAGS] = rsrc->attrs;
values [MONO_MANIFEST_NAME] = string_heap_insert_mstring (&assembly->sheap, rsrc->name);
values [MONO_MANIFEST_IMPLEMENTATION] = implementation;
table->next_idx++;
}
static void
assembly_add_resource (MonoReflectionModuleBuilder *mb, MonoDynamicImage *assembly, MonoReflectionResource *rsrc)
{
MonoDynamicTable *table;
guint32 *values;
char blob_size [6];
guchar hash [20];
char *b = blob_size;
char *name, *sname;
guint32 idx, offset;
if (rsrc->filename) {
name = mono_string_to_utf8 (rsrc->filename);
sname = g_path_get_basename (name);
table = &assembly->tables [MONO_TABLE_FILE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_FILE_SIZE;
values [MONO_FILE_FLAGS] = FILE_CONTAINS_NO_METADATA;
values [MONO_FILE_NAME] = string_heap_insert (&assembly->sheap, sname);
g_free (sname);
mono_sha1_get_digest_from_file (name, hash);
mono_metadata_encode_value (20, b, &b);
values [MONO_FILE_HASH_VALUE] = mono_image_add_stream_data (&assembly->blob, blob_size, b-blob_size);
mono_image_add_stream_data (&assembly->blob, (char*)hash, 20);
g_free (name);
idx = table->next_idx++;
rsrc->offset = 0;
idx = MONO_IMPLEMENTATION_FILE | (idx << MONO_IMPLEMENTATION_BITS);
} else {
char sizebuf [4];
char *data;
guint len;
if (rsrc->data) {
data = mono_array_addr (rsrc->data, char, 0);
len = mono_array_length (rsrc->data);
} else {
data = NULL;
len = 0;
}
offset = len;
sizebuf [0] = offset; sizebuf [1] = offset >> 8;
sizebuf [2] = offset >> 16; sizebuf [3] = offset >> 24;
rsrc->offset = mono_image_add_stream_data (&assembly->resources, sizebuf, 4);
mono_image_add_stream_data (&assembly->resources, data, len);
if (!mb->is_main)
/*
* The entry should be emitted into the MANIFESTRESOURCE table of
* the main module, but that needs to reference the FILE table
* which isn't emitted yet.
*/
return;
else
idx = 0;
}
assembly_add_resource_manifest (mb, assembly, rsrc, idx);
}
static void
set_version_from_string (MonoString *version, guint32 *values)
{
gchar *ver, *p, *str;
guint32 i;
values [MONO_ASSEMBLY_MAJOR_VERSION] = 0;
values [MONO_ASSEMBLY_MINOR_VERSION] = 0;
values [MONO_ASSEMBLY_REV_NUMBER] = 0;
values [MONO_ASSEMBLY_BUILD_NUMBER] = 0;
if (!version)
return;
ver = str = mono_string_to_utf8 (version);
for (i = 0; i < 4; ++i) {
values [MONO_ASSEMBLY_MAJOR_VERSION + i] = strtol (ver, &p, 10);
switch (*p) {
case '.':
p++;
break;
case '*':
/* handle Revision and Build */
p++;
break;
}
ver = p;
}
g_free (str);
}
static guint32
load_public_key (MonoArray *pkey, MonoDynamicImage *assembly) {
gsize len;
guint32 token = 0;
char blob_size [6];
char *b = blob_size;
if (!pkey)
return token;
len = mono_array_length (pkey);
mono_metadata_encode_value (len, b, &b);
token = mono_image_add_stream_data (&assembly->blob, blob_size, b - blob_size);
mono_image_add_stream_data (&assembly->blob, mono_array_addr (pkey, char, 0), len);
assembly->public_key = g_malloc (len);
memcpy (assembly->public_key, mono_array_addr (pkey, char, 0), len);
assembly->public_key_len = len;
/* Special case: check for ECMA key (16 bytes) */
if ((len == MONO_ECMA_KEY_LENGTH) && mono_is_ecma_key (mono_array_addr (pkey, char, 0), len)) {
/* In this case we must reserve 128 bytes (1024 bits) for the signature */
assembly->strong_name_size = MONO_DEFAULT_PUBLIC_KEY_LENGTH;
} else if (len >= MONO_PUBLIC_KEY_HEADER_LENGTH + MONO_MINIMUM_PUBLIC_KEY_LENGTH) {
/* minimum key size (in 2.0) is 384 bits */
assembly->strong_name_size = len - MONO_PUBLIC_KEY_HEADER_LENGTH;
} else {
/* FIXME - verifier */
g_warning ("Invalid public key length: %d bits (total: %d)", (int)MONO_PUBLIC_KEY_BIT_SIZE (len), (int)len);
assembly->strong_name_size = MONO_DEFAULT_PUBLIC_KEY_LENGTH; /* to be safe */
}
assembly->strong_name = g_malloc0 (assembly->strong_name_size);
return token;
}
static void
mono_image_emit_manifest (MonoReflectionModuleBuilder *moduleb)
{
MonoDynamicTable *table;
MonoDynamicImage *assembly;
MonoReflectionAssemblyBuilder *assemblyb;
MonoDomain *domain;
guint32 *values;
int i;
guint32 module_index;
assemblyb = moduleb->assemblyb;
assembly = moduleb->dynamic_image;
domain = mono_object_domain (assemblyb);
/* Emit ASSEMBLY table */
table = &assembly->tables [MONO_TABLE_ASSEMBLY];
alloc_table (table, 1);
values = table->values + MONO_ASSEMBLY_SIZE;
values [MONO_ASSEMBLY_HASH_ALG] = assemblyb->algid? assemblyb->algid: ASSEMBLY_HASH_SHA1;
values [MONO_ASSEMBLY_NAME] = string_heap_insert_mstring (&assembly->sheap, assemblyb->name);
if (assemblyb->culture) {
values [MONO_ASSEMBLY_CULTURE] = string_heap_insert_mstring (&assembly->sheap, assemblyb->culture);
} else {
values [MONO_ASSEMBLY_CULTURE] = string_heap_insert (&assembly->sheap, "");
}
values [MONO_ASSEMBLY_PUBLIC_KEY] = load_public_key (assemblyb->public_key, assembly);
values [MONO_ASSEMBLY_FLAGS] = assemblyb->flags;
set_version_from_string (assemblyb->version, values);
/* Emit FILE + EXPORTED_TYPE table */
module_index = 0;
for (i = 0; i < mono_array_length (assemblyb->modules); ++i) {
int j;
MonoReflectionModuleBuilder *file_module =
mono_array_get (assemblyb->modules, MonoReflectionModuleBuilder*, i);
if (file_module != moduleb) {
mono_image_fill_file_table (domain, (MonoReflectionModule*)file_module, assembly);
module_index ++;
if (file_module->types) {
for (j = 0; j < file_module->num_types; ++j) {
MonoReflectionTypeBuilder *tb = mono_array_get (file_module->types, MonoReflectionTypeBuilder*, j);
mono_image_fill_export_table (domain, tb, module_index, 0, assembly);
}
}
}
}
if (assemblyb->loaded_modules) {
for (i = 0; i < mono_array_length (assemblyb->loaded_modules); ++i) {
MonoReflectionModule *file_module =
mono_array_get (assemblyb->loaded_modules, MonoReflectionModule*, i);
mono_image_fill_file_table (domain, file_module, assembly);
module_index ++;
mono_image_fill_export_table_from_module (domain, file_module, module_index, assembly);
}
}
if (assemblyb->type_forwarders)
mono_image_fill_export_table_from_type_forwarders (assemblyb, assembly);
/* Emit MANIFESTRESOURCE table */
module_index = 0;
for (i = 0; i < mono_array_length (assemblyb->modules); ++i) {
int j;
MonoReflectionModuleBuilder *file_module =
mono_array_get (assemblyb->modules, MonoReflectionModuleBuilder*, i);
/* The table for the main module is emitted later */
if (file_module != moduleb) {
module_index ++;
if (file_module->resources) {
int len = mono_array_length (file_module->resources);
for (j = 0; j < len; ++j) {
MonoReflectionResource* res = (MonoReflectionResource*)mono_array_addr (file_module->resources, MonoReflectionResource, j);
assembly_add_resource_manifest (file_module, assembly, res, MONO_IMPLEMENTATION_FILE | (module_index << MONO_IMPLEMENTATION_BITS));
}
}
}
}
}
#ifndef DISABLE_REFLECTION_EMIT_SAVE
/*
* mono_image_build_metadata() will fill the info in all the needed metadata tables
* for the modulebuilder @moduleb.
* At the end of the process, method and field tokens are fixed up and the
* on-disk compressed metadata representation is created.
*/
void
mono_image_build_metadata (MonoReflectionModuleBuilder *moduleb)
{
MonoDynamicTable *table;
MonoDynamicImage *assembly;
MonoReflectionAssemblyBuilder *assemblyb;
MonoDomain *domain;
MonoPtrArray types;
guint32 *values;
int i, j;
assemblyb = moduleb->assemblyb;
assembly = moduleb->dynamic_image;
domain = mono_object_domain (assemblyb);
if (assembly->text_rva)
return;
assembly->text_rva = START_TEXT_RVA;
if (moduleb->is_main) {
mono_image_emit_manifest (moduleb);
}
table = &assembly->tables [MONO_TABLE_TYPEDEF];
table->rows = 1; /* .<Module> */
table->next_idx++;
alloc_table (table, table->rows);
/*
* Set the first entry.
*/
values = table->values + table->columns;
values [MONO_TYPEDEF_FLAGS] = 0;
values [MONO_TYPEDEF_NAME] = string_heap_insert (&assembly->sheap, "<Module>") ;
values [MONO_TYPEDEF_NAMESPACE] = string_heap_insert (&assembly->sheap, "") ;
values [MONO_TYPEDEF_EXTENDS] = 0;
values [MONO_TYPEDEF_FIELD_LIST] = 1;
values [MONO_TYPEDEF_METHOD_LIST] = 1;
/*
* handle global methods
* FIXME: test what to do when global methods are defined in multiple modules.
*/
if (moduleb->global_methods) {
table = &assembly->tables [MONO_TABLE_METHOD];
table->rows += mono_array_length (moduleb->global_methods);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (moduleb->global_methods); ++i)
mono_image_get_method_info (
mono_array_get (moduleb->global_methods, MonoReflectionMethodBuilder*, i), assembly);
}
if (moduleb->global_fields) {
table = &assembly->tables [MONO_TABLE_FIELD];
table->rows += mono_array_length (moduleb->global_fields);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (moduleb->global_fields); ++i)
mono_image_get_field_info (
mono_array_get (moduleb->global_fields, MonoReflectionFieldBuilder*, i), assembly);
}
table = &assembly->tables [MONO_TABLE_MODULE];
alloc_table (table, 1);
mono_image_fill_module_table (domain, moduleb, assembly);
/* Collect all types into a list sorted by their table_idx */
mono_ptr_array_init (types, moduleb->num_types);
if (moduleb->types)
for (i = 0; i < moduleb->num_types; ++i) {
MonoReflectionTypeBuilder *type = mono_array_get (moduleb->types, MonoReflectionTypeBuilder*, i);
collect_types (&types, type);
}
mono_ptr_array_sort (types, (gpointer)compare_types_by_table_idx);
table = &assembly->tables [MONO_TABLE_TYPEDEF];
table->rows += mono_ptr_array_size (types);
alloc_table (table, table->rows);
/*
* Emit type names + namespaces at one place inside the string heap,
* so load_class_names () needs to touch fewer pages.
*/
for (i = 0; i < mono_ptr_array_size (types); ++i) {
MonoReflectionTypeBuilder *tb = mono_ptr_array_get (types, i);
string_heap_insert_mstring (&assembly->sheap, tb->nspace);
}
for (i = 0; i < mono_ptr_array_size (types); ++i) {
MonoReflectionTypeBuilder *tb = mono_ptr_array_get (types, i);
string_heap_insert_mstring (&assembly->sheap, tb->name);
}
for (i = 0; i < mono_ptr_array_size (types); ++i) {
MonoReflectionTypeBuilder *type = mono_ptr_array_get (types, i);
mono_image_get_type_info (domain, type, assembly);
}
/*
* table->rows is already set above and in mono_image_fill_module_table.
*/
/* add all the custom attributes at the end, once all the indexes are stable */
mono_image_add_cattrs (assembly, 1, MONO_CUSTOM_ATTR_ASSEMBLY, assemblyb->cattrs);
/* CAS assembly permissions */
if (assemblyb->permissions_minimum)
mono_image_add_decl_security (assembly, mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1), assemblyb->permissions_minimum);
if (assemblyb->permissions_optional)
mono_image_add_decl_security (assembly, mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1), assemblyb->permissions_optional);
if (assemblyb->permissions_refused)
mono_image_add_decl_security (assembly, mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1), assemblyb->permissions_refused);
module_add_cattrs (assembly, moduleb);
/* fixup tokens */
mono_g_hash_table_foreach (assembly->token_fixups, (GHFunc)fixup_method, assembly);
/* Create the MethodImpl table. We do this after emitting all methods so we already know
* the final tokens and don't need another fixup pass. */
if (moduleb->global_methods) {
for (i = 0; i < mono_array_length (moduleb->global_methods); ++i) {
MonoReflectionMethodBuilder *mb = mono_array_get (
moduleb->global_methods, MonoReflectionMethodBuilder*, i);
mono_image_add_methodimpl (assembly, mb);
}
}
for (i = 0; i < mono_ptr_array_size (types); ++i) {
MonoReflectionTypeBuilder *type = mono_ptr_array_get (types, i);
if (type->methods) {
for (j = 0; j < type->num_methods; ++j) {
MonoReflectionMethodBuilder *mb = mono_array_get (
type->methods, MonoReflectionMethodBuilder*, j);
mono_image_add_methodimpl (assembly, mb);
}
}
}
mono_ptr_array_destroy (types);
fixup_cattrs (assembly);
}
#else /* DISABLE_REFLECTION_EMIT_SAVE */
void
mono_image_build_metadata (MonoReflectionModuleBuilder *moduleb)
{
g_error ("This mono runtime was configured with --enable-minimal=reflection_emit_save, so saving of dynamic assemblies is not supported.");
}
#endif /* DISABLE_REFLECTION_EMIT_SAVE */
typedef struct {
guint32 import_lookup_table;
guint32 timestamp;
guint32 forwarder;
guint32 name_rva;
guint32 import_address_table_rva;
} MonoIDT;
typedef struct {
guint32 name_rva;
guint32 flags;
} MonoILT;
#ifndef DISABLE_REFLECTION_EMIT
/*
* mono_image_insert_string:
* @module: module builder object
* @str: a string
*
* Insert @str into the user string stream of @module.
*/
guint32
mono_image_insert_string (MonoReflectionModuleBuilder *module, MonoString *str)
{
MonoDynamicImage *assembly;
guint32 idx;
char buf [16];
char *b = buf;
MONO_ARCH_SAVE_REGS;
if (!module->dynamic_image)
mono_image_module_basic_init (module);
assembly = module->dynamic_image;
if (assembly->save) {
mono_metadata_encode_value (1 | (str->length * 2), b, &b);
idx = mono_image_add_stream_data (&assembly->us, buf, b-buf);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
{
char *swapped = g_malloc (2 * mono_string_length (str));
const char *p = (const char*)mono_string_chars (str);
swap_with_size (swapped, p, 2, mono_string_length (str));
mono_image_add_stream_data (&assembly->us, swapped, str->length * 2);
g_free (swapped);
}
#else
mono_image_add_stream_data (&assembly->us, (const char*)mono_string_chars (str), str->length * 2);
#endif
mono_image_add_stream_data (&assembly->us, "", 1);
} else {
idx = assembly->us.index ++;
}
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (MONO_TOKEN_STRING | idx), str);
return MONO_TOKEN_STRING | idx;
}
guint32
mono_image_create_method_token (MonoDynamicImage *assembly, MonoObject *obj, MonoArray *opt_param_types)
{
MonoClass *klass;
guint32 token = 0;
MonoMethodSignature *sig;
klass = obj->vtable->klass;
if (strcmp (klass->name, "MonoMethod") == 0) {
MonoMethod *method = ((MonoReflectionMethod *)obj)->method;
MonoMethodSignature *old;
guint32 sig_token, parent;
int nargs, i;
g_assert (opt_param_types && (mono_method_signature (method)->sentinelpos >= 0));
nargs = mono_array_length (opt_param_types);
old = mono_method_signature (method);
sig = mono_metadata_signature_alloc ( &assembly->image, old->param_count + nargs);
sig->hasthis = old->hasthis;
sig->explicit_this = old->explicit_this;
sig->call_convention = old->call_convention;
sig->generic_param_count = old->generic_param_count;
sig->param_count = old->param_count + nargs;
sig->sentinelpos = old->param_count;
sig->ret = old->ret;
for (i = 0; i < old->param_count; i++)
sig->params [i] = old->params [i];
for (i = 0; i < nargs; i++) {
MonoReflectionType *rt = mono_array_get (opt_param_types, MonoReflectionType *, i);
sig->params [old->param_count + i] = mono_reflection_type_get_handle (rt);
}
parent = mono_image_typedef_or_ref (assembly, &method->klass->byval_arg);
g_assert ((parent & MONO_TYPEDEFORREF_MASK) == MONO_MEMBERREF_PARENT_TYPEREF);
parent >>= MONO_TYPEDEFORREF_BITS;
parent <<= MONO_MEMBERREF_PARENT_BITS;
parent |= MONO_MEMBERREF_PARENT_TYPEREF;
sig_token = method_encode_signature (assembly, sig);
token = mono_image_get_varargs_method_token (assembly, parent, method->name, sig_token);
} else if (strcmp (klass->name, "MethodBuilder") == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)obj;
ReflectionMethodBuilder rmb;
guint32 parent, sig_token;
int nopt_args, nparams, ngparams, i;
char *name;
reflection_methodbuilder_from_method_builder (&rmb, mb);
rmb.opt_types = opt_param_types;
nopt_args = mono_array_length (opt_param_types);
nparams = rmb.parameters ? mono_array_length (rmb.parameters): 0;
ngparams = rmb.generic_params ? mono_array_length (rmb.generic_params): 0;
sig = mono_metadata_signature_alloc (&assembly->image, nparams + nopt_args);
sig->hasthis = !(rmb.attrs & METHOD_ATTRIBUTE_STATIC);
sig->explicit_this = (rmb.call_conv & 0x40) == 0x40;
sig->call_convention = rmb.call_conv;
sig->generic_param_count = ngparams;
sig->param_count = nparams + nopt_args;
sig->sentinelpos = nparams;
sig->ret = mono_reflection_type_get_handle (rmb.rtype);
for (i = 0; i < nparams; i++) {
MonoReflectionType *rt = mono_array_get (rmb.parameters, MonoReflectionType *, i);
sig->params [i] = mono_reflection_type_get_handle (rt);
}
for (i = 0; i < nopt_args; i++) {
MonoReflectionType *rt = mono_array_get (opt_param_types, MonoReflectionType *, i);
sig->params [nparams + i] = mono_reflection_type_get_handle (rt);
}
sig_token = method_builder_encode_signature (assembly, &rmb);
parent = mono_image_create_token (assembly, obj, TRUE, TRUE);
g_assert (mono_metadata_token_table (parent) == MONO_TABLE_METHOD);
parent = mono_metadata_token_index (parent) << MONO_MEMBERREF_PARENT_BITS;
parent |= MONO_MEMBERREF_PARENT_METHODDEF;
name = mono_string_to_utf8 (rmb.name);
token = mono_image_get_varargs_method_token (
assembly, parent, name, sig_token);
g_free (name);
} else {
g_error ("requested method token for %s\n", klass->name);
}
g_hash_table_insert (assembly->vararg_aux_hash, GUINT_TO_POINTER (token), sig);
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), obj);
return token;
}
/*
* mono_image_create_token:
* @assembly: a dynamic assembly
* @obj:
* @register_token: Whenever to register the token in the assembly->tokens hash.
*
* Get a token to insert in the IL code stream for the given MemberInfo.
* The metadata emission routines need to pass FALSE as REGISTER_TOKEN, since by that time,
* the table_idx-es were recomputed, so registering the token would overwrite an existing
* entry.
*/
guint32
mono_image_create_token (MonoDynamicImage *assembly, MonoObject *obj,
gboolean create_open_instance, gboolean register_token)
{
MonoClass *klass;
guint32 token = 0;
klass = obj->vtable->klass;
/* Check for user defined reflection objects */
/* TypeDelegator is the only corlib type which doesn't look like a MonoReflectionType */
if (klass->image != mono_defaults.corlib || (strcmp (klass->name, "TypeDelegator") == 0))
mono_raise_exception (mono_get_exception_not_supported ("User defined subclasses of System.Type are not yet supported")); \
if (strcmp (klass->name, "MethodBuilder") == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)obj;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)mb->type;
if (tb->module->dynamic_image == assembly && !tb->generic_params && !mb->generic_params)
token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
else
token = mono_image_get_methodbuilder_token (assembly, mb, create_open_instance);
/*g_print ("got token 0x%08x for %s\n", token, mono_string_to_utf8 (mb->name));*/
} else if (strcmp (klass->name, "ConstructorBuilder") == 0) {
MonoReflectionCtorBuilder *mb = (MonoReflectionCtorBuilder *)obj;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)mb->type;
if (tb->module->dynamic_image == assembly && !tb->generic_params)
token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
else
token = mono_image_get_ctorbuilder_token (assembly, mb);
/*g_print ("got token 0x%08x for %s\n", token, mono_string_to_utf8 (mb->name));*/
} else if (strcmp (klass->name, "FieldBuilder") == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)obj;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)fb->typeb;
if (tb->generic_params) {
token = mono_image_get_generic_field_token (assembly, fb);
} else {
if ((tb->module->dynamic_image == assembly)) {
token = fb->table_idx | MONO_TOKEN_FIELD_DEF;
} else {
token = mono_image_get_fieldref_token (assembly, (MonoObject*)fb, fb->handle);
}
}
} else if (strcmp (klass->name, "TypeBuilder") == 0) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)obj;
if (create_open_instance && tb->generic_params) {
MonoType *type;
init_type_builder_generics (obj);
type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
token = mono_image_typedef_or_ref_full (assembly, type, TRUE);
token = mono_metadata_token_from_dor (token);
} else {
token = tb->table_idx | MONO_TOKEN_TYPE_DEF;
}
} else if (strcmp (klass->name, "MonoType") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
MonoClass *mc = mono_class_from_mono_type (type);
if (!mono_class_init (mc))
mono_raise_exception (mono_class_get_exception_for_failure (mc));
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref_full (assembly, type, mc->generic_container == NULL || create_open_instance));
} else if (strcmp (klass->name, "GenericTypeParameterBuilder") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref (assembly, type));
} else if (strcmp (klass->name, "MonoGenericClass") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref (assembly, type));
} else if (strcmp (klass->name, "MonoCMethod") == 0 ||
strcmp (klass->name, "MonoMethod") == 0 ||
strcmp (klass->name, "MonoGenericMethod") == 0 ||
strcmp (klass->name, "MonoGenericCMethod") == 0) {
MonoReflectionMethod *m = (MonoReflectionMethod *)obj;
if (m->method->is_inflated) {
if (create_open_instance)
token = mono_image_get_methodspec_token (assembly, m->method);
else
token = mono_image_get_inflated_method_token (assembly, m->method);
} else if ((m->method->klass->image == &assembly->image) &&
!m->method->klass->generic_class) {
static guint32 method_table_idx = 0xffffff;
if (m->method->klass->wastypebuilder) {
/* we use the same token as the one that was assigned
* to the Methodbuilder.
* FIXME: do the equivalent for Fields.
*/
token = m->method->token;
} else {
/*
* Each token should have a unique index, but the indexes are
* assigned by managed code, so we don't know about them. An
* easy solution is to count backwards...
*/
method_table_idx --;
token = MONO_TOKEN_METHOD_DEF | method_table_idx;
}
} else {
token = mono_image_get_methodref_token (assembly, m->method, create_open_instance);
}
/*g_print ("got token 0x%08x for %s\n", token, m->method->name);*/
} else if (strcmp (klass->name, "MonoField") == 0) {
MonoReflectionField *f = (MonoReflectionField *)obj;
if ((f->field->parent->image == &assembly->image) && !is_field_on_inst (f->field)) {
static guint32 field_table_idx = 0xffffff;
field_table_idx --;
token = MONO_TOKEN_FIELD_DEF | field_table_idx;
} else {
token = mono_image_get_fieldref_token (assembly, (MonoObject*)f, f->field);
}
/*g_print ("got token 0x%08x for %s\n", token, f->field->name);*/
} else if (strcmp (klass->name, "MonoArrayMethod") == 0) {
MonoReflectionArrayMethod *m = (MonoReflectionArrayMethod *)obj;
token = mono_image_get_array_token (assembly, m);
} else if (strcmp (klass->name, "SignatureHelper") == 0) {
MonoReflectionSigHelper *s = (MonoReflectionSigHelper*)obj;
token = MONO_TOKEN_SIGNATURE | mono_image_get_sighelper_token (assembly, s);
} else if (strcmp (klass->name, "EnumBuilder") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref (assembly, type));
} else if (strcmp (klass->name, "FieldOnTypeBuilderInst") == 0) {
MonoReflectionFieldOnTypeBuilderInst *f = (MonoReflectionFieldOnTypeBuilderInst*)obj;
token = mono_image_get_field_on_inst_token (assembly, f);
} else if (strcmp (klass->name, "ConstructorOnTypeBuilderInst") == 0) {
MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)obj;
token = mono_image_get_ctor_on_inst_token (assembly, c, create_open_instance);
} else if (strcmp (klass->name, "MethodOnTypeBuilderInst") == 0) {
MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)obj;
token = mono_image_get_method_on_inst_token (assembly, m, create_open_instance);
} else if (is_sre_array (klass) || is_sre_byref (klass) || is_sre_pointer (klass)) {
MonoReflectionType *type = (MonoReflectionType *)obj;
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (type)));
} else {
g_error ("requested token for %s\n", klass->name);
}
if (register_token)
mono_image_register_token (assembly, token, obj);
return token;
}
/*
* mono_image_register_token:
*
* Register the TOKEN->OBJ mapping in the mapping table in ASSEMBLY. This is required for
* the Module.ResolveXXXToken () methods to work.
*/
void
mono_image_register_token (MonoDynamicImage *assembly, guint32 token, MonoObject *obj)
{
MonoObject *prev = mono_g_hash_table_lookup (assembly->tokens, GUINT_TO_POINTER (token));
if (prev) {
/* There could be multiple MethodInfo objects with the same token */
//g_assert (prev == obj);
} else {
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), obj);
}
}
static MonoDynamicImage*
create_dynamic_mono_image (MonoDynamicAssembly *assembly, char *assembly_name, char *module_name)
{
static const guchar entrycode [16] = {0xff, 0x25, 0};
MonoDynamicImage *image;
int i;
const char *version;
if (!strcmp (mono_get_runtime_info ()->framework_version, "2.1"))
version = "v2.0.50727"; /* HACK: SL 2 enforces the .net 2 metadata version */
else
version = mono_get_runtime_info ()->runtime_version;
#if HAVE_BOEHM_GC
/* The MonoGHashTable's need GC tracking */
image = GC_MALLOC (sizeof (MonoDynamicImage));
#else
image = g_new0 (MonoDynamicImage, 1);
#endif
mono_profiler_module_event (&image->image, MONO_PROFILE_START_LOAD);
/*g_print ("created image %p\n", image);*/
/* keep in sync with image.c */
image->image.name = assembly_name;
image->image.assembly_name = image->image.name; /* they may be different */
image->image.module_name = module_name;
image->image.version = g_strdup (version);
image->image.md_version_major = 1;
image->image.md_version_minor = 1;
image->image.dynamic = TRUE;
image->image.references = g_new0 (MonoAssembly*, 1);
image->image.references [0] = NULL;
mono_image_init (&image->image);
image->token_fixups = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC);
image->method_to_table_idx = g_hash_table_new (NULL, NULL);
image->field_to_table_idx = g_hash_table_new (NULL, NULL);
image->method_aux_hash = g_hash_table_new (NULL, NULL);
image->vararg_aux_hash = g_hash_table_new (NULL, NULL);
image->handleref = g_hash_table_new (NULL, NULL);
image->handleref_managed = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC);
image->tokens = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
image->generic_def_objects = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
image->methodspec = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC);
image->typespec = g_hash_table_new ((GHashFunc)mono_metadata_type_hash, (GCompareFunc)mono_metadata_type_equal);
image->typeref = g_hash_table_new ((GHashFunc)mono_metadata_type_hash, (GCompareFunc)mono_metadata_type_equal);
image->blob_cache = g_hash_table_new ((GHashFunc)mono_blob_entry_hash, (GCompareFunc)mono_blob_entry_equal);
image->gen_params = g_ptr_array_new ();
/*g_print ("string heap create for image %p (%s)\n", image, module_name);*/
string_heap_init (&image->sheap);
mono_image_add_stream_data (&image->us, "", 1);
add_to_blob_cached (image, (char*) "", 1, NULL, 0);
/* import tables... */
mono_image_add_stream_data (&image->code, (char*)entrycode, sizeof (entrycode));
image->iat_offset = mono_image_add_stream_zero (&image->code, 8); /* two IAT entries */
image->idt_offset = mono_image_add_stream_zero (&image->code, 2 * sizeof (MonoIDT)); /* two IDT entries */
image->imp_names_offset = mono_image_add_stream_zero (&image->code, 2); /* flags for name entry */
mono_image_add_stream_data (&image->code, "_CorExeMain", 12);
mono_image_add_stream_data (&image->code, "mscoree.dll", 12);
image->ilt_offset = mono_image_add_stream_zero (&image->code, 8); /* two ILT entries */
stream_data_align (&image->code);
image->cli_header_offset = mono_image_add_stream_zero (&image->code, sizeof (MonoCLIHeader));
for (i=0; i < MONO_TABLE_NUM; ++i) {
image->tables [i].next_idx = 1;
image->tables [i].columns = table_sizes [i];
}
image->image.assembly = (MonoAssembly*)assembly;
image->run = assembly->run;
image->save = assembly->save;
image->pe_kind = 0x1; /* ILOnly */
image->machine = 0x14c; /* I386 */
mono_profiler_module_loaded (&image->image, MONO_PROFILE_OK);
return image;
}
#endif
static void
free_blob_cache_entry (gpointer key, gpointer val, gpointer user_data)
{
g_free (key);
}
void
mono_dynamic_image_free (MonoDynamicImage *image)
{
MonoDynamicImage *di = image;
GList *list;
int i;
if (di->methodspec)
mono_g_hash_table_destroy (di->methodspec);
if (di->typespec)
g_hash_table_destroy (di->typespec);
if (di->typeref)
g_hash_table_destroy (di->typeref);
if (di->handleref)
g_hash_table_destroy (di->handleref);
if (di->handleref_managed)
mono_g_hash_table_destroy (di->handleref_managed);
if (di->tokens)
mono_g_hash_table_destroy (di->tokens);
if (di->generic_def_objects)
mono_g_hash_table_destroy (di->generic_def_objects);
if (di->blob_cache) {
g_hash_table_foreach (di->blob_cache, free_blob_cache_entry, NULL);
g_hash_table_destroy (di->blob_cache);
}
if (di->standalonesig_cache)
g_hash_table_destroy (di->standalonesig_cache);
for (list = di->array_methods; list; list = list->next) {
ArrayMethod *am = (ArrayMethod *)list->data;
g_free (am->sig);
g_free (am->name);
g_free (am);
}
g_list_free (di->array_methods);
if (di->gen_params) {
for (i = 0; i < di->gen_params->len; i++) {
GenericParamTableEntry *entry = g_ptr_array_index (di->gen_params, i);
if (entry->gparam->type.type) {
MonoGenericParam *param = entry->gparam->type.type->data.generic_param;
g_free ((char*)mono_generic_param_info (param)->name);
g_free (param);
}
mono_gc_deregister_root ((char*) &entry->gparam);
g_free (entry);
}
g_ptr_array_free (di->gen_params, TRUE);
}
if (di->token_fixups)
mono_g_hash_table_destroy (di->token_fixups);
if (di->method_to_table_idx)
g_hash_table_destroy (di->method_to_table_idx);
if (di->field_to_table_idx)
g_hash_table_destroy (di->field_to_table_idx);
if (di->method_aux_hash)
g_hash_table_destroy (di->method_aux_hash);
if (di->vararg_aux_hash)
g_hash_table_destroy (di->vararg_aux_hash);
g_free (di->strong_name);
g_free (di->win32_res);
if (di->public_key)
g_free (di->public_key);
/*g_print ("string heap destroy for image %p\n", di);*/
mono_dynamic_stream_reset (&di->sheap);
mono_dynamic_stream_reset (&di->code);
mono_dynamic_stream_reset (&di->resources);
mono_dynamic_stream_reset (&di->us);
mono_dynamic_stream_reset (&di->blob);
mono_dynamic_stream_reset (&di->tstream);
mono_dynamic_stream_reset (&di->guid);
for (i = 0; i < MONO_TABLE_NUM; ++i) {
g_free (di->tables [i].values);
}
}
#ifndef DISABLE_REFLECTION_EMIT
/*
* mono_image_basic_init:
* @assembly: an assembly builder object
*
* Create the MonoImage that represents the assembly builder and setup some
* of the helper hash table and the basic metadata streams.
*/
void
mono_image_basic_init (MonoReflectionAssemblyBuilder *assemblyb)
{
MonoDynamicAssembly *assembly;
MonoDynamicImage *image;
MonoDomain *domain = mono_object_domain (assemblyb);
MONO_ARCH_SAVE_REGS;
if (assemblyb->dynamic_assembly)
return;
#if HAVE_BOEHM_GC
/* assembly->assembly.image might be GC allocated */
assembly = assemblyb->dynamic_assembly = GC_MALLOC (sizeof (MonoDynamicAssembly));
#else
assembly = assemblyb->dynamic_assembly = g_new0 (MonoDynamicAssembly, 1);
#endif
mono_profiler_assembly_event (&assembly->assembly, MONO_PROFILE_START_LOAD);
assembly->assembly.ref_count = 1;
assembly->assembly.dynamic = TRUE;
assembly->assembly.corlib_internal = assemblyb->corlib_internal;
assemblyb->assembly.assembly = (MonoAssembly*)assembly;
assembly->assembly.basedir = mono_string_to_utf8 (assemblyb->dir);
if (assemblyb->culture)
assembly->assembly.aname.culture = mono_string_to_utf8 (assemblyb->culture);
else
assembly->assembly.aname.culture = g_strdup ("");
if (assemblyb->version) {
char *vstr = mono_string_to_utf8 (assemblyb->version);
char **version = g_strsplit (vstr, ".", 4);
char **parts = version;
assembly->assembly.aname.major = atoi (*parts++);
assembly->assembly.aname.minor = atoi (*parts++);
assembly->assembly.aname.build = *parts != NULL ? atoi (*parts++) : 0;
assembly->assembly.aname.revision = *parts != NULL ? atoi (*parts) : 0;
g_strfreev (version);
g_free (vstr);
} else {
assembly->assembly.aname.major = 0;
assembly->assembly.aname.minor = 0;
assembly->assembly.aname.build = 0;
assembly->assembly.aname.revision = 0;
}
assembly->run = assemblyb->access != 2;
assembly->save = assemblyb->access != 1;
assembly->domain = domain;
image = create_dynamic_mono_image (assembly, mono_string_to_utf8 (assemblyb->name), g_strdup ("RefEmit_YouForgotToDefineAModule"));
image->initial_image = TRUE;
assembly->assembly.aname.name = image->image.name;
assembly->assembly.image = &image->image;
if (assemblyb->pktoken && assemblyb->pktoken->max_length) {
/* -1 to correct for the trailing NULL byte */
if (assemblyb->pktoken->max_length != MONO_PUBLIC_KEY_TOKEN_LENGTH - 1) {
g_error ("Public key token length invalid for assembly %s: %i", assembly->assembly.aname.name, assemblyb->pktoken->max_length);
}
memcpy (&assembly->assembly.aname.public_key_token, mono_array_addr (assemblyb->pktoken, guint8, 0), assemblyb->pktoken->max_length);
}
mono_domain_assemblies_lock (domain);
domain->domain_assemblies = g_slist_prepend (domain->domain_assemblies, assembly);
mono_domain_assemblies_unlock (domain);
register_assembly (mono_object_domain (assemblyb), &assemblyb->assembly, &assembly->assembly);
mono_profiler_assembly_loaded (&assembly->assembly, MONO_PROFILE_OK);
mono_assembly_invoke_load_hook ((MonoAssembly*)assembly);
}
#endif /* !DISABLE_REFLECTION_EMIT */
#ifndef DISABLE_REFLECTION_EMIT_SAVE
static int
calc_section_size (MonoDynamicImage *assembly)
{
int nsections = 0;
/* alignment constraints */
mono_image_add_stream_zero (&assembly->code, 4 - (assembly->code.index % 4));
g_assert ((assembly->code.index % 4) == 0);
assembly->meta_size += 3;
assembly->meta_size &= ~3;
mono_image_add_stream_zero (&assembly->resources, 4 - (assembly->resources.index % 4));
g_assert ((assembly->resources.index % 4) == 0);
assembly->sections [MONO_SECTION_TEXT].size = assembly->meta_size + assembly->code.index + assembly->resources.index + assembly->strong_name_size;
assembly->sections [MONO_SECTION_TEXT].attrs = SECT_FLAGS_HAS_CODE | SECT_FLAGS_MEM_EXECUTE | SECT_FLAGS_MEM_READ;
nsections++;
if (assembly->win32_res) {
guint32 res_size = (assembly->win32_res_size + 3) & ~3;
assembly->sections [MONO_SECTION_RSRC].size = res_size;
assembly->sections [MONO_SECTION_RSRC].attrs = SECT_FLAGS_HAS_INITIALIZED_DATA | SECT_FLAGS_MEM_READ;
nsections++;
}
assembly->sections [MONO_SECTION_RELOC].size = 12;
assembly->sections [MONO_SECTION_RELOC].attrs = SECT_FLAGS_MEM_READ | SECT_FLAGS_MEM_DISCARDABLE | SECT_FLAGS_HAS_INITIALIZED_DATA;
nsections++;
return nsections;
}
typedef struct {
guint32 id;
guint32 offset;
GSList *children;
MonoReflectionWin32Resource *win32_res; /* Only for leaf nodes */
} ResTreeNode;
static int
resource_tree_compare_by_id (gconstpointer a, gconstpointer b)
{
ResTreeNode *t1 = (ResTreeNode*)a;
ResTreeNode *t2 = (ResTreeNode*)b;
return t1->id - t2->id;
}
/*
* resource_tree_create:
*
* Organize the resources into a resource tree.
*/
static ResTreeNode *
resource_tree_create (MonoArray *win32_resources)
{
ResTreeNode *tree, *res_node, *type_node, *lang_node;
GSList *l;
int i;
tree = g_new0 (ResTreeNode, 1);
for (i = 0; i < mono_array_length (win32_resources); ++i) {
MonoReflectionWin32Resource *win32_res =
(MonoReflectionWin32Resource*)mono_array_addr (win32_resources, MonoReflectionWin32Resource, i);
/* Create node */
/* FIXME: BUG: this stores managed references in unmanaged memory */
lang_node = g_new0 (ResTreeNode, 1);
lang_node->id = win32_res->lang_id;
lang_node->win32_res = win32_res;
/* Create type node if neccesary */
type_node = NULL;
for (l = tree->children; l; l = l->next)
if (((ResTreeNode*)(l->data))->id == win32_res->res_type) {
type_node = (ResTreeNode*)l->data;
break;
}
if (!type_node) {
type_node = g_new0 (ResTreeNode, 1);
type_node->id = win32_res->res_type;
/*
* The resource types have to be sorted otherwise
* Windows Explorer can't display the version information.
*/
tree->children = g_slist_insert_sorted (tree->children,
type_node, resource_tree_compare_by_id);
}
/* Create res node if neccesary */
res_node = NULL;
for (l = type_node->children; l; l = l->next)
if (((ResTreeNode*)(l->data))->id == win32_res->res_id) {
res_node = (ResTreeNode*)l->data;
break;
}
if (!res_node) {
res_node = g_new0 (ResTreeNode, 1);
res_node->id = win32_res->res_id;
type_node->children = g_slist_append (type_node->children, res_node);
}
res_node->children = g_slist_append (res_node->children, lang_node);
}
return tree;
}
/*
* resource_tree_encode:
*
* Encode the resource tree into the format used in the PE file.
*/
static void
resource_tree_encode (ResTreeNode *node, char *begin, char *p, char **endbuf)
{
char *entries;
MonoPEResourceDir dir;
MonoPEResourceDirEntry dir_entry;
MonoPEResourceDataEntry data_entry;
GSList *l;
guint32 res_id_entries;
/*
* For the format of the resource directory, see the article
* "An In-Depth Look into the Win32 Portable Executable File Format" by
* Matt Pietrek
*/
memset (&dir, 0, sizeof (dir));
memset (&dir_entry, 0, sizeof (dir_entry));
memset (&data_entry, 0, sizeof (data_entry));
g_assert (sizeof (dir) == 16);
g_assert (sizeof (dir_entry) == 8);
g_assert (sizeof (data_entry) == 16);
node->offset = p - begin;
/* IMAGE_RESOURCE_DIRECTORY */
res_id_entries = g_slist_length (node->children);
dir.res_id_entries = GUINT16_TO_LE (res_id_entries);
memcpy (p, &dir, sizeof (dir));
p += sizeof (dir);
/* Reserve space for entries */
entries = p;
p += sizeof (dir_entry) * res_id_entries;
/* Write children */
for (l = node->children; l; l = l->next) {
ResTreeNode *child = (ResTreeNode*)l->data;
if (child->win32_res) {
guint32 size;
child->offset = p - begin;
/* IMAGE_RESOURCE_DATA_ENTRY */
data_entry.rde_data_offset = GUINT32_TO_LE (p - begin + sizeof (data_entry));
size = mono_array_length (child->win32_res->res_data);
data_entry.rde_size = GUINT32_TO_LE (size);
memcpy (p, &data_entry, sizeof (data_entry));
p += sizeof (data_entry);
memcpy (p, mono_array_addr (child->win32_res->res_data, char, 0), size);
p += size;
} else {
resource_tree_encode (child, begin, p, &p);
}
}
/* IMAGE_RESOURCE_ENTRY */
for (l = node->children; l; l = l->next) {
ResTreeNode *child = (ResTreeNode*)l->data;
MONO_PE_RES_DIR_ENTRY_SET_NAME (dir_entry, FALSE, child->id);
MONO_PE_RES_DIR_ENTRY_SET_DIR (dir_entry, !child->win32_res, child->offset);
memcpy (entries, &dir_entry, sizeof (dir_entry));
entries += sizeof (dir_entry);
}
*endbuf = p;
}
static void
resource_tree_free (ResTreeNode * node)
{
GSList * list;
for (list = node->children; list; list = list->next)
resource_tree_free ((ResTreeNode*)list->data);
g_slist_free(node->children);
g_free (node);
}
static void
assembly_add_win32_resources (MonoDynamicImage *assembly, MonoReflectionAssemblyBuilder *assemblyb)
{
char *buf;
char *p;
guint32 size, i;
MonoReflectionWin32Resource *win32_res;
ResTreeNode *tree;
if (!assemblyb->win32_resources)
return;
/*
* Resources are stored in a three level tree inside the PE file.
* - level one contains a node for each type of resource
* - level two contains a node for each resource
* - level three contains a node for each instance of a resource for a
* specific language.
*/
tree = resource_tree_create (assemblyb->win32_resources);
/* Estimate the size of the encoded tree */
size = 0;
for (i = 0; i < mono_array_length (assemblyb->win32_resources); ++i) {
win32_res = (MonoReflectionWin32Resource*)mono_array_addr (assemblyb->win32_resources, MonoReflectionWin32Resource, i);
size += mono_array_length (win32_res->res_data);
}
/* Directory structure */
size += mono_array_length (assemblyb->win32_resources) * 256;
p = buf = g_malloc (size);
resource_tree_encode (tree, p, p, &p);
g_assert (p - buf <= size);
assembly->win32_res = g_malloc (p - buf);
assembly->win32_res_size = p - buf;
memcpy (assembly->win32_res, buf, p - buf);
g_free (buf);
resource_tree_free (tree);
}
static void
fixup_resource_directory (char *res_section, char *p, guint32 rva)
{
MonoPEResourceDir *dir = (MonoPEResourceDir*)p;
int i;
p += sizeof (MonoPEResourceDir);
for (i = 0; i < GUINT16_FROM_LE (dir->res_named_entries) + GUINT16_FROM_LE (dir->res_id_entries); ++i) {
MonoPEResourceDirEntry *dir_entry = (MonoPEResourceDirEntry*)p;
char *child = res_section + MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*dir_entry);
if (MONO_PE_RES_DIR_ENTRY_IS_DIR (*dir_entry)) {
fixup_resource_directory (res_section, child, rva);
} else {
MonoPEResourceDataEntry *data_entry = (MonoPEResourceDataEntry*)child;
data_entry->rde_data_offset = GUINT32_TO_LE (GUINT32_FROM_LE (data_entry->rde_data_offset) + rva);
}
p += sizeof (MonoPEResourceDirEntry);
}
}
static void
checked_write_file (HANDLE f, gconstpointer buffer, guint32 numbytes)
{
guint32 dummy;
if (!WriteFile (f, buffer, numbytes, &dummy, NULL))
g_error ("WriteFile returned %d\n", GetLastError ());
}
/*
* mono_image_create_pefile:
* @mb: a module builder object
*
* This function creates the PE-COFF header, the image sections, the CLI header * etc. all the data is written in
* assembly->pefile where it can be easily retrieved later in chunks.
*/
void
mono_image_create_pefile (MonoReflectionModuleBuilder *mb, HANDLE file)
{
MonoMSDOSHeader *msdos;
MonoDotNetHeader *header;
MonoSectionTable *section;
MonoCLIHeader *cli_header;
guint32 size, image_size, virtual_base, text_offset;
guint32 header_start, section_start, file_offset, virtual_offset;
MonoDynamicImage *assembly;
MonoReflectionAssemblyBuilder *assemblyb;
MonoDynamicStream pefile_stream = {0};
MonoDynamicStream *pefile = &pefile_stream;
int i, nsections;
guint32 *rva, value;
guchar *p;
static const unsigned char msheader[] = {
0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68,
0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f,
0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20,
0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
assemblyb = mb->assemblyb;
mono_image_basic_init (assemblyb);
assembly = mb->dynamic_image;
assembly->pe_kind = assemblyb->pe_kind;
assembly->machine = assemblyb->machine;
((MonoDynamicImage*)assemblyb->dynamic_assembly->assembly.image)->pe_kind = assemblyb->pe_kind;
((MonoDynamicImage*)assemblyb->dynamic_assembly->assembly.image)->machine = assemblyb->machine;
mono_image_build_metadata (mb);
if (mb->is_main && assemblyb->resources) {
int len = mono_array_length (assemblyb->resources);
for (i = 0; i < len; ++i)
assembly_add_resource (mb, assembly, (MonoReflectionResource*)mono_array_addr (assemblyb->resources, MonoReflectionResource, i));
}
if (mb->resources) {
int len = mono_array_length (mb->resources);
for (i = 0; i < len; ++i)
assembly_add_resource (mb, assembly, (MonoReflectionResource*)mono_array_addr (mb->resources, MonoReflectionResource, i));
}
build_compressed_metadata (assembly);
if (mb->is_main)
assembly_add_win32_resources (assembly, assemblyb);
nsections = calc_section_size (assembly);
/* The DOS header and stub */
g_assert (sizeof (MonoMSDOSHeader) == sizeof (msheader));
mono_image_add_stream_data (pefile, (char*)msheader, sizeof (msheader));
/* the dotnet header */
header_start = mono_image_add_stream_zero (pefile, sizeof (MonoDotNetHeader));
/* the section tables */
section_start = mono_image_add_stream_zero (pefile, sizeof (MonoSectionTable) * nsections);
file_offset = section_start + sizeof (MonoSectionTable) * nsections;
virtual_offset = VIRT_ALIGN;
image_size = 0;
for (i = 0; i < MONO_SECTION_MAX; ++i) {
if (!assembly->sections [i].size)
continue;
/* align offsets */
file_offset += FILE_ALIGN - 1;
file_offset &= ~(FILE_ALIGN - 1);
virtual_offset += VIRT_ALIGN - 1;
virtual_offset &= ~(VIRT_ALIGN - 1);
assembly->sections [i].offset = file_offset;
assembly->sections [i].rva = virtual_offset;
file_offset += assembly->sections [i].size;
virtual_offset += assembly->sections [i].size;
image_size += (assembly->sections [i].size + VIRT_ALIGN - 1) & ~(VIRT_ALIGN - 1);
}
file_offset += FILE_ALIGN - 1;
file_offset &= ~(FILE_ALIGN - 1);
image_size += section_start + sizeof (MonoSectionTable) * nsections;
/* back-patch info */
msdos = (MonoMSDOSHeader*)pefile->data;
msdos->pe_offset = GUINT32_FROM_LE (sizeof (MonoMSDOSHeader));
header = (MonoDotNetHeader*)(pefile->data + header_start);
header->pesig [0] = 'P';
header->pesig [1] = 'E';
header->coff.coff_machine = GUINT16_FROM_LE (assemblyb->machine);
header->coff.coff_sections = GUINT16_FROM_LE (nsections);
header->coff.coff_time = GUINT32_FROM_LE (time (NULL));
header->coff.coff_opt_header_size = GUINT16_FROM_LE (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4);
if (assemblyb->pekind == 1) {
/* it's a dll */
header->coff.coff_attributes = GUINT16_FROM_LE (0x210e);
} else {
/* it's an exe */
header->coff.coff_attributes = GUINT16_FROM_LE (0x010e);
}
virtual_base = 0x400000; /* FIXME: 0x10000000 if a DLL */
header->pe.pe_magic = GUINT16_FROM_LE (0x10B);
header->pe.pe_major = 6;
header->pe.pe_minor = 0;
size = assembly->sections [MONO_SECTION_TEXT].size;
size += FILE_ALIGN - 1;
size &= ~(FILE_ALIGN - 1);
header->pe.pe_code_size = GUINT32_FROM_LE(size);
size = assembly->sections [MONO_SECTION_RSRC].size;
size += FILE_ALIGN - 1;
size &= ~(FILE_ALIGN - 1);
header->pe.pe_data_size = GUINT32_FROM_LE(size);
g_assert (START_TEXT_RVA == assembly->sections [MONO_SECTION_TEXT].rva);
header->pe.pe_rva_code_base = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_TEXT].rva);
header->pe.pe_rva_data_base = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RSRC].rva);
/* pe_rva_entry_point always at the beginning of the text section */
header->pe.pe_rva_entry_point = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_TEXT].rva);
header->nt.pe_image_base = GUINT32_FROM_LE (virtual_base);
header->nt.pe_section_align = GUINT32_FROM_LE (VIRT_ALIGN);
header->nt.pe_file_alignment = GUINT32_FROM_LE (FILE_ALIGN);
header->nt.pe_os_major = GUINT16_FROM_LE (4);
header->nt.pe_os_minor = GUINT16_FROM_LE (0);
header->nt.pe_subsys_major = GUINT16_FROM_LE (4);
size = section_start;
size += FILE_ALIGN - 1;
size &= ~(FILE_ALIGN - 1);
header->nt.pe_header_size = GUINT32_FROM_LE (size);
size = image_size;
size += VIRT_ALIGN - 1;
size &= ~(VIRT_ALIGN - 1);
header->nt.pe_image_size = GUINT32_FROM_LE (size);
/*
// Translate the PEFileKind value to the value expected by the Windows loader
*/
{
short kind;
/*
// PEFileKinds.Dll == 1
// PEFileKinds.ConsoleApplication == 2
// PEFileKinds.WindowApplication == 3
//
// need to get:
// IMAGE_SUBSYSTEM_WINDOWS_GUI 2 // Image runs in the Windows GUI subsystem.
// IMAGE_SUBSYSTEM_WINDOWS_CUI 3 // Image runs in the Windows character subsystem.
*/
if (assemblyb->pekind == 3)
kind = 2;
else
kind = 3;
header->nt.pe_subsys_required = GUINT16_FROM_LE (kind);
}
header->nt.pe_stack_reserve = GUINT32_FROM_LE (0x00100000);
header->nt.pe_stack_commit = GUINT32_FROM_LE (0x00001000);
header->nt.pe_heap_reserve = GUINT32_FROM_LE (0x00100000);
header->nt.pe_heap_commit = GUINT32_FROM_LE (0x00001000);
header->nt.pe_loader_flags = GUINT32_FROM_LE (0);
header->nt.pe_data_dir_count = GUINT32_FROM_LE (16);
/* fill data directory entries */
header->datadir.pe_resource_table.size = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RSRC].size);
header->datadir.pe_resource_table.rva = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RSRC].rva);
header->datadir.pe_reloc_table.size = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RELOC].size);
header->datadir.pe_reloc_table.rva = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RELOC].rva);
header->datadir.pe_cli_header.size = GUINT32_FROM_LE (72);
header->datadir.pe_cli_header.rva = GUINT32_FROM_LE (assembly->text_rva + assembly->cli_header_offset);
header->datadir.pe_iat.size = GUINT32_FROM_LE (8);
header->datadir.pe_iat.rva = GUINT32_FROM_LE (assembly->text_rva + assembly->iat_offset);
/* patch entrypoint name */
if (assemblyb->pekind == 1)
memcpy (assembly->code.data + assembly->imp_names_offset + 2, "_CorDllMain", 12);
else
memcpy (assembly->code.data + assembly->imp_names_offset + 2, "_CorExeMain", 12);
/* patch imported function RVA name */
rva = (guint32*)(assembly->code.data + assembly->iat_offset);
*rva = GUINT32_FROM_LE (assembly->text_rva + assembly->imp_names_offset);
/* the import table */
header->datadir.pe_import_table.size = GUINT32_FROM_LE (79); /* FIXME: magic number? */
header->datadir.pe_import_table.rva = GUINT32_FROM_LE (assembly->text_rva + assembly->idt_offset);
/* patch imported dll RVA name and other entries in the dir */
rva = (guint32*)(assembly->code.data + assembly->idt_offset + G_STRUCT_OFFSET (MonoIDT, name_rva));
*rva = GUINT32_FROM_LE (assembly->text_rva + assembly->imp_names_offset + 14); /* 14 is hint+strlen+1 of func name */
rva = (guint32*)(assembly->code.data + assembly->idt_offset + G_STRUCT_OFFSET (MonoIDT, import_address_table_rva));
*rva = GUINT32_FROM_LE (assembly->text_rva + assembly->iat_offset);
rva = (guint32*)(assembly->code.data + assembly->idt_offset + G_STRUCT_OFFSET (MonoIDT, import_lookup_table));
*rva = GUINT32_FROM_LE (assembly->text_rva + assembly->ilt_offset);
p = (guchar*)(assembly->code.data + assembly->ilt_offset);
value = (assembly->text_rva + assembly->imp_names_offset);
*p++ = (value) & 0xff;
*p++ = (value >> 8) & (0xff);
*p++ = (value >> 16) & (0xff);
*p++ = (value >> 24) & (0xff);
/* the CLI header info */
cli_header = (MonoCLIHeader*)(assembly->code.data + assembly->cli_header_offset);
cli_header->ch_size = GUINT32_FROM_LE (72);
cli_header->ch_runtime_major = GUINT16_FROM_LE (2);
cli_header->ch_runtime_minor = GUINT16_FROM_LE (5);
cli_header->ch_flags = GUINT32_FROM_LE (assemblyb->pe_kind);
if (assemblyb->entry_point) {
guint32 table_idx = 0;
if (!strcmp (assemblyb->entry_point->object.vtable->klass->name, "MethodBuilder")) {
MonoReflectionMethodBuilder *methodb = (MonoReflectionMethodBuilder*)assemblyb->entry_point;
table_idx = methodb->table_idx;
} else {
table_idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->method_to_table_idx, assemblyb->entry_point->method));
}
cli_header->ch_entry_point = GUINT32_FROM_LE (table_idx | MONO_TOKEN_METHOD_DEF);
} else {
cli_header->ch_entry_point = GUINT32_FROM_LE (0);
}
/* The embedded managed resources */
text_offset = assembly->text_rva + assembly->code.index;
cli_header->ch_resources.rva = GUINT32_FROM_LE (text_offset);
cli_header->ch_resources.size = GUINT32_FROM_LE (assembly->resources.index);
text_offset += assembly->resources.index;
cli_header->ch_metadata.rva = GUINT32_FROM_LE (text_offset);
cli_header->ch_metadata.size = GUINT32_FROM_LE (assembly->meta_size);
text_offset += assembly->meta_size;
if (assembly->strong_name_size) {
cli_header->ch_strong_name.rva = GUINT32_FROM_LE (text_offset);
cli_header->ch_strong_name.size = GUINT32_FROM_LE (assembly->strong_name_size);
text_offset += assembly->strong_name_size;
}
/* write the section tables and section content */
section = (MonoSectionTable*)(pefile->data + section_start);
for (i = 0; i < MONO_SECTION_MAX; ++i) {
static const char section_names [][7] = {
".text", ".rsrc", ".reloc"
};
if (!assembly->sections [i].size)
continue;
strcpy (section->st_name, section_names [i]);
/*g_print ("output section %s (%d), size: %d\n", section->st_name, i, assembly->sections [i].size);*/
section->st_virtual_address = GUINT32_FROM_LE (assembly->sections [i].rva);
section->st_virtual_size = GUINT32_FROM_LE (assembly->sections [i].size);
section->st_raw_data_size = GUINT32_FROM_LE (GUINT32_TO_LE (section->st_virtual_size) + (FILE_ALIGN - 1));
section->st_raw_data_size &= GUINT32_FROM_LE (~(FILE_ALIGN - 1));
section->st_raw_data_ptr = GUINT32_FROM_LE (assembly->sections [i].offset);
section->st_flags = GUINT32_FROM_LE (assembly->sections [i].attrs);
section ++;
}
checked_write_file (file, pefile->data, pefile->index);
mono_dynamic_stream_reset (pefile);
for (i = 0; i < MONO_SECTION_MAX; ++i) {
if (!assembly->sections [i].size)
continue;
if (SetFilePointer (file, assembly->sections [i].offset, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
g_error ("SetFilePointer returned %d\n", GetLastError ());
switch (i) {
case MONO_SECTION_TEXT:
/* patch entry point */
p = (guchar*)(assembly->code.data + 2);
value = (virtual_base + assembly->text_rva + assembly->iat_offset);
*p++ = (value) & 0xff;
*p++ = (value >> 8) & 0xff;
*p++ = (value >> 16) & 0xff;
*p++ = (value >> 24) & 0xff;
checked_write_file (file, assembly->code.data, assembly->code.index);
checked_write_file (file, assembly->resources.data, assembly->resources.index);
checked_write_file (file, assembly->image.raw_metadata, assembly->meta_size);
checked_write_file (file, assembly->strong_name, assembly->strong_name_size);
g_free (assembly->image.raw_metadata);
break;
case MONO_SECTION_RELOC: {
struct {
guint32 page_rva;
guint32 block_size;
guint16 type_and_offset;
guint16 term;
} reloc;
g_assert (sizeof (reloc) == 12);
reloc.page_rva = GUINT32_FROM_LE (assembly->text_rva);
reloc.block_size = GUINT32_FROM_LE (12);
/*
* the entrypoint is always at the start of the text section
* 3 is IMAGE_REL_BASED_HIGHLOW
* 2 is patch_size_rva - text_rva
*/
reloc.type_and_offset = GUINT16_FROM_LE ((3 << 12) + (2));
reloc.term = 0;
checked_write_file (file, &reloc, sizeof (reloc));
break;
}
case MONO_SECTION_RSRC:
if (assembly->win32_res) {
/* Fixup the offsets in the IMAGE_RESOURCE_DATA_ENTRY structures */
fixup_resource_directory (assembly->win32_res, assembly->win32_res, assembly->sections [i].rva);
checked_write_file (file, assembly->win32_res, assembly->win32_res_size);
}
break;
default:
g_assert_not_reached ();
}
}
/* check that the file is properly padded */
if (SetFilePointer (file, file_offset, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
g_error ("SetFilePointer returned %d\n", GetLastError ());
if (! SetEndOfFile (file))
g_error ("SetEndOfFile returned %d\n", GetLastError ());
mono_dynamic_stream_reset (&assembly->code);
mono_dynamic_stream_reset (&assembly->us);
mono_dynamic_stream_reset (&assembly->blob);
mono_dynamic_stream_reset (&assembly->guid);
mono_dynamic_stream_reset (&assembly->sheap);
g_hash_table_foreach (assembly->blob_cache, (GHFunc)g_free, NULL);
g_hash_table_destroy (assembly->blob_cache);
assembly->blob_cache = NULL;
}
#else /* DISABLE_REFLECTION_EMIT_SAVE */
void
mono_image_create_pefile (MonoReflectionModuleBuilder *mb, HANDLE file)
{
g_assert_not_reached ();
}
#endif /* DISABLE_REFLECTION_EMIT_SAVE */
#ifndef DISABLE_REFLECTION_EMIT
MonoReflectionModule *
mono_image_load_module_dynamic (MonoReflectionAssemblyBuilder *ab, MonoString *fileName)
{
char *name;
MonoImage *image;
MonoImageOpenStatus status;
MonoDynamicAssembly *assembly;
guint32 module_count;
MonoImage **new_modules;
gboolean *new_modules_loaded;
name = mono_string_to_utf8 (fileName);
image = mono_image_open (name, &status);
if (!image) {
MonoException *exc;
if (status == MONO_IMAGE_ERROR_ERRNO)
exc = mono_get_exception_file_not_found (fileName);
else
exc = mono_get_exception_bad_image_format (name);
g_free (name);
mono_raise_exception (exc);
}
g_free (name);
assembly = ab->dynamic_assembly;
image->assembly = (MonoAssembly*)assembly;
module_count = image->assembly->image->module_count;
new_modules = g_new0 (MonoImage *, module_count + 1);
new_modules_loaded = g_new0 (gboolean, module_count + 1);
if (image->assembly->image->modules)
memcpy (new_modules, image->assembly->image->modules, module_count * sizeof (MonoImage *));
if (image->assembly->image->modules_loaded)
memcpy (new_modules_loaded, image->assembly->image->modules_loaded, module_count * sizeof (gboolean));
new_modules [module_count] = image;
new_modules_loaded [module_count] = TRUE;
mono_image_addref (image);
g_free (image->assembly->image->modules);
image->assembly->image->modules = new_modules;
image->assembly->image->modules_loaded = new_modules_loaded;
image->assembly->image->module_count ++;
mono_assembly_load_references (image, &status);
if (status) {
mono_image_close (image);
mono_raise_exception (mono_get_exception_file_not_found (fileName));
}
return mono_module_get_object (mono_domain_get (), image);
}
#endif /* DISABLE_REFLECTION_EMIT */
/*
* We need to return always the same object for MethodInfo, FieldInfo etc..
* but we need to consider the reflected type.
* type uses a different hash, since it uses custom hash/equal functions.
*/
typedef struct {
gpointer item;
MonoClass *refclass;
} ReflectedEntry;
static gboolean
reflected_equal (gconstpointer a, gconstpointer b) {
const ReflectedEntry *ea = a;
const ReflectedEntry *eb = b;
return (ea->item == eb->item) && (ea->refclass == eb->refclass);
}
static guint
reflected_hash (gconstpointer a) {
const ReflectedEntry *ea = a;
return mono_aligned_addr_hash (ea->item);
}
#define CHECK_OBJECT(t,p,k) \
do { \
t _obj; \
ReflectedEntry e; \
e.item = (p); \
e.refclass = (k); \
mono_domain_lock (domain); \
if (!domain->refobject_hash) \
domain->refobject_hash = mono_g_hash_table_new_type (reflected_hash, reflected_equal, MONO_HASH_VALUE_GC); \
if ((_obj = mono_g_hash_table_lookup (domain->refobject_hash, &e))) { \
mono_domain_unlock (domain); \
return _obj; \
} \
mono_domain_unlock (domain); \
} while (0)
#ifdef HAVE_BOEHM_GC
/* ReflectedEntry doesn't need to be GC tracked */
#define ALLOC_REFENTRY g_new0 (ReflectedEntry, 1)
#define FREE_REFENTRY(entry) g_free ((entry))
#define REFENTRY_REQUIRES_CLEANUP
#else
#define ALLOC_REFENTRY mono_mempool_alloc (domain->mp, sizeof (ReflectedEntry))
/* FIXME: */
#define FREE_REFENTRY(entry)
#endif
#define CACHE_OBJECT(t,p,o,k) \
do { \
t _obj; \
ReflectedEntry pe; \
pe.item = (p); \
pe.refclass = (k); \
mono_domain_lock (domain); \
if (!domain->refobject_hash) \
domain->refobject_hash = mono_g_hash_table_new_type (reflected_hash, reflected_equal, MONO_HASH_VALUE_GC); \
_obj = mono_g_hash_table_lookup (domain->refobject_hash, &pe); \
if (!_obj) { \
ReflectedEntry *e = ALLOC_REFENTRY; \
e->item = (p); \
e->refclass = (k); \
mono_g_hash_table_insert (domain->refobject_hash, e,o); \
_obj = o; \
} \
mono_domain_unlock (domain); \
return _obj; \
} while (0)
static void
clear_cached_object (MonoDomain *domain, gpointer o, MonoClass *klass)
{
mono_domain_lock (domain);
if (domain->refobject_hash) {
ReflectedEntry pe;
gpointer orig_pe, orig_value;
pe.item = o;
pe.refclass = klass;
if (mono_g_hash_table_lookup_extended (domain->refobject_hash, &pe, &orig_pe, &orig_value)) {
mono_g_hash_table_remove (domain->refobject_hash, &pe);
FREE_REFENTRY (orig_pe);
}
}
mono_domain_unlock (domain);
}
#ifdef REFENTRY_REQUIRES_CLEANUP
static void
cleanup_refobject_hash (gpointer key, gpointer value, gpointer user_data)
{
FREE_REFENTRY (key);
}
#endif
void
mono_reflection_cleanup_domain (MonoDomain *domain)
{
if (domain->refobject_hash) {
/*let's avoid scanning the whole hashtable if not needed*/
#ifdef REFENTRY_REQUIRES_CLEANUP
mono_g_hash_table_foreach (domain->refobject_hash, cleanup_refobject_hash, NULL);
#endif
mono_g_hash_table_destroy (domain->refobject_hash);
domain->refobject_hash = NULL;
}
}
#ifndef DISABLE_REFLECTION_EMIT
static gpointer
register_assembly (MonoDomain *domain, MonoReflectionAssembly *res, MonoAssembly *assembly)
{
CACHE_OBJECT (MonoReflectionAssembly *, assembly, res, NULL);
}
static gpointer
register_module (MonoDomain *domain, MonoReflectionModuleBuilder *res, MonoDynamicImage *module)
{
CACHE_OBJECT (MonoReflectionModuleBuilder *, module, res, NULL);
}
void
mono_image_module_basic_init (MonoReflectionModuleBuilder *moduleb)
{
MonoDynamicImage *image = moduleb->dynamic_image;
MonoReflectionAssemblyBuilder *ab = moduleb->assemblyb;
if (!image) {
MonoError error;
int module_count;
MonoImage **new_modules;
MonoImage *ass;
char *name, *fqname;
/*
* FIXME: we already created an image in mono_image_basic_init (), but
* we don't know which module it belongs to, since that is only
* determined at assembly save time.
*/
/*image = (MonoDynamicImage*)ab->dynamic_assembly->assembly.image; */
name = mono_string_to_utf8 (ab->name);
fqname = mono_string_to_utf8_checked (moduleb->module.fqname, &error);
if (!mono_error_ok (&error)) {
g_free (name);
mono_error_raise_exception (&error);
}
image = create_dynamic_mono_image (ab->dynamic_assembly, name, fqname);
moduleb->module.image = &image->image;
moduleb->dynamic_image = image;
register_module (mono_object_domain (moduleb), moduleb, image);
/* register the module with the assembly */
ass = ab->dynamic_assembly->assembly.image;
module_count = ass->module_count;
new_modules = g_new0 (MonoImage *, module_count + 1);
if (ass->modules)
memcpy (new_modules, ass->modules, module_count * sizeof (MonoImage *));
new_modules [module_count] = &image->image;
mono_image_addref (&image->image);
g_free (ass->modules);
ass->modules = new_modules;
ass->module_count ++;
}
}
void
mono_image_set_wrappers_type (MonoReflectionModuleBuilder *moduleb, MonoReflectionType *type)
{
MonoDynamicImage *image = moduleb->dynamic_image;
g_assert (type->type);
image->wrappers_type = mono_class_from_mono_type (type->type);
}
#endif
/*
* mono_assembly_get_object:
* @domain: an app domain
* @assembly: an assembly
*
* Return an System.Reflection.Assembly object representing the MonoAssembly @assembly.
*/
MonoReflectionAssembly*
mono_assembly_get_object (MonoDomain *domain, MonoAssembly *assembly)
{
static MonoClass *assembly_type;
MonoReflectionAssembly *res;
CHECK_OBJECT (MonoReflectionAssembly *, assembly, NULL);
if (!assembly_type) {
MonoClass *class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoAssembly");
if (class == NULL)
class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Assembly");
g_assert (class);
assembly_type = class;
}
res = (MonoReflectionAssembly *)mono_object_new (domain, assembly_type);
res->assembly = assembly;
CACHE_OBJECT (MonoReflectionAssembly *, assembly, res, NULL);
}
MonoReflectionModule*
mono_module_get_object (MonoDomain *domain, MonoImage *image)
{
static MonoClass *module_type;
MonoReflectionModule *res;
char* basename;
CHECK_OBJECT (MonoReflectionModule *, image, NULL);
if (!module_type) {
MonoClass *class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoModule");
if (class == NULL)
class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Module");
g_assert (class);
module_type = class;
}
res = (MonoReflectionModule *)mono_object_new (domain, module_type);
res->image = image;
MONO_OBJECT_SETREF (res, assembly, (MonoReflectionAssembly *) mono_assembly_get_object(domain, image->assembly));
MONO_OBJECT_SETREF (res, fqname, mono_string_new (domain, image->name));
basename = g_path_get_basename (image->name);
MONO_OBJECT_SETREF (res, name, mono_string_new (domain, basename));
MONO_OBJECT_SETREF (res, scopename, mono_string_new (domain, image->module_name));
g_free (basename);
if (image->assembly->image == image) {
res->token = mono_metadata_make_token (MONO_TABLE_MODULE, 1);
} else {
int i;
res->token = 0;
if (image->assembly->image->modules) {
for (i = 0; i < image->assembly->image->module_count; i++) {
if (image->assembly->image->modules [i] == image)
res->token = mono_metadata_make_token (MONO_TABLE_MODULEREF, i + 1);
}
g_assert (res->token);
}
}
CACHE_OBJECT (MonoReflectionModule *, image, res, NULL);
}
MonoReflectionModule*
mono_module_file_get_object (MonoDomain *domain, MonoImage *image, int table_index)
{
static MonoClass *module_type;
MonoReflectionModule *res;
MonoTableInfo *table;
guint32 cols [MONO_FILE_SIZE];
const char *name;
guint32 i, name_idx;
const char *val;
if (!module_type) {
MonoClass *class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoModule");
if (class == NULL)
class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Module");
g_assert (class);
module_type = class;
}
res = (MonoReflectionModule *)mono_object_new (domain, module_type);
table = &image->tables [MONO_TABLE_FILE];
g_assert (table_index < table->rows);
mono_metadata_decode_row (table, table_index, cols, MONO_FILE_SIZE);
res->image = NULL;
MONO_OBJECT_SETREF (res, assembly, (MonoReflectionAssembly *) mono_assembly_get_object(domain, image->assembly));
name = mono_metadata_string_heap (image, cols [MONO_FILE_NAME]);
/* Check whenever the row has a corresponding row in the moduleref table */
table = &image->tables [MONO_TABLE_MODULEREF];
for (i = 0; i < table->rows; ++i) {
name_idx = mono_metadata_decode_row_col (table, i, MONO_MODULEREF_NAME);
val = mono_metadata_string_heap (image, name_idx);
if (strcmp (val, name) == 0)
res->image = image->modules [i];
}
MONO_OBJECT_SETREF (res, fqname, mono_string_new (domain, name));
MONO_OBJECT_SETREF (res, name, mono_string_new (domain, name));
MONO_OBJECT_SETREF (res, scopename, mono_string_new (domain, name));
res->is_resource = cols [MONO_FILE_FLAGS] && FILE_CONTAINS_NO_METADATA;
res->token = mono_metadata_make_token (MONO_TABLE_FILE, table_index + 1);
return res;
}
static gboolean
mymono_metadata_type_equal (MonoType *t1, MonoType *t2)
{
if ((t1->type != t2->type) ||
(t1->byref != t2->byref))
return FALSE;
switch (t1->type) {
case MONO_TYPE_VOID:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_CHAR:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_STRING:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_OBJECT:
case MONO_TYPE_TYPEDBYREF:
return TRUE;
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_CLASS:
case MONO_TYPE_SZARRAY:
return t1->data.klass == t2->data.klass;
case MONO_TYPE_PTR:
return mymono_metadata_type_equal (t1->data.type, t2->data.type);
case MONO_TYPE_ARRAY:
if (t1->data.array->rank != t2->data.array->rank)
return FALSE;
return t1->data.array->eklass == t2->data.array->eklass;
case MONO_TYPE_GENERICINST: {
int i;
MonoGenericInst *i1 = t1->data.generic_class->context.class_inst;
MonoGenericInst *i2 = t2->data.generic_class->context.class_inst;
if (i1->type_argc != i2->type_argc)
return FALSE;
if (!mono_metadata_type_equal (&t1->data.generic_class->container_class->byval_arg,
&t2->data.generic_class->container_class->byval_arg))
return FALSE;
/* FIXME: we should probably just compare the instance pointers directly. */
for (i = 0; i < i1->type_argc; ++i) {
if (!mono_metadata_type_equal (i1->type_argv [i], i2->type_argv [i]))
return FALSE;
}
return TRUE;
}
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
return t1->data.generic_param == t2->data.generic_param;
default:
g_error ("implement type compare for %0x!", t1->type);
return FALSE;
}
return FALSE;
}
static guint
mymono_metadata_type_hash (MonoType *t1)
{
guint hash;
hash = t1->type;
hash |= t1->byref << 6; /* do not collide with t1->type values */
switch (t1->type) {
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_CLASS:
case MONO_TYPE_SZARRAY:
/* check if the distribution is good enough */
return ((hash << 5) - hash) ^ mono_aligned_addr_hash (t1->data.klass);
case MONO_TYPE_PTR:
return ((hash << 5) - hash) ^ mymono_metadata_type_hash (t1->data.type);
case MONO_TYPE_GENERICINST: {
int i;
MonoGenericInst *inst = t1->data.generic_class->context.class_inst;
hash += g_str_hash (t1->data.generic_class->container_class->name);
hash *= 13;
for (i = 0; i < inst->type_argc; ++i) {
hash += mymono_metadata_type_hash (inst->type_argv [i]);
hash *= 13;
}
return hash;
}
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
return ((hash << 5) - hash) ^ GPOINTER_TO_UINT (t1->data.generic_param);
}
return hash;
}
static gboolean
verify_safe_for_managed_space (MonoType *type)
{
switch (type->type) {
#ifdef DEBUG_HARDER
case MONO_TYPE_ARRAY:
return verify_safe_for_managed_space (&type->data.array->eklass->byval_arg);
case MONO_TYPE_PTR:
return verify_safe_for_managed_space (type->data.type);
case MONO_TYPE_SZARRAY:
return verify_safe_for_managed_space (&type->data.klass->byval_arg);
case MONO_TYPE_GENERICINST: {
MonoGenericInst *inst = type->data.generic_class->inst;
int i;
if (!inst->is_open)
break;
for (i = 0; i < inst->type_argc; ++i)
if (!verify_safe_for_managed_space (inst->type_argv [i]))
return FALSE;
break;
}
#endif
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
return TRUE;
}
return TRUE;
}
static MonoType*
mono_type_normalize (MonoType *type)
{
int i;
MonoGenericClass *gclass;
MonoGenericInst *ginst;
MonoClass *gtd;
MonoGenericContainer *gcontainer;
MonoType **argv = NULL;
gboolean is_denorm_gtd = TRUE, requires_rebind = FALSE;
if (type->type != MONO_TYPE_GENERICINST)
return type;
gclass = type->data.generic_class;
ginst = gclass->context.class_inst;
if (!ginst->is_open)
return type;
gtd = gclass->container_class;
gcontainer = gtd->generic_container;
argv = g_newa (MonoType*, ginst->type_argc);
for (i = 0; i < ginst->type_argc; ++i) {
MonoType *t = ginst->type_argv [i], *norm;
if (t->type != MONO_TYPE_VAR || t->data.generic_param->num != i || t->data.generic_param->owner != gcontainer)
is_denorm_gtd = FALSE;
norm = mono_type_normalize (t);
argv [i] = norm;
if (norm != t)
requires_rebind = TRUE;
}
if (is_denorm_gtd)
return type->byref == gtd->byval_arg.byref ? >d->byval_arg : >d->this_arg;
if (requires_rebind) {
MonoClass *klass = mono_class_bind_generic_parameters (gtd, ginst->type_argc, argv, gclass->is_dynamic);
return type->byref == klass->byval_arg.byref ? &klass->byval_arg : &klass->this_arg;
}
return type;
}
/*
* mono_type_get_object:
* @domain: an app domain
* @type: a type
*
* Return an System.MonoType object representing the type @type.
*/
MonoReflectionType*
mono_type_get_object (MonoDomain *domain, MonoType *type)
{
MonoType *norm_type;
MonoReflectionType *res;
MonoClass *klass = mono_class_from_mono_type (type);
/*we must avoid using @type as it might have come
* from a mono_metadata_type_dup and the caller
* expects that is can be freed.
* Using the right type from
*/
type = klass->byval_arg.byref == type->byref ? &klass->byval_arg : &klass->this_arg;
/* void is very common */
if (type->type == MONO_TYPE_VOID && domain->typeof_void)
return (MonoReflectionType*)domain->typeof_void;
/*
* If the vtable of the given class was already created, we can use
* the MonoType from there and avoid all locking and hash table lookups.
*
* We cannot do this for TypeBuilders as mono_reflection_create_runtime_class expects
* that the resulting object is different.
*/
if (type == &klass->byval_arg && !klass->image->dynamic) {
MonoVTable *vtable = mono_class_try_get_vtable (domain, klass);
if (vtable && vtable->type)
return vtable->type;
}
mono_loader_lock (); /*FIXME mono_class_init and mono_class_vtable acquire it*/
mono_domain_lock (domain);
if (!domain->type_hash)
domain->type_hash = mono_g_hash_table_new_type ((GHashFunc)mymono_metadata_type_hash,
(GCompareFunc)mymono_metadata_type_equal, MONO_HASH_VALUE_GC);
if ((res = mono_g_hash_table_lookup (domain->type_hash, type))) {
mono_domain_unlock (domain);
mono_loader_unlock ();
return res;
}
/*Types must be normalized so a generic instance of the GTD get's the same inner type.
* For example in: Foo<A,B>; Bar<A> : Foo<A, Bar<A>>
* The second Bar will be encoded a generic instance of Bar with <A> as parameter.
* On all other places, Bar<A> will be encoded as the GTD itself. This is an implementation
* artifact of how generics are encoded and should be transparent to managed code so we
* need to weed out this diference when retrieving managed System.Type objects.
*/
norm_type = mono_type_normalize (type);
if (norm_type != type) {
res = mono_type_get_object (domain, norm_type);
mono_g_hash_table_insert (domain->type_hash, type, res);
mono_domain_unlock (domain);
mono_loader_unlock ();
return res;
}
/* This MonoGenericClass hack is no longer necessary. Let's leave it here until we finish with the 2-stage type-builder setup.*/
if ((type->type == MONO_TYPE_GENERICINST) && type->data.generic_class->is_dynamic && !type->data.generic_class->container_class->wastypebuilder)
g_assert (0);
if (!verify_safe_for_managed_space (type)) {
mono_domain_unlock (domain);
mono_loader_unlock ();
mono_raise_exception (mono_get_exception_invalid_operation ("This type cannot be propagated to managed space"));
}
if (mono_class_get_ref_info (klass) && !klass->wastypebuilder) {
gboolean is_type_done = TRUE;
/* Generic parameters have reflection_info set but they are not finished together with their enclosing type.
* We must ensure that once a type is finished we don't return a GenericTypeParameterBuilder.
* We can't simply close the types as this will interfere with other parts of the generics machinery.
*/
if (klass->byval_arg.type == MONO_TYPE_MVAR || klass->byval_arg.type == MONO_TYPE_VAR) {
MonoGenericParam *gparam = klass->byval_arg.data.generic_param;
if (gparam->owner && gparam->owner->is_method) {
MonoMethod *method = gparam->owner->owner.method;
if (method && mono_class_get_generic_type_definition (method->klass)->wastypebuilder)
is_type_done = FALSE;
} else if (gparam->owner && !gparam->owner->is_method) {
MonoClass *klass = gparam->owner->owner.klass;
if (klass && mono_class_get_generic_type_definition (klass)->wastypebuilder)
is_type_done = FALSE;
}
}
/* g_assert_not_reached (); */
/* should this be considered an error condition? */
if (is_type_done && !type->byref) {
mono_domain_unlock (domain);
mono_loader_unlock ();
return mono_class_get_ref_info (klass);
}
}
#ifdef HAVE_SGEN_GC
res = (MonoReflectionType *)mono_gc_alloc_pinned_obj (mono_class_vtable (domain, mono_defaults.monotype_class), mono_class_instance_size (mono_defaults.monotype_class));
#else
res = (MonoReflectionType *)mono_object_new (domain, mono_defaults.monotype_class);
#endif
res->type = type;
mono_g_hash_table_insert (domain->type_hash, type, res);
if (type->type == MONO_TYPE_VOID)
domain->typeof_void = (MonoObject*)res;
mono_domain_unlock (domain);
mono_loader_unlock ();
return res;
}
/*
* mono_method_get_object:
* @domain: an app domain
* @method: a method
* @refclass: the reflected type (can be NULL)
*
* Return an System.Reflection.MonoMethod object representing the method @method.
*/
MonoReflectionMethod*
mono_method_get_object (MonoDomain *domain, MonoMethod *method, MonoClass *refclass)
{
/*
* We use the same C representation for methods and constructors, but the type
* name in C# is different.
*/
static MonoClass *System_Reflection_MonoMethod = NULL;
static MonoClass *System_Reflection_MonoCMethod = NULL;
static MonoClass *System_Reflection_MonoGenericMethod = NULL;
static MonoClass *System_Reflection_MonoGenericCMethod = NULL;
MonoClass *klass;
MonoReflectionMethod *ret;
if (method->is_inflated) {
MonoReflectionGenericMethod *gret;
refclass = method->klass;
CHECK_OBJECT (MonoReflectionMethod *, method, refclass);
if ((*method->name == '.') && (!strcmp (method->name, ".ctor") || !strcmp (method->name, ".cctor"))) {
if (!System_Reflection_MonoGenericCMethod)
System_Reflection_MonoGenericCMethod = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoGenericCMethod");
klass = System_Reflection_MonoGenericCMethod;
} else {
if (!System_Reflection_MonoGenericMethod)
System_Reflection_MonoGenericMethod = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoGenericMethod");
klass = System_Reflection_MonoGenericMethod;
}
gret = (MonoReflectionGenericMethod*)mono_object_new (domain, klass);
gret->method.method = method;
MONO_OBJECT_SETREF (gret, method.name, mono_string_new (domain, method->name));
MONO_OBJECT_SETREF (gret, method.reftype, mono_type_get_object (domain, &refclass->byval_arg));
CACHE_OBJECT (MonoReflectionMethod *, method, (MonoReflectionMethod*)gret, refclass);
}
if (!refclass)
refclass = method->klass;
CHECK_OBJECT (MonoReflectionMethod *, method, refclass);
if (*method->name == '.' && (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0)) {
if (!System_Reflection_MonoCMethod)
System_Reflection_MonoCMethod = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoCMethod");
klass = System_Reflection_MonoCMethod;
}
else {
if (!System_Reflection_MonoMethod)
System_Reflection_MonoMethod = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoMethod");
klass = System_Reflection_MonoMethod;
}
ret = (MonoReflectionMethod*)mono_object_new (domain, klass);
ret->method = method;
MONO_OBJECT_SETREF (ret, reftype, mono_type_get_object (domain, &refclass->byval_arg));
CACHE_OBJECT (MonoReflectionMethod *, method, ret, refclass);
}
/*
* mono_method_clear_object:
*
* Clear the cached reflection objects for the dynamic method METHOD.
*/
void
mono_method_clear_object (MonoDomain *domain, MonoMethod *method)
{
MonoClass *klass;
g_assert (method->dynamic);
klass = method->klass;
while (klass) {
clear_cached_object (domain, method, klass);
klass = klass->parent;
}
/* Added by mono_param_get_objects () */
clear_cached_object (domain, &(method->signature), NULL);
klass = method->klass;
while (klass) {
clear_cached_object (domain, &(method->signature), klass);
klass = klass->parent;
}
}
/*
* mono_field_get_object:
* @domain: an app domain
* @klass: a type
* @field: a field
*
* Return an System.Reflection.MonoField object representing the field @field
* in class @klass.
*/
MonoReflectionField*
mono_field_get_object (MonoDomain *domain, MonoClass *klass, MonoClassField *field)
{
MonoReflectionField *res;
static MonoClass *monofield_klass;
CHECK_OBJECT (MonoReflectionField *, field, klass);
if (!monofield_klass)
monofield_klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoField");
res = (MonoReflectionField *)mono_object_new (domain, monofield_klass);
res->klass = klass;
res->field = field;
MONO_OBJECT_SETREF (res, name, mono_string_new (domain, mono_field_get_name (field)));
if (is_field_on_inst (field)) {
res->attrs = get_field_on_inst_generic_type (field)->attrs;
MONO_OBJECT_SETREF (res, type, mono_type_get_object (domain, field->type));
} else {
if (field->type)
MONO_OBJECT_SETREF (res, type, mono_type_get_object (domain, field->type));
res->attrs = mono_field_get_flags (field);
}
CACHE_OBJECT (MonoReflectionField *, field, res, klass);
}
/*
* mono_property_get_object:
* @domain: an app domain
* @klass: a type
* @property: a property
*
* Return an System.Reflection.MonoProperty object representing the property @property
* in class @klass.
*/
MonoReflectionProperty*
mono_property_get_object (MonoDomain *domain, MonoClass *klass, MonoProperty *property)
{
MonoReflectionProperty *res;
static MonoClass *monoproperty_klass;
CHECK_OBJECT (MonoReflectionProperty *, property, klass);
if (!monoproperty_klass)
monoproperty_klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoProperty");
res = (MonoReflectionProperty *)mono_object_new (domain, monoproperty_klass);
res->klass = klass;
res->property = property;
CACHE_OBJECT (MonoReflectionProperty *, property, res, klass);
}
/*
* mono_event_get_object:
* @domain: an app domain
* @klass: a type
* @event: a event
*
* Return an System.Reflection.MonoEvent object representing the event @event
* in class @klass.
*/
MonoReflectionEvent*
mono_event_get_object (MonoDomain *domain, MonoClass *klass, MonoEvent *event)
{
MonoReflectionEvent *res;
MonoReflectionMonoEvent *mono_event;
static MonoClass *monoevent_klass;
CHECK_OBJECT (MonoReflectionEvent *, event, klass);
if (!monoevent_klass)
monoevent_klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoEvent");
mono_event = (MonoReflectionMonoEvent *)mono_object_new (domain, monoevent_klass);
mono_event->klass = klass;
mono_event->event = event;
res = (MonoReflectionEvent*)mono_event;
CACHE_OBJECT (MonoReflectionEvent *, event, res, klass);
}
/**
* mono_get_reflection_missing_object:
* @domain: Domain where the object lives
*
* Returns the System.Reflection.Missing.Value singleton object
* (of type System.Reflection.Missing).
*
* Used as the value for ParameterInfo.DefaultValue when Optional
* is present
*/
static MonoObject *
mono_get_reflection_missing_object (MonoDomain *domain)
{
MonoObject *obj;
static MonoClassField *missing_value_field = NULL;
if (!missing_value_field) {
MonoClass *missing_klass;
missing_klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Missing");
mono_class_init (missing_klass);
missing_value_field = mono_class_get_field_from_name (missing_klass, "Value");
g_assert (missing_value_field);
}
obj = mono_field_get_value_object (domain, missing_value_field, NULL);
g_assert (obj);
return obj;
}
static MonoObject*
get_dbnull (MonoDomain *domain, MonoObject **dbnull)
{
if (!*dbnull)
*dbnull = mono_get_dbnull_object (domain);
return *dbnull;
}
static MonoObject*
get_reflection_missing (MonoDomain *domain, MonoObject **reflection_missing)
{
if (!*reflection_missing)
*reflection_missing = mono_get_reflection_missing_object (domain);
return *reflection_missing;
}
/*
* mono_param_get_objects:
* @domain: an app domain
* @method: a method
*
* Return an System.Reflection.ParameterInfo array object representing the parameters
* in the method @method.
*/
MonoArray*
mono_param_get_objects_internal (MonoDomain *domain, MonoMethod *method, MonoClass *refclass)
{
static MonoClass *System_Reflection_ParameterInfo;
static MonoClass *System_Reflection_ParameterInfo_array;
MonoError error;
MonoArray *res = NULL;
MonoReflectionMethod *member = NULL;
MonoReflectionParameter *param = NULL;
char **names, **blobs = NULL;
guint32 *types = NULL;
MonoType *type = NULL;
MonoObject *dbnull = NULL;
MonoObject *missing = NULL;
MonoMarshalSpec **mspecs;
MonoMethodSignature *sig;
MonoVTable *pinfo_vtable;
int i;
if (!System_Reflection_ParameterInfo_array) {
MonoClass *klass;
klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "ParameterInfo");
mono_memory_barrier ();
System_Reflection_ParameterInfo = klass;
klass = mono_array_class_get (klass, 1);
mono_memory_barrier ();
System_Reflection_ParameterInfo_array = klass;
}
sig = mono_method_signature_checked (method, &error);
if (!mono_error_ok (&error))
mono_error_raise_exception (&error);
if (!sig->param_count)
return mono_array_new_specific (mono_class_vtable (domain, System_Reflection_ParameterInfo_array), 0);
/* Note: the cache is based on the address of the signature into the method
* since we already cache MethodInfos with the method as keys.
*/
CHECK_OBJECT (MonoArray*, &(method->signature), refclass);
member = mono_method_get_object (domain, method, refclass);
names = g_new (char *, sig->param_count);
mono_method_get_param_names (method, (const char **) names);
mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
mono_method_get_marshal_info (method, mspecs);
res = mono_array_new_specific (mono_class_vtable (domain, System_Reflection_ParameterInfo_array), sig->param_count);
pinfo_vtable = mono_class_vtable (domain, System_Reflection_ParameterInfo);
for (i = 0; i < sig->param_count; ++i) {
param = (MonoReflectionParameter *)mono_object_new_specific (pinfo_vtable);
MONO_OBJECT_SETREF (param, ClassImpl, mono_type_get_object (domain, sig->params [i]));
MONO_OBJECT_SETREF (param, MemberImpl, (MonoObject*)member);
MONO_OBJECT_SETREF (param, NameImpl, mono_string_new (domain, names [i]));
param->PositionImpl = i;
param->AttrsImpl = sig->params [i]->attrs;
if (!(param->AttrsImpl & PARAM_ATTRIBUTE_HAS_DEFAULT)) {
if (param->AttrsImpl & PARAM_ATTRIBUTE_OPTIONAL)
MONO_OBJECT_SETREF (param, DefaultValueImpl, get_reflection_missing (domain, &missing));
else
MONO_OBJECT_SETREF (param, DefaultValueImpl, get_dbnull (domain, &dbnull));
} else {
if (!blobs) {
blobs = g_new0 (char *, sig->param_count);
types = g_new0 (guint32, sig->param_count);
get_default_param_value_blobs (method, blobs, types);
}
/* Build MonoType for the type from the Constant Table */
if (!type)
type = g_new0 (MonoType, 1);
type->type = types [i];
type->data.klass = NULL;
if (types [i] == MONO_TYPE_CLASS)
type->data.klass = mono_defaults.object_class;
else if ((sig->params [i]->type == MONO_TYPE_VALUETYPE) && sig->params [i]->data.klass->enumtype) {
/* For enums, types [i] contains the base type */
type->type = MONO_TYPE_VALUETYPE;
type->data.klass = mono_class_from_mono_type (sig->params [i]);
} else
type->data.klass = mono_class_from_mono_type (type);
MONO_OBJECT_SETREF (param, DefaultValueImpl, mono_get_object_from_blob (domain, type, blobs [i]));
/* Type in the Constant table is MONO_TYPE_CLASS for nulls */
if (types [i] != MONO_TYPE_CLASS && !param->DefaultValueImpl) {
if (param->AttrsImpl & PARAM_ATTRIBUTE_OPTIONAL)
MONO_OBJECT_SETREF (param, DefaultValueImpl, get_reflection_missing (domain, &missing));
else
MONO_OBJECT_SETREF (param, DefaultValueImpl, get_dbnull (domain, &dbnull));
}
}
if (mspecs [i + 1])
MONO_OBJECT_SETREF (param, MarshalAsImpl, (MonoObject*)mono_reflection_marshal_from_marshal_spec (domain, method->klass, mspecs [i + 1]));
mono_array_setref (res, i, param);
}
g_free (names);
g_free (blobs);
g_free (types);
g_free (type);
for (i = mono_method_signature (method)->param_count; i >= 0; i--)
if (mspecs [i])
mono_metadata_free_marshal_spec (mspecs [i]);
g_free (mspecs);
CACHE_OBJECT (MonoArray *, &(method->signature), res, refclass);
}
MonoArray*
mono_param_get_objects (MonoDomain *domain, MonoMethod *method)
{
return mono_param_get_objects_internal (domain, method, NULL);
}
/*
* mono_method_body_get_object:
* @domain: an app domain
* @method: a method
*
* Return an System.Reflection.MethodBody object representing the method @method.
*/
MonoReflectionMethodBody*
mono_method_body_get_object (MonoDomain *domain, MonoMethod *method)
{
static MonoClass *System_Reflection_MethodBody = NULL;
static MonoClass *System_Reflection_LocalVariableInfo = NULL;
static MonoClass *System_Reflection_ExceptionHandlingClause = NULL;
MonoReflectionMethodBody *ret;
MonoMethodHeader *header;
MonoImage *image;
guint32 method_rva, local_var_sig_token;
char *ptr;
unsigned char format, flags;
int i;
if (!System_Reflection_MethodBody)
System_Reflection_MethodBody = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MethodBody");
if (!System_Reflection_LocalVariableInfo)
System_Reflection_LocalVariableInfo = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "LocalVariableInfo");
if (!System_Reflection_ExceptionHandlingClause)
System_Reflection_ExceptionHandlingClause = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "ExceptionHandlingClause");
CHECK_OBJECT (MonoReflectionMethodBody *, method, NULL);
if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME))
return NULL;
image = method->klass->image;
header = mono_method_get_header (method);
if (!image->dynamic) {
/* Obtain local vars signature token */
method_rva = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_METHOD], mono_metadata_token_index (method->token) - 1, MONO_METHOD_RVA);
ptr = mono_image_rva_map (image, method_rva);
flags = *(const unsigned char *) ptr;
format = flags & METHOD_HEADER_FORMAT_MASK;
switch (format){
case METHOD_HEADER_TINY_FORMAT:
local_var_sig_token = 0;
break;
case METHOD_HEADER_FAT_FORMAT:
ptr += 2;
ptr += 2;
ptr += 4;
local_var_sig_token = read32 (ptr);
break;
default:
g_assert_not_reached ();
}
} else
local_var_sig_token = 0; //FIXME
ret = (MonoReflectionMethodBody*)mono_object_new (domain, System_Reflection_MethodBody);
ret->init_locals = header->init_locals;
ret->max_stack = header->max_stack;
ret->local_var_sig_token = local_var_sig_token;
MONO_OBJECT_SETREF (ret, il, mono_array_new_cached (domain, mono_defaults.byte_class, header->code_size));
memcpy (mono_array_addr (ret->il, guint8, 0), header->code, header->code_size);
/* Locals */
MONO_OBJECT_SETREF (ret, locals, mono_array_new_cached (domain, System_Reflection_LocalVariableInfo, header->num_locals));
for (i = 0; i < header->num_locals; ++i) {
MonoReflectionLocalVariableInfo *info = (MonoReflectionLocalVariableInfo*)mono_object_new (domain, System_Reflection_LocalVariableInfo);
MONO_OBJECT_SETREF (info, local_type, mono_type_get_object (domain, header->locals [i]));
info->is_pinned = header->locals [i]->pinned;
info->local_index = i;
mono_array_setref (ret->locals, i, info);
}
/* Exceptions */
MONO_OBJECT_SETREF (ret, clauses, mono_array_new_cached (domain, System_Reflection_ExceptionHandlingClause, header->num_clauses));
for (i = 0; i < header->num_clauses; ++i) {
MonoReflectionExceptionHandlingClause *info = (MonoReflectionExceptionHandlingClause*)mono_object_new (domain, System_Reflection_ExceptionHandlingClause);
MonoExceptionClause *clause = &header->clauses [i];
info->flags = clause->flags;
info->try_offset = clause->try_offset;
info->try_length = clause->try_len;
info->handler_offset = clause->handler_offset;
info->handler_length = clause->handler_len;
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
info->filter_offset = clause->data.filter_offset;
else if (clause->data.catch_class)
MONO_OBJECT_SETREF (info, catch_type, mono_type_get_object (mono_domain_get (), &clause->data.catch_class->byval_arg));
mono_array_setref (ret->clauses, i, info);
}
mono_metadata_free_mh (header);
CACHE_OBJECT (MonoReflectionMethodBody *, method, ret, NULL);
return ret;
}
/**
* mono_get_dbnull_object:
* @domain: Domain where the object lives
*
* Returns the System.DBNull.Value singleton object
*
* Used as the value for ParameterInfo.DefaultValue
*/
MonoObject *
mono_get_dbnull_object (MonoDomain *domain)
{
MonoObject *obj;
static MonoClassField *dbnull_value_field = NULL;
if (!dbnull_value_field) {
MonoClass *dbnull_klass;
dbnull_klass = mono_class_from_name (mono_defaults.corlib, "System", "DBNull");
mono_class_init (dbnull_klass);
dbnull_value_field = mono_class_get_field_from_name (dbnull_klass, "Value");
g_assert (dbnull_value_field);
}
obj = mono_field_get_value_object (domain, dbnull_value_field, NULL);
g_assert (obj);
return obj;
}
static void
get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types)
{
guint32 param_index, i, lastp, crow = 0;
guint32 param_cols [MONO_PARAM_SIZE], const_cols [MONO_CONSTANT_SIZE];
gint32 idx;
MonoClass *klass = method->klass;
MonoImage *image = klass->image;
MonoMethodSignature *methodsig = mono_method_signature (method);
MonoTableInfo *constt;
MonoTableInfo *methodt;
MonoTableInfo *paramt;
if (!methodsig->param_count)
return;
mono_class_init (klass);
if (klass->image->dynamic) {
MonoReflectionMethodAux *aux;
if (method->is_inflated)
method = ((MonoMethodInflated*)method)->declaring;
aux = g_hash_table_lookup (((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
if (aux && aux->param_defaults) {
memcpy (blobs, &(aux->param_defaults [1]), methodsig->param_count * sizeof (char*));
memcpy (types, &(aux->param_default_types [1]), methodsig->param_count * sizeof (guint32));
}
return;
}
methodt = &klass->image->tables [MONO_TABLE_METHOD];
paramt = &klass->image->tables [MONO_TABLE_PARAM];
constt = &image->tables [MONO_TABLE_CONSTANT];
idx = mono_method_get_index (method) - 1;
g_assert (idx != -1);
param_index = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
if (idx + 1 < methodt->rows)
lastp = mono_metadata_decode_row_col (methodt, idx + 1, MONO_METHOD_PARAMLIST);
else
lastp = paramt->rows + 1;
for (i = param_index; i < lastp; ++i) {
guint32 paramseq;
mono_metadata_decode_row (paramt, i - 1, param_cols, MONO_PARAM_SIZE);
paramseq = param_cols [MONO_PARAM_SEQUENCE];
if (!(param_cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_DEFAULT))
continue;
crow = mono_metadata_get_constant_index (image, MONO_TOKEN_PARAM_DEF | i, crow + 1);
if (!crow) {
continue;
}
mono_metadata_decode_row (constt, crow - 1, const_cols, MONO_CONSTANT_SIZE);
blobs [paramseq - 1] = (gpointer) mono_metadata_blob_heap (image, const_cols [MONO_CONSTANT_VALUE]);
types [paramseq - 1] = const_cols [MONO_CONSTANT_TYPE];
}
return;
}
MonoObject *
mono_get_object_from_blob (MonoDomain *domain, MonoType *type, const char *blob)
{
void *retval;
MonoClass *klass;
MonoObject *object;
MonoType *basetype = type;
if (!blob)
return NULL;
klass = mono_class_from_mono_type (type);
if (klass->valuetype) {
object = mono_object_new (domain, klass);
retval = ((gchar *) object + sizeof (MonoObject));
if (klass->enumtype)
basetype = mono_class_enum_basetype (klass);
} else {
retval = &object;
}
if (!mono_get_constant_value_from_blob (domain, basetype->type, blob, retval))
return object;
else
return NULL;
}
static int
assembly_name_to_aname (MonoAssemblyName *assembly, char *p) {
int found_sep;
char *s;
gboolean quoted = FALSE;
memset (assembly, 0, sizeof (MonoAssemblyName));
assembly->culture = "";
memset (assembly->public_key_token, 0, MONO_PUBLIC_KEY_TOKEN_LENGTH);
if (*p == '"') {
quoted = TRUE;
p++;
}
assembly->name = p;
while (*p && (isalnum (*p) || *p == '.' || *p == '-' || *p == '_' || *p == '$' || *p == '@' || g_ascii_isspace (*p)))
p++;
if (quoted) {
if (*p != '"')
return 1;
*p = 0;
p++;
}
if (*p != ',')
return 1;
*p = 0;
/* Remove trailing whitespace */
s = p - 1;
while (*s && g_ascii_isspace (*s))
*s-- = 0;
p ++;
while (g_ascii_isspace (*p))
p++;
while (*p) {
if (*p == 'V' && g_ascii_strncasecmp (p, "Version=", 8) == 0) {
p += 8;
assembly->major = strtoul (p, &s, 10);
if (s == p || *s != '.')
return 1;
p = ++s;
assembly->minor = strtoul (p, &s, 10);
if (s == p || *s != '.')
return 1;
p = ++s;
assembly->build = strtoul (p, &s, 10);
if (s == p || *s != '.')
return 1;
p = ++s;
assembly->revision = strtoul (p, &s, 10);
if (s == p)
return 1;
p = s;
} else if (*p == 'C' && g_ascii_strncasecmp (p, "Culture=", 8) == 0) {
p += 8;
if (g_ascii_strncasecmp (p, "neutral", 7) == 0) {
assembly->culture = "";
p += 7;
} else {
assembly->culture = p;
while (*p && *p != ',') {
p++;
}
}
} else if (*p == 'P' && g_ascii_strncasecmp (p, "PublicKeyToken=", 15) == 0) {
p += 15;
if (strncmp (p, "null", 4) == 0) {
p += 4;
} else {
int len;
gchar *start = p;
while (*p && *p != ',') {
p++;
}
len = (p - start + 1);
if (len > MONO_PUBLIC_KEY_TOKEN_LENGTH)
len = MONO_PUBLIC_KEY_TOKEN_LENGTH;
g_strlcpy ((char*)assembly->public_key_token, start, len);
}
} else {
while (*p && *p != ',')
p++;
}
found_sep = 0;
while (g_ascii_isspace (*p) || *p == ',') {
*p++ = 0;
found_sep = 1;
continue;
}
/* failed */
if (!found_sep)
return 1;
}
return 0;
}
/*
* mono_reflection_parse_type:
* @name: type name
*
* Parse a type name as accepted by the GetType () method and output the info
* extracted in the info structure.
* the name param will be mangled, so, make a copy before passing it to this function.
* The fields in info will be valid until the memory pointed to by name is valid.
*
* See also mono_type_get_name () below.
*
* Returns: 0 on parse error.
*/
static int
_mono_reflection_parse_type (char *name, char **endptr, gboolean is_recursed,
MonoTypeNameParse *info)
{
char *start, *p, *w, *temp, *last_point, *startn;
int in_modifiers = 0;
int isbyref = 0, rank, arity = 0, i;
start = p = w = name;
//FIXME could we just zero the whole struct? memset (&info, 0, sizeof (MonoTypeNameParse))
memset (&info->assembly, 0, sizeof (MonoAssemblyName));
info->name = info->name_space = NULL;
info->nested = NULL;
info->modifiers = NULL;
info->type_arguments = NULL;
/* last_point separates the namespace from the name */
last_point = NULL;
/* Skips spaces */
while (*p == ' ') p++, start++, w++, name++;
while (*p) {
switch (*p) {
case '+':
*p = 0; /* NULL terminate the name */
startn = p + 1;
info->nested = g_list_append (info->nested, startn);
/* we have parsed the nesting namespace + name */
if (info->name)
break;
if (last_point) {
info->name_space = start;
*last_point = 0;
info->name = last_point + 1;
} else {
info->name_space = (char *)"";
info->name = start;
}
break;
case '.':
last_point = p;
break;
case '\\':
++p;
break;
case '&':
case '*':
case '[':
case ',':
case ']':
in_modifiers = 1;
break;
case '`':
++p;
i = strtol (p, &temp, 10);
arity += i;
if (p == temp)
return 0;
p = temp-1;
break;
default:
break;
}
if (in_modifiers)
break;
// *w++ = *p++;
p++;
}
if (!info->name) {
if (last_point) {
info->name_space = start;
*last_point = 0;
info->name = last_point + 1;
} else {
info->name_space = (char *)"";
info->name = start;
}
}
while (*p) {
switch (*p) {
case '&':
if (isbyref) /* only one level allowed by the spec */
return 0;
isbyref = 1;
info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (0));
*p++ = 0;
break;
case '*':
info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (-1));
*p++ = 0;
break;
case '[':
if (arity != 0) {
*p++ = 0;
info->type_arguments = g_ptr_array_new ();
for (i = 0; i < arity; i++) {
MonoTypeNameParse *subinfo = g_new0 (MonoTypeNameParse, 1);
gboolean fqname = FALSE;
g_ptr_array_add (info->type_arguments, subinfo);
if (*p == '[') {
p++;
fqname = TRUE;
}
if (!_mono_reflection_parse_type (p, &p, TRUE, subinfo))
return 0;
/*MS is lenient on [] delimited parameters that aren't fqn - and F# uses them.*/
if (fqname && (*p != ']')) {
char *aname;
if (*p != ',')
return 0;
*p++ = 0;
aname = p;
while (*p && (*p != ']'))
p++;
if (*p != ']')
return 0;
*p++ = 0;
while (*aname) {
if (g_ascii_isspace (*aname)) {
++aname;
continue;
}
break;
}
if (!*aname ||
!assembly_name_to_aname (&subinfo->assembly, aname))
return 0;
} else if (fqname && (*p == ']')) {
*p++ = 0;
}
if (i + 1 < arity) {
if (*p != ',')
return 0;
} else {
if (*p != ']')
return 0;
}
*p++ = 0;
}
arity = 0;
break;
}
rank = 1;
*p++ = 0;
while (*p) {
if (*p == ']')
break;
if (*p == ',')
rank++;
else if (*p == '*') /* '*' means unknown lower bound */
info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (-2));
else
return 0;
++p;
}
if (*p++ != ']')
return 0;
info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (rank));
break;
case ']':
if (is_recursed)
goto end;
return 0;
case ',':
if (is_recursed)
goto end;
*p++ = 0;
while (*p) {
if (g_ascii_isspace (*p)) {
++p;
continue;
}
break;
}
if (!*p)
return 0; /* missing assembly name */
if (!assembly_name_to_aname (&info->assembly, p))
return 0;
break;
default:
return 0;
}
if (info->assembly.name)
break;
}
// *w = 0; /* terminate class name */
end:
if (!info->name || !*info->name)
return 0;
if (endptr)
*endptr = p;
/* add other consistency checks */
return 1;
}
int
mono_reflection_parse_type (char *name, MonoTypeNameParse *info)
{
return _mono_reflection_parse_type (name, NULL, FALSE, info);
}
static MonoType*
_mono_reflection_get_type_from_info (MonoTypeNameParse *info, MonoImage *image, gboolean ignorecase)
{
gboolean type_resolve = FALSE;
MonoType *type;
MonoImage *rootimage = image;
if (info->assembly.name) {
MonoAssembly *assembly = mono_assembly_loaded (&info->assembly);
if (!assembly && image && image->assembly && mono_assembly_names_equal (&info->assembly, &image->assembly->aname))
/*
* This could happen in the AOT compiler case when the search hook is not
* installed.
*/
assembly = image->assembly;
if (!assembly) {
/* then we must load the assembly ourselve - see #60439 */
assembly = mono_assembly_load (&info->assembly, NULL, NULL);
if (!assembly)
return NULL;
}
image = assembly->image;
} else if (!image) {
image = mono_defaults.corlib;
}
type = mono_reflection_get_type_with_rootimage (rootimage, image, info, ignorecase, &type_resolve);
if (type == NULL && !info->assembly.name && image != mono_defaults.corlib) {
image = mono_defaults.corlib;
type = mono_reflection_get_type_with_rootimage (rootimage, image, info, ignorecase, &type_resolve);
}
return type;
}
static MonoType*
mono_reflection_get_type_internal (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase)
{
MonoClass *klass;
GList *mod;
int modval;
gboolean bounded = FALSE;
if (!image)
image = mono_defaults.corlib;
if (ignorecase)
klass = mono_class_from_name_case (image, info->name_space, info->name);
else
klass = mono_class_from_name (image, info->name_space, info->name);
if (!klass)
return NULL;
for (mod = info->nested; mod; mod = mod->next) {
gpointer iter = NULL;
MonoClass *parent;
parent = klass;
mono_class_init (parent);
while ((klass = mono_class_get_nested_types (parent, &iter))) {
if (ignorecase) {
if (mono_utf8_strcasecmp (klass->name, mod->data) == 0)
break;
} else {
if (strcmp (klass->name, mod->data) == 0)
break;
}
}
if (!klass)
break;
}
if (!klass)
return NULL;
if (info->type_arguments) {
MonoType **type_args = g_new0 (MonoType *, info->type_arguments->len);
MonoReflectionType *the_type;
MonoType *instance;
int i;
for (i = 0; i < info->type_arguments->len; i++) {
MonoTypeNameParse *subinfo = g_ptr_array_index (info->type_arguments, i);
type_args [i] = _mono_reflection_get_type_from_info (subinfo, rootimage, ignorecase);
if (!type_args [i]) {
g_free (type_args);
return NULL;
}
}
the_type = mono_type_get_object (mono_domain_get (), &klass->byval_arg);
instance = mono_reflection_bind_generic_parameters (
the_type, info->type_arguments->len, type_args);
g_free (type_args);
if (!instance)
return NULL;
klass = mono_class_from_mono_type (instance);
}
for (mod = info->modifiers; mod; mod = mod->next) {
modval = GPOINTER_TO_UINT (mod->data);
if (!modval) { /* byref: must be last modifier */
return &klass->this_arg;
} else if (modval == -1) {
klass = mono_ptr_class_get (&klass->byval_arg);
} else if (modval == -2) {
bounded = TRUE;
} else { /* array rank */
klass = mono_bounded_array_class_get (klass, modval, bounded);
}
}
return &klass->byval_arg;
}
/*
* mono_reflection_get_type:
* @image: a metadata context
* @info: type description structure
* @ignorecase: flag for case-insensitive string compares
* @type_resolve: whenever type resolve was already tried
*
* Build a MonoType from the type description in @info.
*
*/
MonoType*
mono_reflection_get_type (MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve) {
return mono_reflection_get_type_with_rootimage(image, image, info, ignorecase, type_resolve);
}
static MonoType*
mono_reflection_get_type_internal_dynamic (MonoImage *rootimage, MonoAssembly *assembly, MonoTypeNameParse *info, gboolean ignorecase)
{
MonoReflectionAssemblyBuilder *abuilder;
MonoType *type;
int i;
g_assert (assembly->dynamic);
abuilder = (MonoReflectionAssemblyBuilder*)mono_assembly_get_object (((MonoDynamicAssembly*)assembly)->domain, assembly);
/* Enumerate all modules */
type = NULL;
if (abuilder->modules) {
for (i = 0; i < mono_array_length (abuilder->modules); ++i) {
MonoReflectionModuleBuilder *mb = mono_array_get (abuilder->modules, MonoReflectionModuleBuilder*, i);
type = mono_reflection_get_type_internal (rootimage, &mb->dynamic_image->image, info, ignorecase);
if (type)
break;
}
}
if (!type && abuilder->loaded_modules) {
for (i = 0; i < mono_array_length (abuilder->loaded_modules); ++i) {
MonoReflectionModule *mod = mono_array_get (abuilder->loaded_modules, MonoReflectionModule*, i);
type = mono_reflection_get_type_internal (rootimage, mod->image, info, ignorecase);
if (type)
break;
}
}
return type;
}
MonoType*
mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve)
{
MonoType *type;
MonoReflectionAssembly *assembly;
GString *fullName;
GList *mod;
if (image && image->dynamic)
type = mono_reflection_get_type_internal_dynamic (rootimage, image->assembly, info, ignorecase);
else
type = mono_reflection_get_type_internal (rootimage, image, info, ignorecase);
if (type)
return type;
if (!mono_domain_has_type_resolve (mono_domain_get ()))
return NULL;
if (type_resolve) {
if (*type_resolve)
return NULL;
else
*type_resolve = TRUE;
}
/* Reconstruct the type name */
fullName = g_string_new ("");
if (info->name_space && (info->name_space [0] != '\0'))
g_string_printf (fullName, "%s.%s", info->name_space, info->name);
else
g_string_printf (fullName, "%s", info->name);
for (mod = info->nested; mod; mod = mod->next)
g_string_append_printf (fullName, "+%s", (char*)mod->data);
assembly = mono_domain_try_type_resolve ( mono_domain_get (), fullName->str, NULL);
if (assembly) {
if (assembly->assembly->dynamic)
type = mono_reflection_get_type_internal_dynamic (rootimage, assembly->assembly, info, ignorecase);
else
type = mono_reflection_get_type_internal (rootimage, assembly->assembly->image,
info, ignorecase);
}
g_string_free (fullName, TRUE);
return type;
}
void
mono_reflection_free_type_info (MonoTypeNameParse *info)
{
g_list_free (info->modifiers);
g_list_free (info->nested);
if (info->type_arguments) {
int i;
for (i = 0; i < info->type_arguments->len; i++) {
MonoTypeNameParse *subinfo = g_ptr_array_index (info->type_arguments, i);
mono_reflection_free_type_info (subinfo);
/*We free the subinfo since it is allocated by _mono_reflection_parse_type*/
g_free (subinfo);
}
g_ptr_array_free (info->type_arguments, TRUE);
}
}
/*
* mono_reflection_type_from_name:
* @name: type name.
* @image: a metadata context (can be NULL).
*
* Retrieves a MonoType from its @name. If the name is not fully qualified,
* it defaults to get the type from @image or, if @image is NULL or loading
* from it fails, uses corlib.
*
*/
MonoType*
mono_reflection_type_from_name (char *name, MonoImage *image)
{
MonoType *type = NULL;
MonoTypeNameParse info;
char *tmp;
/* Make a copy since parse_type modifies its argument */
tmp = g_strdup (name);
/*g_print ("requested type %s\n", str);*/
if (mono_reflection_parse_type (tmp, &info)) {
type = _mono_reflection_get_type_from_info (&info, image, FALSE);
}
g_free (tmp);
mono_reflection_free_type_info (&info);
return type;
}
/*
* mono_reflection_get_token:
*
* Return the metadata token of OBJ which should be an object
* representing a metadata element.
*/
guint32
mono_reflection_get_token (MonoObject *obj)
{
MonoClass *klass;
guint32 token = 0;
klass = obj->vtable->klass;
if (strcmp (klass->name, "MethodBuilder") == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)obj;
token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
} else if (strcmp (klass->name, "ConstructorBuilder") == 0) {
MonoReflectionCtorBuilder *mb = (MonoReflectionCtorBuilder *)obj;
token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
} else if (strcmp (klass->name, "FieldBuilder") == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)obj;
token = fb->table_idx | MONO_TOKEN_FIELD_DEF;
} else if (strcmp (klass->name, "TypeBuilder") == 0) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)obj;
token = tb->table_idx | MONO_TOKEN_TYPE_DEF;
} else if (strcmp (klass->name, "MonoType") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
MonoClass *mc = mono_class_from_mono_type (type);
if (!mono_class_init (mc))
mono_raise_exception (mono_class_get_exception_for_failure (mc));
token = mc->type_token;
} else if (strcmp (klass->name, "MonoCMethod") == 0 ||
strcmp (klass->name, "MonoMethod") == 0 ||
strcmp (klass->name, "MonoGenericMethod") == 0 ||
strcmp (klass->name, "MonoGenericCMethod") == 0) {
MonoReflectionMethod *m = (MonoReflectionMethod *)obj;
if (m->method->is_inflated) {
MonoMethodInflated *inflated = (MonoMethodInflated *) m->method;
return inflated->declaring->token;
} else {
token = m->method->token;
}
} else if (strcmp (klass->name, "MonoField") == 0) {
MonoReflectionField *f = (MonoReflectionField*)obj;
if (is_field_on_inst (f->field)) {
MonoDynamicGenericClass *dgclass = (MonoDynamicGenericClass*)f->field->parent->generic_class;
int field_index = f->field - dgclass->fields;
MonoObject *obj;
g_assert (field_index >= 0 && field_index < dgclass->count_fields);
obj = dgclass->field_objects [field_index];
return mono_reflection_get_token (obj);
}
token = mono_class_get_field_token (f->field);
} else if (strcmp (klass->name, "MonoProperty") == 0) {
MonoReflectionProperty *p = (MonoReflectionProperty*)obj;
token = mono_class_get_property_token (p->property);
} else if (strcmp (klass->name, "MonoEvent") == 0) {
MonoReflectionMonoEvent *p = (MonoReflectionMonoEvent*)obj;
token = mono_class_get_event_token (p->event);
} else if (strcmp (klass->name, "ParameterInfo") == 0) {
MonoReflectionParameter *p = (MonoReflectionParameter*)obj;
MonoClass *member_class = mono_object_class (p->MemberImpl);
g_assert (mono_class_is_reflection_method_or_constructor (member_class));
token = mono_method_get_param_token (((MonoReflectionMethod*)p->MemberImpl)->method, p->PositionImpl);
} else if (strcmp (klass->name, "Module") == 0 || strcmp (klass->name, "MonoModule") == 0) {
MonoReflectionModule *m = (MonoReflectionModule*)obj;
token = m->token;
} else if (strcmp (klass->name, "Assembly") == 0 || strcmp (klass->name, "MonoAssembly") == 0) {
token = mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1);
} else {
gchar *msg = g_strdup_printf ("MetadataToken is not supported for type '%s.%s'", klass->name_space, klass->name);
MonoException *ex = mono_get_exception_not_implemented (msg);
g_free (msg);
mono_raise_exception (ex);
}
return token;
}
static void*
load_cattr_value (MonoImage *image, MonoType *t, const char *p, const char **end)
{
int slen, type = t->type;
MonoClass *tklass = t->data.klass;
handle_enum:
switch (type) {
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_BOOLEAN: {
MonoBoolean *bval = g_malloc (sizeof (MonoBoolean));
*bval = *p;
*end = p + 1;
return bval;
}
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2: {
guint16 *val = g_malloc (sizeof (guint16));
*val = read16 (p);
*end = p + 2;
return val;
}
#if SIZEOF_VOID_P == 4
case MONO_TYPE_U:
case MONO_TYPE_I:
#endif
case MONO_TYPE_R4:
case MONO_TYPE_U4:
case MONO_TYPE_I4: {
guint32 *val = g_malloc (sizeof (guint32));
*val = read32 (p);
*end = p + 4;
return val;
}
#if SIZEOF_VOID_P == 8
case MONO_TYPE_U: /* error out instead? this should probably not happen */
case MONO_TYPE_I:
#endif
case MONO_TYPE_U8:
case MONO_TYPE_I8: {
guint64 *val = g_malloc (sizeof (guint64));
*val = read64 (p);
*end = p + 8;
return val;
}
case MONO_TYPE_R8: {
double *val = g_malloc (sizeof (double));
readr8 (p, val);
*end = p + 8;
return val;
}
case MONO_TYPE_VALUETYPE:
if (t->data.klass->enumtype) {
type = mono_class_enum_basetype (t->data.klass)->type;
goto handle_enum;
} else {
MonoClass *k = t->data.klass;
if (mono_is_corlib_image (k->image) && strcmp (k->name_space, "System") == 0 && strcmp (k->name, "DateTime") == 0){
guint64 *val = g_malloc (sizeof (guint64));
*val = read64 (p);
*end = p + 8;
return val;
}
}
g_error ("generic valutype %s not handled in custom attr value decoding", t->data.klass->name);
break;
case MONO_TYPE_STRING:
if (*p == (char)0xFF) {
*end = p + 1;
return NULL;
}
slen = mono_metadata_decode_value (p, &p);
*end = p + slen;
return mono_string_new_len (mono_domain_get (), p, slen);
case MONO_TYPE_CLASS: {
char *n;
MonoType *t;
if (*p == (char)0xFF) {
*end = p + 1;
return NULL;
}
handle_type:
slen = mono_metadata_decode_value (p, &p);
n = g_memdup (p, slen + 1);
n [slen] = 0;
t = mono_reflection_type_from_name (n, image);
if (!t)
g_warning ("Cannot load type '%s'", n);
g_free (n);
*end = p + slen;
if (t)
return mono_type_get_object (mono_domain_get (), t);
else
return NULL;
}
case MONO_TYPE_OBJECT: {
char subt = *p++;
MonoObject *obj;
MonoClass *subc = NULL;
void *val;
if (subt == 0x50) {
goto handle_type;
} else if (subt == 0x0E) {
type = MONO_TYPE_STRING;
goto handle_enum;
} else if (subt == 0x1D) {
MonoType simple_type = {{0}};
int etype = *p;
p ++;
if (etype == 0x51)
/* See Partition II, Appendix B3 */
etype = MONO_TYPE_OBJECT;
type = MONO_TYPE_SZARRAY;
simple_type.type = etype;
tklass = mono_class_from_mono_type (&simple_type);
goto handle_enum;
} else if (subt == 0x55) {
char *n;
MonoType *t;
slen = mono_metadata_decode_value (p, &p);
n = g_memdup (p, slen + 1);
n [slen] = 0;
t = mono_reflection_type_from_name (n, image);
if (!t)
g_error ("Cannot load type '%s'", n);
g_free (n);
p += slen;
subc = mono_class_from_mono_type (t);
} else if (subt >= MONO_TYPE_BOOLEAN && subt <= MONO_TYPE_R8) {
MonoType simple_type = {{0}};
simple_type.type = subt;
subc = mono_class_from_mono_type (&simple_type);
} else {
g_error ("Unknown type 0x%02x for object type encoding in custom attr", subt);
}
val = load_cattr_value (image, &subc->byval_arg, p, end);
obj = mono_object_new (mono_domain_get (), subc);
g_assert (!subc->has_references);
memcpy ((char*)obj + sizeof (MonoObject), val, mono_class_value_size (subc, NULL));
g_free (val);
return obj;
}
case MONO_TYPE_SZARRAY: {
MonoArray *arr;
guint32 i, alen, basetype;
alen = read32 (p);
p += 4;
if (alen == 0xffffffff) {
*end = p;
return NULL;
}
arr = mono_array_new (mono_domain_get(), tklass, alen);
basetype = tklass->byval_arg.type;
if (basetype == MONO_TYPE_VALUETYPE && tklass->enumtype)
basetype = mono_class_enum_basetype (tklass)->type;
switch (basetype)
{
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_BOOLEAN:
for (i = 0; i < alen; i++) {
MonoBoolean val = *p++;
mono_array_set (arr, MonoBoolean, i, val);
}
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
for (i = 0; i < alen; i++) {
guint16 val = read16 (p);
mono_array_set (arr, guint16, i, val);
p += 2;
}
break;
case MONO_TYPE_R4:
case MONO_TYPE_U4:
case MONO_TYPE_I4:
for (i = 0; i < alen; i++) {
guint32 val = read32 (p);
mono_array_set (arr, guint32, i, val);
p += 4;
}
break;
case MONO_TYPE_R8:
for (i = 0; i < alen; i++) {
double val;
readr8 (p, &val);
mono_array_set (arr, double, i, val);
p += 8;
}
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
for (i = 0; i < alen; i++) {
guint64 val = read64 (p);
mono_array_set (arr, guint64, i, val);
p += 8;
}
break;
case MONO_TYPE_CLASS:
case MONO_TYPE_OBJECT:
case MONO_TYPE_STRING:
for (i = 0; i < alen; i++) {
MonoObject *item = load_cattr_value (image, &tklass->byval_arg, p, &p);
mono_array_setref (arr, i, item);
}
break;
default:
g_error ("Type 0x%02x not handled in custom attr array decoding", basetype);
}
*end=p;
return arr;
}
default:
g_error ("Type 0x%02x not handled in custom attr value decoding", type);
}
return NULL;
}
static MonoObject*
create_cattr_typed_arg (MonoType *t, MonoObject *val)
{
static MonoClass *klass;
static MonoMethod *ctor;
MonoObject *retval;
void *params [2], *unboxed;
if (!klass)
klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "CustomAttributeTypedArgument");
if (!ctor)
ctor = mono_class_get_method_from_name (klass, ".ctor", 2);
params [0] = mono_type_get_object (mono_domain_get (), t);
params [1] = val;
retval = mono_object_new (mono_domain_get (), klass);
unboxed = mono_object_unbox (retval);
mono_runtime_invoke (ctor, unboxed, params, NULL);
return retval;
}
static MonoObject*
create_cattr_named_arg (void *minfo, MonoObject *typedarg)
{
static MonoClass *klass;
static MonoMethod *ctor;
MonoObject *retval;
void *unboxed, *params [2];
if (!klass)
klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "CustomAttributeNamedArgument");
if (!ctor)
ctor = mono_class_get_method_from_name (klass, ".ctor", 2);
params [0] = minfo;
params [1] = typedarg;
retval = mono_object_new (mono_domain_get (), klass);
unboxed = mono_object_unbox (retval);
mono_runtime_invoke (ctor, unboxed, params, NULL);
return retval;
}
static gboolean
type_is_reference (MonoType *type)
{
switch (type->type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_CHAR:
case MONO_TYPE_U:
case MONO_TYPE_I:
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_U8:
case MONO_TYPE_I8:
case MONO_TYPE_R8:
case MONO_TYPE_R4:
case MONO_TYPE_VALUETYPE:
return FALSE;
default:
return TRUE;
}
}
static void
free_param_data (MonoMethodSignature *sig, void **params) {
int i;
for (i = 0; i < sig->param_count; ++i) {
if (!type_is_reference (sig->params [i]))
g_free (params [i]);
}
}
/*
* Find the field index in the metadata FieldDef table.
*/
static guint32
find_field_index (MonoClass *klass, MonoClassField *field) {
int i;
for (i = 0; i < klass->field.count; ++i) {
if (field == &klass->fields [i])
return klass->field.first + 1 + i;
}
return 0;
}
/*
* Find the property index in the metadata Property table.
*/
static guint32
find_property_index (MonoClass *klass, MonoProperty *property) {
int i;
for (i = 0; i < klass->ext->property.count; ++i) {
if (property == &klass->ext->properties [i])
return klass->ext->property.first + 1 + i;
}
return 0;
}
/*
* Find the event index in the metadata Event table.
*/
static guint32
find_event_index (MonoClass *klass, MonoEvent *event) {
int i;
for (i = 0; i < klass->ext->event.count; ++i) {
if (event == &klass->ext->events [i])
return klass->ext->event.first + 1 + i;
}
return 0;
}
static MonoObject*
create_custom_attr (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len)
{
const char *p = (const char*)data;
const char *named;
guint32 i, j, num_named;
MonoObject *attr;
void *params_buf [32];
void **params;
MonoMethodSignature *sig;
mono_class_init (method->klass);
if (!mono_verifier_verify_cattr_content (image, method, data, len, NULL))
return NULL;
if (len == 0) {
attr = mono_object_new (mono_domain_get (), method->klass);
mono_runtime_invoke (method, attr, NULL, NULL);
return attr;
}
if (len < 2 || read16 (p) != 0x0001) /* Prolog */
return NULL;
/*g_print ("got attr %s\n", method->klass->name);*/
sig = mono_method_signature (method);
if (sig->param_count < 32)
params = params_buf;
else
/* Allocate using GC so it gets GC tracking */
params = mono_gc_alloc_fixed (sig->param_count * sizeof (void*), NULL);
/* skip prolog */
p += 2;
for (i = 0; i < mono_method_signature (method)->param_count; ++i) {
params [i] = load_cattr_value (image, mono_method_signature (method)->params [i], p, &p);
}
named = p;
attr = mono_object_new (mono_domain_get (), method->klass);
mono_runtime_invoke (method, attr, params, NULL);
free_param_data (method->signature, params);
num_named = read16 (named);
named += 2;
for (j = 0; j < num_named; j++) {
gint name_len;
char *name, named_type, data_type;
named_type = *named++;
data_type = *named++; /* type of data */
if (data_type == MONO_TYPE_SZARRAY)
data_type = *named++;
if (data_type == MONO_TYPE_ENUM) {
gint type_len;
char *type_name;
type_len = mono_metadata_decode_blob_size (named, &named);
type_name = g_malloc (type_len + 1);
memcpy (type_name, named, type_len);
type_name [type_len] = 0;
named += type_len;
/* FIXME: lookup the type and check type consistency */
g_free (type_name);
}
name_len = mono_metadata_decode_blob_size (named, &named);
name = g_malloc (name_len + 1);
memcpy (name, named, name_len);
name [name_len] = 0;
named += name_len;
if (named_type == 0x53) {
MonoClassField *field = mono_class_get_field_from_name (mono_object_class (attr), name);
void *val = load_cattr_value (image, field->type, named, &named);
mono_field_set_value (attr, field, val);
if (!type_is_reference (field->type))
g_free (val);
} else if (named_type == 0x54) {
MonoProperty *prop;
void *pparams [1];
MonoType *prop_type;
prop = mono_class_get_property_from_name (mono_object_class (attr), name);
/* can we have more that 1 arg in a custom attr named property? */
prop_type = prop->get? mono_method_signature (prop->get)->ret :
mono_method_signature (prop->set)->params [mono_method_signature (prop->set)->param_count - 1];
pparams [0] = load_cattr_value (image, prop_type, named, &named);
mono_property_set_value (prop, attr, pparams, NULL);
if (!type_is_reference (prop_type))
g_free (pparams [0]);
}
g_free (name);
}
if (params != params_buf)
mono_gc_free_fixed (params);
return attr;
}
/*
* mono_reflection_create_custom_attr_data_args:
*
* Create an array of typed and named arguments from the cattr blob given by DATA.
* TYPED_ARGS and NAMED_ARGS will contain the objects representing the arguments,
* NAMED_ARG_INFO will contain information about the named arguments.
*/
void
mono_reflection_create_custom_attr_data_args (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len, MonoArray **typed_args, MonoArray **named_args, CattrNamedArg **named_arg_info)
{
MonoArray *typedargs, *namedargs;
MonoClass *attrklass;
MonoDomain *domain;
const char *p = (const char*)data;
const char *named;
guint32 i, j, num_named;
CattrNamedArg *arginfo = NULL;
if (!mono_verifier_verify_cattr_content (image, method, data, len, NULL))
return;
mono_class_init (method->klass);
*typed_args = NULL;
*named_args = NULL;
*named_arg_info = NULL;
domain = mono_domain_get ();
if (len < 2 || read16 (p) != 0x0001) /* Prolog */
return;
typedargs = mono_array_new (domain, mono_get_object_class (), mono_method_signature (method)->param_count);
/* skip prolog */
p += 2;
for (i = 0; i < mono_method_signature (method)->param_count; ++i) {
MonoObject *obj;
void *val;
val = load_cattr_value (image, mono_method_signature (method)->params [i], p, &p);
obj = type_is_reference (mono_method_signature (method)->params [i]) ?
val : mono_value_box (domain, mono_class_from_mono_type (mono_method_signature (method)->params [i]), val);
mono_array_setref (typedargs, i, obj);
if (!type_is_reference (mono_method_signature (method)->params [i]))
g_free (val);
}
named = p;
num_named = read16 (named);
namedargs = mono_array_new (domain, mono_get_object_class (), num_named);
named += 2;
attrklass = method->klass;
arginfo = g_new0 (CattrNamedArg, num_named);
*named_arg_info = arginfo;
for (j = 0; j < num_named; j++) {
gint name_len;
char *name, named_type, data_type;
named_type = *named++;
data_type = *named++; /* type of data */
if (data_type == MONO_TYPE_SZARRAY)
data_type = *named++;
if (data_type == MONO_TYPE_ENUM) {
gint type_len;
char *type_name;
type_len = mono_metadata_decode_blob_size (named, &named);
type_name = g_malloc (type_len + 1);
memcpy (type_name, named, type_len);
type_name [type_len] = 0;
named += type_len;
/* FIXME: lookup the type and check type consistency */
g_free (type_name);
}
name_len = mono_metadata_decode_blob_size (named, &named);
name = g_malloc (name_len + 1);
memcpy (name, named, name_len);
name [name_len] = 0;
named += name_len;
if (named_type == 0x53) {
MonoObject *obj;
MonoClassField *field = mono_class_get_field_from_name (attrklass, name);
void *val;
arginfo [j].type = field->type;
arginfo [j].field = field;
val = load_cattr_value (image, field->type, named, &named);
obj = type_is_reference (field->type) ? val : mono_value_box (domain, mono_class_from_mono_type (field->type), val);
mono_array_setref (namedargs, j, obj);
if (!type_is_reference (field->type))
g_free (val);
} else if (named_type == 0x54) {
MonoObject *obj;
MonoType *prop_type;
MonoProperty *prop = mono_class_get_property_from_name (attrklass, name);
void *val;
prop_type = prop->get? mono_method_signature (prop->get)->ret :
mono_method_signature (prop->set)->params [mono_method_signature (prop->set)->param_count - 1];
arginfo [j].type = prop_type;
arginfo [j].prop = prop;
val = load_cattr_value (image, prop_type, named, &named);
obj = type_is_reference (prop_type) ? val : mono_value_box (domain, mono_class_from_mono_type (prop_type), val);
mono_array_setref (namedargs, j, obj);
if (!type_is_reference (prop_type))
g_free (val);
}
g_free (name);
}
*typed_args = typedargs;
*named_args = namedargs;
}
void
mono_reflection_resolve_custom_attribute_data (MonoReflectionMethod *ref_method, MonoReflectionAssembly *assembly, gpointer data, guint32 len, MonoArray **ctor_args, MonoArray **named_args)
{
MonoDomain *domain;
MonoArray *typedargs, *namedargs;
MonoImage *image;
MonoMethod *method;
CattrNamedArg *arginfo;
int i;
*ctor_args = NULL;
*named_args = NULL;
if (len == 0)
return;
image = assembly->assembly->image;
method = ref_method->method;
domain = mono_object_domain (ref_method);
if (!mono_class_init (method->klass))
mono_raise_exception (mono_class_get_exception_for_failure (method->klass));
mono_reflection_create_custom_attr_data_args (image, method, data, len, &typedargs, &namedargs, &arginfo);
if (mono_loader_get_last_error ())
mono_raise_exception (mono_loader_error_prepare_exception (mono_loader_get_last_error ()));
if (!typedargs || !namedargs)
return;
for (i = 0; i < mono_method_signature (method)->param_count; ++i) {
MonoObject *obj = mono_array_get (typedargs, MonoObject*, i);
MonoObject *typedarg;
typedarg = create_cattr_typed_arg (mono_method_signature (method)->params [i], obj);
mono_array_setref (typedargs, i, typedarg);
}
for (i = 0; i < mono_array_length (namedargs); ++i) {
MonoObject *obj = mono_array_get (namedargs, MonoObject*, i);
MonoObject *typedarg, *namedarg, *minfo;
if (arginfo [i].prop)
minfo = (MonoObject*)mono_property_get_object (domain, NULL, arginfo [i].prop);
else
minfo = (MonoObject*)mono_field_get_object (domain, NULL, arginfo [i].field);
typedarg = create_cattr_typed_arg (arginfo [i].type, obj);
namedarg = create_cattr_named_arg (minfo, typedarg);
mono_array_setref (namedargs, i, namedarg);
}
*ctor_args = typedargs;
*named_args = namedargs;
}
static MonoObject*
create_custom_attr_data (MonoImage *image, MonoCustomAttrEntry *cattr)
{
static MonoMethod *ctor;
MonoDomain *domain;
MonoObject *attr;
void *params [4];
g_assert (image->assembly);
if (!ctor)
ctor = mono_class_get_method_from_name (mono_defaults.customattribute_data_class, ".ctor", 4);
domain = mono_domain_get ();
attr = mono_object_new (domain, mono_defaults.customattribute_data_class);
params [0] = mono_method_get_object (domain, cattr->ctor, NULL);
params [1] = mono_assembly_get_object (domain, image->assembly);
params [2] = (gpointer)&cattr->data;
params [3] = &cattr->data_size;
mono_runtime_invoke (ctor, attr, params, NULL);
return attr;
}
MonoArray*
mono_custom_attrs_construct (MonoCustomAttrInfo *cinfo)
{
MonoArray *result;
MonoObject *attr;
int i;
result = mono_array_new_cached (mono_domain_get (), mono_defaults.attribute_class, cinfo->num_attrs);
for (i = 0; i < cinfo->num_attrs; ++i) {
if (!cinfo->attrs [i].ctor)
/* The cattr type is not finished yet */
/* We should include the type name but cinfo doesn't contain it */
mono_raise_exception (mono_get_exception_type_load (NULL, NULL));
attr = create_custom_attr (cinfo->image, cinfo->attrs [i].ctor, cinfo->attrs [i].data, cinfo->attrs [i].data_size);
mono_array_setref (result, i, attr);
}
return result;
}
static MonoArray*
mono_custom_attrs_construct_by_type (MonoCustomAttrInfo *cinfo, MonoClass *attr_klass)
{
MonoArray *result;
MonoObject *attr;
int i, n;
n = 0;
for (i = 0; i < cinfo->num_attrs; ++i) {
if (mono_class_is_assignable_from (attr_klass, cinfo->attrs [i].ctor->klass))
n ++;
}
result = mono_array_new_cached (mono_domain_get (), mono_defaults.attribute_class, n);
n = 0;
for (i = 0; i < cinfo->num_attrs; ++i) {
if (mono_class_is_assignable_from (attr_klass, cinfo->attrs [i].ctor->klass)) {
attr = create_custom_attr (cinfo->image, cinfo->attrs [i].ctor, cinfo->attrs [i].data, cinfo->attrs [i].data_size);
mono_array_setref (result, n, attr);
n ++;
}
}
return result;
}
static MonoArray*
mono_custom_attrs_data_construct (MonoCustomAttrInfo *cinfo)
{
MonoArray *result;
MonoObject *attr;
int i;
result = mono_array_new (mono_domain_get (), mono_defaults.customattribute_data_class, cinfo->num_attrs);
for (i = 0; i < cinfo->num_attrs; ++i) {
attr = create_custom_attr_data (cinfo->image, &cinfo->attrs [i]);
mono_array_setref (result, i, attr);
}
return result;
}
/**
* mono_custom_attrs_from_index:
*
* Returns: NULL if no attributes are found or if a loading error occurs.
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_index (MonoImage *image, guint32 idx)
{
guint32 mtoken, i, len;
guint32 cols [MONO_CUSTOM_ATTR_SIZE];
MonoTableInfo *ca;
MonoCustomAttrInfo *ainfo;
GList *tmp, *list = NULL;
const char *data;
ca = &image->tables [MONO_TABLE_CUSTOMATTRIBUTE];
i = mono_metadata_custom_attrs_from_index (image, idx);
if (!i)
return NULL;
i --;
while (i < ca->rows) {
if (mono_metadata_decode_row_col (ca, i, MONO_CUSTOM_ATTR_PARENT) != idx)
break;
list = g_list_prepend (list, GUINT_TO_POINTER (i));
++i;
}
len = g_list_length (list);
if (!len)
return NULL;
ainfo = g_malloc0 (MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * len);
ainfo->num_attrs = len;
ainfo->image = image;
for (i = 0, tmp = list; i < len; ++i, tmp = tmp->next) {
mono_metadata_decode_row (ca, GPOINTER_TO_UINT (tmp->data), cols, MONO_CUSTOM_ATTR_SIZE);
mtoken = cols [MONO_CUSTOM_ATTR_TYPE] >> MONO_CUSTOM_ATTR_TYPE_BITS;
switch (cols [MONO_CUSTOM_ATTR_TYPE] & MONO_CUSTOM_ATTR_TYPE_MASK) {
case MONO_CUSTOM_ATTR_TYPE_METHODDEF:
mtoken |= MONO_TOKEN_METHOD_DEF;
break;
case MONO_CUSTOM_ATTR_TYPE_MEMBERREF:
mtoken |= MONO_TOKEN_MEMBER_REF;
break;
default:
g_error ("Unknown table for custom attr type %08x", cols [MONO_CUSTOM_ATTR_TYPE]);
break;
}
ainfo->attrs [i].ctor = mono_get_method (image, mtoken, NULL);
if (!ainfo->attrs [i].ctor) {
g_warning ("Can't find custom attr constructor image: %s mtoken: 0x%08x", image->name, mtoken);
g_list_free (list);
g_free (ainfo);
return NULL;
}
if (!mono_verifier_verify_cattr_blob (image, cols [MONO_CUSTOM_ATTR_VALUE], NULL)) {
/*FIXME raising an exception here doesn't make any sense*/
g_warning ("Invalid custom attribute blob on image %s for index %x", image->name, idx);
g_list_free (list);
g_free (ainfo);
return NULL;
}
data = mono_metadata_blob_heap (image, cols [MONO_CUSTOM_ATTR_VALUE]);
ainfo->attrs [i].data_size = mono_metadata_decode_value (data, &data);
ainfo->attrs [i].data = (guchar*)data;
}
g_list_free (list);
return ainfo;
}
MonoCustomAttrInfo*
mono_custom_attrs_from_method (MonoMethod *method)
{
guint32 idx;
/*
* An instantiated method has the same cattrs as the generic method definition.
*
* LAMESPEC: The .NET SRE throws an exception for instantiations of generic method builders
* Note that this stanza is not necessary for non-SRE types, but it's a micro-optimization
*/
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
if (method->dynamic || method->klass->image->dynamic)
return lookup_custom_attr (method->klass->image, method);
if (!method->token)
/* Synthetic methods */
return NULL;
idx = mono_method_get_index (method);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_METHODDEF;
return mono_custom_attrs_from_index (method->klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_class (MonoClass *klass)
{
guint32 idx;
if (klass->generic_class)
klass = klass->generic_class->container_class;
if (klass->image->dynamic)
return lookup_custom_attr (klass->image, klass);
if (klass->byval_arg.type == MONO_TYPE_VAR || klass->byval_arg.type == MONO_TYPE_MVAR) {
idx = mono_metadata_token_index (klass->sizes.generic_param_token);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_GENERICPAR;
} else {
idx = mono_metadata_token_index (klass->type_token);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_TYPEDEF;
}
return mono_custom_attrs_from_index (klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_assembly (MonoAssembly *assembly)
{
guint32 idx;
if (assembly->image->dynamic)
return lookup_custom_attr (assembly->image, assembly);
idx = 1; /* there is only one assembly */
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_ASSEMBLY;
return mono_custom_attrs_from_index (assembly->image, idx);
}
static MonoCustomAttrInfo*
mono_custom_attrs_from_module (MonoImage *image)
{
guint32 idx;
if (image->dynamic)
return lookup_custom_attr (image, image);
idx = 1; /* there is only one module */
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_MODULE;
return mono_custom_attrs_from_index (image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_property (MonoClass *klass, MonoProperty *property)
{
guint32 idx;
if (klass->image->dynamic) {
property = mono_metadata_get_corresponding_property_from_generic_type_definition (property);
return lookup_custom_attr (klass->image, property);
}
idx = find_property_index (klass, property);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_PROPERTY;
return mono_custom_attrs_from_index (klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_event (MonoClass *klass, MonoEvent *event)
{
guint32 idx;
if (klass->image->dynamic) {
event = mono_metadata_get_corresponding_event_from_generic_type_definition (event);
return lookup_custom_attr (klass->image, event);
}
idx = find_event_index (klass, event);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_EVENT;
return mono_custom_attrs_from_index (klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_field (MonoClass *klass, MonoClassField *field)
{
guint32 idx;
if (klass->image->dynamic) {
field = mono_metadata_get_corresponding_field_from_generic_type_definition (field);
return lookup_custom_attr (klass->image, field);
}
idx = find_field_index (klass, field);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_FIELDDEF;
return mono_custom_attrs_from_index (klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_param (MonoMethod *method, guint32 param)
{
MonoTableInfo *ca;
guint32 i, idx, method_index;
guint32 param_list, param_last, param_pos, found;
MonoImage *image;
MonoReflectionMethodAux *aux;
/*
* An instantiated method has the same cattrs as the generic method definition.
*
* LAMESPEC: The .NET SRE throws an exception for instantiations of generic method builders
* Note that this stanza is not necessary for non-SRE types, but it's a micro-optimization
*/
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
if (method->klass->image->dynamic) {
MonoCustomAttrInfo *res, *ainfo;
int size;
aux = g_hash_table_lookup (((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
if (!aux || !aux->param_cattr)
return NULL;
/* Need to copy since it will be freed later */
ainfo = aux->param_cattr [param];
if (!ainfo)
return NULL;
size = MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * ainfo->num_attrs;
res = g_malloc0 (size);
memcpy (res, ainfo, size);
return res;
}
image = method->klass->image;
method_index = mono_method_get_index (method);
if (!method_index)
return NULL;
ca = &image->tables [MONO_TABLE_METHOD];
param_list = mono_metadata_decode_row_col (ca, method_index - 1, MONO_METHOD_PARAMLIST);
if (method_index == ca->rows) {
ca = &image->tables [MONO_TABLE_PARAM];
param_last = ca->rows + 1;
} else {
param_last = mono_metadata_decode_row_col (ca, method_index, MONO_METHOD_PARAMLIST);
ca = &image->tables [MONO_TABLE_PARAM];
}
found = FALSE;
for (i = param_list; i < param_last; ++i) {
param_pos = mono_metadata_decode_row_col (ca, i - 1, MONO_PARAM_SEQUENCE);
if (param_pos == param) {
found = TRUE;
break;
}
}
if (!found)
return NULL;
idx = i;
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_PARAMDEF;
return mono_custom_attrs_from_index (image, idx);
}
gboolean
mono_custom_attrs_has_attr (MonoCustomAttrInfo *ainfo, MonoClass *attr_klass)
{
int i;
MonoClass *klass;
for (i = 0; i < ainfo->num_attrs; ++i) {
klass = ainfo->attrs [i].ctor->klass;
if (mono_class_has_parent (klass, attr_klass) || (MONO_CLASS_IS_INTERFACE (attr_klass) && mono_class_is_assignable_from (attr_klass, klass)))
return TRUE;
}
return FALSE;
}
MonoObject*
mono_custom_attrs_get_attr (MonoCustomAttrInfo *ainfo, MonoClass *attr_klass)
{
int i, attr_index;
MonoClass *klass;
MonoArray *attrs;
attr_index = -1;
for (i = 0; i < ainfo->num_attrs; ++i) {
klass = ainfo->attrs [i].ctor->klass;
if (mono_class_has_parent (klass, attr_klass)) {
attr_index = i;
break;
}
}
if (attr_index == -1)
return NULL;
attrs = mono_custom_attrs_construct (ainfo);
if (attrs)
return mono_array_get (attrs, MonoObject*, attr_index);
else
return NULL;
}
/*
* mono_reflection_get_custom_attrs_info:
* @obj: a reflection object handle
*
* Return the custom attribute info for attributes defined for the
* reflection handle @obj. The objects.
*
* FIXME this function leaks like a sieve for SRE objects.
*/
MonoCustomAttrInfo*
mono_reflection_get_custom_attrs_info (MonoObject *obj)
{
MonoClass *klass;
MonoCustomAttrInfo *cinfo = NULL;
klass = obj->vtable->klass;
if (klass == mono_defaults.monotype_class) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
klass = mono_class_from_mono_type (type);
/*We cannot mono_class_init the class from which we'll load the custom attributes since this must work with broken types.*/
cinfo = mono_custom_attrs_from_class (klass);
} else if (strcmp ("Assembly", klass->name) == 0 || strcmp ("MonoAssembly", klass->name) == 0) {
MonoReflectionAssembly *rassembly = (MonoReflectionAssembly*)obj;
cinfo = mono_custom_attrs_from_assembly (rassembly->assembly);
} else if (strcmp ("Module", klass->name) == 0 || strcmp ("MonoModule", klass->name) == 0) {
MonoReflectionModule *module = (MonoReflectionModule*)obj;
cinfo = mono_custom_attrs_from_module (module->image);
} else if (strcmp ("MonoProperty", klass->name) == 0) {
MonoReflectionProperty *rprop = (MonoReflectionProperty*)obj;
cinfo = mono_custom_attrs_from_property (rprop->property->parent, rprop->property);
} else if (strcmp ("MonoEvent", klass->name) == 0) {
MonoReflectionMonoEvent *revent = (MonoReflectionMonoEvent*)obj;
cinfo = mono_custom_attrs_from_event (revent->event->parent, revent->event);
} else if (strcmp ("MonoField", klass->name) == 0) {
MonoReflectionField *rfield = (MonoReflectionField*)obj;
cinfo = mono_custom_attrs_from_field (rfield->field->parent, rfield->field);
} else if ((strcmp ("MonoMethod", klass->name) == 0) || (strcmp ("MonoCMethod", klass->name) == 0)) {
MonoReflectionMethod *rmethod = (MonoReflectionMethod*)obj;
cinfo = mono_custom_attrs_from_method (rmethod->method);
} else if ((strcmp ("MonoGenericMethod", klass->name) == 0) || (strcmp ("MonoGenericCMethod", klass->name) == 0)) {
MonoReflectionMethod *rmethod = (MonoReflectionMethod*)obj;
cinfo = mono_custom_attrs_from_method (rmethod->method);
} else if (strcmp ("ParameterInfo", klass->name) == 0) {
MonoReflectionParameter *param = (MonoReflectionParameter*)obj;
MonoClass *member_class = mono_object_class (param->MemberImpl);
if (mono_class_is_reflection_method_or_constructor (member_class)) {
MonoReflectionMethod *rmethod = (MonoReflectionMethod*)param->MemberImpl;
cinfo = mono_custom_attrs_from_param (rmethod->method, param->PositionImpl + 1);
} else if (is_sr_mono_property (member_class)) {
MonoReflectionProperty *prop = (MonoReflectionProperty *)param->MemberImpl;
MonoMethod *method;
if (!(method = prop->property->get))
method = prop->property->set;
g_assert (method);
cinfo = mono_custom_attrs_from_param (method, param->PositionImpl + 1);
}
#ifndef DISABLE_REFLECTION_EMIT
else if (is_sre_method_on_tb_inst (member_class)) {/*XXX This is a workaround for Compiler Context*/
MonoMethod *method = mono_reflection_method_on_tb_inst_get_handle ((MonoReflectionMethodOnTypeBuilderInst*)param->MemberImpl);
cinfo = mono_custom_attrs_from_param (method, param->PositionImpl + 1);
} else if (is_sre_ctor_on_tb_inst (member_class)) { /*XX This is a workaround for Compiler Context*/
MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)param->MemberImpl;
MonoMethod *method = NULL;
if (is_sre_ctor_builder (mono_object_class (c->cb)))
method = ((MonoReflectionCtorBuilder *)c->cb)->mhandle;
else if (is_sr_mono_cmethod (mono_object_class (c->cb)))
method = ((MonoReflectionMethod *)c->cb)->method;
else
g_error ("mono_reflection_get_custom_attrs_info:: can't handle a CTBI with base_method of type %s", mono_type_get_full_name (member_class));
cinfo = mono_custom_attrs_from_param (method, param->PositionImpl + 1);
}
#endif
else {
char *type_name = mono_type_get_full_name (member_class);
char *msg = g_strdup_printf ("Custom attributes on a ParamInfo with member %s are not supported", type_name);
MonoException *ex = mono_get_exception_not_supported (msg);
g_free (type_name);
g_free (msg);
mono_raise_exception (ex);
}
} else if (strcmp ("AssemblyBuilder", klass->name) == 0) {
MonoReflectionAssemblyBuilder *assemblyb = (MonoReflectionAssemblyBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, assemblyb->assembly.assembly->image, assemblyb->cattrs);
} else if (strcmp ("TypeBuilder", klass->name) == 0) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, &tb->module->dynamic_image->image, tb->cattrs);
} else if (strcmp ("ModuleBuilder", klass->name) == 0) {
MonoReflectionModuleBuilder *mb = (MonoReflectionModuleBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, &mb->dynamic_image->image, mb->cattrs);
} else if (strcmp ("ConstructorBuilder", klass->name) == 0) {
MonoReflectionCtorBuilder *cb = (MonoReflectionCtorBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, cb->mhandle->klass->image, cb->cattrs);
} else if (strcmp ("MethodBuilder", klass->name) == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, mb->mhandle->klass->image, mb->cattrs);
} else if (strcmp ("FieldBuilder", klass->name) == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, &((MonoReflectionTypeBuilder*)fb->typeb)->module->dynamic_image->image, fb->cattrs);
} else if (strcmp ("MonoGenericClass", klass->name) == 0) {
MonoReflectionGenericClass *gclass = (MonoReflectionGenericClass*)obj;
cinfo = mono_reflection_get_custom_attrs_info ((MonoObject*)gclass->generic_type);
} else { /* handle other types here... */
g_error ("get custom attrs not yet supported for %s", klass->name);
}
return cinfo;
}
/*
* mono_reflection_get_custom_attrs_by_type:
* @obj: a reflection object handle
*
* Return an array with all the custom attributes defined of the
* reflection handle @obj. If @attr_klass is non-NULL, only custom attributes
* of that type are returned. The objects are fully build. Return NULL if a loading error
* occurs.
*/
MonoArray*
mono_reflection_get_custom_attrs_by_type (MonoObject *obj, MonoClass *attr_klass)
{
MonoArray *result;
MonoCustomAttrInfo *cinfo;
cinfo = mono_reflection_get_custom_attrs_info (obj);
if (cinfo) {
if (attr_klass)
result = mono_custom_attrs_construct_by_type (cinfo, attr_klass);
else
result = mono_custom_attrs_construct (cinfo);
if (!cinfo->cached)
mono_custom_attrs_free (cinfo);
} else {
if (mono_loader_get_last_error ())
return NULL;
result = mono_array_new_cached (mono_domain_get (), mono_defaults.attribute_class, 0);
}
return result;
}
/*
* mono_reflection_get_custom_attrs:
* @obj: a reflection object handle
*
* Return an array with all the custom attributes defined of the
* reflection handle @obj. The objects are fully build. Return NULL if a loading error
* occurs.
*/
MonoArray*
mono_reflection_get_custom_attrs (MonoObject *obj)
{
return mono_reflection_get_custom_attrs_by_type (obj, NULL);
}
/*
* mono_reflection_get_custom_attrs_data:
* @obj: a reflection obj handle
*
* Returns an array of System.Reflection.CustomAttributeData,
* which include information about attributes reflected on
* types loaded using the Reflection Only methods
*/
MonoArray*
mono_reflection_get_custom_attrs_data (MonoObject *obj)
{
MonoArray *result;
MonoCustomAttrInfo *cinfo;
cinfo = mono_reflection_get_custom_attrs_info (obj);
if (cinfo) {
result = mono_custom_attrs_data_construct (cinfo);
if (!cinfo->cached)
mono_custom_attrs_free (cinfo);
} else
result = mono_array_new (mono_domain_get (), mono_defaults.customattribute_data_class, 0);
return result;
}
static MonoReflectionType*
mono_reflection_type_get_underlying_system_type (MonoReflectionType* t)
{
static MonoMethod *method_get_underlying_system_type = NULL;
MonoMethod *usertype_method;
if (!method_get_underlying_system_type)
method_get_underlying_system_type = mono_class_get_method_from_name (mono_defaults.systemtype_class, "get_UnderlyingSystemType", 0);
usertype_method = mono_object_get_virtual_method ((MonoObject *) t, method_get_underlying_system_type);
return (MonoReflectionType *) mono_runtime_invoke (usertype_method, t, NULL, NULL);
}
static gboolean
is_corlib_type (MonoClass *class)
{
return class->image == mono_defaults.corlib;
}
#define check_corlib_type_cached(_class, _namespace, _name) do { \
static MonoClass *cached_class; \
if (cached_class) \
return cached_class == _class; \
if (is_corlib_type (_class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
cached_class = _class; \
return TRUE; \
} \
return FALSE; \
} while (0) \
#ifndef DISABLE_REFLECTION_EMIT
static gboolean
is_sre_array (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "ArrayType");
}
static gboolean
is_sre_byref (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "ByRefType");
}
static gboolean
is_sre_pointer (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "PointerType");
}
static gboolean
is_sre_generic_instance (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoGenericClass");
}
static gboolean
is_sre_type_builder (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "TypeBuilder");
}
static gboolean
is_sre_method_builder (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "MethodBuilder");
}
static gboolean
is_sre_ctor_builder (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "ConstructorBuilder");
}
static gboolean
is_sre_field_builder (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "FieldBuilder");
}
static gboolean
is_sre_method_on_tb_inst (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "MethodOnTypeBuilderInst");
}
static gboolean
is_sre_ctor_on_tb_inst (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "ConstructorOnTypeBuilderInst");
}
MonoType*
mono_reflection_type_get_handle (MonoReflectionType* ref)
{
MonoClass *class;
if (!ref)
return NULL;
if (ref->type)
return ref->type;
if (is_usertype (ref)) {
ref = mono_reflection_type_get_underlying_system_type (ref);
if (ref == NULL || is_usertype (ref))
return NULL;
if (ref->type)
return ref->type;
}
class = mono_object_class (ref);
if (is_sre_array (class)) {
MonoType *res;
MonoReflectionArrayType *sre_array = (MonoReflectionArrayType*)ref;
MonoType *base = mono_reflection_type_get_handle (sre_array->element_type);
g_assert (base);
if (sre_array->rank == 0) //single dimentional array
res = &mono_array_class_get (mono_class_from_mono_type (base), 1)->byval_arg;
else
res = &mono_bounded_array_class_get (mono_class_from_mono_type (base), sre_array->rank, TRUE)->byval_arg;
sre_array->type.type = res;
return res;
} else if (is_sre_byref (class)) {
MonoType *res;
MonoReflectionDerivedType *sre_byref = (MonoReflectionDerivedType*)ref;
MonoType *base = mono_reflection_type_get_handle (sre_byref->element_type);
g_assert (base);
res = &mono_class_from_mono_type (base)->this_arg;
sre_byref->type.type = res;
return res;
} else if (is_sre_pointer (class)) {
MonoType *res;
MonoReflectionDerivedType *sre_pointer = (MonoReflectionDerivedType*)ref;
MonoType *base = mono_reflection_type_get_handle (sre_pointer->element_type);
g_assert (base);
res = &mono_ptr_class_get (base)->byval_arg;
sre_pointer->type.type = res;
return res;
} else if (is_sre_generic_instance (class)) {
MonoType *res, **types;
MonoReflectionGenericClass *gclass = (MonoReflectionGenericClass*)ref;
int i, count;
count = mono_array_length (gclass->type_arguments);
types = g_new0 (MonoType*, count);
for (i = 0; i < count; ++i) {
MonoReflectionType *t = mono_array_get (gclass->type_arguments, gpointer, i);
types [i] = mono_reflection_type_get_handle (t);
if (!types[i]) {
g_free (types);
return NULL;
}
}
res = mono_reflection_bind_generic_parameters (gclass->generic_type, count, types);
g_free (types);
g_assert (res);
gclass->type.type = res;
return res;
}
g_error ("Cannot handle corlib user type %s", mono_type_full_name (&mono_object_class(ref)->byval_arg));
return NULL;
}
void
mono_reflection_create_unmanaged_type (MonoReflectionType *type)
{
mono_reflection_type_get_handle (type);
}
void
mono_reflection_register_with_runtime (MonoReflectionType *type)
{
MonoType *res = mono_reflection_type_get_handle (type);
MonoDomain *domain = mono_object_domain ((MonoObject*)type);
MonoClass *class;
if (!res)
mono_raise_exception (mono_get_exception_argument (NULL, "Invalid generic instantiation, one or more arguments are not proper user types"));
class = mono_class_from_mono_type (res);
mono_loader_lock (); /*same locking as mono_type_get_object*/
mono_domain_lock (domain);
if (!class->image->dynamic) {
mono_class_setup_supertypes (class);
} else {
if (!domain->type_hash)
domain->type_hash = mono_g_hash_table_new_type ((GHashFunc)mymono_metadata_type_hash,
(GCompareFunc)mymono_metadata_type_equal, MONO_HASH_VALUE_GC);
mono_g_hash_table_insert (domain->type_hash, res, type);
}
mono_domain_unlock (domain);
mono_loader_unlock ();
}
/**
* LOCKING: Assumes the loader lock is held.
*/
static MonoMethodSignature*
parameters_to_signature (MonoImage *image, MonoArray *parameters) {
MonoMethodSignature *sig;
int count, i;
count = parameters? mono_array_length (parameters): 0;
sig = image_g_malloc0 (image, MONO_SIZEOF_METHOD_SIGNATURE + sizeof (MonoType*) * count);
sig->param_count = count;
sig->sentinelpos = -1; /* FIXME */
for (i = 0; i < count; ++i)
sig->params [i] = mono_type_array_get_and_resolve (parameters, i);
return sig;
}
/**
* LOCKING: Assumes the loader lock is held.
*/
static MonoMethodSignature*
ctor_builder_to_signature (MonoImage *image, MonoReflectionCtorBuilder *ctor) {
MonoMethodSignature *sig;
sig = parameters_to_signature (image, ctor->parameters);
sig->hasthis = ctor->attrs & METHOD_ATTRIBUTE_STATIC? 0: 1;
sig->ret = &mono_defaults.void_class->byval_arg;
return sig;
}
/**
* LOCKING: Assumes the loader lock is held.
*/
static MonoMethodSignature*
method_builder_to_signature (MonoImage *image, MonoReflectionMethodBuilder *method) {
MonoMethodSignature *sig;
sig = parameters_to_signature (image, method->parameters);
sig->hasthis = method->attrs & METHOD_ATTRIBUTE_STATIC? 0: 1;
sig->ret = method->rtype? mono_reflection_type_get_handle ((MonoReflectionType*)method->rtype): &mono_defaults.void_class->byval_arg;
sig->generic_param_count = method->generic_params ? mono_array_length (method->generic_params) : 0;
return sig;
}
static MonoMethodSignature*
dynamic_method_to_signature (MonoReflectionDynamicMethod *method) {
MonoMethodSignature *sig;
sig = parameters_to_signature (NULL, method->parameters);
sig->hasthis = method->attrs & METHOD_ATTRIBUTE_STATIC? 0: 1;
sig->ret = method->rtype? mono_reflection_type_get_handle (method->rtype): &mono_defaults.void_class->byval_arg;
sig->generic_param_count = 0;
return sig;
}
static void
get_prop_name_and_type (MonoObject *prop, char **name, MonoType **type)
{
MonoClass *klass = mono_object_class (prop);
if (strcmp (klass->name, "PropertyBuilder") == 0) {
MonoReflectionPropertyBuilder *pb = (MonoReflectionPropertyBuilder *)prop;
*name = mono_string_to_utf8 (pb->name);
*type = mono_reflection_type_get_handle ((MonoReflectionType*)pb->type);
} else {
MonoReflectionProperty *p = (MonoReflectionProperty *)prop;
*name = g_strdup (p->property->name);
if (p->property->get)
*type = mono_method_signature (p->property->get)->ret;
else
*type = mono_method_signature (p->property->set)->params [mono_method_signature (p->property->set)->param_count - 1];
}
}
static void
get_field_name_and_type (MonoObject *field, char **name, MonoType **type)
{
MonoClass *klass = mono_object_class (field);
if (strcmp (klass->name, "FieldBuilder") == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)field;
*name = mono_string_to_utf8 (fb->name);
*type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
} else {
MonoReflectionField *f = (MonoReflectionField *)field;
*name = g_strdup (mono_field_get_name (f->field));
*type = f->field->type;
}
}
#else /* DISABLE_REFLECTION_EMIT */
void
mono_reflection_register_with_runtime (MonoReflectionType *type)
{
/* This is empty */
}
static gboolean
is_sre_type_builder (MonoClass *class)
{
return FALSE;
}
static gboolean
is_sre_generic_instance (MonoClass *class)
{
return FALSE;
}
static void
init_type_builder_generics (MonoObject *type)
{
}
#endif /* !DISABLE_REFLECTION_EMIT */
static gboolean
is_sr_mono_field (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoField");
}
static gboolean
is_sr_mono_property (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoProperty");
}
static gboolean
is_sr_mono_method (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoMethod");
}
static gboolean
is_sr_mono_cmethod (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoCMethod");
}
static gboolean
is_sr_mono_generic_method (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoGenericMethod");
}
static gboolean
is_sr_mono_generic_cmethod (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoGenericCMethod");
}
gboolean
mono_class_is_reflection_method_or_constructor (MonoClass *class)
{
return is_sr_mono_method (class) || is_sr_mono_cmethod (class) || is_sr_mono_generic_method (class) || is_sr_mono_generic_cmethod (class);
}
static gboolean
is_usertype (MonoReflectionType *ref)
{
MonoClass *class = mono_object_class (ref);
return class->image != mono_defaults.corlib || strcmp ("TypeDelegator", class->name) == 0;
}
static MonoReflectionType*
mono_reflection_type_resolve_user_types (MonoReflectionType *type)
{
if (!type || type->type)
return type;
if (is_usertype (type)) {
type = mono_reflection_type_get_underlying_system_type (type);
if (is_usertype (type))
mono_raise_exception (mono_get_exception_not_supported ("User defined subclasses of System.Type are not yet supported22"));
}
return type;
}
/*
* Encode a value in a custom attribute stream of bytes.
* The value to encode is either supplied as an object in argument val
* (valuetypes are boxed), or as a pointer to the data in the
* argument argval.
* @type represents the type of the value
* @buffer is the start of the buffer
* @p the current position in the buffer
* @buflen contains the size of the buffer and is used to return the new buffer size
* if this needs to be realloced.
* @retbuffer and @retp return the start and the position of the buffer
*/
static void
encode_cattr_value (MonoAssembly *assembly, char *buffer, char *p, char **retbuffer, char **retp, guint32 *buflen, MonoType *type, MonoObject *arg, char *argval)
{
MonoTypeEnum simple_type;
if ((p-buffer) + 10 >= *buflen) {
char *newbuf;
*buflen *= 2;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
if (!argval)
argval = ((char*)arg + sizeof (MonoObject));
simple_type = type->type;
handle_enum:
switch (simple_type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_U1:
case MONO_TYPE_I1:
*p++ = *argval;
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
swap_with_size (p, argval, 2, 1);
p += 2;
break;
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_R4:
swap_with_size (p, argval, 4, 1);
p += 4;
break;
case MONO_TYPE_R8:
#if defined(ARM_FPU_FPA) && G_BYTE_ORDER == G_LITTLE_ENDIAN
p [0] = argval [4];
p [1] = argval [5];
p [2] = argval [6];
p [3] = argval [7];
p [4] = argval [0];
p [5] = argval [1];
p [6] = argval [2];
p [7] = argval [3];
#else
swap_with_size (p, argval, 8, 1);
#endif
p += 8;
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
swap_with_size (p, argval, 8, 1);
p += 8;
break;
case MONO_TYPE_VALUETYPE:
if (type->data.klass->enumtype) {
simple_type = mono_class_enum_basetype (type->data.klass)->type;
goto handle_enum;
} else {
g_warning ("generic valutype %s not handled in custom attr value decoding", type->data.klass->name);
}
break;
case MONO_TYPE_STRING: {
char *str;
guint32 slen;
if (!arg) {
*p++ = 0xFF;
break;
}
str = mono_string_to_utf8 ((MonoString*)arg);
slen = strlen (str);
if ((p-buffer) + 10 + slen >= *buflen) {
char *newbuf;
*buflen *= 2;
*buflen += slen;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
mono_metadata_encode_value (slen, p, &p);
memcpy (p, str, slen);
p += slen;
g_free (str);
break;
}
case MONO_TYPE_CLASS: {
char *str;
guint32 slen;
if (!arg) {
*p++ = 0xFF;
break;
}
handle_type:
str = type_get_qualified_name (mono_reflection_type_get_handle ((MonoReflectionType*)arg), NULL);
slen = strlen (str);
if ((p-buffer) + 10 + slen >= *buflen) {
char *newbuf;
*buflen *= 2;
*buflen += slen;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
mono_metadata_encode_value (slen, p, &p);
memcpy (p, str, slen);
p += slen;
g_free (str);
break;
}
case MONO_TYPE_SZARRAY: {
int len, i;
MonoClass *eclass, *arg_eclass;
if (!arg) {
*p++ = 0xff; *p++ = 0xff; *p++ = 0xff; *p++ = 0xff;
break;
}
len = mono_array_length ((MonoArray*)arg);
*p++ = len & 0xff;
*p++ = (len >> 8) & 0xff;
*p++ = (len >> 16) & 0xff;
*p++ = (len >> 24) & 0xff;
*retp = p;
*retbuffer = buffer;
eclass = type->data.klass;
arg_eclass = mono_object_class (arg)->element_class;
if (!eclass) {
/* Happens when we are called from the MONO_TYPE_OBJECT case below */
eclass = mono_defaults.object_class;
}
if (eclass == mono_defaults.object_class && arg_eclass->valuetype) {
char *elptr = mono_array_addr ((MonoArray*)arg, char, 0);
int elsize = mono_class_array_element_size (arg_eclass);
for (i = 0; i < len; ++i) {
encode_cattr_value (assembly, buffer, p, &buffer, &p, buflen, &arg_eclass->byval_arg, NULL, elptr);
elptr += elsize;
}
} else if (eclass->valuetype && arg_eclass->valuetype) {
char *elptr = mono_array_addr ((MonoArray*)arg, char, 0);
int elsize = mono_class_array_element_size (eclass);
for (i = 0; i < len; ++i) {
encode_cattr_value (assembly, buffer, p, &buffer, &p, buflen, &eclass->byval_arg, NULL, elptr);
elptr += elsize;
}
} else {
for (i = 0; i < len; ++i) {
encode_cattr_value (assembly, buffer, p, &buffer, &p, buflen, &eclass->byval_arg, mono_array_get ((MonoArray*)arg, MonoObject*, i), NULL);
}
}
break;
}
case MONO_TYPE_OBJECT: {
MonoClass *klass;
char *str;
guint32 slen;
/*
* The parameter type is 'object' but the type of the actual
* argument is not. So we have to add type information to the blob
* too. This is completely undocumented in the spec.
*/
if (arg == NULL) {
*p++ = MONO_TYPE_STRING; // It's same hack as MS uses
*p++ = 0xFF;
break;
}
klass = mono_object_class (arg);
if (mono_object_isinst (arg, mono_defaults.systemtype_class)) {
*p++ = 0x50;
goto handle_type;
} else if (klass->enumtype) {
*p++ = 0x55;
} else if (klass == mono_defaults.string_class) {
simple_type = MONO_TYPE_STRING;
*p++ = 0x0E;
goto handle_enum;
} else if (klass->rank == 1) {
*p++ = 0x1D;
if (klass->element_class->byval_arg.type == MONO_TYPE_OBJECT)
/* See Partition II, Appendix B3 */
*p++ = 0x51;
else
*p++ = klass->element_class->byval_arg.type;
encode_cattr_value (assembly, buffer, p, &buffer, &p, buflen, &klass->byval_arg, arg, NULL);
break;
} else if (klass->byval_arg.type >= MONO_TYPE_BOOLEAN && klass->byval_arg.type <= MONO_TYPE_R8) {
*p++ = simple_type = klass->byval_arg.type;
goto handle_enum;
} else {
g_error ("unhandled type in custom attr");
}
str = type_get_qualified_name (mono_class_get_type(klass), NULL);
slen = strlen (str);
if ((p-buffer) + 10 + slen >= *buflen) {
char *newbuf;
*buflen *= 2;
*buflen += slen;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
mono_metadata_encode_value (slen, p, &p);
memcpy (p, str, slen);
p += slen;
g_free (str);
simple_type = mono_class_enum_basetype (klass)->type;
goto handle_enum;
}
default:
g_error ("type 0x%02x not yet supported in custom attr encoder", simple_type);
}
*retp = p;
*retbuffer = buffer;
}
static void
encode_field_or_prop_type (MonoType *type, char *p, char **retp)
{
if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype) {
char *str = type_get_qualified_name (type, NULL);
int slen = strlen (str);
*p++ = 0x55;
/*
* This seems to be optional...
* *p++ = 0x80;
*/
mono_metadata_encode_value (slen, p, &p);
memcpy (p, str, slen);
p += slen;
g_free (str);
} else if (type->type == MONO_TYPE_OBJECT) {
*p++ = 0x51;
} else if (type->type == MONO_TYPE_CLASS) {
/* it should be a type: encode_cattr_value () has the check */
*p++ = 0x50;
} else {
mono_metadata_encode_value (type->type, p, &p);
if (type->type == MONO_TYPE_SZARRAY)
/* See the examples in Partition VI, Annex B */
encode_field_or_prop_type (&type->data.klass->byval_arg, p, &p);
}
*retp = p;
}
#ifndef DISABLE_REFLECTION_EMIT
static void
encode_named_val (MonoReflectionAssembly *assembly, char *buffer, char *p, char **retbuffer, char **retp, guint32 *buflen, MonoType *type, char *name, MonoObject *value)
{
int len;
/* Preallocate a large enough buffer */
if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype) {
char *str = type_get_qualified_name (type, NULL);
len = strlen (str);
g_free (str);
} else if (type->type == MONO_TYPE_SZARRAY && type->data.klass->enumtype) {
char *str = type_get_qualified_name (&type->data.klass->byval_arg, NULL);
len = strlen (str);
g_free (str);
} else {
len = 0;
}
len += strlen (name);
if ((p-buffer) + 20 + len >= *buflen) {
char *newbuf;
*buflen *= 2;
*buflen += len;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
encode_field_or_prop_type (type, p, &p);
len = strlen (name);
mono_metadata_encode_value (len, p, &p);
memcpy (p, name, len);
p += len;
encode_cattr_value (assembly->assembly, buffer, p, &buffer, &p, buflen, type, value, NULL);
*retp = p;
*retbuffer = buffer;
}
/*
* mono_reflection_get_custom_attrs_blob:
* @ctor: custom attribute constructor
* @ctorArgs: arguments o the constructor
* @properties:
* @propValues:
* @fields:
* @fieldValues:
*
* Creates the blob of data that needs to be saved in the metadata and that represents
* the custom attributed described by @ctor, @ctorArgs etc.
* Returns: a Byte array representing the blob of data.
*/
MonoArray*
mono_reflection_get_custom_attrs_blob (MonoReflectionAssembly *assembly, MonoObject *ctor, MonoArray *ctorArgs, MonoArray *properties, MonoArray *propValues, MonoArray *fields, MonoArray* fieldValues)
{
MonoArray *result;
MonoMethodSignature *sig;
MonoObject *arg;
char *buffer, *p;
guint32 buflen, i;
MONO_ARCH_SAVE_REGS;
if (strcmp (ctor->vtable->klass->name, "MonoCMethod")) {
/* sig is freed later so allocate it in the heap */
sig = ctor_builder_to_signature (NULL, (MonoReflectionCtorBuilder*)ctor);
} else {
sig = mono_method_signature (((MonoReflectionMethod*)ctor)->method);
}
g_assert (mono_array_length (ctorArgs) == sig->param_count);
buflen = 256;
p = buffer = g_malloc (buflen);
/* write the prolog */
*p++ = 1;
*p++ = 0;
for (i = 0; i < sig->param_count; ++i) {
arg = mono_array_get (ctorArgs, MonoObject*, i);
encode_cattr_value (assembly->assembly, buffer, p, &buffer, &p, &buflen, sig->params [i], arg, NULL);
}
i = 0;
if (properties)
i += mono_array_length (properties);
if (fields)
i += mono_array_length (fields);
*p++ = i & 0xff;
*p++ = (i >> 8) & 0xff;
if (properties) {
MonoObject *prop;
for (i = 0; i < mono_array_length (properties); ++i) {
MonoType *ptype;
char *pname;
prop = mono_array_get (properties, gpointer, i);
get_prop_name_and_type (prop, &pname, &ptype);
*p++ = 0x54; /* PROPERTY signature */
encode_named_val (assembly, buffer, p, &buffer, &p, &buflen, ptype, pname, (MonoObject*)mono_array_get (propValues, gpointer, i));
g_free (pname);
}
}
if (fields) {
MonoObject *field;
for (i = 0; i < mono_array_length (fields); ++i) {
MonoType *ftype;
char *fname;
field = mono_array_get (fields, gpointer, i);
get_field_name_and_type (field, &fname, &ftype);
*p++ = 0x53; /* FIELD signature */
encode_named_val (assembly, buffer, p, &buffer, &p, &buflen, ftype, fname, (MonoObject*)mono_array_get (fieldValues, gpointer, i));
g_free (fname);
}
}
g_assert (p - buffer <= buflen);
buflen = p - buffer;
result = mono_array_new (mono_domain_get (), mono_defaults.byte_class, buflen);
p = mono_array_addr (result, char, 0);
memcpy (p, buffer, buflen);
g_free (buffer);
if (strcmp (ctor->vtable->klass->name, "MonoCMethod"))
g_free (sig);
return result;
}
/*
* mono_reflection_setup_internal_class:
* @tb: a TypeBuilder object
*
* Creates a MonoClass that represents the TypeBuilder.
* This is a trick that lets us simplify a lot of reflection code
* (and will allow us to support Build and Run assemblies easier).
*/
void
mono_reflection_setup_internal_class (MonoReflectionTypeBuilder *tb)
{
MonoError error;
MonoClass *klass, *parent;
MONO_ARCH_SAVE_REGS;
RESOLVE_TYPE (tb->parent);
mono_loader_lock ();
if (tb->parent) {
/* check so we can compile corlib correctly */
if (strcmp (mono_object_class (tb->parent)->name, "TypeBuilder") == 0) {
/* mono_class_setup_mono_type () guaranteess type->data.klass is valid */
parent = mono_reflection_type_get_handle ((MonoReflectionType*)tb->parent)->data.klass;
} else {
parent = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb->parent));
}
} else {
parent = NULL;
}
/* the type has already being created: it means we just have to change the parent */
if (tb->type.type) {
klass = mono_class_from_mono_type (tb->type.type);
klass->parent = NULL;
/* fool mono_class_setup_parent */
klass->supertypes = NULL;
mono_class_setup_parent (klass, parent);
mono_class_setup_mono_type (klass);
mono_loader_unlock ();
return;
}
klass = mono_image_alloc0 (&tb->module->dynamic_image->image, sizeof (MonoClass));
klass->image = &tb->module->dynamic_image->image;
klass->inited = 1; /* we lie to the runtime */
klass->name = mono_string_to_utf8_image (klass->image, tb->name, &error);
if (!mono_error_ok (&error))
goto failure;
klass->name_space = mono_string_to_utf8_image (klass->image, tb->nspace, &error);
if (!mono_error_ok (&error))
goto failure;
klass->type_token = MONO_TOKEN_TYPE_DEF | tb->table_idx;
klass->flags = tb->attrs;
mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
klass->element_class = klass;
if (mono_class_get_ref_info (klass) == NULL) {
mono_class_set_ref_info (klass, tb);
/* Put into cache so mono_class_get () will find it.
Skip nested types as those should not be available on the global scope. */
if (!tb->nesting_type) {
mono_image_add_to_name_cache (klass->image, klass->name_space, klass->name, tb->table_idx);
} else {
klass->image->reflection_info_unregister_classes =
g_slist_prepend (klass->image->reflection_info_unregister_classes, klass);
}
} else {
g_assert (mono_class_get_ref_info (klass) == tb);
}
mono_g_hash_table_insert (tb->module->dynamic_image->tokens,
GUINT_TO_POINTER (MONO_TOKEN_TYPE_DEF | tb->table_idx), tb);
if (parent != NULL) {
mono_class_setup_parent (klass, parent);
} else if (strcmp (klass->name, "Object") == 0 && strcmp (klass->name_space, "System") == 0) {
const char *old_n = klass->name;
/* trick to get relative numbering right when compiling corlib */
klass->name = "BuildingObject";
mono_class_setup_parent (klass, mono_defaults.object_class);
klass->name = old_n;
}
if ((!strcmp (klass->name, "ValueType") && !strcmp (klass->name_space, "System")) ||
(!strcmp (klass->name, "Object") && !strcmp (klass->name_space, "System")) ||
(!strcmp (klass->name, "Enum") && !strcmp (klass->name_space, "System"))) {
klass->instance_size = sizeof (MonoObject);
klass->size_inited = 1;
mono_class_setup_vtable_general (klass, NULL, 0, NULL);
}
mono_class_setup_mono_type (klass);
mono_class_setup_supertypes (klass);
/*
* FIXME: handle interfaces.
*/
tb->type.type = &klass->byval_arg;
if (tb->nesting_type) {
g_assert (tb->nesting_type->type);
klass->nested_in = mono_class_from_mono_type (mono_reflection_type_get_handle (tb->nesting_type));
}
/*g_print ("setup %s as %s (%p)\n", klass->name, ((MonoObject*)tb)->vtable->klass->name, tb);*/
mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
mono_loader_unlock ();
return;
failure:
mono_loader_unlock ();
mono_error_raise_exception (&error);
}
/*
* mono_reflection_setup_generic_class:
* @tb: a TypeBuilder object
*
* Setup the generic class before adding the first generic parameter.
*/
void
mono_reflection_setup_generic_class (MonoReflectionTypeBuilder *tb)
{
}
/*
* mono_reflection_create_generic_class:
* @tb: a TypeBuilder object
*
* Creates the generic class after all generic parameters have been added.
*/
void
mono_reflection_create_generic_class (MonoReflectionTypeBuilder *tb)
{
MonoClass *klass;
int count, i;
MONO_ARCH_SAVE_REGS;
klass = mono_class_from_mono_type (tb->type.type);
count = tb->generic_params ? mono_array_length (tb->generic_params) : 0;
if (klass->generic_container || (count == 0))
return;
g_assert (tb->generic_container && (tb->generic_container->owner.klass == klass));
klass->generic_container = mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
klass->generic_container->owner.klass = klass;
klass->generic_container->type_argc = count;
klass->generic_container->type_params = mono_image_alloc0 (klass->image, sizeof (MonoGenericParamFull) * count);
klass->is_generic = 1;
for (i = 0; i < count; i++) {
MonoReflectionGenericParam *gparam = mono_array_get (tb->generic_params, gpointer, i);
MonoGenericParamFull *param = (MonoGenericParamFull *) mono_reflection_type_get_handle ((MonoReflectionType*)gparam)->data.generic_param;
klass->generic_container->type_params [i] = *param;
/*Make sure we are a diferent type instance */
klass->generic_container->type_params [i].param.owner = klass->generic_container;
klass->generic_container->type_params [i].info.pklass = NULL;
klass->generic_container->type_params [i].info.flags = gparam->attrs;
g_assert (klass->generic_container->type_params [i].param.owner);
}
klass->generic_container->context.class_inst = mono_get_shared_generic_inst (klass->generic_container);
}
/*
* mono_reflection_create_internal_class:
* @tb: a TypeBuilder object
*
* Actually create the MonoClass that is associated with the TypeBuilder.
*/
void
mono_reflection_create_internal_class (MonoReflectionTypeBuilder *tb)
{
MonoClass *klass;
MONO_ARCH_SAVE_REGS;
klass = mono_class_from_mono_type (tb->type.type);
mono_loader_lock ();
if (klass->enumtype && mono_class_enum_basetype (klass) == NULL) {
MonoReflectionFieldBuilder *fb;
MonoClass *ec;
MonoType *enum_basetype;
g_assert (tb->fields != NULL);
g_assert (mono_array_length (tb->fields) >= 1);
fb = mono_array_get (tb->fields, MonoReflectionFieldBuilder*, 0);
if (!mono_type_is_valid_enum_basetype (mono_reflection_type_get_handle ((MonoReflectionType*)fb->type))) {
mono_loader_unlock ();
return;
}
enum_basetype = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
klass->element_class = mono_class_from_mono_type (enum_basetype);
if (!klass->element_class)
klass->element_class = mono_class_from_mono_type (enum_basetype);
/*
* get the element_class from the current corlib.
*/
ec = default_class_from_mono_type (enum_basetype);
klass->instance_size = ec->instance_size;
klass->size_inited = 1;
/*
* this is almost safe to do with enums and it's needed to be able
* to create objects of the enum type (for use in SetConstant).
*/
/* FIXME: Does this mean enums can't have method overrides ? */
mono_class_setup_vtable_general (klass, NULL, 0, NULL);
}
mono_loader_unlock ();
}
static MonoMarshalSpec*
mono_marshal_spec_from_builder (MonoImage *image, MonoAssembly *assembly,
MonoReflectionMarshal *minfo)
{
MonoMarshalSpec *res;
res = image_g_new0 (image, MonoMarshalSpec, 1);
res->native = minfo->type;
switch (minfo->type) {
case MONO_NATIVE_LPARRAY:
res->data.array_data.elem_type = minfo->eltype;
if (minfo->has_size) {
res->data.array_data.param_num = minfo->param_num;
res->data.array_data.num_elem = minfo->count;
res->data.array_data.elem_mult = minfo->param_num == -1 ? 0 : 1;
}
else {
res->data.array_data.param_num = -1;
res->data.array_data.num_elem = -1;
res->data.array_data.elem_mult = -1;
}
break;
case MONO_NATIVE_BYVALTSTR:
case MONO_NATIVE_BYVALARRAY:
res->data.array_data.num_elem = minfo->count;
break;
case MONO_NATIVE_CUSTOM:
if (minfo->marshaltyperef)
res->data.custom_data.custom_name =
type_get_fully_qualified_name (mono_reflection_type_get_handle ((MonoReflectionType*)minfo->marshaltyperef));
if (minfo->mcookie)
res->data.custom_data.cookie = mono_string_to_utf8 (minfo->mcookie);
break;
default:
break;
}
return res;
}
#endif /* !DISABLE_REFLECTION_EMIT */
MonoReflectionMarshal*
mono_reflection_marshal_from_marshal_spec (MonoDomain *domain, MonoClass *klass,
MonoMarshalSpec *spec)
{
static MonoClass *System_Reflection_Emit_UnmanagedMarshalClass;
MonoReflectionMarshal *minfo;
MonoType *mtype;
if (!System_Reflection_Emit_UnmanagedMarshalClass) {
System_Reflection_Emit_UnmanagedMarshalClass = mono_class_from_name (
mono_defaults.corlib, "System.Reflection.Emit", "UnmanagedMarshal");
g_assert (System_Reflection_Emit_UnmanagedMarshalClass);
}
minfo = (MonoReflectionMarshal*)mono_object_new (domain, System_Reflection_Emit_UnmanagedMarshalClass);
minfo->type = spec->native;
switch (minfo->type) {
case MONO_NATIVE_LPARRAY:
minfo->eltype = spec->data.array_data.elem_type;
minfo->count = spec->data.array_data.num_elem;
minfo->param_num = spec->data.array_data.param_num;
break;
case MONO_NATIVE_BYVALTSTR:
case MONO_NATIVE_BYVALARRAY:
minfo->count = spec->data.array_data.num_elem;
break;
case MONO_NATIVE_CUSTOM:
if (spec->data.custom_data.custom_name) {
mtype = mono_reflection_type_from_name (spec->data.custom_data.custom_name, klass->image);
if (mtype)
MONO_OBJECT_SETREF (minfo, marshaltyperef, mono_type_get_object (domain, mtype));
MONO_OBJECT_SETREF (minfo, marshaltype, mono_string_new (domain, spec->data.custom_data.custom_name));
}
if (spec->data.custom_data.cookie)
MONO_OBJECT_SETREF (minfo, mcookie, mono_string_new (domain, spec->data.custom_data.cookie));
break;
default:
break;
}
return minfo;
}
#ifndef DISABLE_REFLECTION_EMIT
static MonoMethod*
reflection_methodbuilder_to_mono_method (MonoClass *klass,
ReflectionMethodBuilder *rmb,
MonoMethodSignature *sig)
{
MonoError error;
MonoMethod *m;
MonoMethodWrapper *wrapperm;
MonoMarshalSpec **specs;
MonoReflectionMethodAux *method_aux;
MonoImage *image;
gboolean dynamic;
int i;
mono_error_init (&error);
/*
* Methods created using a MethodBuilder should have their memory allocated
* inside the image mempool, while dynamic methods should have their memory
* malloc'd.
*/
dynamic = rmb->refs != NULL;
image = dynamic ? NULL : klass->image;
if (!dynamic)
g_assert (!klass->generic_class);
mono_loader_lock ();
if ((rmb->attrs & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(rmb->iattrs & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
m = (MonoMethod *)image_g_new0 (image, MonoMethodPInvoke, 1);
else
m = (MonoMethod *)image_g_new0 (image, MonoMethodWrapper, 1);
wrapperm = (MonoMethodWrapper*)m;
m->dynamic = dynamic;
m->slot = -1;
m->flags = rmb->attrs;
m->iflags = rmb->iattrs;
m->name = mono_string_to_utf8_image (image, rmb->name, &error);
g_assert (mono_error_ok (&error));
m->klass = klass;
m->signature = sig;
m->sre_method = TRUE;
m->skip_visibility = rmb->skip_visibility;
if (rmb->table_idx)
m->token = MONO_TOKEN_METHOD_DEF | (*rmb->table_idx);
if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
if (klass == mono_defaults.string_class && !strcmp (m->name, ".ctor"))
m->string_ctor = 1;
m->signature->pinvoke = 1;
} else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
m->signature->pinvoke = 1;
method_aux = image_g_new0 (image, MonoReflectionMethodAux, 1);
method_aux->dllentry = rmb->dllentry ? mono_string_to_utf8_image (image, rmb->dllentry, &error) : image_strdup (image, m->name);
g_assert (mono_error_ok (&error));
method_aux->dll = mono_string_to_utf8_image (image, rmb->dll, &error);
g_assert (mono_error_ok (&error));
((MonoMethodPInvoke*)m)->piflags = (rmb->native_cc << 8) | (rmb->charset ? (rmb->charset - 1) * 2 : 0) | rmb->extra_flags;
if (klass->image->dynamic)
g_hash_table_insert (((MonoDynamicImage*)klass->image)->method_aux_hash, m, method_aux);
mono_loader_unlock ();
return m;
} else if (!(m->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
!(m->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
MonoMethodHeader *header;
guint32 code_size;
gint32 max_stack, i;
gint32 num_locals = 0;
gint32 num_clauses = 0;
guint8 *code;
if (rmb->ilgen) {
code = mono_array_addr (rmb->ilgen->code, guint8, 0);
code_size = rmb->ilgen->code_len;
max_stack = rmb->ilgen->max_stack;
num_locals = rmb->ilgen->locals ? mono_array_length (rmb->ilgen->locals) : 0;
if (rmb->ilgen->ex_handlers)
num_clauses = method_count_clauses (rmb->ilgen);
} else {
if (rmb->code) {
code = mono_array_addr (rmb->code, guint8, 0);
code_size = mono_array_length (rmb->code);
/* we probably need to run a verifier on the code... */
max_stack = 8;
}
else {
code = NULL;
code_size = 0;
max_stack = 8;
}
}
header = image_g_malloc0 (image, MONO_SIZEOF_METHOD_HEADER + num_locals * sizeof (MonoType*));
header->code_size = code_size;
header->code = image_g_malloc (image, code_size);
memcpy ((char*)header->code, code, code_size);
header->max_stack = max_stack;
header->init_locals = rmb->init_locals;
header->num_locals = num_locals;
for (i = 0; i < num_locals; ++i) {
MonoReflectionLocalBuilder *lb =
mono_array_get (rmb->ilgen->locals, MonoReflectionLocalBuilder*, i);
header->locals [i] = image_g_new0 (image, MonoType, 1);
memcpy (header->locals [i], mono_reflection_type_get_handle ((MonoReflectionType*)lb->type), MONO_SIZEOF_TYPE);
}
header->num_clauses = num_clauses;
if (num_clauses) {
header->clauses = method_encode_clauses (image, (MonoDynamicImage*)klass->image,
rmb->ilgen, num_clauses);
}
wrapperm->header = header;
}
if (rmb->generic_params) {
int count = mono_array_length (rmb->generic_params);
MonoGenericContainer *container = rmb->generic_container;
g_assert (container);
container->type_argc = count;
container->type_params = image_g_new0 (image, MonoGenericParamFull, count);
container->owner.method = m;
m->is_generic = TRUE;
mono_method_set_generic_container (m, container);
for (i = 0; i < count; i++) {
MonoReflectionGenericParam *gp =
mono_array_get (rmb->generic_params, MonoReflectionGenericParam*, i);
MonoGenericParamFull *param = (MonoGenericParamFull *) mono_reflection_type_get_handle ((MonoReflectionType*)gp)->data.generic_param;
container->type_params [i] = *param;
}
/*
* The method signature might have pointers to generic parameters that belong to other methods.
* This is a valid SRE case, but the resulting method signature must be encoded using the proper
* generic parameters.
*/
for (i = 0; i < m->signature->param_count; ++i) {
MonoType *t = m->signature->params [i];
if (t->type == MONO_TYPE_MVAR) {
MonoGenericParam *gparam = t->data.generic_param;
if (gparam->num < count) {
m->signature->params [i] = mono_metadata_type_dup (image, m->signature->params [i]);
m->signature->params [i]->data.generic_param = mono_generic_container_get_param (container, gparam->num);
}
}
}
if (klass->generic_container) {
container->parent = klass->generic_container;
container->context.class_inst = klass->generic_container->context.class_inst;
}
container->context.method_inst = mono_get_shared_generic_inst (container);
}
if (rmb->refs) {
MonoMethodWrapper *mw = (MonoMethodWrapper*)m;
int i;
void **data;
m->wrapper_type = MONO_WRAPPER_DYNAMIC_METHOD;
mw->method_data = data = image_g_new (image, gpointer, rmb->nrefs + 1);
data [0] = GUINT_TO_POINTER (rmb->nrefs);
for (i = 0; i < rmb->nrefs; ++i)
data [i + 1] = rmb->refs [i];
}
method_aux = NULL;
/* Parameter info */
if (rmb->pinfo) {
if (!method_aux)
method_aux = image_g_new0 (image, MonoReflectionMethodAux, 1);
method_aux->param_names = image_g_new0 (image, char *, mono_method_signature (m)->param_count + 1);
for (i = 0; i <= m->signature->param_count; ++i) {
MonoReflectionParamBuilder *pb;
if ((pb = mono_array_get (rmb->pinfo, MonoReflectionParamBuilder*, i))) {
if ((i > 0) && (pb->attrs)) {
/* Make a copy since it might point to a shared type structure */
m->signature->params [i - 1] = mono_metadata_type_dup (klass->image, m->signature->params [i - 1]);
m->signature->params [i - 1]->attrs = pb->attrs;
}
if (pb->attrs & PARAM_ATTRIBUTE_HAS_DEFAULT) {
MonoDynamicImage *assembly;
guint32 idx, def_type, len;
char *p;
const char *p2;
if (!method_aux->param_defaults) {
method_aux->param_defaults = image_g_new0 (image, guint8*, m->signature->param_count + 1);
method_aux->param_default_types = image_g_new0 (image, guint32, m->signature->param_count + 1);
}
assembly = (MonoDynamicImage*)klass->image;
idx = encode_constant (assembly, pb->def_value, &def_type);
/* Copy the data from the blob since it might get realloc-ed */
p = assembly->blob.data + idx;
len = mono_metadata_decode_blob_size (p, &p2);
len += p2 - p;
method_aux->param_defaults [i] = image_g_malloc (image, len);
method_aux->param_default_types [i] = def_type;
memcpy ((gpointer)method_aux->param_defaults [i], p, len);
}
if (pb->name) {
method_aux->param_names [i] = mono_string_to_utf8_image (image, pb->name, &error);
g_assert (mono_error_ok (&error));
}
if (pb->cattrs) {
if (!method_aux->param_cattr)
method_aux->param_cattr = image_g_new0 (image, MonoCustomAttrInfo*, m->signature->param_count + 1);
method_aux->param_cattr [i] = mono_custom_attrs_from_builders (image, klass->image, pb->cattrs);
}
}
}
}
/* Parameter marshalling */
specs = NULL;
if (rmb->pinfo)
for (i = 0; i < mono_array_length (rmb->pinfo); ++i) {
MonoReflectionParamBuilder *pb;
if ((pb = mono_array_get (rmb->pinfo, MonoReflectionParamBuilder*, i))) {
if (pb->marshal_info) {
if (specs == NULL)
specs = image_g_new0 (image, MonoMarshalSpec*, sig->param_count + 1);
specs [pb->position] =
mono_marshal_spec_from_builder (image, klass->image->assembly, pb->marshal_info);
}
}
}
if (specs != NULL) {
if (!method_aux)
method_aux = image_g_new0 (image, MonoReflectionMethodAux, 1);
method_aux->param_marshall = specs;
}
if (klass->image->dynamic && method_aux)
g_hash_table_insert (((MonoDynamicImage*)klass->image)->method_aux_hash, m, method_aux);
mono_loader_unlock ();
return m;
}
static MonoMethod*
ctorbuilder_to_mono_method (MonoClass *klass, MonoReflectionCtorBuilder* mb)
{
ReflectionMethodBuilder rmb;
MonoMethodSignature *sig;
mono_loader_lock ();
sig = ctor_builder_to_signature (klass->image, mb);
mono_loader_unlock ();
reflection_methodbuilder_from_ctor_builder (&rmb, mb);
mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig);
mono_save_custom_attrs (klass->image, mb->mhandle, mb->cattrs);
/* If we are in a generic class, we might be called multiple times from inflate_method */
if (!((MonoDynamicImage*)(MonoDynamicImage*)klass->image)->save && !klass->generic_container) {
/* ilgen is no longer needed */
mb->ilgen = NULL;
}
return mb->mhandle;
}
static MonoMethod*
methodbuilder_to_mono_method (MonoClass *klass, MonoReflectionMethodBuilder* mb)
{
ReflectionMethodBuilder rmb;
MonoMethodSignature *sig;
mono_loader_lock ();
sig = method_builder_to_signature (klass->image, mb);
mono_loader_unlock ();
reflection_methodbuilder_from_method_builder (&rmb, mb);
mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig);
mono_save_custom_attrs (klass->image, mb->mhandle, mb->cattrs);
/* If we are in a generic class, we might be called multiple times from inflate_method */
if (!((MonoDynamicImage*)(MonoDynamicImage*)klass->image)->save && !klass->generic_container) {
/* ilgen is no longer needed */
mb->ilgen = NULL;
}
return mb->mhandle;
}
static MonoClassField*
fieldbuilder_to_mono_class_field (MonoClass *klass, MonoReflectionFieldBuilder* fb)
{
MonoClassField *field;
MonoType *custom;
field = g_new0 (MonoClassField, 1);
field->name = mono_string_to_utf8 (fb->name);
if (fb->attrs || fb->modreq || fb->modopt) {
field->type = mono_metadata_type_dup (NULL, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type));
field->type->attrs = fb->attrs;
g_assert (klass->image->dynamic);
custom = add_custom_modifiers ((MonoDynamicImage*)klass->image, field->type, fb->modreq, fb->modopt);
g_free (field->type);
field->type = custom;
} else {
field->type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
}
if (fb->offset != -1)
field->offset = fb->offset;
field->parent = klass;
mono_save_custom_attrs (klass->image, field, fb->cattrs);
// FIXME: Can't store fb->def_value/RVA, is it needed for field_on_insts ?
return field;
}
#endif
MonoType*
mono_reflection_bind_generic_parameters (MonoReflectionType *type, int type_argc, MonoType **types)
{
MonoClass *klass;
MonoReflectionTypeBuilder *tb = NULL;
gboolean is_dynamic = FALSE;
MonoDomain *domain;
MonoClass *geninst;
mono_loader_lock ();
domain = mono_object_domain (type);
if (is_sre_type_builder (mono_object_class (type))) {
tb = (MonoReflectionTypeBuilder *) type;
is_dynamic = TRUE;
} else if (is_sre_generic_instance (mono_object_class (type))) {
MonoReflectionGenericClass *rgi = (MonoReflectionGenericClass *) type;
MonoReflectionType *gtd = rgi->generic_type;
if (is_sre_type_builder (mono_object_class (gtd))) {
tb = (MonoReflectionTypeBuilder *)gtd;
is_dynamic = TRUE;
}
}
/* FIXME: fix the CreateGenericParameters protocol to avoid the two stage setup of TypeBuilders */
if (tb && tb->generic_container)
mono_reflection_create_generic_class (tb);
klass = mono_class_from_mono_type (mono_reflection_type_get_handle (type));
if (!klass->generic_container) {
mono_loader_unlock ();
return NULL;
}
if (klass->wastypebuilder) {
tb = (MonoReflectionTypeBuilder *) mono_class_get_ref_info (klass);
is_dynamic = TRUE;
}
mono_loader_unlock ();
geninst = mono_class_bind_generic_parameters (klass, type_argc, types, is_dynamic);
return &geninst->byval_arg;
}
MonoClass*
mono_class_bind_generic_parameters (MonoClass *klass, int type_argc, MonoType **types, gboolean is_dynamic)
{
MonoGenericClass *gclass;
MonoGenericInst *inst;
g_assert (klass->generic_container);
inst = mono_metadata_get_generic_inst (type_argc, types);
gclass = mono_metadata_lookup_generic_class (klass, inst, is_dynamic);
return mono_generic_class_get_class (gclass);
}
MonoReflectionMethod*
mono_reflection_bind_generic_method_parameters (MonoReflectionMethod *rmethod, MonoArray *types)
{
MonoClass *klass;
MonoMethod *method, *inflated;
MonoMethodInflated *imethod;
MonoGenericContext tmp_context;
MonoGenericInst *ginst;
MonoType **type_argv;
int count, i;
MONO_ARCH_SAVE_REGS;
/*FIXME but this no longer should happen*/
if (!strcmp (rmethod->object.vtable->klass->name, "MethodBuilder")) {
#ifndef DISABLE_REFLECTION_EMIT
MonoReflectionMethodBuilder *mb = NULL;
MonoReflectionTypeBuilder *tb;
MonoClass *klass;
mb = (MonoReflectionMethodBuilder *) rmethod;
tb = (MonoReflectionTypeBuilder *) mb->type;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
method = methodbuilder_to_mono_method (klass, mb);
#else
g_assert_not_reached ();
method = NULL;
#endif
} else {
method = rmethod->method;
}
klass = method->klass;
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
count = mono_method_signature (method)->generic_param_count;
if (count != mono_array_length (types))
return NULL;
type_argv = g_new0 (MonoType *, count);
for (i = 0; i < count; i++) {
MonoReflectionType *garg = mono_array_get (types, gpointer, i);
type_argv [i] = mono_reflection_type_get_handle (garg);
}
ginst = mono_metadata_get_generic_inst (count, type_argv);
g_free (type_argv);
tmp_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
tmp_context.method_inst = ginst;
inflated = mono_class_inflate_generic_method (method, &tmp_context);
imethod = (MonoMethodInflated *) inflated;
/*FIXME but I think this is no longer necessary*/
if (method->klass->image->dynamic) {
MonoDynamicImage *image = (MonoDynamicImage*)method->klass->image;
/*
* This table maps metadata structures representing inflated methods/fields
* to the reflection objects representing their generic definitions.
*/
mono_loader_lock ();
mono_g_hash_table_insert (image->generic_def_objects, imethod, rmethod);
mono_loader_unlock ();
}
return mono_method_get_object (mono_object_domain (rmethod), inflated, NULL);
}
#ifndef DISABLE_REFLECTION_EMIT
static MonoMethod *
inflate_mono_method (MonoClass *klass, MonoMethod *method, MonoObject *obj)
{
MonoMethodInflated *imethod;
MonoGenericContext *context;
int i;
/*
* With generic code sharing the klass might not be inflated.
* This can happen because classes inflated with their own
* type arguments are "normalized" to the uninflated class.
*/
if (!klass->generic_class)
return method;
context = mono_class_get_context (klass);
if (klass->method.count && klass->methods) {
/* Find the already created inflated method */
for (i = 0; i < klass->method.count; ++i) {
g_assert (klass->methods [i]->is_inflated);
if (((MonoMethodInflated*)klass->methods [i])->declaring == method)
break;
}
g_assert (i < klass->method.count);
imethod = (MonoMethodInflated*)klass->methods [i];
} else {
imethod = (MonoMethodInflated *) mono_class_inflate_generic_method_full (method, klass, context);
}
if (method->is_generic && method->klass->image->dynamic) {
MonoDynamicImage *image = (MonoDynamicImage*)method->klass->image;
mono_loader_lock ();
mono_g_hash_table_insert (image->generic_def_objects, imethod, obj);
mono_loader_unlock ();
}
return (MonoMethod *) imethod;
}
static MonoMethod *
inflate_method (MonoReflectionType *type, MonoObject *obj)
{
MonoMethod *method;
MonoClass *gklass;
MonoClass *type_class = mono_object_class (type);
if (is_sre_generic_instance (type_class)) {
MonoReflectionGenericClass *mgc = (MonoReflectionGenericClass*)type;
gklass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)mgc->generic_type));
} else if (is_sre_type_builder (type_class)) {
gklass = mono_class_from_mono_type (mono_reflection_type_get_handle (type));
} else if (type->type) {
gklass = mono_class_from_mono_type (type->type);
gklass = mono_class_get_generic_type_definition (gklass);
} else {
g_error ("Can't handle type %s", mono_type_get_full_name (mono_object_class (type)));
}
if (!strcmp (obj->vtable->klass->name, "MethodBuilder"))
if (((MonoReflectionMethodBuilder*)obj)->mhandle)
method = ((MonoReflectionMethodBuilder*)obj)->mhandle;
else
method = methodbuilder_to_mono_method (gklass, (MonoReflectionMethodBuilder *) obj);
else if (!strcmp (obj->vtable->klass->name, "ConstructorBuilder"))
method = ctorbuilder_to_mono_method (gklass, (MonoReflectionCtorBuilder *) obj);
else if (!strcmp (obj->vtable->klass->name, "MonoMethod") || !strcmp (obj->vtable->klass->name, "MonoCMethod"))
method = ((MonoReflectionMethod *) obj)->method;
else {
method = NULL; /* prevent compiler warning */
g_error ("can't handle type %s", obj->vtable->klass->name);
}
return inflate_mono_method (mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)type)), method, obj);
}
/*TODO avoid saving custom attrs for generic classes as it's enough to have them on the generic type definition.*/
void
mono_reflection_generic_class_initialize (MonoReflectionGenericClass *type, MonoArray *methods,
MonoArray *ctors, MonoArray *fields, MonoArray *properties,
MonoArray *events)
{
MonoGenericClass *gclass;
MonoDynamicGenericClass *dgclass;
MonoClass *klass, *gklass;
MonoType *gtype;
int i;
MONO_ARCH_SAVE_REGS;
gtype = mono_reflection_type_get_handle ((MonoReflectionType*)type);
klass = mono_class_from_mono_type (gtype);
g_assert (gtype->type == MONO_TYPE_GENERICINST);
gclass = gtype->data.generic_class;
if (!gclass->is_dynamic)
return;
dgclass = (MonoDynamicGenericClass *) gclass;
if (dgclass->initialized)
return;
gklass = gclass->container_class;
mono_class_init (gklass);
dgclass->count_methods = methods ? mono_array_length (methods) : 0;
dgclass->count_ctors = ctors ? mono_array_length (ctors) : 0;
dgclass->count_fields = fields ? mono_array_length (fields) : 0;
dgclass->methods = mono_image_set_new0 (gclass->owner, MonoMethod *, dgclass->count_methods);
dgclass->ctors = mono_image_set_new0 (gclass->owner, MonoMethod *, dgclass->count_ctors);
dgclass->fields = mono_image_set_new0 (gclass->owner, MonoClassField, dgclass->count_fields);
dgclass->field_objects = mono_image_set_new0 (gclass->owner, MonoObject*, dgclass->count_fields);
dgclass->field_generic_types = mono_image_set_new0 (gclass->owner, MonoType*, dgclass->count_fields);
for (i = 0; i < dgclass->count_methods; i++) {
MonoObject *obj = mono_array_get (methods, gpointer, i);
dgclass->methods [i] = inflate_method ((MonoReflectionType*)type, obj);
}
for (i = 0; i < dgclass->count_ctors; i++) {
MonoObject *obj = mono_array_get (ctors, gpointer, i);
dgclass->ctors [i] = inflate_method ((MonoReflectionType*)type, obj);
}
for (i = 0; i < dgclass->count_fields; i++) {
MonoObject *obj = mono_array_get (fields, gpointer, i);
MonoClassField *field, *inflated_field = NULL;
if (!strcmp (obj->vtable->klass->name, "FieldBuilder"))
inflated_field = field = fieldbuilder_to_mono_class_field (klass, (MonoReflectionFieldBuilder *) obj);
else if (!strcmp (obj->vtable->klass->name, "MonoField"))
field = ((MonoReflectionField *) obj)->field;
else {
field = NULL; /* prevent compiler warning */
g_assert_not_reached ();
}
dgclass->fields [i] = *field;
dgclass->fields [i].parent = klass;
dgclass->fields [i].type = mono_class_inflate_generic_type (
field->type, mono_generic_class_get_context ((MonoGenericClass *) dgclass));
dgclass->field_generic_types [i] = field->type;
MOVING_GC_REGISTER (&dgclass->field_objects [i]);
dgclass->field_objects [i] = obj;
if (inflated_field) {
g_free (inflated_field);
} else {
dgclass->fields [i].name = mono_image_set_strdup (gclass->owner, dgclass->fields [i].name);
}
}
dgclass->initialized = TRUE;
}
void
mono_reflection_free_dynamic_generic_class (MonoGenericClass *gclass)
{
MonoDynamicGenericClass *dgclass;
int i;
g_assert (gclass->is_dynamic);
dgclass = (MonoDynamicGenericClass *)gclass;
for (i = 0; i < dgclass->count_fields; ++i) {
MonoClassField *field = dgclass->fields + i;
mono_metadata_free_type (field->type);
#if HAVE_SGEN_GC
MONO_GC_UNREGISTER_ROOT (dgclass->field_objects [i]);
#endif
}
}
static void
fix_partial_generic_class (MonoClass *klass)
{
MonoClass *gklass = klass->generic_class->container_class;
MonoDynamicGenericClass *dgclass;
int i;
if (klass->wastypebuilder)
return;
dgclass = (MonoDynamicGenericClass *) klass->generic_class;
if (klass->parent != gklass->parent) {
MonoError error;
MonoType *parent_type = mono_class_inflate_generic_type_checked (&gklass->parent->byval_arg, &klass->generic_class->context, &error);
if (mono_error_ok (&error)) {
MonoClass *parent = mono_class_from_mono_type (parent_type);
mono_metadata_free_type (parent_type);
if (parent != klass->parent) {
/*fool mono_class_setup_parent*/
klass->supertypes = NULL;
mono_class_setup_parent (klass, parent);
}
} else {
mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
mono_error_cleanup (&error);
if (gklass->wastypebuilder)
klass->wastypebuilder = TRUE;
return;
}
}
if (!dgclass->initialized)
return;
if (klass->method.count != gklass->method.count) {
klass->method.count = gklass->method.count;
klass->methods = mono_image_alloc (klass->image, sizeof (MonoMethod*) * (klass->method.count + 1));
for (i = 0; i < klass->method.count; i++) {
klass->methods [i] = mono_class_inflate_generic_method_full (
gklass->methods [i], klass, mono_class_get_context (klass));
}
}
if (klass->interface_count && klass->interface_count != gklass->interface_count) {
klass->interface_count = gklass->interface_count;
klass->interfaces = mono_image_alloc (klass->image, sizeof (MonoClass*) * gklass->interface_count);
klass->interfaces_packed = NULL; /*make setup_interface_offsets happy*/
for (i = 0; i < gklass->interface_count; ++i) {
MonoType *iface_type = mono_class_inflate_generic_type (&gklass->interfaces [i]->byval_arg, mono_class_get_context (klass));
klass->interfaces [i] = mono_class_from_mono_type (iface_type);
mono_metadata_free_type (iface_type);
ensure_runtime_vtable (klass->interfaces [i]);
}
klass->interfaces_inited = 1;
}
if (klass->field.count != gklass->field.count) {
klass->field.count = gklass->field.count;
klass->fields = image_g_new0 (klass->image, MonoClassField, klass->field.count);
for (i = 0; i < klass->field.count; i++) {
klass->fields [i] = gklass->fields [i];
klass->fields [i].parent = klass;
klass->fields [i].type = mono_class_inflate_generic_type (gklass->fields [i].type, mono_class_get_context (klass));
}
}
/*We can only finish with this klass once it's parent has as well*/
if (gklass->wastypebuilder)
klass->wastypebuilder = TRUE;
return;
}
static void
ensure_generic_class_runtime_vtable (MonoClass *klass)
{
MonoClass *gklass = klass->generic_class->container_class;
ensure_runtime_vtable (gklass);
fix_partial_generic_class (klass);
}
static void
ensure_runtime_vtable (MonoClass *klass)
{
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
int i, num, j;
if (!klass->image->dynamic || (!tb && !klass->generic_class) || klass->wastypebuilder)
return;
if (klass->parent)
ensure_runtime_vtable (klass->parent);
if (tb) {
num = tb->ctors? mono_array_length (tb->ctors): 0;
num += tb->num_methods;
klass->method.count = num;
klass->methods = mono_image_alloc (klass->image, sizeof (MonoMethod*) * num);
num = tb->ctors? mono_array_length (tb->ctors): 0;
for (i = 0; i < num; ++i)
klass->methods [i] = ctorbuilder_to_mono_method (klass, mono_array_get (tb->ctors, MonoReflectionCtorBuilder*, i));
num = tb->num_methods;
j = i;
for (i = 0; i < num; ++i)
klass->methods [j++] = methodbuilder_to_mono_method (klass, mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i));
if (tb->interfaces) {
klass->interface_count = mono_array_length (tb->interfaces);
klass->interfaces = mono_image_alloc (klass->image, sizeof (MonoClass*) * klass->interface_count);
for (i = 0; i < klass->interface_count; ++i) {
MonoType *iface = mono_type_array_get_and_resolve (tb->interfaces, i);
klass->interfaces [i] = mono_class_from_mono_type (iface);
ensure_runtime_vtable (klass->interfaces [i]);
}
klass->interfaces_inited = 1;
}
} else if (klass->generic_class){
ensure_generic_class_runtime_vtable (klass);
}
if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
int slot_num = 0;
for (i = 0; i < klass->method.count; ++i) {
MonoMethod *im = klass->methods [i];
if (!(im->flags & METHOD_ATTRIBUTE_STATIC))
im->slot = slot_num++;
}
klass->interfaces_packed = NULL; /*make setup_interface_offsets happy*/
mono_class_setup_interface_offsets (klass);
mono_class_setup_interface_id (klass);
}
/*
* The generic vtable is needed even if image->run is not set since some
* runtime code like ves_icall_Type_GetMethodsByName depends on
* method->slot being defined.
*/
/*
* tb->methods could not be freed since it is used for determining
* overrides during dynamic vtable construction.
*/
}
static MonoMethod*
mono_reflection_method_get_handle (MonoObject *method)
{
MonoClass *class = mono_object_class (method);
if (is_sr_mono_method (class) || is_sr_mono_generic_method (class)) {
MonoReflectionMethod *sr_method = (MonoReflectionMethod*)method;
return sr_method->method;
}
if (is_sre_method_builder (class)) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder*)method;
return mb->mhandle;
}
if (is_sre_method_on_tb_inst (class)) {
MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)method;
MonoMethod *result;
/*FIXME move this to a proper method and unify with resolve_object*/
if (m->method_args) {
result = mono_reflection_method_on_tb_inst_get_handle (m);
} else {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst);
MonoClass *inflated_klass = mono_class_from_mono_type (type);
MonoMethod *mono_method;
if (is_sre_method_builder (mono_object_class (m->mb)))
mono_method = ((MonoReflectionMethodBuilder *)m->mb)->mhandle;
else if (is_sr_mono_method (mono_object_class (m->mb)))
mono_method = ((MonoReflectionMethod *)m->mb)->method;
else
g_error ("resolve_object:: can't handle a MTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (m->mb)));
result = inflate_mono_method (inflated_klass, mono_method, (MonoObject*)m->mb);
}
return result;
}
g_error ("Can't handle methods of type %s:%s", class->name_space, class->name);
return NULL;
}
void
mono_reflection_get_dynamic_overrides (MonoClass *klass, MonoMethod ***overrides, int *num_overrides)
{
MonoReflectionTypeBuilder *tb;
int i, onum;
*overrides = NULL;
*num_overrides = 0;
g_assert (klass->image->dynamic);
if (!mono_class_get_ref_info (klass))
return;
g_assert (strcmp (((MonoObject*)mono_class_get_ref_info (klass))->vtable->klass->name, "TypeBuilder") == 0);
tb = (MonoReflectionTypeBuilder*)mono_class_get_ref_info (klass);
onum = 0;
if (tb->methods) {
for (i = 0; i < tb->num_methods; ++i) {
MonoReflectionMethodBuilder *mb =
mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i);
if (mb->override_method)
onum ++;
}
}
if (onum) {
*overrides = g_new0 (MonoMethod*, onum * 2);
onum = 0;
for (i = 0; i < tb->num_methods; ++i) {
MonoReflectionMethodBuilder *mb =
mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i);
if (mb->override_method) {
(*overrides) [onum * 2] = mono_reflection_method_get_handle ((MonoObject *)mb->override_method);
(*overrides) [onum * 2 + 1] = mb->mhandle;
g_assert (mb->mhandle);
onum ++;
}
}
}
*num_overrides = onum;
}
static void
typebuilder_setup_fields (MonoClass *klass, MonoError *error)
{
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
MonoReflectionFieldBuilder *fb;
MonoClassField *field;
MonoImage *image = klass->image;
const char *p, *p2;
int i;
guint32 len, idx, real_size = 0;
klass->field.count = tb->num_fields;
klass->field.first = 0;
mono_error_init (error);
if (tb->class_size) {
g_assert ((tb->packing_size & 0xfffffff0) == 0);
klass->packing_size = tb->packing_size;
real_size = klass->instance_size + tb->class_size;
}
if (!klass->field.count) {
klass->instance_size = MAX (klass->instance_size, real_size);
return;
}
klass->fields = image_g_new0 (image, MonoClassField, klass->field.count);
mono_class_alloc_ext (klass);
klass->ext->field_def_values = image_g_new0 (image, MonoFieldDefaultValue, klass->field.count);
/*
This is, guess what, a hack.
The issue is that the runtime doesn't know how to setup the fields of a typebuider and crash.
On the static path no field class is resolved, only types are built. This is the right thing to do
but we suck.
Setting size_inited is harmless because we're doing the same job as mono_class_setup_fields anyway.
*/
klass->size_inited = 1;
for (i = 0; i < klass->field.count; ++i) {
fb = mono_array_get (tb->fields, gpointer, i);
field = &klass->fields [i];
field->name = mono_string_to_utf8_image (image, fb->name, error);
if (!mono_error_ok (error))
return;
if (fb->attrs) {
field->type = mono_metadata_type_dup (klass->image, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type));
field->type->attrs = fb->attrs;
} else {
field->type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
}
if ((fb->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) && fb->rva_data)
klass->ext->field_def_values [i].data = mono_array_addr (fb->rva_data, char, 0);
if (fb->offset != -1)
field->offset = fb->offset;
field->parent = klass;
fb->handle = field;
mono_save_custom_attrs (klass->image, field, fb->cattrs);
if (klass->enumtype && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
klass->cast_class = klass->element_class = mono_class_from_mono_type (field->type);
}
if (fb->def_value) {
MonoDynamicImage *assembly = (MonoDynamicImage*)klass->image;
field->type->attrs |= FIELD_ATTRIBUTE_HAS_DEFAULT;
idx = encode_constant (assembly, fb->def_value, &klass->ext->field_def_values [i].def_type);
/* Copy the data from the blob since it might get realloc-ed */
p = assembly->blob.data + idx;
len = mono_metadata_decode_blob_size (p, &p2);
len += p2 - p;
klass->ext->field_def_values [i].data = mono_image_alloc (image, len);
memcpy ((gpointer)klass->ext->field_def_values [i].data, p, len);
}
}
klass->instance_size = MAX (klass->instance_size, real_size);
mono_class_layout_fields (klass);
}
static void
typebuilder_setup_properties (MonoClass *klass, MonoError *error)
{
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
MonoReflectionPropertyBuilder *pb;
MonoImage *image = klass->image;
MonoProperty *properties;
int i;
mono_error_init (error);
if (!klass->ext)
klass->ext = image_g_new0 (image, MonoClassExt, 1);
klass->ext->property.count = tb->properties ? mono_array_length (tb->properties) : 0;
klass->ext->property.first = 0;
properties = image_g_new0 (image, MonoProperty, klass->ext->property.count);
klass->ext->properties = properties;
for (i = 0; i < klass->ext->property.count; ++i) {
pb = mono_array_get (tb->properties, MonoReflectionPropertyBuilder*, i);
properties [i].parent = klass;
properties [i].attrs = pb->attrs;
properties [i].name = mono_string_to_utf8_image (image, pb->name, error);
if (!mono_error_ok (error))
return;
if (pb->get_method)
properties [i].get = pb->get_method->mhandle;
if (pb->set_method)
properties [i].set = pb->set_method->mhandle;
mono_save_custom_attrs (klass->image, &properties [i], pb->cattrs);
if (pb->def_value) {
guint32 len, idx;
const char *p, *p2;
MonoDynamicImage *assembly = (MonoDynamicImage*)klass->image;
if (!klass->ext->prop_def_values)
klass->ext->prop_def_values = image_g_new0 (image, MonoFieldDefaultValue, klass->ext->property.count);
properties [i].attrs |= PROPERTY_ATTRIBUTE_HAS_DEFAULT;
idx = encode_constant (assembly, pb->def_value, &klass->ext->prop_def_values [i].def_type);
/* Copy the data from the blob since it might get realloc-ed */
p = assembly->blob.data + idx;
len = mono_metadata_decode_blob_size (p, &p2);
len += p2 - p;
klass->ext->prop_def_values [i].data = mono_image_alloc (image, len);
memcpy ((gpointer)klass->ext->prop_def_values [i].data, p, len);
}
}
}
MonoReflectionEvent *
mono_reflection_event_builder_get_event_info (MonoReflectionTypeBuilder *tb, MonoReflectionEventBuilder *eb)
{
MonoEvent *event = g_new0 (MonoEvent, 1);
MonoClass *klass;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
event->parent = klass;
event->attrs = eb->attrs;
event->name = mono_string_to_utf8 (eb->name);
if (eb->add_method)
event->add = eb->add_method->mhandle;
if (eb->remove_method)
event->remove = eb->remove_method->mhandle;
if (eb->raise_method)
event->raise = eb->raise_method->mhandle;
#ifndef MONO_SMALL_CONFIG
if (eb->other_methods) {
int j;
event->other = g_new0 (MonoMethod*, mono_array_length (eb->other_methods) + 1);
for (j = 0; j < mono_array_length (eb->other_methods); ++j) {
MonoReflectionMethodBuilder *mb =
mono_array_get (eb->other_methods,
MonoReflectionMethodBuilder*, j);
event->other [j] = mb->mhandle;
}
}
#endif
return mono_event_get_object (mono_object_domain (tb), klass, event);
}
static void
typebuilder_setup_events (MonoClass *klass, MonoError *error)
{
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
MonoReflectionEventBuilder *eb;
MonoImage *image = klass->image;
MonoEvent *events;
int i;
mono_error_init (error);
if (!klass->ext)
klass->ext = image_g_new0 (image, MonoClassExt, 1);
klass->ext->event.count = tb->events ? mono_array_length (tb->events) : 0;
klass->ext->event.first = 0;
events = image_g_new0 (image, MonoEvent, klass->ext->event.count);
klass->ext->events = events;
for (i = 0; i < klass->ext->event.count; ++i) {
eb = mono_array_get (tb->events, MonoReflectionEventBuilder*, i);
events [i].parent = klass;
events [i].attrs = eb->attrs;
events [i].name = mono_string_to_utf8_image (image, eb->name, error);
if (!mono_error_ok (error))
return;
if (eb->add_method)
events [i].add = eb->add_method->mhandle;
if (eb->remove_method)
events [i].remove = eb->remove_method->mhandle;
if (eb->raise_method)
events [i].raise = eb->raise_method->mhandle;
#ifndef MONO_SMALL_CONFIG
if (eb->other_methods) {
int j;
events [i].other = image_g_new0 (image, MonoMethod*, mono_array_length (eb->other_methods) + 1);
for (j = 0; j < mono_array_length (eb->other_methods); ++j) {
MonoReflectionMethodBuilder *mb =
mono_array_get (eb->other_methods,
MonoReflectionMethodBuilder*, j);
events [i].other [j] = mb->mhandle;
}
}
#endif
mono_save_custom_attrs (klass->image, &events [i], eb->cattrs);
}
}
static gboolean
remove_instantiations_of_and_ensure_contents (gpointer key,
gpointer value,
gpointer user_data)
{
MonoType *type = (MonoType*)key;
MonoClass *klass = (MonoClass*)user_data;
if ((type->type == MONO_TYPE_GENERICINST) && (type->data.generic_class->container_class == klass)) {
fix_partial_generic_class (mono_class_from_mono_type (type)); //Ensure it's safe to use it.
return TRUE;
} else
return FALSE;
}
static void
check_array_for_usertypes (MonoArray *arr)
{
int i;
if (!arr)
return;
for (i = 0; i < mono_array_length (arr); ++i)
RESOLVE_ARRAY_TYPE_ELEMENT (arr, i);
}
MonoReflectionType*
mono_reflection_create_runtime_class (MonoReflectionTypeBuilder *tb)
{
MonoError error;
MonoClass *klass;
MonoDomain* domain;
MonoReflectionType* res;
int i, j;
MONO_ARCH_SAVE_REGS;
domain = mono_object_domain (tb);
klass = mono_class_from_mono_type (tb->type.type);
/*
* Check for user defined Type subclasses.
*/
RESOLVE_TYPE (tb->parent);
check_array_for_usertypes (tb->interfaces);
if (tb->fields) {
for (i = 0; i < mono_array_length (tb->fields); ++i) {
MonoReflectionFieldBuilder *fb = mono_array_get (tb->fields, gpointer, i);
if (fb) {
RESOLVE_TYPE (fb->type);
check_array_for_usertypes (fb->modreq);
check_array_for_usertypes (fb->modopt);
if (fb->marshal_info && fb->marshal_info->marshaltyperef)
RESOLVE_TYPE (fb->marshal_info->marshaltyperef);
}
}
}
if (tb->methods) {
for (i = 0; i < mono_array_length (tb->methods); ++i) {
MonoReflectionMethodBuilder *mb = mono_array_get (tb->methods, gpointer, i);
if (mb) {
RESOLVE_TYPE (mb->rtype);
check_array_for_usertypes (mb->return_modreq);
check_array_for_usertypes (mb->return_modopt);
check_array_for_usertypes (mb->parameters);
if (mb->param_modreq)
for (j = 0; j < mono_array_length (mb->param_modreq); ++j)
check_array_for_usertypes (mono_array_get (mb->param_modreq, MonoArray*, j));
if (mb->param_modopt)
for (j = 0; j < mono_array_length (mb->param_modopt); ++j)
check_array_for_usertypes (mono_array_get (mb->param_modopt, MonoArray*, j));
}
}
}
if (tb->ctors) {
for (i = 0; i < mono_array_length (tb->ctors); ++i) {
MonoReflectionCtorBuilder *mb = mono_array_get (tb->ctors, gpointer, i);
if (mb) {
check_array_for_usertypes (mb->parameters);
if (mb->param_modreq)
for (j = 0; j < mono_array_length (mb->param_modreq); ++j)
check_array_for_usertypes (mono_array_get (mb->param_modreq, MonoArray*, j));
if (mb->param_modopt)
for (j = 0; j < mono_array_length (mb->param_modopt); ++j)
check_array_for_usertypes (mono_array_get (mb->param_modopt, MonoArray*, j));
}
}
}
mono_save_custom_attrs (klass->image, klass, tb->cattrs);
/*
* we need to lock the domain because the lock will be taken inside
* So, we need to keep the locking order correct.
*/
mono_loader_lock ();
mono_domain_lock (domain);
if (klass->wastypebuilder) {
mono_domain_unlock (domain);
mono_loader_unlock ();
return mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
}
/*
* Fields to set in klass:
* the various flags: delegate/unicode/contextbound etc.
*/
klass->flags = tb->attrs;
klass->has_cctor = 1;
klass->has_finalize = 1;
/* fool mono_class_setup_parent */
klass->supertypes = NULL;
mono_class_setup_parent (klass, klass->parent);
mono_class_setup_mono_type (klass);
#if 0
if (!((MonoDynamicImage*)klass->image)->run) {
if (klass->generic_container) {
/* FIXME: The code below can't handle generic classes */
klass->wastypebuilder = TRUE;
mono_loader_unlock ();
mono_domain_unlock (domain);
return mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
}
}
#endif
/* enums are done right away */
if (!klass->enumtype)
ensure_runtime_vtable (klass);
if (tb->subtypes) {
for (i = 0; i < mono_array_length (tb->subtypes); ++i) {
MonoReflectionTypeBuilder *subtb = mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i);
mono_class_alloc_ext (klass);
klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)subtb)));
}
}
klass->nested_classes_inited = TRUE;
/* fields and object layout */
if (klass->parent) {
if (!klass->parent->size_inited)
mono_class_init (klass->parent);
klass->instance_size = klass->parent->instance_size;
klass->sizes.class_size = 0;
klass->min_align = klass->parent->min_align;
/* if the type has no fields we won't call the field_setup
* routine which sets up klass->has_references.
*/
klass->has_references |= klass->parent->has_references;
} else {
klass->instance_size = sizeof (MonoObject);
klass->min_align = 1;
}
/* FIXME: handle packing_size and instance_size */
typebuilder_setup_fields (klass, &error);
if (!mono_error_ok (&error))
goto failure;
typebuilder_setup_properties (klass, &error);
if (!mono_error_ok (&error))
goto failure;
typebuilder_setup_events (klass, &error);
if (!mono_error_ok (&error))
goto failure;
klass->wastypebuilder = TRUE;
/*
* If we are a generic TypeBuilder, there might be instantiations in the type cache
* which have type System.Reflection.MonoGenericClass, but after the type is created,
* we want to return normal System.MonoType objects, so clear these out from the cache.
*
* Together with this we must ensure the contents of all instances to match the created type.
*/
if (domain->type_hash && klass->generic_container)
mono_g_hash_table_foreach_remove (domain->type_hash, remove_instantiations_of_and_ensure_contents, klass);
mono_domain_unlock (domain);
mono_loader_unlock ();
if (klass->enumtype && !mono_class_is_valid_enum (klass)) {
mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
mono_raise_exception (mono_get_exception_type_load (tb->name, NULL));
}
res = mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
g_assert (res != (MonoReflectionType*)tb);
return res;
failure:
mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
klass->wastypebuilder = TRUE;
mono_domain_unlock (domain);
mono_loader_unlock ();
mono_error_raise_exception (&error);
return NULL;
}
void
mono_reflection_initialize_generic_parameter (MonoReflectionGenericParam *gparam)
{
MonoGenericParamFull *param;
MonoImage *image;
MonoClass *pklass;
MONO_ARCH_SAVE_REGS;
param = g_new0 (MonoGenericParamFull, 1);
if (gparam->mbuilder) {
if (!gparam->mbuilder->generic_container) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)gparam->mbuilder->type;
MonoClass *klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
gparam->mbuilder->generic_container = mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
gparam->mbuilder->generic_container->is_method = TRUE;
/*
* Cannot set owner.method, since the MonoMethod is not created yet.
* Set the image field instead, so type_in_image () works.
*/
gparam->mbuilder->generic_container->image = klass->image;
}
param->param.owner = gparam->mbuilder->generic_container;
} else if (gparam->tbuilder) {
if (!gparam->tbuilder->generic_container) {
MonoClass *klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)gparam->tbuilder));
gparam->tbuilder->generic_container = mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
gparam->tbuilder->generic_container->owner.klass = klass;
}
param->param.owner = gparam->tbuilder->generic_container;
}
param->info.name = mono_string_to_utf8 (gparam->name);
param->param.num = gparam->index;
image = &gparam->tbuilder->module->dynamic_image->image;
pklass = mono_class_from_generic_parameter ((MonoGenericParam *) param, image, gparam->mbuilder != NULL);
gparam->type.type = &pklass->byval_arg;
mono_class_set_ref_info (pklass, gparam);
mono_image_lock (image);
image->reflection_info_unregister_classes = g_slist_prepend (image->reflection_info_unregister_classes, pklass);
mono_image_unlock (image);
}
MonoArray *
mono_reflection_sighelper_get_signature_local (MonoReflectionSigHelper *sig)
{
MonoReflectionModuleBuilder *module = sig->module;
MonoDynamicImage *assembly = module != NULL ? module->dynamic_image : NULL;
guint32 na = sig->arguments ? mono_array_length (sig->arguments) : 0;
guint32 buflen, i;
MonoArray *result;
SigBuffer buf;
check_array_for_usertypes (sig->arguments);
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x07);
sigbuffer_add_value (&buf, na);
if (assembly != NULL){
for (i = 0; i < na; ++i) {
MonoReflectionType *type = mono_array_get (sig->arguments, MonoReflectionType*, i);
encode_reflection_type (assembly, type, &buf);
}
}
buflen = buf.p - buf.buf;
result = mono_array_new (mono_domain_get (), mono_defaults.byte_class, buflen);
memcpy (mono_array_addr (result, char, 0), buf.buf, buflen);
sigbuffer_free (&buf);
return result;
}
MonoArray *
mono_reflection_sighelper_get_signature_field (MonoReflectionSigHelper *sig)
{
MonoDynamicImage *assembly = sig->module->dynamic_image;
guint32 na = sig->arguments ? mono_array_length (sig->arguments) : 0;
guint32 buflen, i;
MonoArray *result;
SigBuffer buf;
check_array_for_usertypes (sig->arguments);
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x06);
for (i = 0; i < na; ++i) {
MonoReflectionType *type = mono_array_get (sig->arguments, MonoReflectionType*, i);
encode_reflection_type (assembly, type, &buf);
}
buflen = buf.p - buf.buf;
result = mono_array_new (mono_domain_get (), mono_defaults.byte_class, buflen);
memcpy (mono_array_addr (result, char, 0), buf.buf, buflen);
sigbuffer_free (&buf);
return result;
}
void
mono_reflection_create_dynamic_method (MonoReflectionDynamicMethod *mb)
{
ReflectionMethodBuilder rmb;
MonoMethodSignature *sig;
MonoClass *klass;
GSList *l;
int i;
sig = dynamic_method_to_signature (mb);
reflection_methodbuilder_from_dynamic_method (&rmb, mb);
/*
* Resolve references.
*/
/*
* Every second entry in the refs array is reserved for storing handle_class,
* which is needed by the ldtoken implementation in the JIT.
*/
rmb.nrefs = mb->nrefs;
rmb.refs = g_new0 (gpointer, mb->nrefs + 1);
for (i = 0; i < mb->nrefs; i += 2) {
MonoClass *handle_class;
gpointer ref;
MonoObject *obj = mono_array_get (mb->refs, MonoObject*, i);
if (strcmp (obj->vtable->klass->name, "DynamicMethod") == 0) {
MonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)obj;
/*
* The referenced DynamicMethod should already be created by the managed
* code, except in the case of circular references. In that case, we store
* method in the refs array, and fix it up later when the referenced
* DynamicMethod is created.
*/
if (method->mhandle) {
ref = method->mhandle;
} else {
/* FIXME: GC object stored in unmanaged memory */
ref = method;
/* FIXME: GC object stored in unmanaged memory */
method->referenced_by = g_slist_append (method->referenced_by, mb);
}
handle_class = mono_defaults.methodhandle_class;
} else {
MonoException *ex = NULL;
ref = resolve_object (mb->module->image, obj, &handle_class, NULL);
if (!ref)
ex = mono_get_exception_type_load (NULL, NULL);
else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
ex = mono_security_core_clr_ensure_dynamic_method_resolved_object (ref, handle_class);
if (ex) {
g_free (rmb.refs);
mono_raise_exception (ex);
return;
}
}
rmb.refs [i] = ref; /* FIXME: GC object stored in unmanaged memory (change also resolve_object() signature) */
rmb.refs [i + 1] = handle_class;
}
klass = mb->owner ? mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)mb->owner)) : mono_defaults.object_class;
mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig);
/* Fix up refs entries pointing at us */
for (l = mb->referenced_by; l; l = l->next) {
MonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)l->data;
MonoMethodWrapper *wrapper = (MonoMethodWrapper*)method->mhandle;
gpointer *data;
g_assert (method->mhandle);
data = (gpointer*)wrapper->method_data;
for (i = 0; i < GPOINTER_TO_UINT (data [0]); i += 2) {
if ((data [i + 1] == mb) && (data [i + 1 + 1] == mono_defaults.methodhandle_class))
data [i + 1] = mb->mhandle;
}
}
g_slist_free (mb->referenced_by);
g_free (rmb.refs);
/* ilgen is no longer needed */
mb->ilgen = NULL;
}
#endif /* DISABLE_REFLECTION_EMIT */
void
mono_reflection_destroy_dynamic_method (MonoReflectionDynamicMethod *mb)
{
g_assert (mb);
if (mb->mhandle)
mono_runtime_free_method (
mono_object_get_domain ((MonoObject*)mb), mb->mhandle);
}
/**
*
* mono_reflection_is_valid_dynamic_token:
*
* Returns TRUE if token is valid.
*
*/
gboolean
mono_reflection_is_valid_dynamic_token (MonoDynamicImage *image, guint32 token)
{
return mono_g_hash_table_lookup (image->tokens, GUINT_TO_POINTER (token)) != NULL;
}
MonoMethodSignature *
mono_reflection_lookup_signature (MonoImage *image, MonoMethod *method, guint32 token)
{
MonoMethodSignature *sig;
g_assert (image->dynamic);
sig = g_hash_table_lookup (((MonoDynamicImage*)image)->vararg_aux_hash, GUINT_TO_POINTER (token));
if (sig)
return sig;
return mono_method_signature (method);
}
#ifndef DISABLE_REFLECTION_EMIT
/**
* mono_reflection_lookup_dynamic_token:
*
* Finish the Builder object pointed to by TOKEN and return the corresponding
* runtime structure. If HANDLE_CLASS is not NULL, it is set to the class required by
* mono_ldtoken. If valid_token is TRUE, assert if it is not found in the token->object
* mapping table.
*
* LOCKING: Take the loader lock
*/
gpointer
mono_reflection_lookup_dynamic_token (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
{
MonoDynamicImage *assembly = (MonoDynamicImage*)image;
MonoObject *obj;
MonoClass *klass;
mono_loader_lock ();
obj = mono_g_hash_table_lookup (assembly->tokens, GUINT_TO_POINTER (token));
mono_loader_unlock ();
if (!obj) {
if (valid_token)
g_error ("Could not find required dynamic token 0x%08x", token);
else
return NULL;
}
if (!handle_class)
handle_class = &klass;
return resolve_object (image, obj, handle_class, context);
}
/*
* ensure_complete_type:
*
* Ensure that KLASS is completed if it is a dynamic type, or references
* dynamic types.
*/
static void
ensure_complete_type (MonoClass *klass)
{
if (klass->image->dynamic && !klass->wastypebuilder && mono_class_get_ref_info (klass)) {
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
// Asserting here could break a lot of code
//g_assert (klass->wastypebuilder);
}
if (klass->generic_class) {
MonoGenericInst *inst = klass->generic_class->context.class_inst;
int i;
for (i = 0; i < inst->type_argc; ++i) {
ensure_complete_type (mono_class_from_mono_type (inst->type_argv [i]));
}
}
}
static gpointer
resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, MonoGenericContext *context)
{
gpointer result = NULL;
if (strcmp (obj->vtable->klass->name, "String") == 0) {
result = mono_string_intern ((MonoString*)obj);
*handle_class = mono_defaults.string_class;
g_assert (result);
} else if (strcmp (obj->vtable->klass->name, "MonoType") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
MonoClass *mc = mono_class_from_mono_type (type);
if (!mono_class_init (mc))
mono_raise_exception (mono_class_get_exception_for_failure (mc));
if (context) {
MonoType *inflated = mono_class_inflate_generic_type (type, context);
result = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
} else {
result = mono_class_from_mono_type (type);
}
*handle_class = mono_defaults.typehandle_class;
g_assert (result);
} else if (strcmp (obj->vtable->klass->name, "MonoMethod") == 0 ||
strcmp (obj->vtable->klass->name, "MonoCMethod") == 0 ||
strcmp (obj->vtable->klass->name, "MonoGenericCMethod") == 0 ||
strcmp (obj->vtable->klass->name, "MonoGenericMethod") == 0) {
result = ((MonoReflectionMethod*)obj)->method;
if (context)
result = mono_class_inflate_generic_method (result, context);
*handle_class = mono_defaults.methodhandle_class;
g_assert (result);
} else if (strcmp (obj->vtable->klass->name, "MethodBuilder") == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder*)obj;
result = mb->mhandle;
if (!result) {
/* Type is not yet created */
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)mb->type;
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
/*
* Hopefully this has been filled in by calling CreateType() on the
* TypeBuilder.
*/
/*
* TODO: This won't work if the application finishes another
* TypeBuilder instance instead of this one.
*/
result = mb->mhandle;
}
if (context)
result = mono_class_inflate_generic_method (result, context);
*handle_class = mono_defaults.methodhandle_class;
} else if (strcmp (obj->vtable->klass->name, "ConstructorBuilder") == 0) {
MonoReflectionCtorBuilder *cb = (MonoReflectionCtorBuilder*)obj;
result = cb->mhandle;
if (!result) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)cb->type;
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
result = cb->mhandle;
}
if (context)
result = mono_class_inflate_generic_method (result, context);
*handle_class = mono_defaults.methodhandle_class;
} else if (strcmp (obj->vtable->klass->name, "MonoField") == 0) {
MonoClassField *field = ((MonoReflectionField*)obj)->field;
ensure_complete_type (field->parent);
if (context) {
MonoType *inflated = mono_class_inflate_generic_type (&field->parent->byval_arg, context);
MonoClass *class = mono_class_from_mono_type (inflated);
MonoClassField *inflated_field;
gpointer iter = NULL;
mono_metadata_free_type (inflated);
while ((inflated_field = mono_class_get_fields (class, &iter))) {
if (!strcmp (field->name, inflated_field->name))
break;
}
g_assert (inflated_field && !strcmp (field->name, inflated_field->name));
result = inflated_field;
} else {
result = field;
}
*handle_class = mono_defaults.fieldhandle_class;
g_assert (result);
} else if (strcmp (obj->vtable->klass->name, "FieldBuilder") == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder*)obj;
result = fb->handle;
if (!result) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)fb->typeb;
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
result = fb->handle;
}
if (fb->handle && fb->handle->parent->generic_container) {
MonoClass *klass = fb->handle->parent;
MonoType *type = mono_class_inflate_generic_type (&klass->byval_arg, context);
MonoClass *inflated = mono_class_from_mono_type (type);
result = mono_class_get_field_from_name (inflated, mono_field_get_name (fb->handle));
g_assert (result);
mono_metadata_free_type (type);
}
*handle_class = mono_defaults.fieldhandle_class;
} else if (strcmp (obj->vtable->klass->name, "TypeBuilder") == 0) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)obj;
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)tb);
MonoClass *klass;
klass = type->data.klass;
if (klass->wastypebuilder) {
/* Already created */
result = klass;
}
else {
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
result = type->data.klass;
g_assert (result);
}
*handle_class = mono_defaults.typehandle_class;
} else if (strcmp (obj->vtable->klass->name, "SignatureHelper") == 0) {
MonoReflectionSigHelper *helper = (MonoReflectionSigHelper*)obj;
MonoMethodSignature *sig;
int nargs, i;
if (helper->arguments)
nargs = mono_array_length (helper->arguments);
else
nargs = 0;
sig = mono_metadata_signature_alloc (image, nargs);
sig->explicit_this = helper->call_conv & 64 ? 1 : 0;
sig->hasthis = helper->call_conv & 32 ? 1 : 0;
if (helper->unmanaged_call_conv) { /* unmanaged */
sig->call_convention = helper->unmanaged_call_conv - 1;
sig->pinvoke = TRUE;
} else if (helper->call_conv & 0x02) {
sig->call_convention = MONO_CALL_VARARG;
} else {
sig->call_convention = MONO_CALL_DEFAULT;
}
sig->param_count = nargs;
/* TODO: Copy type ? */
sig->ret = helper->return_type->type;
for (i = 0; i < nargs; ++i)
sig->params [i] = mono_type_array_get_and_resolve (helper->arguments, i);
result = sig;
*handle_class = NULL;
} else if (strcmp (obj->vtable->klass->name, "DynamicMethod") == 0) {
MonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)obj;
/* Already created by the managed code */
g_assert (method->mhandle);
result = method->mhandle;
*handle_class = mono_defaults.methodhandle_class;
} else if (strcmp (obj->vtable->klass->name, "GenericTypeParameterBuilder") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
type = mono_class_inflate_generic_type (type, context);
result = mono_class_from_mono_type (type);
*handle_class = mono_defaults.typehandle_class;
g_assert (result);
mono_metadata_free_type (type);
} else if (strcmp (obj->vtable->klass->name, "MonoGenericClass") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
type = mono_class_inflate_generic_type (type, context);
result = mono_class_from_mono_type (type);
*handle_class = mono_defaults.typehandle_class;
g_assert (result);
mono_metadata_free_type (type);
} else if (strcmp (obj->vtable->klass->name, "FieldOnTypeBuilderInst") == 0) {
MonoReflectionFieldOnTypeBuilderInst *f = (MonoReflectionFieldOnTypeBuilderInst*)obj;
MonoClass *inflated;
MonoType *type;
MonoClassField *field;
if (is_sre_field_builder (mono_object_class (f->fb)))
field = ((MonoReflectionFieldBuilder*)f->fb)->handle;
else if (is_sr_mono_field (mono_object_class (f->fb)))
field = ((MonoReflectionField*)f->fb)->field;
else
g_error ("resolve_object:: can't handle a FTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (f->fb)));
type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)f->inst), context);
inflated = mono_class_from_mono_type (type);
result = field = mono_class_get_field_from_name (inflated, mono_field_get_name (field));
ensure_complete_type (field->parent);
g_assert (result);
mono_metadata_free_type (type);
*handle_class = mono_defaults.fieldhandle_class;
} else if (strcmp (obj->vtable->klass->name, "ConstructorOnTypeBuilderInst") == 0) {
MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)obj;
MonoType *type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)c->inst), context);
MonoClass *inflated_klass = mono_class_from_mono_type (type);
MonoMethod *method;
if (is_sre_ctor_builder (mono_object_class (c->cb)))
method = ((MonoReflectionCtorBuilder *)c->cb)->mhandle;
else if (is_sr_mono_cmethod (mono_object_class (c->cb)))
method = ((MonoReflectionMethod *)c->cb)->method;
else
g_error ("resolve_object:: can't handle a CTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (c->cb)));
result = inflate_mono_method (inflated_klass, method, (MonoObject*)c->cb);
*handle_class = mono_defaults.methodhandle_class;
mono_metadata_free_type (type);
} else if (strcmp (obj->vtable->klass->name, "MethodOnTypeBuilderInst") == 0) {
MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)obj;
if (m->method_args) {
result = mono_reflection_method_on_tb_inst_get_handle (m);
if (context)
result = mono_class_inflate_generic_method (result, context);
} else {
MonoType *type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)m->inst), context);
MonoClass *inflated_klass = mono_class_from_mono_type (type);
MonoMethod *method;
if (is_sre_method_builder (mono_object_class (m->mb)))
method = ((MonoReflectionMethodBuilder *)m->mb)->mhandle;
else if (is_sr_mono_method (mono_object_class (m->mb)))
method = ((MonoReflectionMethod *)m->mb)->method;
else
g_error ("resolve_object:: can't handle a MTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (m->mb)));
result = inflate_mono_method (inflated_klass, method, (MonoObject*)m->mb);
mono_metadata_free_type (type);
}
*handle_class = mono_defaults.methodhandle_class;
} else if (strcmp (obj->vtable->klass->name, "MonoArrayMethod") == 0) {
MonoReflectionArrayMethod *m = (MonoReflectionArrayMethod*)obj;
MonoType *mtype;
MonoClass *klass;
MonoMethod *method;
gpointer iter;
char *name;
mtype = mono_reflection_type_get_handle (m->parent);
klass = mono_class_from_mono_type (mtype);
/* Find the method */
name = mono_string_to_utf8 (m->name);
iter = NULL;
while ((method = mono_class_get_methods (klass, &iter))) {
if (!strcmp (method->name, name))
break;
}
g_free (name);
// FIXME:
g_assert (method);
// FIXME: Check parameters/return value etc. match
result = method;
*handle_class = mono_defaults.methodhandle_class;
} else if (is_sre_array (mono_object_get_class(obj)) ||
is_sre_byref (mono_object_get_class(obj)) ||
is_sre_pointer (mono_object_get_class(obj))) {
MonoReflectionType *ref_type = (MonoReflectionType *)obj;
MonoType *type = mono_reflection_type_get_handle (ref_type);
result = mono_class_from_mono_type (type);
*handle_class = mono_defaults.typehandle_class;
} else {
g_print ("%s\n", obj->vtable->klass->name);
g_assert_not_reached ();
}
return result;
}
#else /* DISABLE_REFLECTION_EMIT */
MonoArray*
mono_reflection_get_custom_attrs_blob (MonoReflectionAssembly *assembly, MonoObject *ctor, MonoArray *ctorArgs, MonoArray *properties, MonoArray *propValues, MonoArray *fields, MonoArray* fieldValues)
{
g_assert_not_reached ();
return NULL;
}
void
mono_reflection_setup_internal_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
}
void
mono_reflection_setup_generic_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
}
void
mono_reflection_create_generic_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
}
void
mono_reflection_create_internal_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
}
void
mono_image_basic_init (MonoReflectionAssemblyBuilder *assemblyb)
{
g_error ("This mono runtime was configured with --enable-minimal=reflection_emit, so System.Reflection.Emit is not supported.");
}
void
mono_image_module_basic_init (MonoReflectionModuleBuilder *moduleb)
{
g_assert_not_reached ();
}
void
mono_image_set_wrappers_type (MonoReflectionModuleBuilder *moduleb, MonoReflectionType *type)
{
g_assert_not_reached ();
}
MonoReflectionModule *
mono_image_load_module_dynamic (MonoReflectionAssemblyBuilder *ab, MonoString *fileName)
{
g_assert_not_reached ();
return NULL;
}
guint32
mono_image_insert_string (MonoReflectionModuleBuilder *module, MonoString *str)
{
g_assert_not_reached ();
return 0;
}
guint32
mono_image_create_method_token (MonoDynamicImage *assembly, MonoObject *obj, MonoArray *opt_param_types)
{
g_assert_not_reached ();
return 0;
}
guint32
mono_image_create_token (MonoDynamicImage *assembly, MonoObject *obj,
gboolean create_open_instance, gboolean register_token)
{
g_assert_not_reached ();
return 0;
}
void
mono_image_register_token (MonoDynamicImage *assembly, guint32 token, MonoObject *obj)
{
}
void
mono_reflection_generic_class_initialize (MonoReflectionGenericClass *type, MonoArray *methods,
MonoArray *ctors, MonoArray *fields, MonoArray *properties,
MonoArray *events)
{
g_assert_not_reached ();
}
void
mono_reflection_get_dynamic_overrides (MonoClass *klass, MonoMethod ***overrides, int *num_overrides)
{
*overrides = NULL;
*num_overrides = 0;
}
MonoReflectionEvent *
mono_reflection_event_builder_get_event_info (MonoReflectionTypeBuilder *tb, MonoReflectionEventBuilder *eb)
{
g_assert_not_reached ();
return NULL;
}
MonoReflectionType*
mono_reflection_create_runtime_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
return NULL;
}
void
mono_reflection_initialize_generic_parameter (MonoReflectionGenericParam *gparam)
{
g_assert_not_reached ();
}
MonoArray *
mono_reflection_sighelper_get_signature_local (MonoReflectionSigHelper *sig)
{
g_assert_not_reached ();
return NULL;
}
MonoArray *
mono_reflection_sighelper_get_signature_field (MonoReflectionSigHelper *sig)
{
g_assert_not_reached ();
return NULL;
}
void
mono_reflection_create_dynamic_method (MonoReflectionDynamicMethod *mb)
{
}
gpointer
mono_reflection_lookup_dynamic_token (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
{
return NULL;
}
MonoType*
mono_reflection_type_get_handle (MonoReflectionType* ref)
{
if (!ref)
return NULL;
return ref->type;
}
#endif /* DISABLE_REFLECTION_EMIT */
/* SECURITY_ACTION_* are defined in mono/metadata/tabledefs.h */
const static guint32 declsec_flags_map[] = {
0x00000000, /* empty */
MONO_DECLSEC_FLAG_REQUEST, /* SECURITY_ACTION_REQUEST (x01) */
MONO_DECLSEC_FLAG_DEMAND, /* SECURITY_ACTION_DEMAND (x02) */
MONO_DECLSEC_FLAG_ASSERT, /* SECURITY_ACTION_ASSERT (x03) */
MONO_DECLSEC_FLAG_DENY, /* SECURITY_ACTION_DENY (x04) */
MONO_DECLSEC_FLAG_PERMITONLY, /* SECURITY_ACTION_PERMITONLY (x05) */
MONO_DECLSEC_FLAG_LINKDEMAND, /* SECURITY_ACTION_LINKDEMAND (x06) */
MONO_DECLSEC_FLAG_INHERITANCEDEMAND, /* SECURITY_ACTION_INHERITANCEDEMAND (x07) */
MONO_DECLSEC_FLAG_REQUEST_MINIMUM, /* SECURITY_ACTION_REQUEST_MINIMUM (x08) */
MONO_DECLSEC_FLAG_REQUEST_OPTIONAL, /* SECURITY_ACTION_REQUEST_OPTIONAL (x09) */
MONO_DECLSEC_FLAG_REQUEST_REFUSE, /* SECURITY_ACTION_REQUEST_REFUSE (x0A) */
MONO_DECLSEC_FLAG_PREJIT_GRANT, /* SECURITY_ACTION_PREJIT_GRANT (x0B) */
MONO_DECLSEC_FLAG_PREJIT_DENY, /* SECURITY_ACTION_PREJIT_DENY (x0C) */
MONO_DECLSEC_FLAG_NONCAS_DEMAND, /* SECURITY_ACTION_NONCAS_DEMAND (x0D) */
MONO_DECLSEC_FLAG_NONCAS_LINKDEMAND, /* SECURITY_ACTION_NONCAS_LINKDEMAND (x0E) */
MONO_DECLSEC_FLAG_NONCAS_INHERITANCEDEMAND, /* SECURITY_ACTION_NONCAS_INHERITANCEDEMAND (x0F) */
MONO_DECLSEC_FLAG_LINKDEMAND_CHOICE, /* SECURITY_ACTION_LINKDEMAND_CHOICE (x10) */
MONO_DECLSEC_FLAG_INHERITANCEDEMAND_CHOICE, /* SECURITY_ACTION_INHERITANCEDEMAND_CHOICE (x11) */
MONO_DECLSEC_FLAG_DEMAND_CHOICE, /* SECURITY_ACTION_DEMAND_CHOICE (x12) */
};
/*
* Returns flags that includes all available security action associated to the handle.
* @token: metadata token (either for a class or a method)
* @image: image where resides the metadata.
*/
static guint32
mono_declsec_get_flags (MonoImage *image, guint32 token)
{
int index = mono_metadata_declsec_from_index (image, token);
MonoTableInfo *t = &image->tables [MONO_TABLE_DECLSECURITY];
guint32 result = 0;
guint32 action;
int i;
/* HasSecurity can be present for other, not specially encoded, attributes,
e.g. SuppressUnmanagedCodeSecurityAttribute */
if (index < 0)
return 0;
for (i = index; i < t->rows; i++) {
guint32 cols [MONO_DECL_SECURITY_SIZE];
mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
if (cols [MONO_DECL_SECURITY_PARENT] != token)
break;
action = cols [MONO_DECL_SECURITY_ACTION];
if ((action >= MONO_DECLSEC_ACTION_MIN) && (action <= MONO_DECLSEC_ACTION_MAX)) {
result |= declsec_flags_map [action];
} else {
g_assert_not_reached ();
}
}
return result;
}
/*
* Get the security actions (in the form of flags) associated with the specified method.
*
* @method: The method for which we want the declarative security flags.
* Return the declarative security flags for the method (only).
*
* Note: To keep MonoMethod size down we do not cache the declarative security flags
* (except for the stack modifiers which are kept in the MonoJitInfo structure)
*/
guint32
mono_declsec_flags_from_method (MonoMethod *method)
{
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
/* FIXME: No cache (for the moment) */
guint32 idx = mono_method_get_index (method);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
return mono_declsec_get_flags (method->klass->image, idx);
}
return 0;
}
/*
* Get the security actions (in the form of flags) associated with the specified class.
*
* @klass: The class for which we want the declarative security flags.
* Return the declarative security flags for the class.
*
* Note: We cache the flags inside the MonoClass structure as this will get
* called very often (at least for each method).
*/
guint32
mono_declsec_flags_from_class (MonoClass *klass)
{
if (klass->flags & TYPE_ATTRIBUTE_HAS_SECURITY) {
if (!klass->ext || !klass->ext->declsec_flags) {
guint32 idx;
idx = mono_metadata_token_index (klass->type_token);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
mono_loader_lock ();
mono_class_alloc_ext (klass);
mono_loader_unlock ();
/* we cache the flags on classes */
klass->ext->declsec_flags = mono_declsec_get_flags (klass->image, idx);
}
return klass->ext->declsec_flags;
}
return 0;
}
/*
* Get the security actions (in the form of flags) associated with the specified assembly.
*
* @assembly: The assembly for which we want the declarative security flags.
* Return the declarative security flags for the assembly.
*/
guint32
mono_declsec_flags_from_assembly (MonoAssembly *assembly)
{
guint32 idx = 1; /* there is only one assembly */
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY;
return mono_declsec_get_flags (assembly->image, idx);
}
/*
* Fill actions for the specific index (which may either be an encoded class token or
* an encoded method token) from the metadata image.
* Returns TRUE if some actions requiring code generation are present, FALSE otherwise.
*/
static MonoBoolean
fill_actions_from_index (MonoImage *image, guint32 token, MonoDeclSecurityActions* actions,
guint32 id_std, guint32 id_noncas, guint32 id_choice)
{
MonoBoolean result = FALSE;
MonoTableInfo *t;
guint32 cols [MONO_DECL_SECURITY_SIZE];
int index = mono_metadata_declsec_from_index (image, token);
int i;
t = &image->tables [MONO_TABLE_DECLSECURITY];
for (i = index; i < t->rows; i++) {
mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
if (cols [MONO_DECL_SECURITY_PARENT] != token)
return result;
/* if present only replace (class) permissions with method permissions */
/* if empty accept either class or method permissions */
if (cols [MONO_DECL_SECURITY_ACTION] == id_std) {
if (!actions->demand.blob) {
const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
actions->demand.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
actions->demand.blob = (char*) (blob + 2);
actions->demand.size = mono_metadata_decode_blob_size (blob, &blob);
result = TRUE;
}
} else if (cols [MONO_DECL_SECURITY_ACTION] == id_noncas) {
if (!actions->noncasdemand.blob) {
const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
actions->noncasdemand.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
actions->noncasdemand.blob = (char*) (blob + 2);
actions->noncasdemand.size = mono_metadata_decode_blob_size (blob, &blob);
result = TRUE;
}
} else if (cols [MONO_DECL_SECURITY_ACTION] == id_choice) {
if (!actions->demandchoice.blob) {
const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
actions->demandchoice.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
actions->demandchoice.blob = (char*) (blob + 2);
actions->demandchoice.size = mono_metadata_decode_blob_size (blob, &blob);
result = TRUE;
}
}
}
return result;
}
static MonoBoolean
mono_declsec_get_class_demands_params (MonoClass *klass, MonoDeclSecurityActions* demands,
guint32 id_std, guint32 id_noncas, guint32 id_choice)
{
guint32 idx = mono_metadata_token_index (klass->type_token);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
return fill_actions_from_index (klass->image, idx, demands, id_std, id_noncas, id_choice);
}
static MonoBoolean
mono_declsec_get_method_demands_params (MonoMethod *method, MonoDeclSecurityActions* demands,
guint32 id_std, guint32 id_noncas, guint32 id_choice)
{
guint32 idx = mono_method_get_index (method);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
return fill_actions_from_index (method->klass->image, idx, demands, id_std, id_noncas, id_choice);
}
/*
* Collect all actions (that requires to generate code in mini) assigned for
* the specified method.
* Note: Don't use the content of actions if the function return FALSE.
*/
MonoBoolean
mono_declsec_get_demands (MonoMethod *method, MonoDeclSecurityActions* demands)
{
guint32 mask = MONO_DECLSEC_FLAG_DEMAND | MONO_DECLSEC_FLAG_NONCAS_DEMAND |
MONO_DECLSEC_FLAG_DEMAND_CHOICE;
MonoBoolean result = FALSE;
guint32 flags;
/* quick exit if no declarative security is present in the metadata */
if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
return FALSE;
/* we want the original as the wrapper is "free" of the security informations */
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
method = mono_marshal_method_from_wrapper (method);
if (!method)
return FALSE;
}
/* First we look for method-level attributes */
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
mono_class_init (method->klass);
memset (demands, 0, sizeof (MonoDeclSecurityActions));
result = mono_declsec_get_method_demands_params (method, demands,
SECURITY_ACTION_DEMAND, SECURITY_ACTION_NONCASDEMAND, SECURITY_ACTION_DEMANDCHOICE);
}
/* Here we use (or create) the class declarative cache to look for demands */
flags = mono_declsec_flags_from_class (method->klass);
if (flags & mask) {
if (!result) {
mono_class_init (method->klass);
memset (demands, 0, sizeof (MonoDeclSecurityActions));
}
result |= mono_declsec_get_class_demands_params (method->klass, demands,
SECURITY_ACTION_DEMAND, SECURITY_ACTION_NONCASDEMAND, SECURITY_ACTION_DEMANDCHOICE);
}
/* The boolean return value is used as a shortcut in case nothing needs to
be generated (e.g. LinkDemand[Choice] and InheritanceDemand[Choice]) */
return result;
}
/*
* Collect all Link actions: LinkDemand, NonCasLinkDemand and LinkDemandChoice (2.0).
*
* Note: Don't use the content of actions if the function return FALSE.
*/
MonoBoolean
mono_declsec_get_linkdemands (MonoMethod *method, MonoDeclSecurityActions* klass, MonoDeclSecurityActions *cmethod)
{
MonoBoolean result = FALSE;
guint32 flags;
/* quick exit if no declarative security is present in the metadata */
if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
return FALSE;
/* we want the original as the wrapper is "free" of the security informations */
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
method = mono_marshal_method_from_wrapper (method);
if (!method)
return FALSE;
}
/* results are independant - zeroize both */
memset (cmethod, 0, sizeof (MonoDeclSecurityActions));
memset (klass, 0, sizeof (MonoDeclSecurityActions));
/* First we look for method-level attributes */
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
mono_class_init (method->klass);
result = mono_declsec_get_method_demands_params (method, cmethod,
SECURITY_ACTION_LINKDEMAND, SECURITY_ACTION_NONCASLINKDEMAND, SECURITY_ACTION_LINKDEMANDCHOICE);
}
/* Here we use (or create) the class declarative cache to look for demands */
flags = mono_declsec_flags_from_class (method->klass);
if (flags & (MONO_DECLSEC_FLAG_LINKDEMAND | MONO_DECLSEC_FLAG_NONCAS_LINKDEMAND | MONO_DECLSEC_FLAG_LINKDEMAND_CHOICE)) {
mono_class_init (method->klass);
result |= mono_declsec_get_class_demands_params (method->klass, klass,
SECURITY_ACTION_LINKDEMAND, SECURITY_ACTION_NONCASLINKDEMAND, SECURITY_ACTION_LINKDEMANDCHOICE);
}
return result;
}
/*
* Collect all Inherit actions: InheritanceDemand, NonCasInheritanceDemand and InheritanceDemandChoice (2.0).
*
* @klass The inherited class - this is the class that provides the security check (attributes)
* @demans
* return TRUE if inheritance demands (any kind) are present, FALSE otherwise.
*
* Note: Don't use the content of actions if the function return FALSE.
*/
MonoBoolean
mono_declsec_get_inheritdemands_class (MonoClass *klass, MonoDeclSecurityActions* demands)
{
MonoBoolean result = FALSE;
guint32 flags;
/* quick exit if no declarative security is present in the metadata */
if (!klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
return FALSE;
/* Here we use (or create) the class declarative cache to look for demands */
flags = mono_declsec_flags_from_class (klass);
if (flags & (MONO_DECLSEC_FLAG_INHERITANCEDEMAND | MONO_DECLSEC_FLAG_NONCAS_INHERITANCEDEMAND | MONO_DECLSEC_FLAG_INHERITANCEDEMAND_CHOICE)) {
mono_class_init (klass);
memset (demands, 0, sizeof (MonoDeclSecurityActions));
result |= mono_declsec_get_class_demands_params (klass, demands,
SECURITY_ACTION_INHERITDEMAND, SECURITY_ACTION_NONCASINHERITANCE, SECURITY_ACTION_INHERITDEMANDCHOICE);
}
return result;
}
/*
* Collect all Inherit actions: InheritanceDemand, NonCasInheritanceDemand and InheritanceDemandChoice (2.0).
*
* Note: Don't use the content of actions if the function return FALSE.
*/
MonoBoolean
mono_declsec_get_inheritdemands_method (MonoMethod *method, MonoDeclSecurityActions* demands)
{
/* quick exit if no declarative security is present in the metadata */
if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
return FALSE;
/* we want the original as the wrapper is "free" of the security informations */
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
method = mono_marshal_method_from_wrapper (method);
if (!method)
return FALSE;
}
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
mono_class_init (method->klass);
memset (demands, 0, sizeof (MonoDeclSecurityActions));
return mono_declsec_get_method_demands_params (method, demands,
SECURITY_ACTION_INHERITDEMAND, SECURITY_ACTION_NONCASINHERITANCE, SECURITY_ACTION_INHERITDEMANDCHOICE);
}
return FALSE;
}
static MonoBoolean
get_declsec_action (MonoImage *image, guint32 token, guint32 action, MonoDeclSecurityEntry *entry)
{
guint32 cols [MONO_DECL_SECURITY_SIZE];
MonoTableInfo *t;
int i;
int index = mono_metadata_declsec_from_index (image, token);
if (index == -1)
return FALSE;
t = &image->tables [MONO_TABLE_DECLSECURITY];
for (i = index; i < t->rows; i++) {
mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
/* shortcut - index are ordered */
if (token != cols [MONO_DECL_SECURITY_PARENT])
return FALSE;
if (cols [MONO_DECL_SECURITY_ACTION] == action) {
const char *metadata = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
entry->blob = (char*) (metadata + 2);
entry->size = mono_metadata_decode_blob_size (metadata, &metadata);
return TRUE;
}
}
return FALSE;
}
MonoBoolean
mono_declsec_get_method_action (MonoMethod *method, guint32 action, MonoDeclSecurityEntry *entry)
{
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
guint32 idx = mono_method_get_index (method);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
return get_declsec_action (method->klass->image, idx, action, entry);
}
return FALSE;
}
MonoBoolean
mono_declsec_get_class_action (MonoClass *klass, guint32 action, MonoDeclSecurityEntry *entry)
{
/* use cache */
guint32 flags = mono_declsec_flags_from_class (klass);
if (declsec_flags_map [action] & flags) {
guint32 idx = mono_metadata_token_index (klass->type_token);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
return get_declsec_action (klass->image, idx, action, entry);
}
return FALSE;
}
MonoBoolean
mono_declsec_get_assembly_action (MonoAssembly *assembly, guint32 action, MonoDeclSecurityEntry *entry)
{
guint32 idx = 1; /* there is only one assembly */
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY;
return get_declsec_action (assembly->image, idx, action, entry);
}
gboolean
mono_reflection_call_is_assignable_to (MonoClass *klass, MonoClass *oklass)
{
MonoObject *res, *exc;
void *params [1];
static MonoClass *System_Reflection_Emit_TypeBuilder = NULL;
static MonoMethod *method = NULL;
if (!System_Reflection_Emit_TypeBuilder) {
System_Reflection_Emit_TypeBuilder = mono_class_from_name (mono_defaults.corlib, "System.Reflection.Emit", "TypeBuilder");
g_assert (System_Reflection_Emit_TypeBuilder);
}
if (method == NULL) {
method = mono_class_get_method_from_name (System_Reflection_Emit_TypeBuilder, "IsAssignableTo", 1);
g_assert (method);
}
/*
* The result of mono_type_get_object () might be a System.MonoType but we
* need a TypeBuilder so use mono_class_get_ref_info (klass).
*/
g_assert (mono_class_get_ref_info (klass));
g_assert (!strcmp (((MonoObject*)(mono_class_get_ref_info (klass)))->vtable->klass->name, "TypeBuilder"));
params [0] = mono_type_get_object (mono_domain_get (), &oklass->byval_arg);
res = mono_runtime_invoke (method, (MonoObject*)(mono_class_get_ref_info (klass)), params, &exc);
if (exc)
return FALSE;
else
return *(MonoBoolean*)mono_object_unbox (res);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_4718_0 |
crossvul-cpp_data_good_1718_1 | /* $OpenBSD: monitor_wrap.c,v 1.85 2015/05/01 03:23:51 djm Exp $ */
/*
* Copyright 2002 Niels Provos <provos@citi.umich.edu>
* Copyright 2002 Markus Friedl <markus@openbsd.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "includes.h"
#include <sys/types.h>
#include <sys/uio.h>
#include <errno.h>
#include <pwd.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#ifdef WITH_OPENSSL
#include <openssl/bn.h>
#include <openssl/dh.h>
#include <openssl/evp.h>
#endif
#include "openbsd-compat/sys-queue.h"
#include "xmalloc.h"
#include "ssh.h"
#ifdef WITH_OPENSSL
#include "dh.h"
#endif
#include "buffer.h"
#include "key.h"
#include "cipher.h"
#include "kex.h"
#include "hostfile.h"
#include "auth.h"
#include "auth-options.h"
#include "packet.h"
#include "mac.h"
#include "log.h"
#ifdef TARGET_OS_MAC /* XXX Broken krb5 headers on Mac */
#undef TARGET_OS_MAC
#include "zlib.h"
#define TARGET_OS_MAC 1
#else
#include "zlib.h"
#endif
#include "monitor.h"
#ifdef GSSAPI
#include "ssh-gss.h"
#endif
#include "monitor_wrap.h"
#include "atomicio.h"
#include "monitor_fdpass.h"
#include "misc.h"
#include "uuencode.h"
#include "channels.h"
#include "session.h"
#include "servconf.h"
#include "roaming.h"
#include "ssherr.h"
/* Imports */
extern int compat20;
extern z_stream incoming_stream;
extern z_stream outgoing_stream;
extern struct monitor *pmonitor;
extern Buffer loginmsg;
extern ServerOptions options;
void
mm_log_handler(LogLevel level, const char *msg, void *ctx)
{
Buffer log_msg;
struct monitor *mon = (struct monitor *)ctx;
if (mon->m_log_sendfd == -1)
fatal("%s: no log channel", __func__);
buffer_init(&log_msg);
/*
* Placeholder for packet length. Will be filled in with the actual
* packet length once the packet has been constucted. This saves
* fragile math.
*/
buffer_put_int(&log_msg, 0);
buffer_put_int(&log_msg, level);
buffer_put_cstring(&log_msg, msg);
put_u32(buffer_ptr(&log_msg), buffer_len(&log_msg) - 4);
if (atomicio(vwrite, mon->m_log_sendfd, buffer_ptr(&log_msg),
buffer_len(&log_msg)) != buffer_len(&log_msg))
fatal("%s: write: %s", __func__, strerror(errno));
buffer_free(&log_msg);
}
int
mm_is_monitor(void)
{
/*
* m_pid is only set in the privileged part, and
* points to the unprivileged child.
*/
return (pmonitor && pmonitor->m_pid > 0);
}
void
mm_request_send(int sock, enum monitor_reqtype type, Buffer *m)
{
u_int mlen = buffer_len(m);
u_char buf[5];
debug3("%s entering: type %d", __func__, type);
put_u32(buf, mlen + 1);
buf[4] = (u_char) type; /* 1st byte of payload is mesg-type */
if (atomicio(vwrite, sock, buf, sizeof(buf)) != sizeof(buf))
fatal("%s: write: %s", __func__, strerror(errno));
if (atomicio(vwrite, sock, buffer_ptr(m), mlen) != mlen)
fatal("%s: write: %s", __func__, strerror(errno));
}
void
mm_request_receive(int sock, Buffer *m)
{
u_char buf[4];
u_int msg_len;
debug3("%s entering", __func__);
if (atomicio(read, sock, buf, sizeof(buf)) != sizeof(buf)) {
if (errno == EPIPE)
cleanup_exit(255);
fatal("%s: read: %s", __func__, strerror(errno));
}
msg_len = get_u32(buf);
if (msg_len > 256 * 1024)
fatal("%s: read: bad msg_len %d", __func__, msg_len);
buffer_clear(m);
buffer_append_space(m, msg_len);
if (atomicio(read, sock, buffer_ptr(m), msg_len) != msg_len)
fatal("%s: read: %s", __func__, strerror(errno));
}
void
mm_request_receive_expect(int sock, enum monitor_reqtype type, Buffer *m)
{
u_char rtype;
debug3("%s entering: type %d", __func__, type);
mm_request_receive(sock, m);
rtype = buffer_get_char(m);
if (rtype != type)
fatal("%s: read: rtype %d != type %d", __func__,
rtype, type);
}
#ifdef WITH_OPENSSL
DH *
mm_choose_dh(int min, int nbits, int max)
{
BIGNUM *p, *g;
int success = 0;
Buffer m;
buffer_init(&m);
buffer_put_int(&m, min);
buffer_put_int(&m, nbits);
buffer_put_int(&m, max);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_MODULI, &m);
debug3("%s: waiting for MONITOR_ANS_MODULI", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_MODULI, &m);
success = buffer_get_char(&m);
if (success == 0)
fatal("%s: MONITOR_ANS_MODULI failed", __func__);
if ((p = BN_new()) == NULL)
fatal("%s: BN_new failed", __func__);
if ((g = BN_new()) == NULL)
fatal("%s: BN_new failed", __func__);
buffer_get_bignum2(&m, p);
buffer_get_bignum2(&m, g);
debug3("%s: remaining %d", __func__, buffer_len(&m));
buffer_free(&m);
return (dh_new_group(g, p));
}
#endif
int
mm_key_sign(Key *key, u_char **sigp, u_int *lenp,
const u_char *data, u_int datalen)
{
struct kex *kex = *pmonitor->m_pkex;
Buffer m;
debug3("%s entering", __func__);
buffer_init(&m);
buffer_put_int(&m, kex->host_key_index(key, 0, active_state));
buffer_put_string(&m, data, datalen);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SIGN, &m);
debug3("%s: waiting for MONITOR_ANS_SIGN", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_SIGN, &m);
*sigp = buffer_get_string(&m, lenp);
buffer_free(&m);
return (0);
}
struct passwd *
mm_getpwnamallow(const char *username)
{
Buffer m;
struct passwd *pw;
u_int len, i;
ServerOptions *newopts;
debug3("%s entering", __func__);
buffer_init(&m);
buffer_put_cstring(&m, username);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PWNAM, &m);
debug3("%s: waiting for MONITOR_ANS_PWNAM", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PWNAM, &m);
if (buffer_get_char(&m) == 0) {
pw = NULL;
goto out;
}
pw = buffer_get_string(&m, &len);
if (len != sizeof(struct passwd))
fatal("%s: struct passwd size mismatch", __func__);
pw->pw_name = buffer_get_string(&m, NULL);
pw->pw_passwd = buffer_get_string(&m, NULL);
#ifdef HAVE_STRUCT_PASSWD_PW_GECOS
pw->pw_gecos = buffer_get_string(&m, NULL);
#endif
#ifdef HAVE_STRUCT_PASSWD_PW_CLASS
pw->pw_class = buffer_get_string(&m, NULL);
#endif
pw->pw_dir = buffer_get_string(&m, NULL);
pw->pw_shell = buffer_get_string(&m, NULL);
out:
/* copy options block as a Match directive may have changed some */
newopts = buffer_get_string(&m, &len);
if (len != sizeof(*newopts))
fatal("%s: option block size mismatch", __func__);
#define M_CP_STROPT(x) do { \
if (newopts->x != NULL) \
newopts->x = buffer_get_string(&m, NULL); \
} while (0)
#define M_CP_STRARRAYOPT(x, nx) do { \
for (i = 0; i < newopts->nx; i++) \
newopts->x[i] = buffer_get_string(&m, NULL); \
} while (0)
/* See comment in servconf.h */
COPY_MATCH_STRING_OPTS();
#undef M_CP_STROPT
#undef M_CP_STRARRAYOPT
copy_set_server_options(&options, newopts, 1);
free(newopts);
buffer_free(&m);
return (pw);
}
char *
mm_auth2_read_banner(void)
{
Buffer m;
char *banner;
debug3("%s entering", __func__);
buffer_init(&m);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_AUTH2_READ_BANNER, &m);
buffer_clear(&m);
mm_request_receive_expect(pmonitor->m_recvfd,
MONITOR_ANS_AUTH2_READ_BANNER, &m);
banner = buffer_get_string(&m, NULL);
buffer_free(&m);
/* treat empty banner as missing banner */
if (strlen(banner) == 0) {
free(banner);
banner = NULL;
}
return (banner);
}
/* Inform the privileged process about service and style */
void
mm_inform_authserv(char *service, char *style)
{
Buffer m;
debug3("%s entering", __func__);
buffer_init(&m);
buffer_put_cstring(&m, service);
buffer_put_cstring(&m, style ? style : "");
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_AUTHSERV, &m);
buffer_free(&m);
}
/* Do the password authentication */
int
mm_auth_password(Authctxt *authctxt, char *password)
{
Buffer m;
int authenticated = 0;
debug3("%s entering", __func__);
buffer_init(&m);
buffer_put_cstring(&m, password);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_AUTHPASSWORD, &m);
debug3("%s: waiting for MONITOR_ANS_AUTHPASSWORD", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_AUTHPASSWORD, &m);
authenticated = buffer_get_int(&m);
buffer_free(&m);
debug3("%s: user %sauthenticated",
__func__, authenticated ? "" : "not ");
return (authenticated);
}
int
mm_user_key_allowed(struct passwd *pw, Key *key, int pubkey_auth_attempt)
{
return (mm_key_allowed(MM_USERKEY, NULL, NULL, key,
pubkey_auth_attempt));
}
int
mm_hostbased_key_allowed(struct passwd *pw, char *user, char *host,
Key *key)
{
return (mm_key_allowed(MM_HOSTKEY, user, host, key, 0));
}
int
mm_auth_rhosts_rsa_key_allowed(struct passwd *pw, char *user,
char *host, Key *key)
{
int ret;
key->type = KEY_RSA; /* XXX hack for key_to_blob */
ret = mm_key_allowed(MM_RSAHOSTKEY, user, host, key, 0);
key->type = KEY_RSA1;
return (ret);
}
int
mm_key_allowed(enum mm_keytype type, char *user, char *host, Key *key,
int pubkey_auth_attempt)
{
Buffer m;
u_char *blob;
u_int len;
int allowed = 0, have_forced = 0;
debug3("%s entering", __func__);
/* Convert the key to a blob and the pass it over */
if (!key_to_blob(key, &blob, &len))
return (0);
buffer_init(&m);
buffer_put_int(&m, type);
buffer_put_cstring(&m, user ? user : "");
buffer_put_cstring(&m, host ? host : "");
buffer_put_string(&m, blob, len);
buffer_put_int(&m, pubkey_auth_attempt);
free(blob);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_KEYALLOWED, &m);
debug3("%s: waiting for MONITOR_ANS_KEYALLOWED", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_KEYALLOWED, &m);
allowed = buffer_get_int(&m);
/* fake forced command */
auth_clear_options();
have_forced = buffer_get_int(&m);
forced_command = have_forced ? xstrdup("true") : NULL;
buffer_free(&m);
return (allowed);
}
/*
* This key verify needs to send the key type along, because the
* privileged parent makes the decision if the key is allowed
* for authentication.
*/
int
mm_key_verify(Key *key, u_char *sig, u_int siglen, u_char *data, u_int datalen)
{
Buffer m;
u_char *blob;
u_int len;
int verified = 0;
debug3("%s entering", __func__);
/* Convert the key to a blob and the pass it over */
if (!key_to_blob(key, &blob, &len))
return (0);
buffer_init(&m);
buffer_put_string(&m, blob, len);
buffer_put_string(&m, sig, siglen);
buffer_put_string(&m, data, datalen);
free(blob);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_KEYVERIFY, &m);
debug3("%s: waiting for MONITOR_ANS_KEYVERIFY", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_KEYVERIFY, &m);
verified = buffer_get_int(&m);
buffer_free(&m);
return (verified);
}
void
mm_send_keystate(struct monitor *monitor)
{
struct ssh *ssh = active_state; /* XXX */
struct sshbuf *m;
int r;
if ((m = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if ((r = ssh_packet_get_state(ssh, m)) != 0)
fatal("%s: get_state failed: %s",
__func__, ssh_err(r));
mm_request_send(monitor->m_recvfd, MONITOR_REQ_KEYEXPORT, m);
debug3("%s: Finished sending state", __func__);
sshbuf_free(m);
}
int
mm_pty_allocate(int *ptyfd, int *ttyfd, char *namebuf, size_t namebuflen)
{
Buffer m;
char *p, *msg;
int success = 0, tmp1 = -1, tmp2 = -1;
/* Kludge: ensure there are fds free to receive the pty/tty */
if ((tmp1 = dup(pmonitor->m_recvfd)) == -1 ||
(tmp2 = dup(pmonitor->m_recvfd)) == -1) {
error("%s: cannot allocate fds for pty", __func__);
if (tmp1 > 0)
close(tmp1);
if (tmp2 > 0)
close(tmp2);
return 0;
}
close(tmp1);
close(tmp2);
buffer_init(&m);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PTY, &m);
debug3("%s: waiting for MONITOR_ANS_PTY", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PTY, &m);
success = buffer_get_int(&m);
if (success == 0) {
debug3("%s: pty alloc failed", __func__);
buffer_free(&m);
return (0);
}
p = buffer_get_string(&m, NULL);
msg = buffer_get_string(&m, NULL);
buffer_free(&m);
strlcpy(namebuf, p, namebuflen); /* Possible truncation */
free(p);
buffer_append(&loginmsg, msg, strlen(msg));
free(msg);
if ((*ptyfd = mm_receive_fd(pmonitor->m_recvfd)) == -1 ||
(*ttyfd = mm_receive_fd(pmonitor->m_recvfd)) == -1)
fatal("%s: receive fds failed", __func__);
/* Success */
return (1);
}
void
mm_session_pty_cleanup2(Session *s)
{
Buffer m;
if (s->ttyfd == -1)
return;
buffer_init(&m);
buffer_put_cstring(&m, s->tty);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PTYCLEANUP, &m);
buffer_free(&m);
/* closed dup'ed master */
if (s->ptymaster != -1 && close(s->ptymaster) < 0)
error("close(s->ptymaster/%d): %s",
s->ptymaster, strerror(errno));
/* unlink pty from session */
s->ttyfd = -1;
}
#ifdef USE_PAM
void
mm_start_pam(Authctxt *authctxt)
{
Buffer m;
debug3("%s entering", __func__);
if (!options.use_pam)
fatal("UsePAM=no, but ended up in %s anyway", __func__);
buffer_init(&m);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_START, &m);
buffer_free(&m);
}
u_int
mm_do_pam_account(void)
{
Buffer m;
u_int ret;
char *msg;
debug3("%s entering", __func__);
if (!options.use_pam)
fatal("UsePAM=no, but ended up in %s anyway", __func__);
buffer_init(&m);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_ACCOUNT, &m);
mm_request_receive_expect(pmonitor->m_recvfd,
MONITOR_ANS_PAM_ACCOUNT, &m);
ret = buffer_get_int(&m);
msg = buffer_get_string(&m, NULL);
buffer_append(&loginmsg, msg, strlen(msg));
free(msg);
buffer_free(&m);
debug3("%s returning %d", __func__, ret);
return (ret);
}
void *
mm_sshpam_init_ctx(Authctxt *authctxt)
{
Buffer m;
int success;
debug3("%s", __func__);
buffer_init(&m);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_INIT_CTX, &m);
debug3("%s: waiting for MONITOR_ANS_PAM_INIT_CTX", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_INIT_CTX, &m);
success = buffer_get_int(&m);
if (success == 0) {
debug3("%s: pam_init_ctx failed", __func__);
buffer_free(&m);
return (NULL);
}
buffer_free(&m);
return (authctxt);
}
int
mm_sshpam_query(void *ctx, char **name, char **info,
u_int *num, char ***prompts, u_int **echo_on)
{
Buffer m;
u_int i;
int ret;
debug3("%s", __func__);
buffer_init(&m);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_QUERY, &m);
debug3("%s: waiting for MONITOR_ANS_PAM_QUERY", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_QUERY, &m);
ret = buffer_get_int(&m);
debug3("%s: pam_query returned %d", __func__, ret);
*name = buffer_get_string(&m, NULL);
*info = buffer_get_string(&m, NULL);
*num = buffer_get_int(&m);
if (*num > PAM_MAX_NUM_MSG)
fatal("%s: recieved %u PAM messages, expected <= %u",
__func__, *num, PAM_MAX_NUM_MSG);
*prompts = xcalloc((*num + 1), sizeof(char *));
*echo_on = xcalloc((*num + 1), sizeof(u_int));
for (i = 0; i < *num; ++i) {
(*prompts)[i] = buffer_get_string(&m, NULL);
(*echo_on)[i] = buffer_get_int(&m);
}
buffer_free(&m);
return (ret);
}
int
mm_sshpam_respond(void *ctx, u_int num, char **resp)
{
Buffer m;
u_int i;
int ret;
debug3("%s", __func__);
buffer_init(&m);
buffer_put_int(&m, num);
for (i = 0; i < num; ++i)
buffer_put_cstring(&m, resp[i]);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_RESPOND, &m);
debug3("%s: waiting for MONITOR_ANS_PAM_RESPOND", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_RESPOND, &m);
ret = buffer_get_int(&m);
debug3("%s: pam_respond returned %d", __func__, ret);
buffer_free(&m);
return (ret);
}
void
mm_sshpam_free_ctx(void *ctxtp)
{
Buffer m;
debug3("%s", __func__);
buffer_init(&m);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_FREE_CTX, &m);
debug3("%s: waiting for MONITOR_ANS_PAM_FREE_CTX", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_FREE_CTX, &m);
buffer_free(&m);
}
#endif /* USE_PAM */
/* Request process termination */
void
mm_terminate(void)
{
Buffer m;
buffer_init(&m);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_TERM, &m);
buffer_free(&m);
}
#ifdef WITH_SSH1
int
mm_ssh1_session_key(BIGNUM *num)
{
int rsafail;
Buffer m;
buffer_init(&m);
buffer_put_bignum2(&m, num);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SESSKEY, &m);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_SESSKEY, &m);
rsafail = buffer_get_int(&m);
buffer_get_bignum2(&m, num);
buffer_free(&m);
return (rsafail);
}
#endif
static void
mm_chall_setup(char **name, char **infotxt, u_int *numprompts,
char ***prompts, u_int **echo_on)
{
*name = xstrdup("");
*infotxt = xstrdup("");
*numprompts = 1;
*prompts = xcalloc(*numprompts, sizeof(char *));
*echo_on = xcalloc(*numprompts, sizeof(u_int));
(*echo_on)[0] = 0;
}
int
mm_bsdauth_query(void *ctx, char **name, char **infotxt,
u_int *numprompts, char ***prompts, u_int **echo_on)
{
Buffer m;
u_int success;
char *challenge;
debug3("%s: entering", __func__);
buffer_init(&m);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_BSDAUTHQUERY, &m);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_BSDAUTHQUERY,
&m);
success = buffer_get_int(&m);
if (success == 0) {
debug3("%s: no challenge", __func__);
buffer_free(&m);
return (-1);
}
/* Get the challenge, and format the response */
challenge = buffer_get_string(&m, NULL);
buffer_free(&m);
mm_chall_setup(name, infotxt, numprompts, prompts, echo_on);
(*prompts)[0] = challenge;
debug3("%s: received challenge: %s", __func__, challenge);
return (0);
}
int
mm_bsdauth_respond(void *ctx, u_int numresponses, char **responses)
{
Buffer m;
int authok;
debug3("%s: entering", __func__);
if (numresponses != 1)
return (-1);
buffer_init(&m);
buffer_put_cstring(&m, responses[0]);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_BSDAUTHRESPOND, &m);
mm_request_receive_expect(pmonitor->m_recvfd,
MONITOR_ANS_BSDAUTHRESPOND, &m);
authok = buffer_get_int(&m);
buffer_free(&m);
return ((authok == 0) ? -1 : 0);
}
#ifdef SKEY
int
mm_skey_query(void *ctx, char **name, char **infotxt,
u_int *numprompts, char ***prompts, u_int **echo_on)
{
Buffer m;
u_int success;
char *challenge;
debug3("%s: entering", __func__);
buffer_init(&m);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SKEYQUERY, &m);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_SKEYQUERY,
&m);
success = buffer_get_int(&m);
if (success == 0) {
debug3("%s: no challenge", __func__);
buffer_free(&m);
return (-1);
}
/* Get the challenge, and format the response */
challenge = buffer_get_string(&m, NULL);
buffer_free(&m);
debug3("%s: received challenge: %s", __func__, challenge);
mm_chall_setup(name, infotxt, numprompts, prompts, echo_on);
xasprintf(*prompts, "%s%s", challenge, SKEY_PROMPT);
free(challenge);
return (0);
}
int
mm_skey_respond(void *ctx, u_int numresponses, char **responses)
{
Buffer m;
int authok;
debug3("%s: entering", __func__);
if (numresponses != 1)
return (-1);
buffer_init(&m);
buffer_put_cstring(&m, responses[0]);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SKEYRESPOND, &m);
mm_request_receive_expect(pmonitor->m_recvfd,
MONITOR_ANS_SKEYRESPOND, &m);
authok = buffer_get_int(&m);
buffer_free(&m);
return ((authok == 0) ? -1 : 0);
}
#endif /* SKEY */
void
mm_ssh1_session_id(u_char session_id[16])
{
Buffer m;
int i;
debug3("%s entering", __func__);
buffer_init(&m);
for (i = 0; i < 16; i++)
buffer_put_char(&m, session_id[i]);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SESSID, &m);
buffer_free(&m);
}
#ifdef WITH_SSH1
int
mm_auth_rsa_key_allowed(struct passwd *pw, BIGNUM *client_n, Key **rkey)
{
Buffer m;
Key *key;
u_char *blob;
u_int blen;
int allowed = 0, have_forced = 0;
debug3("%s entering", __func__);
buffer_init(&m);
buffer_put_bignum2(&m, client_n);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_RSAKEYALLOWED, &m);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_RSAKEYALLOWED, &m);
allowed = buffer_get_int(&m);
/* fake forced command */
auth_clear_options();
have_forced = buffer_get_int(&m);
forced_command = have_forced ? xstrdup("true") : NULL;
if (allowed && rkey != NULL) {
blob = buffer_get_string(&m, &blen);
if ((key = key_from_blob(blob, blen)) == NULL)
fatal("%s: key_from_blob failed", __func__);
*rkey = key;
free(blob);
}
buffer_free(&m);
return (allowed);
}
BIGNUM *
mm_auth_rsa_generate_challenge(Key *key)
{
Buffer m;
BIGNUM *challenge;
u_char *blob;
u_int blen;
debug3("%s entering", __func__);
if ((challenge = BN_new()) == NULL)
fatal("%s: BN_new failed", __func__);
key->type = KEY_RSA; /* XXX cheat for key_to_blob */
if (key_to_blob(key, &blob, &blen) == 0)
fatal("%s: key_to_blob failed", __func__);
key->type = KEY_RSA1;
buffer_init(&m);
buffer_put_string(&m, blob, blen);
free(blob);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_RSACHALLENGE, &m);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_RSACHALLENGE, &m);
buffer_get_bignum2(&m, challenge);
buffer_free(&m);
return (challenge);
}
int
mm_auth_rsa_verify_response(Key *key, BIGNUM *p, u_char response[16])
{
Buffer m;
u_char *blob;
u_int blen;
int success = 0;
debug3("%s entering", __func__);
key->type = KEY_RSA; /* XXX cheat for key_to_blob */
if (key_to_blob(key, &blob, &blen) == 0)
fatal("%s: key_to_blob failed", __func__);
key->type = KEY_RSA1;
buffer_init(&m);
buffer_put_string(&m, blob, blen);
buffer_put_string(&m, response, 16);
free(blob);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_RSARESPONSE, &m);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_RSARESPONSE, &m);
success = buffer_get_int(&m);
buffer_free(&m);
return (success);
}
#endif
#ifdef SSH_AUDIT_EVENTS
void
mm_audit_event(ssh_audit_event_t event)
{
Buffer m;
debug3("%s entering", __func__);
buffer_init(&m);
buffer_put_int(&m, event);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_AUDIT_EVENT, &m);
buffer_free(&m);
}
void
mm_audit_run_command(const char *command)
{
Buffer m;
debug3("%s entering command %s", __func__, command);
buffer_init(&m);
buffer_put_cstring(&m, command);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_AUDIT_COMMAND, &m);
buffer_free(&m);
}
#endif /* SSH_AUDIT_EVENTS */
#ifdef GSSAPI
OM_uint32
mm_ssh_gssapi_server_ctx(Gssctxt **ctx, gss_OID goid)
{
Buffer m;
OM_uint32 major;
/* Client doesn't get to see the context */
*ctx = NULL;
buffer_init(&m);
buffer_put_string(&m, goid->elements, goid->length);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSSETUP, &m);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSSETUP, &m);
major = buffer_get_int(&m);
buffer_free(&m);
return (major);
}
OM_uint32
mm_ssh_gssapi_accept_ctx(Gssctxt *ctx, gss_buffer_desc *in,
gss_buffer_desc *out, OM_uint32 *flags)
{
Buffer m;
OM_uint32 major;
u_int len;
buffer_init(&m);
buffer_put_string(&m, in->value, in->length);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSSTEP, &m);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSSTEP, &m);
major = buffer_get_int(&m);
out->value = buffer_get_string(&m, &len);
out->length = len;
if (flags)
*flags = buffer_get_int(&m);
buffer_free(&m);
return (major);
}
OM_uint32
mm_ssh_gssapi_checkmic(Gssctxt *ctx, gss_buffer_t gssbuf, gss_buffer_t gssmic)
{
Buffer m;
OM_uint32 major;
buffer_init(&m);
buffer_put_string(&m, gssbuf->value, gssbuf->length);
buffer_put_string(&m, gssmic->value, gssmic->length);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSCHECKMIC, &m);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSCHECKMIC,
&m);
major = buffer_get_int(&m);
buffer_free(&m);
return(major);
}
int
mm_ssh_gssapi_userok(char *user)
{
Buffer m;
int authenticated = 0;
buffer_init(&m);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSUSEROK, &m);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSUSEROK,
&m);
authenticated = buffer_get_int(&m);
buffer_free(&m);
debug3("%s: user %sauthenticated",__func__, authenticated ? "" : "not ");
return (authenticated);
}
#endif /* GSSAPI */
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_1718_1 |
crossvul-cpp_data_bad_4286_0 | /* CBOR-to-JSON translation utility */
#include "rtjsonsrc/osrtjson.h"
#include "rtcborsrc/osrtcbor.h"
#include "rtxsrc/rtxCharStr.h"
#include "rtxsrc/rtxContext.h"
#include "rtxsrc/rtxFile.h"
#include "rtxsrc/rtxHexDump.h"
#include <stdio.h>
#ifndef _NO_INT64_SUPPORT
#define OSUINTTYPE OSUINT64
#define OSINTTYPE OSINT64
#define rtCborDecUInt rtCborDecUInt64
#define rtCborDecInt rtCborDecInt64
#else
#define OSUINTTYPE OSUINT32
#define OSINTTYPE OSINT32
#define rtCborDecUInt rtCborDecUInt32
#define rtCborDecInt rtCborDecInt32
#endif
static int cborTagNotSupp (OSCTXT* pctxt, OSOCTET tag)
{
char numbuf[10];
char errtext[80];
rtxUIntToCharStr (tag, numbuf, sizeof(numbuf), 0);
rtxStrJoin (errtext, sizeof(errtext), "CBOR tag ", numbuf, 0, 0, 0);
rtxErrAddStrParm (pctxt, errtext);
return RTERR_NOTSUPP;
}
static int cborElemNameToJson (OSCTXT* pCborCtxt, OSCTXT* pJsonCtxt)
{
char* pElemName = 0;
OSOCTET ub;
int ret;
/* Read byte from stream */
ret = rtxReadBytes (pCborCtxt, &ub, 1);
if (0 != ret) return LOG_RTERR (pCborCtxt, ret);
/* Decode element name (note: only string type is currently supported) */
ret = rtCborDecDynUTF8Str (pCborCtxt, ub, &pElemName);
if (0 != ret) return LOG_RTERR (pCborCtxt, ret);
/* Encode map element name as string */
ret = rtJsonEncStringValue (pJsonCtxt, (const OSUTF8CHAR*)pElemName);
rtxMemFreePtr (pCborCtxt, pElemName);
if (0 != ret) return LOG_RTERR (pJsonCtxt, ret);
OSRTSAFEPUTCHAR (pJsonCtxt, ':');
return 0;
}
static int cbor2json (OSCTXT* pCborCtxt, OSCTXT* pJsonCtxt)
{
int ret = 0;
OSOCTET tag, ub;
/* Read byte from stream */
ret = rtxReadBytes (pCborCtxt, &ub, 1);
if (0 != ret) return LOG_RTERR (pCborCtxt, ret);
tag = ub >> 5;
/* Switch on tag value */
switch (tag) {
case OSRTCBOR_UINT: {
OSUINTTYPE value;
ret = rtCborDecUInt (pCborCtxt, ub, &value);
if (0 != ret) return LOG_RTERR (pCborCtxt, ret);
/* Encode JSON */
#ifndef _NO_INT64_SUPPORT
ret = rtJsonEncUInt64Value (pJsonCtxt, value);
#else
ret = rtJsonEncUIntValue (pJsonCtxt, value);
#endif
if (0 != ret) return LOG_RTERR (pJsonCtxt, ret);
break;
}
case OSRTCBOR_NEGINT: {
OSINTTYPE value;
ret = rtCborDecInt (pCborCtxt, ub, &value);
if (0 != ret) return LOG_RTERR (pCborCtxt, ret);
/* Encode JSON */
#ifndef _NO_INT64_SUPPORT
ret = rtJsonEncInt64Value (pJsonCtxt, value);
#else
ret = rtJsonEncIntValue (pJsonCtxt, value);
#endif
if (0 != ret) return LOG_RTERR (pJsonCtxt, ret);
break;
}
case OSRTCBOR_BYTESTR: {
OSDynOctStr64 byteStr;
ret = rtCborDecDynByteStr (pCborCtxt, ub, &byteStr);
if (0 != ret) return LOG_RTERR (pCborCtxt, ret);
/* Encode JSON */
ret = rtJsonEncHexStr (pJsonCtxt, byteStr.numocts, byteStr.data);
rtxMemFreePtr (pCborCtxt, byteStr.data);
if (0 != ret) return LOG_RTERR (pJsonCtxt, ret);
break;
}
case OSRTCBOR_UTF8STR: {
OSUTF8CHAR* utf8str;
ret = rtCborDecDynUTF8Str (pCborCtxt, ub, (char**)&utf8str);
ret = rtJsonEncStringValue (pJsonCtxt, utf8str);
rtxMemFreePtr (pCborCtxt, utf8str);
if (0 != ret) return LOG_RTERR (pJsonCtxt, ret);
break;
}
case OSRTCBOR_ARRAY:
case OSRTCBOR_MAP: {
OSOCTET len = ub & 0x1F;
char startChar = (tag == OSRTCBOR_ARRAY) ? '[' : '{';
char endChar = (tag == OSRTCBOR_ARRAY) ? ']' : '}';
OSRTSAFEPUTCHAR (pJsonCtxt, startChar);
if (len == OSRTCBOR_INDEF) {
OSBOOL first = TRUE;
for (;;) {
if (OSRTCBOR_MATCHEOC (pCborCtxt)) {
pCborCtxt->buffer.byteIndex++;
break;
}
if (!first)
OSRTSAFEPUTCHAR (pJsonCtxt, ',');
else
first = FALSE;
/* If map, decode object name */
if (tag == OSRTCBOR_MAP) {
ret = cborElemNameToJson (pCborCtxt, pJsonCtxt);
}
/* Make recursive call */
if (0 == ret)
ret = cbor2json (pCborCtxt, pJsonCtxt);
if (0 != ret) {
OSCTXT* pctxt =
(rtxErrGetErrorCnt(pJsonCtxt) > 0) ? pJsonCtxt : pCborCtxt;
return LOG_RTERR (pctxt, ret);
}
}
}
else { /* definite length */
OSSIZE nitems;
/* Decode tag and number of items */
ret = rtCborDecSize (pCborCtxt, len, &nitems);
if (0 == ret) {
OSSIZE i;
/* Loop to decode array items */
for (i = 0; i < nitems; i++) {
if (0 != i) OSRTSAFEPUTCHAR (pJsonCtxt, ',');
/* If map, decode object name */
if (tag == OSRTCBOR_MAP) {
ret = cborElemNameToJson (pCborCtxt, pJsonCtxt);
}
/* Make recursive call */
if (0 == ret)
ret = cbor2json (pCborCtxt, pJsonCtxt);
if (0 != ret) {
OSCTXT* pctxt =
(rtxErrGetErrorCnt(pJsonCtxt) > 0) ? pJsonCtxt : pCborCtxt;
return LOG_RTERR (pctxt, ret);
}
}
}
}
OSRTSAFEPUTCHAR (pJsonCtxt, endChar);
break;
}
case OSRTCBOR_FLOAT:
if (tag == OSRTCBOR_FALSEENC || tag == OSRTCBOR_TRUEENC) {
OSBOOL boolval = (ub == OSRTCBOR_TRUEENC) ? TRUE : FALSE;
ret = rtJsonEncBoolValue (pJsonCtxt, boolval);
if (0 != ret) return LOG_RTERR (pJsonCtxt, ret);
}
else if (tag == OSRTCBOR_FLT16ENC ||
tag == OSRTCBOR_FLT32ENC ||
tag == OSRTCBOR_FLT64ENC) {
OSDOUBLE fltval;
ret = rtCborDecFloat (pCborCtxt, ub, &fltval);
if (0 != ret) return LOG_RTERR (pCborCtxt, ret);
/* Encode JSON */
ret = rtJsonEncDoubleValue (pJsonCtxt, fltval, 0);
if (0 != ret) return LOG_RTERR (pJsonCtxt, ret);
}
else {
ret = cborTagNotSupp (pCborCtxt, tag);
}
break;
default:
ret = cborTagNotSupp (pCborCtxt, tag);
}
return ret;
}
int main (int argc, char** argv)
{
OSCTXT jsonCtxt, cborCtxt;
OSOCTET* pMsgBuf = 0;
size_t msglen;
OSBOOL verbose = FALSE;
const char* filename = "message.cbor";
const char* outfname = "message.json";
int ret;
/* Process command line arguments */
if (argc > 1) {
int i;
for (i = 1; i < argc; i++) {
if (!strcmp (argv[i], "-v")) verbose = TRUE;
else if (!strcmp (argv[i], "-i")) filename = argv[++i];
else if (!strcmp (argv[i], "-o")) outfname = argv[++i];
else {
printf ("usage: cbor2json [-v] [-i <filename>] [-o filename]\n");
printf (" -v verbose mode: print trace info\n");
printf (" -i <filename> read CBOR msg from <filename>\n");
printf (" -o <filename> write JSON data to <filename>\n");
return 1;
}
}
}
/* Initialize context structures */
ret = rtxInitContext (&jsonCtxt);
if (ret != 0) {
rtxErrPrint (&jsonCtxt);
return ret;
}
rtxErrInit();
/* rtxSetDiag (&jsonCtxt, verbose); */
ret = rtxInitContext (&cborCtxt);
if (ret != 0) {
rtxErrPrint (&cborCtxt);
return ret;
}
/* rtxSetDiag (&cborCtxt, verbose); */
/* Create file input stream */
#if 0
/* Streaming not supported in open source version
ret = rtxStreamFileCreateReader (&jsonCtxt, filename);
*/
#else
/* Read input file into memory buffer */
ret = rtxFileReadBinary (&cborCtxt, filename, &pMsgBuf, &msglen);
if (0 == ret) {
ret = rtxInitContextBuffer (&cborCtxt, pMsgBuf, msglen);
}
#endif
if (0 != ret) {
rtxErrPrint (&jsonCtxt);
rtxFreeContext (&jsonCtxt);
rtxFreeContext (&cborCtxt);
return ret;
}
/* Init JSON output buffer */
ret = rtxInitContextBuffer (&jsonCtxt, 0, 0);
if (0 != ret) {
rtxErrPrint (&jsonCtxt);
rtxFreeContext (&jsonCtxt);
rtxFreeContext (&cborCtxt);
return ret;
}
/* Invoke the translation function */
ret = cbor2json (&cborCtxt, &jsonCtxt);
if (0 == ret && cborCtxt.level != 0)
ret = LOG_RTERR (&cborCtxt, RTERR_UNBAL);
if (0 == ret && 0 != outfname) {
/* Write encoded JSON data to output file */
OSRTSAFEPUTCHAR (&jsonCtxt, '\0'); /* null terminate buffer */
int fileret = rtxFileWriteText
(outfname, (const char*)jsonCtxt.buffer.data);
if (0 != fileret) {
printf ("unable to write message data to '%s', status = %d\n",
outfname, fileret);
}
}
if (0 != ret) {
rtxErrPrint (&jsonCtxt);
rtxErrPrint (&cborCtxt);
}
rtxFreeContext (&jsonCtxt);
rtxFreeContext (&cborCtxt);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_4286_0 |
crossvul-cpp_data_good_2989_1 | /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
* Copyright (c) 2016 Facebook
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/bpf.h>
#include <linux/bpf_verifier.h>
#include <linux/filter.h>
#include <net/netlink.h>
#include <linux/file.h>
#include <linux/vmalloc.h>
#include <linux/stringify.h>
#include "disasm.h"
static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
#define BPF_PROG_TYPE(_id, _name) \
[_id] = & _name ## _verifier_ops,
#define BPF_MAP_TYPE(_id, _ops)
#include <linux/bpf_types.h>
#undef BPF_PROG_TYPE
#undef BPF_MAP_TYPE
};
/* bpf_check() is a static code analyzer that walks eBPF program
* instruction by instruction and updates register/stack state.
* All paths of conditional branches are analyzed until 'bpf_exit' insn.
*
* The first pass is depth-first-search to check that the program is a DAG.
* It rejects the following programs:
* - larger than BPF_MAXINSNS insns
* - if loop is present (detected via back-edge)
* - unreachable insns exist (shouldn't be a forest. program = one function)
* - out of bounds or malformed jumps
* The second pass is all possible path descent from the 1st insn.
* Since it's analyzing all pathes through the program, the length of the
* analysis is limited to 64k insn, which may be hit even if total number of
* insn is less then 4K, but there are too many branches that change stack/regs.
* Number of 'branches to be analyzed' is limited to 1k
*
* On entry to each instruction, each register has a type, and the instruction
* changes the types of the registers depending on instruction semantics.
* If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
* copied to R1.
*
* All registers are 64-bit.
* R0 - return register
* R1-R5 argument passing registers
* R6-R9 callee saved registers
* R10 - frame pointer read-only
*
* At the start of BPF program the register R1 contains a pointer to bpf_context
* and has type PTR_TO_CTX.
*
* Verifier tracks arithmetic operations on pointers in case:
* BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
* BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
* 1st insn copies R10 (which has FRAME_PTR) type into R1
* and 2nd arithmetic instruction is pattern matched to recognize
* that it wants to construct a pointer to some element within stack.
* So after 2nd insn, the register R1 has type PTR_TO_STACK
* (and -20 constant is saved for further stack bounds checking).
* Meaning that this reg is a pointer to stack plus known immediate constant.
*
* Most of the time the registers have SCALAR_VALUE type, which
* means the register has some value, but it's not a valid pointer.
* (like pointer plus pointer becomes SCALAR_VALUE type)
*
* When verifier sees load or store instructions the type of base register
* can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
* types recognized by check_mem_access() function.
*
* PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
* and the range of [ptr, ptr + map's value_size) is accessible.
*
* registers used to pass values to function calls are checked against
* function argument constraints.
*
* ARG_PTR_TO_MAP_KEY is one of such argument constraints.
* It means that the register type passed to this function must be
* PTR_TO_STACK and it will be used inside the function as
* 'pointer to map element key'
*
* For example the argument constraints for bpf_map_lookup_elem():
* .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
* .arg1_type = ARG_CONST_MAP_PTR,
* .arg2_type = ARG_PTR_TO_MAP_KEY,
*
* ret_type says that this function returns 'pointer to map elem value or null'
* function expects 1st argument to be a const pointer to 'struct bpf_map' and
* 2nd argument should be a pointer to stack, which will be used inside
* the helper function as a pointer to map element key.
*
* On the kernel side the helper function looks like:
* u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
* {
* struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
* void *key = (void *) (unsigned long) r2;
* void *value;
*
* here kernel can access 'key' and 'map' pointers safely, knowing that
* [key, key + map->key_size) bytes are valid and were initialized on
* the stack of eBPF program.
* }
*
* Corresponding eBPF program may look like:
* BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
* BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
* BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
* BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
* here verifier looks at prototype of map_lookup_elem() and sees:
* .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
* Now verifier knows that this map has key of R1->map_ptr->key_size bytes
*
* Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
* Now verifier checks that [R2, R2 + map's key_size) are within stack limits
* and were initialized prior to this call.
* If it's ok, then verifier allows this BPF_CALL insn and looks at
* .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
* R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
* returns ether pointer to map value or NULL.
*
* When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
* insn, the register holding that pointer in the true branch changes state to
* PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
* branch. See check_cond_jmp_op().
*
* After the call R0 is set to return type of the function and registers R1-R5
* are set to NOT_INIT to indicate that they are no longer readable.
*/
/* verifier_state + insn_idx are pushed to stack when branch is encountered */
struct bpf_verifier_stack_elem {
/* verifer state is 'st'
* before processing instruction 'insn_idx'
* and after processing instruction 'prev_insn_idx'
*/
struct bpf_verifier_state st;
int insn_idx;
int prev_insn_idx;
struct bpf_verifier_stack_elem *next;
};
#define BPF_COMPLEXITY_LIMIT_INSNS 131072
#define BPF_COMPLEXITY_LIMIT_STACK 1024
#define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA)
struct bpf_call_arg_meta {
struct bpf_map *map_ptr;
bool raw_mode;
bool pkt_access;
int regno;
int access_size;
};
static DEFINE_MUTEX(bpf_verifier_lock);
/* log_level controls verbosity level of eBPF verifier.
* verbose() is used to dump the verification trace to the log, so the user
* can figure out what's wrong with the program
*/
static __printf(2, 3) void verbose(struct bpf_verifier_env *env,
const char *fmt, ...)
{
struct bpf_verifer_log *log = &env->log;
unsigned int n;
va_list args;
if (!log->level || !log->ubuf || bpf_verifier_log_full(log))
return;
va_start(args, fmt);
n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
va_end(args);
WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
"verifier log line truncated - local buffer too short\n");
n = min(log->len_total - log->len_used - 1, n);
log->kbuf[n] = '\0';
if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
log->len_used += n;
else
log->ubuf = NULL;
}
static bool type_is_pkt_pointer(enum bpf_reg_type type)
{
return type == PTR_TO_PACKET ||
type == PTR_TO_PACKET_META;
}
/* string representation of 'enum bpf_reg_type' */
static const char * const reg_type_str[] = {
[NOT_INIT] = "?",
[SCALAR_VALUE] = "inv",
[PTR_TO_CTX] = "ctx",
[CONST_PTR_TO_MAP] = "map_ptr",
[PTR_TO_MAP_VALUE] = "map_value",
[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
[PTR_TO_STACK] = "fp",
[PTR_TO_PACKET] = "pkt",
[PTR_TO_PACKET_META] = "pkt_meta",
[PTR_TO_PACKET_END] = "pkt_end",
};
static void print_verifier_state(struct bpf_verifier_env *env,
struct bpf_verifier_state *state)
{
struct bpf_reg_state *reg;
enum bpf_reg_type t;
int i;
for (i = 0; i < MAX_BPF_REG; i++) {
reg = &state->regs[i];
t = reg->type;
if (t == NOT_INIT)
continue;
verbose(env, " R%d=%s", i, reg_type_str[t]);
if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
tnum_is_const(reg->var_off)) {
/* reg->off should be 0 for SCALAR_VALUE */
verbose(env, "%lld", reg->var_off.value + reg->off);
} else {
verbose(env, "(id=%d", reg->id);
if (t != SCALAR_VALUE)
verbose(env, ",off=%d", reg->off);
if (type_is_pkt_pointer(t))
verbose(env, ",r=%d", reg->range);
else if (t == CONST_PTR_TO_MAP ||
t == PTR_TO_MAP_VALUE ||
t == PTR_TO_MAP_VALUE_OR_NULL)
verbose(env, ",ks=%d,vs=%d",
reg->map_ptr->key_size,
reg->map_ptr->value_size);
if (tnum_is_const(reg->var_off)) {
/* Typically an immediate SCALAR_VALUE, but
* could be a pointer whose offset is too big
* for reg->off
*/
verbose(env, ",imm=%llx", reg->var_off.value);
} else {
if (reg->smin_value != reg->umin_value &&
reg->smin_value != S64_MIN)
verbose(env, ",smin_value=%lld",
(long long)reg->smin_value);
if (reg->smax_value != reg->umax_value &&
reg->smax_value != S64_MAX)
verbose(env, ",smax_value=%lld",
(long long)reg->smax_value);
if (reg->umin_value != 0)
verbose(env, ",umin_value=%llu",
(unsigned long long)reg->umin_value);
if (reg->umax_value != U64_MAX)
verbose(env, ",umax_value=%llu",
(unsigned long long)reg->umax_value);
if (!tnum_is_unknown(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, ",var_off=%s", tn_buf);
}
}
verbose(env, ")");
}
}
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] == STACK_SPILL)
verbose(env, " fp%d=%s",
-MAX_BPF_STACK + i * BPF_REG_SIZE,
reg_type_str[state->stack[i].spilled_ptr.type]);
}
verbose(env, "\n");
}
static int copy_stack_state(struct bpf_verifier_state *dst,
const struct bpf_verifier_state *src)
{
if (!src->stack)
return 0;
if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
/* internal bug, make state invalid to reject the program */
memset(dst, 0, sizeof(*dst));
return -EFAULT;
}
memcpy(dst->stack, src->stack,
sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
return 0;
}
/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
* make it consume minimal amount of memory. check_stack_write() access from
* the program calls into realloc_verifier_state() to grow the stack size.
* Note there is a non-zero 'parent' pointer inside bpf_verifier_state
* which this function copies over. It points to previous bpf_verifier_state
* which is never reallocated
*/
static int realloc_verifier_state(struct bpf_verifier_state *state, int size,
bool copy_old)
{
u32 old_size = state->allocated_stack;
struct bpf_stack_state *new_stack;
int slot = size / BPF_REG_SIZE;
if (size <= old_size || !size) {
if (copy_old)
return 0;
state->allocated_stack = slot * BPF_REG_SIZE;
if (!size && old_size) {
kfree(state->stack);
state->stack = NULL;
}
return 0;
}
new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
GFP_KERNEL);
if (!new_stack)
return -ENOMEM;
if (copy_old) {
if (state->stack)
memcpy(new_stack, state->stack,
sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
memset(new_stack + old_size / BPF_REG_SIZE, 0,
sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
}
state->allocated_stack = slot * BPF_REG_SIZE;
kfree(state->stack);
state->stack = new_stack;
return 0;
}
static void free_verifier_state(struct bpf_verifier_state *state,
bool free_self)
{
kfree(state->stack);
if (free_self)
kfree(state);
}
/* copy verifier state from src to dst growing dst stack space
* when necessary to accommodate larger src stack
*/
static int copy_verifier_state(struct bpf_verifier_state *dst,
const struct bpf_verifier_state *src)
{
int err;
err = realloc_verifier_state(dst, src->allocated_stack, false);
if (err)
return err;
memcpy(dst, src, offsetof(struct bpf_verifier_state, allocated_stack));
return copy_stack_state(dst, src);
}
static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
int *insn_idx)
{
struct bpf_verifier_state *cur = env->cur_state;
struct bpf_verifier_stack_elem *elem, *head = env->head;
int err;
if (env->head == NULL)
return -ENOENT;
if (cur) {
err = copy_verifier_state(cur, &head->st);
if (err)
return err;
}
if (insn_idx)
*insn_idx = head->insn_idx;
if (prev_insn_idx)
*prev_insn_idx = head->prev_insn_idx;
elem = head->next;
free_verifier_state(&head->st, false);
kfree(head);
env->head = elem;
env->stack_size--;
return 0;
}
static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
int insn_idx, int prev_insn_idx)
{
struct bpf_verifier_state *cur = env->cur_state;
struct bpf_verifier_stack_elem *elem;
int err;
elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
if (!elem)
goto err;
elem->insn_idx = insn_idx;
elem->prev_insn_idx = prev_insn_idx;
elem->next = env->head;
env->head = elem;
env->stack_size++;
err = copy_verifier_state(&elem->st, cur);
if (err)
goto err;
if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
verbose(env, "BPF program is too complex\n");
goto err;
}
return &elem->st;
err:
/* pop all elements and return */
while (!pop_stack(env, NULL, NULL));
return NULL;
}
#define CALLER_SAVED_REGS 6
static const int caller_saved[CALLER_SAVED_REGS] = {
BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
};
static void __mark_reg_not_init(struct bpf_reg_state *reg);
/* Mark the unknown part of a register (variable offset or scalar value) as
* known to have the value @imm.
*/
static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
{
reg->id = 0;
reg->var_off = tnum_const(imm);
reg->smin_value = (s64)imm;
reg->smax_value = (s64)imm;
reg->umin_value = imm;
reg->umax_value = imm;
}
/* Mark the 'variable offset' part of a register as zero. This should be
* used only on registers holding a pointer type.
*/
static void __mark_reg_known_zero(struct bpf_reg_state *reg)
{
__mark_reg_known(reg, 0);
}
static void mark_reg_known_zero(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs */
for (regno = 0; regno < MAX_BPF_REG; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_known_zero(regs + regno);
}
static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
{
return type_is_pkt_pointer(reg->type);
}
static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
{
return reg_is_pkt_pointer(reg) ||
reg->type == PTR_TO_PACKET_END;
}
/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
enum bpf_reg_type which)
{
/* The register can already have a range from prior markings.
* This is fine as long as it hasn't been advanced from its
* origin.
*/
return reg->type == which &&
reg->id == 0 &&
reg->off == 0 &&
tnum_equals_const(reg->var_off, 0);
}
/* Attempts to improve min/max values based on var_off information */
static void __update_reg_bounds(struct bpf_reg_state *reg)
{
/* min signed is max(sign bit) | min(other bits) */
reg->smin_value = max_t(s64, reg->smin_value,
reg->var_off.value | (reg->var_off.mask & S64_MIN));
/* max signed is min(sign bit) | max(other bits) */
reg->smax_value = min_t(s64, reg->smax_value,
reg->var_off.value | (reg->var_off.mask & S64_MAX));
reg->umin_value = max(reg->umin_value, reg->var_off.value);
reg->umax_value = min(reg->umax_value,
reg->var_off.value | reg->var_off.mask);
}
/* Uses signed min/max values to inform unsigned, and vice-versa */
static void __reg_deduce_bounds(struct bpf_reg_state *reg)
{
/* Learn sign from signed bounds.
* If we cannot cross the sign boundary, then signed and unsigned bounds
* are the same, so combine. This works even in the negative case, e.g.
* -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
*/
if (reg->smin_value >= 0 || reg->smax_value < 0) {
reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
reg->umin_value);
reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
reg->umax_value);
return;
}
/* Learn sign from unsigned bounds. Signed bounds cross the sign
* boundary, so we must be careful.
*/
if ((s64)reg->umax_value >= 0) {
/* Positive. We can't learn anything from the smin, but smax
* is positive, hence safe.
*/
reg->smin_value = reg->umin_value;
reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
reg->umax_value);
} else if ((s64)reg->umin_value < 0) {
/* Negative. We can't learn anything from the smax, but smin
* is negative, hence safe.
*/
reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
reg->umin_value);
reg->smax_value = reg->umax_value;
}
}
/* Attempts to improve var_off based on unsigned min/max information */
static void __reg_bound_offset(struct bpf_reg_state *reg)
{
reg->var_off = tnum_intersect(reg->var_off,
tnum_range(reg->umin_value,
reg->umax_value));
}
/* Reset the min/max bounds of a register */
static void __mark_reg_unbounded(struct bpf_reg_state *reg)
{
reg->smin_value = S64_MIN;
reg->smax_value = S64_MAX;
reg->umin_value = 0;
reg->umax_value = U64_MAX;
}
/* Mark a register as having a completely unknown (scalar) value. */
static void __mark_reg_unknown(struct bpf_reg_state *reg)
{
reg->type = SCALAR_VALUE;
reg->id = 0;
reg->off = 0;
reg->var_off = tnum_unknown;
__mark_reg_unbounded(reg);
}
static void mark_reg_unknown(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs */
for (regno = 0; regno < MAX_BPF_REG; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_unknown(regs + regno);
}
static void __mark_reg_not_init(struct bpf_reg_state *reg)
{
__mark_reg_unknown(reg);
reg->type = NOT_INIT;
}
static void mark_reg_not_init(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs */
for (regno = 0; regno < MAX_BPF_REG; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_not_init(regs + regno);
}
static void init_reg_state(struct bpf_verifier_env *env,
struct bpf_reg_state *regs)
{
int i;
for (i = 0; i < MAX_BPF_REG; i++) {
mark_reg_not_init(env, regs, i);
regs[i].live = REG_LIVE_NONE;
}
/* frame pointer */
regs[BPF_REG_FP].type = PTR_TO_STACK;
mark_reg_known_zero(env, regs, BPF_REG_FP);
/* 1st arg to a function */
regs[BPF_REG_1].type = PTR_TO_CTX;
mark_reg_known_zero(env, regs, BPF_REG_1);
}
enum reg_arg_type {
SRC_OP, /* register is used as source operand */
DST_OP, /* register is used as destination operand */
DST_OP_NO_MARK /* same as above, check only, don't mark */
};
static void mark_reg_read(const struct bpf_verifier_state *state, u32 regno)
{
struct bpf_verifier_state *parent = state->parent;
if (regno == BPF_REG_FP)
/* We don't need to worry about FP liveness because it's read-only */
return;
while (parent) {
/* if read wasn't screened by an earlier write ... */
if (state->regs[regno].live & REG_LIVE_WRITTEN)
break;
/* ... then we depend on parent's value */
parent->regs[regno].live |= REG_LIVE_READ;
state = parent;
parent = state->parent;
}
}
static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
enum reg_arg_type t)
{
struct bpf_reg_state *regs = env->cur_state->regs;
if (regno >= MAX_BPF_REG) {
verbose(env, "R%d is invalid\n", regno);
return -EINVAL;
}
if (t == SRC_OP) {
/* check whether register used as source operand can be read */
if (regs[regno].type == NOT_INIT) {
verbose(env, "R%d !read_ok\n", regno);
return -EACCES;
}
mark_reg_read(env->cur_state, regno);
} else {
/* check whether register used as dest operand can be written to */
if (regno == BPF_REG_FP) {
verbose(env, "frame pointer is read only\n");
return -EACCES;
}
regs[regno].live |= REG_LIVE_WRITTEN;
if (t == DST_OP)
mark_reg_unknown(env, regs, regno);
}
return 0;
}
static bool is_spillable_regtype(enum bpf_reg_type type)
{
switch (type) {
case PTR_TO_MAP_VALUE:
case PTR_TO_MAP_VALUE_OR_NULL:
case PTR_TO_STACK:
case PTR_TO_CTX:
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
case PTR_TO_PACKET_END:
case CONST_PTR_TO_MAP:
return true;
default:
return false;
}
}
/* check_stack_read/write functions track spill/fill of registers,
* stack boundary and alignment are checked in check_mem_access()
*/
static int check_stack_write(struct bpf_verifier_env *env,
struct bpf_verifier_state *state, int off,
int size, int value_regno)
{
int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
err = realloc_verifier_state(state, round_up(slot + 1, BPF_REG_SIZE),
true);
if (err)
return err;
/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
* so it's aligned access and [off, off + size) are within stack limits
*/
if (!env->allow_ptr_leaks &&
state->stack[spi].slot_type[0] == STACK_SPILL &&
size != BPF_REG_SIZE) {
verbose(env, "attempt to corrupt spilled pointer on stack\n");
return -EACCES;
}
if (value_regno >= 0 &&
is_spillable_regtype(state->regs[value_regno].type)) {
/* register containing pointer is being spilled into stack */
if (size != BPF_REG_SIZE) {
verbose(env, "invalid size of register spill\n");
return -EACCES;
}
/* save register state */
state->stack[spi].spilled_ptr = state->regs[value_regno];
state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
for (i = 0; i < BPF_REG_SIZE; i++)
state->stack[spi].slot_type[i] = STACK_SPILL;
} else {
/* regular write of data into stack */
state->stack[spi].spilled_ptr = (struct bpf_reg_state) {};
for (i = 0; i < size; i++)
state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
STACK_MISC;
}
return 0;
}
static void mark_stack_slot_read(const struct bpf_verifier_state *state, int slot)
{
struct bpf_verifier_state *parent = state->parent;
while (parent) {
/* if read wasn't screened by an earlier write ... */
if (state->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN)
break;
/* ... then we depend on parent's value */
parent->stack[slot].spilled_ptr.live |= REG_LIVE_READ;
state = parent;
parent = state->parent;
}
}
static int check_stack_read(struct bpf_verifier_env *env,
struct bpf_verifier_state *state, int off, int size,
int value_regno)
{
int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
u8 *stype;
if (state->allocated_stack <= slot) {
verbose(env, "invalid read from stack off %d+0 size %d\n",
off, size);
return -EACCES;
}
stype = state->stack[spi].slot_type;
if (stype[0] == STACK_SPILL) {
if (size != BPF_REG_SIZE) {
verbose(env, "invalid size of register spill\n");
return -EACCES;
}
for (i = 1; i < BPF_REG_SIZE; i++) {
if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
verbose(env, "corrupted spill memory\n");
return -EACCES;
}
}
if (value_regno >= 0) {
/* restore register state from stack */
state->regs[value_regno] = state->stack[spi].spilled_ptr;
mark_stack_slot_read(state, spi);
}
return 0;
} else {
for (i = 0; i < size; i++) {
if (stype[(slot - i) % BPF_REG_SIZE] != STACK_MISC) {
verbose(env, "invalid read from stack off %d+%d size %d\n",
off, i, size);
return -EACCES;
}
}
if (value_regno >= 0)
/* have read misc data from the stack */
mark_reg_unknown(env, state->regs, value_regno);
return 0;
}
}
/* check read/write into map element returned by bpf_map_lookup_elem() */
static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_map *map = regs[regno].map_ptr;
if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
off + size > map->value_size) {
verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
map->value_size, off, size);
return -EACCES;
}
return 0;
}
/* check read/write into a map element with possible variable offset */
static int check_map_access(struct bpf_verifier_env *env, u32 regno,
int off, int size, bool zero_size_allowed)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *reg = &state->regs[regno];
int err;
/* We may have adjusted the register to this map value, so we
* need to try adding each of min_value and max_value to off
* to make sure our theoretical access will be safe.
*/
if (env->log.level)
print_verifier_state(env, state);
/* The minimum value is only important with signed
* comparisons where we can't assume the floor of a
* value is 0. If we are using signed variables for our
* index'es we need to make sure that whatever we use
* will have a set floor within our range.
*/
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
regno);
return -EACCES;
}
err = __check_map_access(env, regno, reg->smin_value + off, size,
zero_size_allowed);
if (err) {
verbose(env, "R%d min value is outside of the array range\n",
regno);
return err;
}
/* If we haven't set a max value then we need to bail since we can't be
* sure we won't do bad things.
* If reg->umax_value + off could overflow, treat that as unbounded too.
*/
if (reg->umax_value >= BPF_MAX_VAR_OFF) {
verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
regno);
return -EACCES;
}
err = __check_map_access(env, regno, reg->umax_value + off, size,
zero_size_allowed);
if (err)
verbose(env, "R%d max value is outside of the array range\n",
regno);
return err;
}
#define MAX_PACKET_OFF 0xffff
static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
const struct bpf_call_arg_meta *meta,
enum bpf_access_type t)
{
switch (env->prog->type) {
case BPF_PROG_TYPE_LWT_IN:
case BPF_PROG_TYPE_LWT_OUT:
/* dst_input() and dst_output() can't write for now */
if (t == BPF_WRITE)
return false;
/* fallthrough */
case BPF_PROG_TYPE_SCHED_CLS:
case BPF_PROG_TYPE_SCHED_ACT:
case BPF_PROG_TYPE_XDP:
case BPF_PROG_TYPE_LWT_XMIT:
case BPF_PROG_TYPE_SK_SKB:
if (meta)
return meta->pkt_access;
env->seen_direct_write = true;
return true;
default:
return false;
}
}
static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
int off, int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = ®s[regno];
if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
(u64)off + size > reg->range) {
verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
off, size, regno, reg->id, reg->off, reg->range);
return -EACCES;
}
return 0;
}
static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = ®s[regno];
int err;
/* We may have added a variable offset to the packet pointer; but any
* reg->range we have comes after that. We are only checking the fixed
* offset.
*/
/* We don't allow negative numbers, because we aren't tracking enough
* detail to prove they're safe.
*/
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
regno);
return -EACCES;
}
err = __check_packet_access(env, regno, off, size, zero_size_allowed);
if (err) {
verbose(env, "R%d offset is outside of the packet\n", regno);
return err;
}
return err;
}
/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
enum bpf_access_type t, enum bpf_reg_type *reg_type)
{
struct bpf_insn_access_aux info = {
.reg_type = *reg_type,
};
if (env->ops->is_valid_access &&
env->ops->is_valid_access(off, size, t, &info)) {
/* A non zero info.ctx_field_size indicates that this field is a
* candidate for later verifier transformation to load the whole
* field and then apply a mask when accessed with a narrower
* access than actual ctx access size. A zero info.ctx_field_size
* will only allow for whole field access and rejects any other
* type of narrower access.
*/
*reg_type = info.reg_type;
env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
/* remember the offset of last byte accessed in ctx */
if (env->prog->aux->max_ctx_offset < off + size)
env->prog->aux->max_ctx_offset = off + size;
return 0;
}
verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
return -EACCES;
}
static bool __is_pointer_value(bool allow_ptr_leaks,
const struct bpf_reg_state *reg)
{
if (allow_ptr_leaks)
return false;
return reg->type != SCALAR_VALUE;
}
static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
{
return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
}
static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
int off, int size, bool strict)
{
struct tnum reg_off;
int ip_align;
/* Byte size accesses are always allowed. */
if (!strict || size == 1)
return 0;
/* For platforms that do not have a Kconfig enabling
* CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
* NET_IP_ALIGN is universally set to '2'. And on platforms
* that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
* to this code only in strict mode where we want to emulate
* the NET_IP_ALIGN==2 checking. Therefore use an
* unconditional IP align value of '2'.
*/
ip_align = 2;
reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
if (!tnum_is_aligned(reg_off, size)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env,
"misaligned packet access off %d+%s+%d+%d size %d\n",
ip_align, tn_buf, reg->off, off, size);
return -EACCES;
}
return 0;
}
static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
const char *pointer_desc,
int off, int size, bool strict)
{
struct tnum reg_off;
/* Byte size accesses are always allowed. */
if (!strict || size == 1)
return 0;
reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
if (!tnum_is_aligned(reg_off, size)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
pointer_desc, tn_buf, reg->off, off, size);
return -EACCES;
}
return 0;
}
static int check_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
int off, int size)
{
bool strict = env->strict_alignment;
const char *pointer_desc = "";
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
/* Special case, because of NET_IP_ALIGN. Given metadata sits
* right in front, treat it the very same way.
*/
return check_pkt_ptr_alignment(env, reg, off, size, strict);
case PTR_TO_MAP_VALUE:
pointer_desc = "value ";
break;
case PTR_TO_CTX:
pointer_desc = "context ";
break;
case PTR_TO_STACK:
pointer_desc = "stack ";
break;
default:
break;
}
return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
strict);
}
/* check whether memory at (regno + off) is accessible for t = (read | write)
* if t==write, value_regno is a register which value is stored into memory
* if t==read, value_regno is a register which will receive the value from memory
* if t==write && value_regno==-1, some unknown value is stored into memory
* if t==read && value_regno==-1, don't care what we read from memory
*/
static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off,
int bpf_size, enum bpf_access_type t,
int value_regno)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = regs + regno;
int size, err = 0;
size = bpf_size_to_bytes(bpf_size);
if (size < 0)
return size;
/* alignment checks will add in reg->off themselves */
err = check_ptr_alignment(env, reg, off, size);
if (err)
return err;
/* for access checks, reg->off is just part of off */
off += reg->off;
if (reg->type == PTR_TO_MAP_VALUE) {
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into map\n", value_regno);
return -EACCES;
}
err = check_map_access(env, regno, off, size, false);
if (!err && t == BPF_READ && value_regno >= 0)
mark_reg_unknown(env, regs, value_regno);
} else if (reg->type == PTR_TO_CTX) {
enum bpf_reg_type reg_type = SCALAR_VALUE;
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into ctx\n", value_regno);
return -EACCES;
}
/* ctx accesses must be at a fixed offset, so that we can
* determine what type of data were returned.
*/
if (reg->off) {
verbose(env,
"dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n",
regno, reg->off, off - reg->off);
return -EACCES;
}
if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env,
"variable ctx access var_off=%s off=%d size=%d",
tn_buf, off, size);
return -EACCES;
}
err = check_ctx_access(env, insn_idx, off, size, t, ®_type);
if (!err && t == BPF_READ && value_regno >= 0) {
/* ctx access returns either a scalar, or a
* PTR_TO_PACKET[_META,_END]. In the latter
* case, we know the offset is zero.
*/
if (reg_type == SCALAR_VALUE)
mark_reg_unknown(env, regs, value_regno);
else
mark_reg_known_zero(env, regs,
value_regno);
regs[value_regno].id = 0;
regs[value_regno].off = 0;
regs[value_regno].range = 0;
regs[value_regno].type = reg_type;
}
} else if (reg->type == PTR_TO_STACK) {
/* stack accesses must be at a fixed offset, so that we can
* determine what type of data were returned.
* See check_stack_read().
*/
if (!tnum_is_const(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "variable stack access var_off=%s off=%d size=%d",
tn_buf, off, size);
return -EACCES;
}
off += reg->var_off.value;
if (off >= 0 || off < -MAX_BPF_STACK) {
verbose(env, "invalid stack off=%d size=%d\n", off,
size);
return -EACCES;
}
if (env->prog->aux->stack_depth < -off)
env->prog->aux->stack_depth = -off;
if (t == BPF_WRITE)
err = check_stack_write(env, state, off, size,
value_regno);
else
err = check_stack_read(env, state, off, size,
value_regno);
} else if (reg_is_pkt_pointer(reg)) {
if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
verbose(env, "cannot write into packet\n");
return -EACCES;
}
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into packet\n",
value_regno);
return -EACCES;
}
err = check_packet_access(env, regno, off, size, false);
if (!err && t == BPF_READ && value_regno >= 0)
mark_reg_unknown(env, regs, value_regno);
} else {
verbose(env, "R%d invalid mem access '%s'\n", regno,
reg_type_str[reg->type]);
return -EACCES;
}
if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
regs[value_regno].type == SCALAR_VALUE) {
/* b/h/w load zero-extends, mark upper bits as known 0 */
regs[value_regno].var_off =
tnum_cast(regs[value_regno].var_off, size);
__update_reg_bounds(®s[value_regno]);
}
return err;
}
static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
{
int err;
if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
insn->imm != 0) {
verbose(env, "BPF_XADD uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->src_reg)) {
verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
return -EACCES;
}
/* check whether atomic_add can read the memory */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_READ, -1);
if (err)
return err;
/* check whether atomic_add can write into the same memory */
return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE, -1);
}
/* Does this register contain a constant zero? */
static bool register_is_null(struct bpf_reg_state reg)
{
return reg.type == SCALAR_VALUE && tnum_equals_const(reg.var_off, 0);
}
/* when register 'regno' is passed into function that will read 'access_size'
* bytes from that pointer, make sure that it's within stack boundary
* and all elements of stack are initialized.
* Unlike most pointer bounds-checking functions, this one doesn't take an
* 'off' argument, so it has to add in reg->off itself.
*/
static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
int access_size, bool zero_size_allowed,
struct bpf_call_arg_meta *meta)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *regs = state->regs;
int off, i, slot, spi;
if (regs[regno].type != PTR_TO_STACK) {
/* Allow zero-byte read from NULL, regardless of pointer type */
if (zero_size_allowed && access_size == 0 &&
register_is_null(regs[regno]))
return 0;
verbose(env, "R%d type=%s expected=%s\n", regno,
reg_type_str[regs[regno].type],
reg_type_str[PTR_TO_STACK]);
return -EACCES;
}
/* Only allow fixed-offset stack reads */
if (!tnum_is_const(regs[regno].var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off);
verbose(env, "invalid variable stack read R%d var_off=%s\n",
regno, tn_buf);
}
off = regs[regno].off + regs[regno].var_off.value;
if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
regno, off, access_size);
return -EACCES;
}
if (env->prog->aux->stack_depth < -off)
env->prog->aux->stack_depth = -off;
if (meta && meta->raw_mode) {
meta->access_size = access_size;
meta->regno = regno;
return 0;
}
for (i = 0; i < access_size; i++) {
slot = -(off + i) - 1;
spi = slot / BPF_REG_SIZE;
if (state->allocated_stack <= slot ||
state->stack[spi].slot_type[slot % BPF_REG_SIZE] !=
STACK_MISC) {
verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
off, i, access_size);
return -EACCES;
}
}
return 0;
}
static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
int access_size, bool zero_size_allowed,
struct bpf_call_arg_meta *meta)
{
struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
return check_packet_access(env, regno, reg->off, access_size,
zero_size_allowed);
case PTR_TO_MAP_VALUE:
return check_map_access(env, regno, reg->off, access_size,
zero_size_allowed);
default: /* scalar_value|ptr_to_stack or invalid ptr */
return check_stack_boundary(env, regno, access_size,
zero_size_allowed, meta);
}
}
static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
enum bpf_arg_type arg_type,
struct bpf_call_arg_meta *meta)
{
struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
enum bpf_reg_type expected_type, type = reg->type;
int err = 0;
if (arg_type == ARG_DONTCARE)
return 0;
err = check_reg_arg(env, regno, SRC_OP);
if (err)
return err;
if (arg_type == ARG_ANYTHING) {
if (is_pointer_value(env, regno)) {
verbose(env, "R%d leaks addr into helper function\n",
regno);
return -EACCES;
}
return 0;
}
if (type_is_pkt_pointer(type) &&
!may_access_direct_pkt_data(env, meta, BPF_READ)) {
verbose(env, "helper access to the packet is not allowed\n");
return -EACCES;
}
if (arg_type == ARG_PTR_TO_MAP_KEY ||
arg_type == ARG_PTR_TO_MAP_VALUE) {
expected_type = PTR_TO_STACK;
if (!type_is_pkt_pointer(type) &&
type != expected_type)
goto err_type;
} else if (arg_type == ARG_CONST_SIZE ||
arg_type == ARG_CONST_SIZE_OR_ZERO) {
expected_type = SCALAR_VALUE;
if (type != expected_type)
goto err_type;
} else if (arg_type == ARG_CONST_MAP_PTR) {
expected_type = CONST_PTR_TO_MAP;
if (type != expected_type)
goto err_type;
} else if (arg_type == ARG_PTR_TO_CTX) {
expected_type = PTR_TO_CTX;
if (type != expected_type)
goto err_type;
} else if (arg_type == ARG_PTR_TO_MEM ||
arg_type == ARG_PTR_TO_MEM_OR_NULL ||
arg_type == ARG_PTR_TO_UNINIT_MEM) {
expected_type = PTR_TO_STACK;
/* One exception here. In case function allows for NULL to be
* passed in as argument, it's a SCALAR_VALUE type. Final test
* happens during stack boundary checking.
*/
if (register_is_null(*reg) &&
arg_type == ARG_PTR_TO_MEM_OR_NULL)
/* final test in check_stack_boundary() */;
else if (!type_is_pkt_pointer(type) &&
type != PTR_TO_MAP_VALUE &&
type != expected_type)
goto err_type;
meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
} else {
verbose(env, "unsupported arg_type %d\n", arg_type);
return -EFAULT;
}
if (arg_type == ARG_CONST_MAP_PTR) {
/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
meta->map_ptr = reg->map_ptr;
} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
/* bpf_map_xxx(..., map_ptr, ..., key) call:
* check that [key, key + map->key_size) are within
* stack limits and initialized
*/
if (!meta->map_ptr) {
/* in function declaration map_ptr must come before
* map_key, so that it's verified and known before
* we have to check map_key here. Otherwise it means
* that kernel subsystem misconfigured verifier
*/
verbose(env, "invalid map_ptr to access map->key\n");
return -EACCES;
}
if (type_is_pkt_pointer(type))
err = check_packet_access(env, regno, reg->off,
meta->map_ptr->key_size,
false);
else
err = check_stack_boundary(env, regno,
meta->map_ptr->key_size,
false, NULL);
} else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
/* bpf_map_xxx(..., map_ptr, ..., value) call:
* check [value, value + map->value_size) validity
*/
if (!meta->map_ptr) {
/* kernel subsystem misconfigured verifier */
verbose(env, "invalid map_ptr to access map->value\n");
return -EACCES;
}
if (type_is_pkt_pointer(type))
err = check_packet_access(env, regno, reg->off,
meta->map_ptr->value_size,
false);
else
err = check_stack_boundary(env, regno,
meta->map_ptr->value_size,
false, NULL);
} else if (arg_type == ARG_CONST_SIZE ||
arg_type == ARG_CONST_SIZE_OR_ZERO) {
bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
/* bpf_xxx(..., buf, len) call will access 'len' bytes
* from stack pointer 'buf'. Check it
* note: regno == len, regno - 1 == buf
*/
if (regno == 0) {
/* kernel subsystem misconfigured verifier */
verbose(env,
"ARG_CONST_SIZE cannot be first argument\n");
return -EACCES;
}
/* The register is SCALAR_VALUE; the access check
* happens using its boundaries.
*/
if (!tnum_is_const(reg->var_off))
/* For unprivileged variable accesses, disable raw
* mode so that the program is required to
* initialize all the memory that the helper could
* just partially fill up.
*/
meta = NULL;
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
regno);
return -EACCES;
}
if (reg->umin_value == 0) {
err = check_helper_mem_access(env, regno - 1, 0,
zero_size_allowed,
meta);
if (err)
return err;
}
if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
regno);
return -EACCES;
}
err = check_helper_mem_access(env, regno - 1,
reg->umax_value,
zero_size_allowed, meta);
}
return err;
err_type:
verbose(env, "R%d type=%s expected=%s\n", regno,
reg_type_str[type], reg_type_str[expected_type]);
return -EACCES;
}
static int check_map_func_compatibility(struct bpf_verifier_env *env,
struct bpf_map *map, int func_id)
{
if (!map)
return 0;
/* We need a two way check, first is from map perspective ... */
switch (map->map_type) {
case BPF_MAP_TYPE_PROG_ARRAY:
if (func_id != BPF_FUNC_tail_call)
goto error;
break;
case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
if (func_id != BPF_FUNC_perf_event_read &&
func_id != BPF_FUNC_perf_event_output &&
func_id != BPF_FUNC_perf_event_read_value)
goto error;
break;
case BPF_MAP_TYPE_STACK_TRACE:
if (func_id != BPF_FUNC_get_stackid)
goto error;
break;
case BPF_MAP_TYPE_CGROUP_ARRAY:
if (func_id != BPF_FUNC_skb_under_cgroup &&
func_id != BPF_FUNC_current_task_under_cgroup)
goto error;
break;
/* devmap returns a pointer to a live net_device ifindex that we cannot
* allow to be modified from bpf side. So do not allow lookup elements
* for now.
*/
case BPF_MAP_TYPE_DEVMAP:
if (func_id != BPF_FUNC_redirect_map)
goto error;
break;
/* Restrict bpf side of cpumap, open when use-cases appear */
case BPF_MAP_TYPE_CPUMAP:
if (func_id != BPF_FUNC_redirect_map)
goto error;
break;
case BPF_MAP_TYPE_ARRAY_OF_MAPS:
case BPF_MAP_TYPE_HASH_OF_MAPS:
if (func_id != BPF_FUNC_map_lookup_elem)
goto error;
break;
case BPF_MAP_TYPE_SOCKMAP:
if (func_id != BPF_FUNC_sk_redirect_map &&
func_id != BPF_FUNC_sock_map_update &&
func_id != BPF_FUNC_map_delete_elem)
goto error;
break;
default:
break;
}
/* ... and second from the function itself. */
switch (func_id) {
case BPF_FUNC_tail_call:
if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
goto error;
break;
case BPF_FUNC_perf_event_read:
case BPF_FUNC_perf_event_output:
case BPF_FUNC_perf_event_read_value:
if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
goto error;
break;
case BPF_FUNC_get_stackid:
if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
goto error;
break;
case BPF_FUNC_current_task_under_cgroup:
case BPF_FUNC_skb_under_cgroup:
if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
goto error;
break;
case BPF_FUNC_redirect_map:
if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
map->map_type != BPF_MAP_TYPE_CPUMAP)
goto error;
break;
case BPF_FUNC_sk_redirect_map:
if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
goto error;
break;
case BPF_FUNC_sock_map_update:
if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
goto error;
break;
default:
break;
}
return 0;
error:
verbose(env, "cannot pass map_type %d into func %s#%d\n",
map->map_type, func_id_name(func_id), func_id);
return -EINVAL;
}
static int check_raw_mode(const struct bpf_func_proto *fn)
{
int count = 0;
if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
count++;
return count > 1 ? -EINVAL : 0;
}
/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
* are now invalid, so turn them into unknown SCALAR_VALUE.
*/
static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *regs = state->regs, *reg;
int i;
for (i = 0; i < MAX_BPF_REG; i++)
if (reg_is_pkt_pointer_any(®s[i]))
mark_reg_unknown(env, regs, i);
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
reg = &state->stack[i].spilled_ptr;
if (reg_is_pkt_pointer_any(reg))
__mark_reg_unknown(reg);
}
}
static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
{
const struct bpf_func_proto *fn = NULL;
struct bpf_reg_state *regs;
struct bpf_call_arg_meta meta;
bool changes_data;
int i, err;
/* find function prototype */
if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
func_id);
return -EINVAL;
}
if (env->ops->get_func_proto)
fn = env->ops->get_func_proto(func_id);
if (!fn) {
verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
func_id);
return -EINVAL;
}
/* eBPF programs must be GPL compatible to use GPL-ed functions */
if (!env->prog->gpl_compatible && fn->gpl_only) {
verbose(env, "cannot call GPL only function from proprietary program\n");
return -EINVAL;
}
changes_data = bpf_helper_changes_pkt_data(fn->func);
memset(&meta, 0, sizeof(meta));
meta.pkt_access = fn->pkt_access;
/* We only support one arg being in raw mode at the moment, which
* is sufficient for the helper functions we have right now.
*/
err = check_raw_mode(fn);
if (err) {
verbose(env, "kernel subsystem misconfigured func %s#%d\n",
func_id_name(func_id), func_id);
return err;
}
/* check args */
err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
if (err)
return err;
/* Mark slots with STACK_MISC in case of raw mode, stack offset
* is inferred from register state.
*/
for (i = 0; i < meta.access_size; i++) {
err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, BPF_WRITE, -1);
if (err)
return err;
}
regs = cur_regs(env);
/* reset caller saved regs */
for (i = 0; i < CALLER_SAVED_REGS; i++) {
mark_reg_not_init(env, regs, caller_saved[i]);
check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
}
/* update return register (already marked as written above) */
if (fn->ret_type == RET_INTEGER) {
/* sets type to SCALAR_VALUE */
mark_reg_unknown(env, regs, BPF_REG_0);
} else if (fn->ret_type == RET_VOID) {
regs[BPF_REG_0].type = NOT_INIT;
} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
struct bpf_insn_aux_data *insn_aux;
regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
/* There is no offset yet applied, variable or fixed */
mark_reg_known_zero(env, regs, BPF_REG_0);
regs[BPF_REG_0].off = 0;
/* remember map_ptr, so that check_map_access()
* can check 'value_size' boundary of memory access
* to map element returned from bpf_map_lookup_elem()
*/
if (meta.map_ptr == NULL) {
verbose(env,
"kernel subsystem misconfigured verifier\n");
return -EINVAL;
}
regs[BPF_REG_0].map_ptr = meta.map_ptr;
regs[BPF_REG_0].id = ++env->id_gen;
insn_aux = &env->insn_aux_data[insn_idx];
if (!insn_aux->map_ptr)
insn_aux->map_ptr = meta.map_ptr;
else if (insn_aux->map_ptr != meta.map_ptr)
insn_aux->map_ptr = BPF_MAP_PTR_POISON;
} else {
verbose(env, "unknown return type %d of func %s#%d\n",
fn->ret_type, func_id_name(func_id), func_id);
return -EINVAL;
}
err = check_map_func_compatibility(env, meta.map_ptr, func_id);
if (err)
return err;
if (changes_data)
clear_all_pkt_pointers(env);
return 0;
}
static void coerce_reg_to_32(struct bpf_reg_state *reg)
{
/* clear high 32 bits */
reg->var_off = tnum_cast(reg->var_off, 4);
/* Update bounds */
__update_reg_bounds(reg);
}
static bool signed_add_overflows(s64 a, s64 b)
{
/* Do the add in u64, where overflow is well-defined */
s64 res = (s64)((u64)a + (u64)b);
if (b < 0)
return res > a;
return res < a;
}
static bool signed_sub_overflows(s64 a, s64 b)
{
/* Do the sub in u64, where overflow is well-defined */
s64 res = (s64)((u64)a - (u64)b);
if (b < 0)
return res < a;
return res > a;
}
/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
* Caller should also handle BPF_MOV case separately.
* If we return -EACCES, caller may want to try again treating pointer as a
* scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
*/
static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
const struct bpf_reg_state *ptr_reg,
const struct bpf_reg_state *off_reg)
{
struct bpf_reg_state *regs = cur_regs(env), *dst_reg;
bool known = tnum_is_const(off_reg->var_off);
s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
u8 opcode = BPF_OP(insn->code);
u32 dst = insn->dst_reg;
dst_reg = ®s[dst];
if (WARN_ON_ONCE(known && (smin_val != smax_val))) {
print_verifier_state(env, env->cur_state);
verbose(env,
"verifier internal error: known but bad sbounds\n");
return -EINVAL;
}
if (WARN_ON_ONCE(known && (umin_val != umax_val))) {
print_verifier_state(env, env->cur_state);
verbose(env,
"verifier internal error: known but bad ubounds\n");
return -EINVAL;
}
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops on pointers produce (meaningless) scalars */
if (!env->allow_ptr_leaks)
verbose(env,
"R%d 32-bit pointer arithmetic prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
dst);
return -EACCES;
}
if (ptr_reg->type == CONST_PTR_TO_MAP) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_PACKET_END) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
dst);
return -EACCES;
}
/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
* The id may be overwritten later if we create a new variable offset.
*/
dst_reg->type = ptr_reg->type;
dst_reg->id = ptr_reg->id;
switch (opcode) {
case BPF_ADD:
/* We can take a fixed offset as long as it doesn't overflow
* the s32 'off' field
*/
if (known && (ptr_reg->off + smin_val ==
(s64)(s32)(ptr_reg->off + smin_val))) {
/* pointer += K. Accumulate it into fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->off = ptr_reg->off + smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. Note that off_reg->off
* == 0, since it's a scalar.
* dst_reg gets the pointer type and since some positive
* integer value was added to the pointer, give it a new 'id'
* if it's a PTR_TO_PACKET.
* this creates a new 'base' pointer, off_reg (variable) gets
* added into the variable offset, and we copy the fixed offset
* from ptr_reg.
*/
if (signed_add_overflows(smin_ptr, smin_val) ||
signed_add_overflows(smax_ptr, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr + smin_val;
dst_reg->smax_value = smax_ptr + smax_val;
}
if (umin_ptr + umin_val < umin_ptr ||
umax_ptr + umax_val < umax_ptr) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value = umin_ptr + umin_val;
dst_reg->umax_value = umax_ptr + umax_val;
}
dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
dst_reg->range = 0;
}
break;
case BPF_SUB:
if (dst_reg == off_reg) {
/* scalar -= pointer. Creates an unknown scalar */
if (!env->allow_ptr_leaks)
verbose(env, "R%d tried to subtract pointer from scalar\n",
dst);
return -EACCES;
}
/* We don't allow subtraction from FP, because (according to
* test_verifier.c test "invalid fp arithmetic", JITs might not
* be able to deal with it.
*/
if (ptr_reg->type == PTR_TO_STACK) {
if (!env->allow_ptr_leaks)
verbose(env, "R%d subtraction from stack pointer prohibited\n",
dst);
return -EACCES;
}
if (known && (ptr_reg->off - smin_val ==
(s64)(s32)(ptr_reg->off - smin_val))) {
/* pointer -= K. Subtract it from fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->id = ptr_reg->id;
dst_reg->off = ptr_reg->off - smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. If the subtrahend is known
* nonnegative, then any reg->range we had before is still good.
*/
if (signed_sub_overflows(smin_ptr, smax_val) ||
signed_sub_overflows(smax_ptr, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr - smax_val;
dst_reg->smax_value = smax_ptr - smin_val;
}
if (umin_ptr < umax_val) {
/* Overflow possible, we know nothing */
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
/* Cannot overflow (as long as bounds are consistent) */
dst_reg->umin_value = umin_ptr - umax_val;
dst_reg->umax_value = umax_ptr - umin_val;
}
dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
if (smin_val < 0)
dst_reg->range = 0;
}
break;
case BPF_AND:
case BPF_OR:
case BPF_XOR:
/* bitwise ops on pointers are troublesome, prohibit for now.
* (However, in principle we could allow some cases, e.g.
* ptr &= ~3 which would reduce min_value by 3.)
*/
if (!env->allow_ptr_leaks)
verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
default:
/* other operators (e.g. MUL,LSH) produce non-pointer results */
if (!env->allow_ptr_leaks)
verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
}
__update_reg_bounds(dst_reg);
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
}
static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
struct bpf_reg_state *dst_reg,
struct bpf_reg_state src_reg)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
bool src_known, dst_known;
s64 smin_val, smax_val;
u64 umin_val, umax_val;
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops are (32,32)->64 */
coerce_reg_to_32(dst_reg);
coerce_reg_to_32(&src_reg);
}
smin_val = src_reg.smin_value;
smax_val = src_reg.smax_value;
umin_val = src_reg.umin_value;
umax_val = src_reg.umax_value;
src_known = tnum_is_const(src_reg.var_off);
dst_known = tnum_is_const(dst_reg->var_off);
switch (opcode) {
case BPF_ADD:
if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
signed_add_overflows(dst_reg->smax_value, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value += smin_val;
dst_reg->smax_value += smax_val;
}
if (dst_reg->umin_value + umin_val < umin_val ||
dst_reg->umax_value + umax_val < umax_val) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value += umin_val;
dst_reg->umax_value += umax_val;
}
dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
break;
case BPF_SUB:
if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
signed_sub_overflows(dst_reg->smax_value, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value -= smax_val;
dst_reg->smax_value -= smin_val;
}
if (dst_reg->umin_value < umax_val) {
/* Overflow possible, we know nothing */
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
/* Cannot overflow (as long as bounds are consistent) */
dst_reg->umin_value -= umax_val;
dst_reg->umax_value -= umin_val;
}
dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
break;
case BPF_MUL:
dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
if (smin_val < 0 || dst_reg->smin_value < 0) {
/* Ain't nobody got time to multiply that sign */
__mark_reg_unbounded(dst_reg);
__update_reg_bounds(dst_reg);
break;
}
/* Both values are positive, so we can work with unsigned and
* copy the result to signed (unless it exceeds S64_MAX).
*/
if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
/* Potential overflow, we know nothing */
__mark_reg_unbounded(dst_reg);
/* (except what we can learn from the var_off) */
__update_reg_bounds(dst_reg);
break;
}
dst_reg->umin_value *= umin_val;
dst_reg->umax_value *= umax_val;
if (dst_reg->umax_value > S64_MAX) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
break;
case BPF_AND:
if (src_known && dst_known) {
__mark_reg_known(dst_reg, dst_reg->var_off.value &
src_reg.var_off.value);
break;
}
/* We get our minimum from the var_off, since that's inherently
* bitwise. Our maximum is the minimum of the operands' maxima.
*/
dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
dst_reg->umin_value = dst_reg->var_off.value;
dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
if (dst_reg->smin_value < 0 || smin_val < 0) {
/* Lose signed bounds when ANDing negative numbers,
* ain't nobody got time for that.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
/* ANDing two positives gives a positive, so safe to
* cast result into s64.
*/
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_OR:
if (src_known && dst_known) {
__mark_reg_known(dst_reg, dst_reg->var_off.value |
src_reg.var_off.value);
break;
}
/* We get our maximum from the var_off, and our minimum is the
* maximum of the operands' minima
*/
dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
dst_reg->umax_value = dst_reg->var_off.value |
dst_reg->var_off.mask;
if (dst_reg->smin_value < 0 || smin_val < 0) {
/* Lose signed bounds when ORing negative numbers,
* ain't nobody got time for that.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
/* ORing two positives gives a positive, so safe to
* cast result into s64.
*/
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_LSH:
if (umax_val > 63) {
/* Shifts greater than 63 are undefined. This includes
* shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* We lose all sign bit information (except what we can pick
* up from var_off)
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
/* If we might shift our top bit out, then we know nothing */
if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value <<= umin_val;
dst_reg->umax_value <<= umax_val;
}
if (src_known)
dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
else
dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val);
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_RSH:
if (umax_val > 63) {
/* Shifts greater than 63 are undefined. This includes
* shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* BPF_RSH is an unsigned shift, so make the appropriate casts */
if (dst_reg->smin_value < 0) {
if (umin_val) {
/* Sign bit will be cleared */
dst_reg->smin_value = 0;
} else {
/* Lost sign bit information */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
}
} else {
dst_reg->smin_value =
(u64)(dst_reg->smin_value) >> umax_val;
}
if (src_known)
dst_reg->var_off = tnum_rshift(dst_reg->var_off,
umin_val);
else
dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val);
dst_reg->umin_value >>= umax_val;
dst_reg->umax_value >>= umin_val;
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
default:
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
}
/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
* and var_off.
*/
static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env), *dst_reg, *src_reg;
struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
u8 opcode = BPF_OP(insn->code);
int rc;
dst_reg = ®s[insn->dst_reg];
src_reg = NULL;
if (dst_reg->type != SCALAR_VALUE)
ptr_reg = dst_reg;
if (BPF_SRC(insn->code) == BPF_X) {
src_reg = ®s[insn->src_reg];
if (src_reg->type != SCALAR_VALUE) {
if (dst_reg->type != SCALAR_VALUE) {
/* Combining two pointers by any ALU op yields
* an arbitrary scalar.
*/
if (!env->allow_ptr_leaks) {
verbose(env, "R%d pointer %s pointer prohibited\n",
insn->dst_reg,
bpf_alu_string[opcode >> 4]);
return -EACCES;
}
mark_reg_unknown(env, regs, insn->dst_reg);
return 0;
} else {
/* scalar += pointer
* This is legal, but we have to reverse our
* src/dest handling in computing the range
*/
rc = adjust_ptr_min_max_vals(env, insn,
src_reg, dst_reg);
if (rc == -EACCES && env->allow_ptr_leaks) {
/* scalar += unknown scalar */
__mark_reg_unknown(&off_reg);
return adjust_scalar_min_max_vals(
env, insn,
dst_reg, off_reg);
}
return rc;
}
} else if (ptr_reg) {
/* pointer += scalar */
rc = adjust_ptr_min_max_vals(env, insn,
dst_reg, src_reg);
if (rc == -EACCES && env->allow_ptr_leaks) {
/* unknown scalar += scalar */
__mark_reg_unknown(dst_reg);
return adjust_scalar_min_max_vals(
env, insn, dst_reg, *src_reg);
}
return rc;
}
} else {
/* Pretend the src is a reg with a known value, since we only
* need to be able to read from this state.
*/
off_reg.type = SCALAR_VALUE;
__mark_reg_known(&off_reg, insn->imm);
src_reg = &off_reg;
if (ptr_reg) { /* pointer += K */
rc = adjust_ptr_min_max_vals(env, insn,
ptr_reg, src_reg);
if (rc == -EACCES && env->allow_ptr_leaks) {
/* unknown scalar += K */
__mark_reg_unknown(dst_reg);
return adjust_scalar_min_max_vals(
env, insn, dst_reg, off_reg);
}
return rc;
}
}
/* Got here implies adding two SCALAR_VALUEs */
if (WARN_ON_ONCE(ptr_reg)) {
print_verifier_state(env, env->cur_state);
verbose(env, "verifier internal error: unexpected ptr_reg\n");
return -EINVAL;
}
if (WARN_ON(!src_reg)) {
print_verifier_state(env, env->cur_state);
verbose(env, "verifier internal error: no src_reg\n");
return -EINVAL;
}
return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
}
/* check validity of 32-bit and 64-bit arithmetic operations */
static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode == BPF_END || opcode == BPF_NEG) {
if (opcode == BPF_NEG) {
if (BPF_SRC(insn->code) != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->off != 0 || insn->imm != 0) {
verbose(env, "BPF_NEG uses reserved fields\n");
return -EINVAL;
}
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
(insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
BPF_CLASS(insn->code) == BPF_ALU64) {
verbose(env, "BPF_END uses reserved fields\n");
return -EINVAL;
}
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer arithmetic prohibited\n",
insn->dst_reg);
return -EACCES;
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
} else if (opcode == BPF_MOV) {
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
if (BPF_SRC(insn->code) == BPF_X) {
if (BPF_CLASS(insn->code) == BPF_ALU64) {
/* case: R1 = R2
* copy register state to dest reg
*/
regs[insn->dst_reg] = regs[insn->src_reg];
regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
} else {
/* R1 = (u32) R2 */
if (is_pointer_value(env, insn->src_reg)) {
verbose(env,
"R%d partial copy of pointer\n",
insn->src_reg);
return -EACCES;
}
mark_reg_unknown(env, regs, insn->dst_reg);
/* high 32 bits are known zero. */
regs[insn->dst_reg].var_off = tnum_cast(
regs[insn->dst_reg].var_off, 4);
__update_reg_bounds(®s[insn->dst_reg]);
}
} else {
/* case: R = imm
* remember the value we stored into this reg
*/
regs[insn->dst_reg].type = SCALAR_VALUE;
__mark_reg_known(regs + insn->dst_reg, insn->imm);
}
} else if (opcode > BPF_END) {
verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
return -EINVAL;
} else { /* all other ALU ops: and, sub, xor, add, ... */
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
verbose(env, "div by zero\n");
return -EINVAL;
}
if ((opcode == BPF_LSH || opcode == BPF_RSH ||
opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
if (insn->imm < 0 || insn->imm >= size) {
verbose(env, "invalid shift %d\n", insn->imm);
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
return adjust_reg_min_max_vals(env, insn);
}
return 0;
}
static void find_good_pkt_pointers(struct bpf_verifier_state *state,
struct bpf_reg_state *dst_reg,
enum bpf_reg_type type,
bool range_right_open)
{
struct bpf_reg_state *regs = state->regs, *reg;
u16 new_range;
int i;
if (dst_reg->off < 0 ||
(dst_reg->off == 0 && range_right_open))
/* This doesn't give us any range */
return;
if (dst_reg->umax_value > MAX_PACKET_OFF ||
dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
/* Risk of overflow. For instance, ptr + (1<<63) may be less
* than pkt_end, but that's because it's also less than pkt.
*/
return;
new_range = dst_reg->off;
if (range_right_open)
new_range--;
/* Examples for register markings:
*
* pkt_data in dst register:
*
* r2 = r3;
* r2 += 8;
* if (r2 > pkt_end) goto <handle exception>
* <access okay>
*
* r2 = r3;
* r2 += 8;
* if (r2 < pkt_end) goto <access okay>
* <handle exception>
*
* Where:
* r2 == dst_reg, pkt_end == src_reg
* r2=pkt(id=n,off=8,r=0)
* r3=pkt(id=n,off=0,r=0)
*
* pkt_data in src register:
*
* r2 = r3;
* r2 += 8;
* if (pkt_end >= r2) goto <access okay>
* <handle exception>
*
* r2 = r3;
* r2 += 8;
* if (pkt_end <= r2) goto <handle exception>
* <access okay>
*
* Where:
* pkt_end == dst_reg, r2 == src_reg
* r2=pkt(id=n,off=8,r=0)
* r3=pkt(id=n,off=0,r=0)
*
* Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
* or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
* and [r3, r3 + 8-1) respectively is safe to access depending on
* the check.
*/
/* If our ids match, then we must have the same max_value. And we
* don't care about the other reg's fixed offset, since if it's too big
* the range won't allow anything.
* dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
*/
for (i = 0; i < MAX_BPF_REG; i++)
if (regs[i].type == type && regs[i].id == dst_reg->id)
/* keep the maximum range already checked */
regs[i].range = max(regs[i].range, new_range);
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
reg = &state->stack[i].spilled_ptr;
if (reg->type == type && reg->id == dst_reg->id)
reg->range = max(reg->range, new_range);
}
}
/* Adjusts the register min/max values in the case that the dst_reg is the
* variable register that we are working on, and src_reg is a constant or we're
* simply doing a BPF_K check.
* In JEQ/JNE cases we also adjust the var_off values.
*/
static void reg_set_min_max(struct bpf_reg_state *true_reg,
struct bpf_reg_state *false_reg, u64 val,
u8 opcode)
{
/* If the dst_reg is a pointer, we can't learn anything about its
* variable offset from the compare (unless src_reg were a pointer into
* the same object, but we don't bother with that.
* Since false_reg and true_reg have the same type by construction, we
* only need to check one of them for pointerness.
*/
if (__is_pointer_value(false, false_reg))
return;
switch (opcode) {
case BPF_JEQ:
/* If this is false then we know nothing Jon Snow, but if it is
* true then we know for sure.
*/
__mark_reg_known(true_reg, val);
break;
case BPF_JNE:
/* If this is true we know nothing Jon Snow, but if it is false
* we know the value for sure;
*/
__mark_reg_known(false_reg, val);
break;
case BPF_JGT:
false_reg->umax_value = min(false_reg->umax_value, val);
true_reg->umin_value = max(true_reg->umin_value, val + 1);
break;
case BPF_JSGT:
false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
break;
case BPF_JLT:
false_reg->umin_value = max(false_reg->umin_value, val);
true_reg->umax_value = min(true_reg->umax_value, val - 1);
break;
case BPF_JSLT:
false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
break;
case BPF_JGE:
false_reg->umax_value = min(false_reg->umax_value, val - 1);
true_reg->umin_value = max(true_reg->umin_value, val);
break;
case BPF_JSGE:
false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
break;
case BPF_JLE:
false_reg->umin_value = max(false_reg->umin_value, val + 1);
true_reg->umax_value = min(true_reg->umax_value, val);
break;
case BPF_JSLE:
false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
break;
default:
break;
}
__reg_deduce_bounds(false_reg);
__reg_deduce_bounds(true_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(false_reg);
__reg_bound_offset(true_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(false_reg);
__update_reg_bounds(true_reg);
}
/* Same as above, but for the case that dst_reg holds a constant and src_reg is
* the variable reg.
*/
static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
struct bpf_reg_state *false_reg, u64 val,
u8 opcode)
{
if (__is_pointer_value(false, false_reg))
return;
switch (opcode) {
case BPF_JEQ:
/* If this is false then we know nothing Jon Snow, but if it is
* true then we know for sure.
*/
__mark_reg_known(true_reg, val);
break;
case BPF_JNE:
/* If this is true we know nothing Jon Snow, but if it is false
* we know the value for sure;
*/
__mark_reg_known(false_reg, val);
break;
case BPF_JGT:
true_reg->umax_value = min(true_reg->umax_value, val - 1);
false_reg->umin_value = max(false_reg->umin_value, val);
break;
case BPF_JSGT:
true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
break;
case BPF_JLT:
true_reg->umin_value = max(true_reg->umin_value, val + 1);
false_reg->umax_value = min(false_reg->umax_value, val);
break;
case BPF_JSLT:
true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
break;
case BPF_JGE:
true_reg->umax_value = min(true_reg->umax_value, val);
false_reg->umin_value = max(false_reg->umin_value, val + 1);
break;
case BPF_JSGE:
true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
break;
case BPF_JLE:
true_reg->umin_value = max(true_reg->umin_value, val);
false_reg->umax_value = min(false_reg->umax_value, val - 1);
break;
case BPF_JSLE:
true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
break;
default:
break;
}
__reg_deduce_bounds(false_reg);
__reg_deduce_bounds(true_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(false_reg);
__reg_bound_offset(true_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(false_reg);
__update_reg_bounds(true_reg);
}
/* Regs are known to be equal, so intersect their min/max/var_off */
static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
struct bpf_reg_state *dst_reg)
{
src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
dst_reg->umin_value);
src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
dst_reg->umax_value);
src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
dst_reg->smin_value);
src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
dst_reg->smax_value);
src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
dst_reg->var_off);
/* We might have learned new bounds from the var_off. */
__update_reg_bounds(src_reg);
__update_reg_bounds(dst_reg);
/* We might have learned something about the sign bit. */
__reg_deduce_bounds(src_reg);
__reg_deduce_bounds(dst_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(src_reg);
__reg_bound_offset(dst_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(src_reg);
__update_reg_bounds(dst_reg);
}
static void reg_combine_min_max(struct bpf_reg_state *true_src,
struct bpf_reg_state *true_dst,
struct bpf_reg_state *false_src,
struct bpf_reg_state *false_dst,
u8 opcode)
{
switch (opcode) {
case BPF_JEQ:
__reg_combine_min_max(true_src, true_dst);
break;
case BPF_JNE:
__reg_combine_min_max(false_src, false_dst);
break;
}
}
static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
bool is_null)
{
struct bpf_reg_state *reg = ®s[regno];
if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
/* Old offset (both fixed and variable parts) should
* have been known-zero, because we don't allow pointer
* arithmetic on pointers that might be NULL.
*/
if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
!tnum_equals_const(reg->var_off, 0) ||
reg->off)) {
__mark_reg_known_zero(reg);
reg->off = 0;
}
if (is_null) {
reg->type = SCALAR_VALUE;
} else if (reg->map_ptr->inner_map_meta) {
reg->type = CONST_PTR_TO_MAP;
reg->map_ptr = reg->map_ptr->inner_map_meta;
} else {
reg->type = PTR_TO_MAP_VALUE;
}
/* We don't need id from this point onwards anymore, thus we
* should better reset it, so that state pruning has chances
* to take effect.
*/
reg->id = 0;
}
}
/* The logic is similar to find_good_pkt_pointers(), both could eventually
* be folded together at some point.
*/
static void mark_map_regs(struct bpf_verifier_state *state, u32 regno,
bool is_null)
{
struct bpf_reg_state *regs = state->regs;
u32 id = regs[regno].id;
int i;
for (i = 0; i < MAX_BPF_REG; i++)
mark_map_reg(regs, i, id, is_null);
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
}
}
static bool try_match_pkt_pointers(const struct bpf_insn *insn,
struct bpf_reg_state *dst_reg,
struct bpf_reg_state *src_reg,
struct bpf_verifier_state *this_branch,
struct bpf_verifier_state *other_branch)
{
if (BPF_SRC(insn->code) != BPF_X)
return false;
switch (BPF_OP(insn->code)) {
case BPF_JGT:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
find_good_pkt_pointers(this_branch, dst_reg,
dst_reg->type, false);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end > pkt_data', pkt_data > pkt_meta' */
find_good_pkt_pointers(other_branch, src_reg,
src_reg->type, true);
} else {
return false;
}
break;
case BPF_JLT:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
find_good_pkt_pointers(other_branch, dst_reg,
dst_reg->type, true);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end < pkt_data', pkt_data > pkt_meta' */
find_good_pkt_pointers(this_branch, src_reg,
src_reg->type, false);
} else {
return false;
}
break;
case BPF_JGE:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
find_good_pkt_pointers(this_branch, dst_reg,
dst_reg->type, true);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
find_good_pkt_pointers(other_branch, src_reg,
src_reg->type, false);
} else {
return false;
}
break;
case BPF_JLE:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
find_good_pkt_pointers(other_branch, dst_reg,
dst_reg->type, false);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
find_good_pkt_pointers(this_branch, src_reg,
src_reg->type, true);
} else {
return false;
}
break;
default:
return false;
}
return true;
}
static int check_cond_jmp_op(struct bpf_verifier_env *env,
struct bpf_insn *insn, int *insn_idx)
{
struct bpf_verifier_state *other_branch, *this_branch = env->cur_state;
struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode > BPF_JSLE) {
verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
return -EINVAL;
}
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0) {
verbose(env, "BPF_JMP uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->src_reg)) {
verbose(env, "R%d pointer comparison prohibited\n",
insn->src_reg);
return -EACCES;
}
} else {
if (insn->src_reg != BPF_REG_0) {
verbose(env, "BPF_JMP uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
dst_reg = ®s[insn->dst_reg];
/* detect if R == 0 where R was initialized to zero earlier */
if (BPF_SRC(insn->code) == BPF_K &&
(opcode == BPF_JEQ || opcode == BPF_JNE) &&
dst_reg->type == SCALAR_VALUE &&
tnum_equals_const(dst_reg->var_off, insn->imm)) {
if (opcode == BPF_JEQ) {
/* if (imm == imm) goto pc+off;
* only follow the goto, ignore fall-through
*/
*insn_idx += insn->off;
return 0;
} else {
/* if (imm != imm) goto pc+off;
* only follow fall-through branch, since
* that's where the program will go
*/
return 0;
}
}
other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
if (!other_branch)
return -EFAULT;
/* detect if we are comparing against a constant value so we can adjust
* our min/max values for our dst register.
* this is only legit if both are scalars (or pointers to the same
* object, I suppose, but we don't support that right now), because
* otherwise the different base pointers mean the offsets aren't
* comparable.
*/
if (BPF_SRC(insn->code) == BPF_X) {
if (dst_reg->type == SCALAR_VALUE &&
regs[insn->src_reg].type == SCALAR_VALUE) {
if (tnum_is_const(regs[insn->src_reg].var_off))
reg_set_min_max(&other_branch->regs[insn->dst_reg],
dst_reg, regs[insn->src_reg].var_off.value,
opcode);
else if (tnum_is_const(dst_reg->var_off))
reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
®s[insn->src_reg],
dst_reg->var_off.value, opcode);
else if (opcode == BPF_JEQ || opcode == BPF_JNE)
/* Comparing for equality, we can combine knowledge */
reg_combine_min_max(&other_branch->regs[insn->src_reg],
&other_branch->regs[insn->dst_reg],
®s[insn->src_reg],
®s[insn->dst_reg], opcode);
}
} else if (dst_reg->type == SCALAR_VALUE) {
reg_set_min_max(&other_branch->regs[insn->dst_reg],
dst_reg, insn->imm, opcode);
}
/* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
if (BPF_SRC(insn->code) == BPF_K &&
insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
/* Mark all identical map registers in each branch as either
* safe or unknown depending R == 0 or R != 0 conditional.
*/
mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
} else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
this_branch, other_branch) &&
is_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer comparison prohibited\n",
insn->dst_reg);
return -EACCES;
}
if (env->log.level)
print_verifier_state(env, this_branch);
return 0;
}
/* return the map pointer stored inside BPF_LD_IMM64 instruction */
static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
{
u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
return (struct bpf_map *) (unsigned long) imm64;
}
/* verify BPF_LD_IMM64 instruction */
static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
int err;
if (BPF_SIZE(insn->code) != BPF_DW) {
verbose(env, "invalid BPF_LD_IMM insn\n");
return -EINVAL;
}
if (insn->off != 0) {
verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
return -EINVAL;
}
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
if (insn->src_reg == 0) {
u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
regs[insn->dst_reg].type = SCALAR_VALUE;
__mark_reg_known(®s[insn->dst_reg], imm);
return 0;
}
/* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
return 0;
}
static bool may_access_skb(enum bpf_prog_type type)
{
switch (type) {
case BPF_PROG_TYPE_SOCKET_FILTER:
case BPF_PROG_TYPE_SCHED_CLS:
case BPF_PROG_TYPE_SCHED_ACT:
return true;
default:
return false;
}
}
/* verify safety of LD_ABS|LD_IND instructions:
* - they can only appear in the programs where ctx == skb
* - since they are wrappers of function calls, they scratch R1-R5 registers,
* preserve R6-R9, and store return value into R0
*
* Implicit input:
* ctx == skb == R6 == CTX
*
* Explicit input:
* SRC == any register
* IMM == 32-bit immediate
*
* Output:
* R0 - 8/16/32-bit skb data converted to cpu endianness
*/
static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 mode = BPF_MODE(insn->code);
int i, err;
if (!may_access_skb(env->prog->type)) {
verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
return -EINVAL;
}
if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
BPF_SIZE(insn->code) == BPF_DW ||
(mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
return -EINVAL;
}
/* check whether implicit source operand (register R6) is readable */
err = check_reg_arg(env, BPF_REG_6, SRC_OP);
if (err)
return err;
if (regs[BPF_REG_6].type != PTR_TO_CTX) {
verbose(env,
"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
return -EINVAL;
}
if (mode == BPF_IND) {
/* check explicit source operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
}
/* reset caller saved regs to unreadable */
for (i = 0; i < CALLER_SAVED_REGS; i++) {
mark_reg_not_init(env, regs, caller_saved[i]);
check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
}
/* mark destination R0 register as readable, since it contains
* the value fetched from the packet.
* Already marked as written above.
*/
mark_reg_unknown(env, regs, BPF_REG_0);
return 0;
}
static int check_return_code(struct bpf_verifier_env *env)
{
struct bpf_reg_state *reg;
struct tnum range = tnum_range(0, 1);
switch (env->prog->type) {
case BPF_PROG_TYPE_CGROUP_SKB:
case BPF_PROG_TYPE_CGROUP_SOCK:
case BPF_PROG_TYPE_SOCK_OPS:
case BPF_PROG_TYPE_CGROUP_DEVICE:
break;
default:
return 0;
}
reg = cur_regs(env) + BPF_REG_0;
if (reg->type != SCALAR_VALUE) {
verbose(env, "At program exit the register R0 is not a known value (%s)\n",
reg_type_str[reg->type]);
return -EINVAL;
}
if (!tnum_in(range, reg->var_off)) {
verbose(env, "At program exit the register R0 ");
if (!tnum_is_unknown(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "has value %s", tn_buf);
} else {
verbose(env, "has unknown scalar value");
}
verbose(env, " should have been 0 or 1\n");
return -EINVAL;
}
return 0;
}
/* non-recursive DFS pseudo code
* 1 procedure DFS-iterative(G,v):
* 2 label v as discovered
* 3 let S be a stack
* 4 S.push(v)
* 5 while S is not empty
* 6 t <- S.pop()
* 7 if t is what we're looking for:
* 8 return t
* 9 for all edges e in G.adjacentEdges(t) do
* 10 if edge e is already labelled
* 11 continue with the next edge
* 12 w <- G.adjacentVertex(t,e)
* 13 if vertex w is not discovered and not explored
* 14 label e as tree-edge
* 15 label w as discovered
* 16 S.push(w)
* 17 continue at 5
* 18 else if vertex w is discovered
* 19 label e as back-edge
* 20 else
* 21 // vertex w is explored
* 22 label e as forward- or cross-edge
* 23 label t as explored
* 24 S.pop()
*
* convention:
* 0x10 - discovered
* 0x11 - discovered and fall-through edge labelled
* 0x12 - discovered and fall-through and branch edges labelled
* 0x20 - explored
*/
enum {
DISCOVERED = 0x10,
EXPLORED = 0x20,
FALLTHROUGH = 1,
BRANCH = 2,
};
#define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
static int *insn_stack; /* stack of insns to process */
static int cur_stack; /* current stack index */
static int *insn_state;
/* t, w, e - match pseudo-code above:
* t - index of current instruction
* w - next instruction
* e - edge
*/
static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
{
if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
return 0;
if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
return 0;
if (w < 0 || w >= env->prog->len) {
verbose(env, "jump out of range from insn %d to %d\n", t, w);
return -EINVAL;
}
if (e == BRANCH)
/* mark branch target for state pruning */
env->explored_states[w] = STATE_LIST_MARK;
if (insn_state[w] == 0) {
/* tree-edge */
insn_state[t] = DISCOVERED | e;
insn_state[w] = DISCOVERED;
if (cur_stack >= env->prog->len)
return -E2BIG;
insn_stack[cur_stack++] = w;
return 1;
} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
verbose(env, "back-edge from insn %d to %d\n", t, w);
return -EINVAL;
} else if (insn_state[w] == EXPLORED) {
/* forward- or cross-edge */
insn_state[t] = DISCOVERED | e;
} else {
verbose(env, "insn state internal bug\n");
return -EFAULT;
}
return 0;
}
/* non-recursive depth-first-search to detect loops in BPF program
* loop == back-edge in directed graph
*/
static int check_cfg(struct bpf_verifier_env *env)
{
struct bpf_insn *insns = env->prog->insnsi;
int insn_cnt = env->prog->len;
int ret = 0;
int i, t;
insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
if (!insn_state)
return -ENOMEM;
insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
if (!insn_stack) {
kfree(insn_state);
return -ENOMEM;
}
insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
insn_stack[0] = 0; /* 0 is the first instruction */
cur_stack = 1;
peek_stack:
if (cur_stack == 0)
goto check_state;
t = insn_stack[cur_stack - 1];
if (BPF_CLASS(insns[t].code) == BPF_JMP) {
u8 opcode = BPF_OP(insns[t].code);
if (opcode == BPF_EXIT) {
goto mark_explored;
} else if (opcode == BPF_CALL) {
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
if (t + 1 < insn_cnt)
env->explored_states[t + 1] = STATE_LIST_MARK;
} else if (opcode == BPF_JA) {
if (BPF_SRC(insns[t].code) != BPF_K) {
ret = -EINVAL;
goto err_free;
}
/* unconditional jump with single edge */
ret = push_insn(t, t + insns[t].off + 1,
FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
/* tell verifier to check for equivalent states
* after every call and jump
*/
if (t + 1 < insn_cnt)
env->explored_states[t + 1] = STATE_LIST_MARK;
} else {
/* conditional jump with two edges */
env->explored_states[t] = STATE_LIST_MARK;
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
}
} else {
/* all other non-branch instructions with single
* fall-through edge
*/
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
}
mark_explored:
insn_state[t] = EXPLORED;
if (cur_stack-- <= 0) {
verbose(env, "pop stack internal bug\n");
ret = -EFAULT;
goto err_free;
}
goto peek_stack;
check_state:
for (i = 0; i < insn_cnt; i++) {
if (insn_state[i] != EXPLORED) {
verbose(env, "unreachable insn %d\n", i);
ret = -EINVAL;
goto err_free;
}
}
ret = 0; /* cfg looks good */
err_free:
kfree(insn_state);
kfree(insn_stack);
return ret;
}
/* check %cur's range satisfies %old's */
static bool range_within(struct bpf_reg_state *old,
struct bpf_reg_state *cur)
{
return old->umin_value <= cur->umin_value &&
old->umax_value >= cur->umax_value &&
old->smin_value <= cur->smin_value &&
old->smax_value >= cur->smax_value;
}
/* Maximum number of register states that can exist at once */
#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
struct idpair {
u32 old;
u32 cur;
};
/* If in the old state two registers had the same id, then they need to have
* the same id in the new state as well. But that id could be different from
* the old state, so we need to track the mapping from old to new ids.
* Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
* regs with old id 5 must also have new id 9 for the new state to be safe. But
* regs with a different old id could still have new id 9, we don't care about
* that.
* So we look through our idmap to see if this old id has been seen before. If
* so, we require the new id to match; otherwise, we add the id pair to the map.
*/
static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
{
unsigned int i;
for (i = 0; i < ID_MAP_SIZE; i++) {
if (!idmap[i].old) {
/* Reached an empty slot; haven't seen this id before */
idmap[i].old = old_id;
idmap[i].cur = cur_id;
return true;
}
if (idmap[i].old == old_id)
return idmap[i].cur == cur_id;
}
/* We ran out of idmap slots, which should be impossible */
WARN_ON_ONCE(1);
return false;
}
/* Returns true if (rold safe implies rcur safe) */
static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
struct idpair *idmap)
{
if (!(rold->live & REG_LIVE_READ))
/* explored state didn't use this */
return true;
if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0)
return true;
if (rold->type == NOT_INIT)
/* explored state can't have used this */
return true;
if (rcur->type == NOT_INIT)
return false;
switch (rold->type) {
case SCALAR_VALUE:
if (rcur->type == SCALAR_VALUE) {
/* new val must satisfy old val knowledge */
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
} else {
/* if we knew anything about the old value, we're not
* equal, because we can't know anything about the
* scalar value of the pointer in the new value.
*/
return rold->umin_value == 0 &&
rold->umax_value == U64_MAX &&
rold->smin_value == S64_MIN &&
rold->smax_value == S64_MAX &&
tnum_is_unknown(rold->var_off);
}
case PTR_TO_MAP_VALUE:
/* If the new min/max/var_off satisfy the old ones and
* everything else matches, we are OK.
* We don't care about the 'id' value, because nothing
* uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
*/
return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_MAP_VALUE_OR_NULL:
/* a PTR_TO_MAP_VALUE could be safe to use as a
* PTR_TO_MAP_VALUE_OR_NULL into the same map.
* However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
* checked, doing so could have affected others with the same
* id, and we can't check for that because we lost the id when
* we converted to a PTR_TO_MAP_VALUE.
*/
if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
return false;
if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
return false;
/* Check our ids match any regs they're supposed to */
return check_ids(rold->id, rcur->id, idmap);
case PTR_TO_PACKET_META:
case PTR_TO_PACKET:
if (rcur->type != rold->type)
return false;
/* We must have at least as much range as the old ptr
* did, so that any accesses which were safe before are
* still safe. This is true even if old range < old off,
* since someone could have accessed through (ptr - k), or
* even done ptr -= k in a register, to get a safe access.
*/
if (rold->range > rcur->range)
return false;
/* If the offsets don't match, we can't trust our alignment;
* nor can we be sure that we won't fall out of range.
*/
if (rold->off != rcur->off)
return false;
/* id relations must be preserved */
if (rold->id && !check_ids(rold->id, rcur->id, idmap))
return false;
/* new val must satisfy old val knowledge */
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_CTX:
case CONST_PTR_TO_MAP:
case PTR_TO_STACK:
case PTR_TO_PACKET_END:
/* Only valid matches are exact, which memcmp() above
* would have accepted
*/
default:
/* Don't know what's going on, just say it's not safe */
return false;
}
/* Shouldn't get here; if we do, say it's not safe */
WARN_ON_ONCE(1);
return false;
}
static bool stacksafe(struct bpf_verifier_state *old,
struct bpf_verifier_state *cur,
struct idpair *idmap)
{
int i, spi;
/* if explored stack has more populated slots than current stack
* such stacks are not equivalent
*/
if (old->allocated_stack > cur->allocated_stack)
return false;
/* walk slots of the explored stack and ignore any additional
* slots in the current stack, since explored(safe) state
* didn't use them
*/
for (i = 0; i < old->allocated_stack; i++) {
spi = i / BPF_REG_SIZE;
if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
continue;
if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
cur->stack[spi].slot_type[i % BPF_REG_SIZE])
/* Ex: old explored (safe) state has STACK_SPILL in
* this stack slot, but current has has STACK_MISC ->
* this verifier states are not equivalent,
* return false to continue verification of this path
*/
return false;
if (i % BPF_REG_SIZE)
continue;
if (old->stack[spi].slot_type[0] != STACK_SPILL)
continue;
if (!regsafe(&old->stack[spi].spilled_ptr,
&cur->stack[spi].spilled_ptr,
idmap))
/* when explored and current stack slot are both storing
* spilled registers, check that stored pointers types
* are the same as well.
* Ex: explored safe path could have stored
* (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
* but current path has stored:
* (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
* such verifier states are not equivalent.
* return false to continue verification of this path
*/
return false;
}
return true;
}
/* compare two verifier states
*
* all states stored in state_list are known to be valid, since
* verifier reached 'bpf_exit' instruction through them
*
* this function is called when verifier exploring different branches of
* execution popped from the state stack. If it sees an old state that has
* more strict register state and more strict stack state then this execution
* branch doesn't need to be explored further, since verifier already
* concluded that more strict state leads to valid finish.
*
* Therefore two states are equivalent if register state is more conservative
* and explored stack state is more conservative than the current one.
* Example:
* explored current
* (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
* (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
*
* In other words if current stack state (one being explored) has more
* valid slots than old one that already passed validation, it means
* the verifier can stop exploring and conclude that current state is valid too
*
* Similarly with registers. If explored state has register type as invalid
* whereas register type in current state is meaningful, it means that
* the current state will reach 'bpf_exit' instruction safely
*/
static bool states_equal(struct bpf_verifier_env *env,
struct bpf_verifier_state *old,
struct bpf_verifier_state *cur)
{
struct idpair *idmap;
bool ret = false;
int i;
idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
/* If we failed to allocate the idmap, just say it's not safe */
if (!idmap)
return false;
for (i = 0; i < MAX_BPF_REG; i++) {
if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
goto out_free;
}
if (!stacksafe(old, cur, idmap))
goto out_free;
ret = true;
out_free:
kfree(idmap);
return ret;
}
/* A write screens off any subsequent reads; but write marks come from the
* straight-line code between a state and its parent. When we arrive at a
* jump target (in the first iteration of the propagate_liveness() loop),
* we didn't arrive by the straight-line code, so read marks in state must
* propagate to parent regardless of state's write marks.
*/
static bool do_propagate_liveness(const struct bpf_verifier_state *state,
struct bpf_verifier_state *parent)
{
bool writes = parent == state->parent; /* Observe write marks */
bool touched = false; /* any changes made? */
int i;
if (!parent)
return touched;
/* Propagate read liveness of registers... */
BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
/* We don't need to worry about FP liveness because it's read-only */
for (i = 0; i < BPF_REG_FP; i++) {
if (parent->regs[i].live & REG_LIVE_READ)
continue;
if (writes && (state->regs[i].live & REG_LIVE_WRITTEN))
continue;
if (state->regs[i].live & REG_LIVE_READ) {
parent->regs[i].live |= REG_LIVE_READ;
touched = true;
}
}
/* ... and stack slots */
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
i < parent->allocated_stack / BPF_REG_SIZE; i++) {
if (parent->stack[i].slot_type[0] != STACK_SPILL)
continue;
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
continue;
if (writes &&
(state->stack[i].spilled_ptr.live & REG_LIVE_WRITTEN))
continue;
if (state->stack[i].spilled_ptr.live & REG_LIVE_READ) {
parent->stack[i].spilled_ptr.live |= REG_LIVE_READ;
touched = true;
}
}
return touched;
}
/* "parent" is "a state from which we reach the current state", but initially
* it is not the state->parent (i.e. "the state whose straight-line code leads
* to the current state"), instead it is the state that happened to arrive at
* a (prunable) equivalent of the current state. See comment above
* do_propagate_liveness() for consequences of this.
* This function is just a more efficient way of calling mark_reg_read() or
* mark_stack_slot_read() on each reg in "parent" that is read in "state",
* though it requires that parent != state->parent in the call arguments.
*/
static void propagate_liveness(const struct bpf_verifier_state *state,
struct bpf_verifier_state *parent)
{
while (do_propagate_liveness(state, parent)) {
/* Something changed, so we need to feed those changes onward */
state = parent;
parent = state->parent;
}
}
static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
{
struct bpf_verifier_state_list *new_sl;
struct bpf_verifier_state_list *sl;
struct bpf_verifier_state *cur = env->cur_state;
int i, err;
sl = env->explored_states[insn_idx];
if (!sl)
/* this 'insn_idx' instruction wasn't marked, so we will not
* be doing state search here
*/
return 0;
while (sl != STATE_LIST_MARK) {
if (states_equal(env, &sl->state, cur)) {
/* reached equivalent register/stack state,
* prune the search.
* Registers read by the continuation are read by us.
* If we have any write marks in env->cur_state, they
* will prevent corresponding reads in the continuation
* from reaching our parent (an explored_state). Our
* own state will get the read marks recorded, but
* they'll be immediately forgotten as we're pruning
* this state and will pop a new one.
*/
propagate_liveness(&sl->state, cur);
return 1;
}
sl = sl->next;
}
/* there were no equivalent states, remember current one.
* technically the current state is not proven to be safe yet,
* but it will either reach bpf_exit (which means it's safe) or
* it will be rejected. Since there are no loops, we won't be
* seeing this 'insn_idx' instruction again on the way to bpf_exit
*/
new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
if (!new_sl)
return -ENOMEM;
/* add new state to the head of linked list */
err = copy_verifier_state(&new_sl->state, cur);
if (err) {
free_verifier_state(&new_sl->state, false);
kfree(new_sl);
return err;
}
new_sl->next = env->explored_states[insn_idx];
env->explored_states[insn_idx] = new_sl;
/* connect new state to parentage chain */
cur->parent = &new_sl->state;
/* clear write marks in current state: the writes we did are not writes
* our child did, so they don't screen off its reads from us.
* (There are no read marks in current state, because reads always mark
* their parent and current state never has children yet. Only
* explored_states can get read marks.)
*/
for (i = 0; i < BPF_REG_FP; i++)
cur->regs[i].live = REG_LIVE_NONE;
for (i = 0; i < cur->allocated_stack / BPF_REG_SIZE; i++)
if (cur->stack[i].slot_type[0] == STACK_SPILL)
cur->stack[i].spilled_ptr.live = REG_LIVE_NONE;
return 0;
}
static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
int insn_idx, int prev_insn_idx)
{
if (env->dev_ops && env->dev_ops->insn_hook)
return env->dev_ops->insn_hook(env, insn_idx, prev_insn_idx);
return 0;
}
static int do_check(struct bpf_verifier_env *env)
{
struct bpf_verifier_state *state;
struct bpf_insn *insns = env->prog->insnsi;
struct bpf_reg_state *regs;
int insn_cnt = env->prog->len;
int insn_idx, prev_insn_idx = 0;
int insn_processed = 0;
bool do_print_state = false;
state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
if (!state)
return -ENOMEM;
env->cur_state = state;
init_reg_state(env, state->regs);
state->parent = NULL;
insn_idx = 0;
for (;;) {
struct bpf_insn *insn;
u8 class;
int err;
if (insn_idx >= insn_cnt) {
verbose(env, "invalid insn idx %d insn_cnt %d\n",
insn_idx, insn_cnt);
return -EFAULT;
}
insn = &insns[insn_idx];
class = BPF_CLASS(insn->code);
if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
verbose(env,
"BPF program is too large. Processed %d insn\n",
insn_processed);
return -E2BIG;
}
err = is_state_visited(env, insn_idx);
if (err < 0)
return err;
if (err == 1) {
/* found equivalent state, can prune the search */
if (env->log.level) {
if (do_print_state)
verbose(env, "\nfrom %d to %d: safe\n",
prev_insn_idx, insn_idx);
else
verbose(env, "%d: safe\n", insn_idx);
}
goto process_bpf_exit;
}
if (need_resched())
cond_resched();
if (env->log.level > 1 || (env->log.level && do_print_state)) {
if (env->log.level > 1)
verbose(env, "%d:", insn_idx);
else
verbose(env, "\nfrom %d to %d:",
prev_insn_idx, insn_idx);
print_verifier_state(env, state);
do_print_state = false;
}
if (env->log.level) {
verbose(env, "%d: ", insn_idx);
print_bpf_insn(verbose, env, insn,
env->allow_ptr_leaks);
}
err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
if (err)
return err;
regs = cur_regs(env);
env->insn_aux_data[insn_idx].seen = true;
if (class == BPF_ALU || class == BPF_ALU64) {
err = check_alu_op(env, insn);
if (err)
return err;
} else if (class == BPF_LDX) {
enum bpf_reg_type *prev_src_type, src_reg_type;
/* check for reserved fields is already done */
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
src_reg_type = regs[insn->src_reg].type;
/* check that memory (src_reg + off) is readable,
* the state of dst_reg will be updated by this func
*/
err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
BPF_SIZE(insn->code), BPF_READ,
insn->dst_reg);
if (err)
return err;
prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
if (*prev_src_type == NOT_INIT) {
/* saw a valid insn
* dst_reg = *(u32 *)(src_reg + off)
* save type to validate intersecting paths
*/
*prev_src_type = src_reg_type;
} else if (src_reg_type != *prev_src_type &&
(src_reg_type == PTR_TO_CTX ||
*prev_src_type == PTR_TO_CTX)) {
/* ABuser program is trying to use the same insn
* dst_reg = *(u32*) (src_reg + off)
* with different pointer types:
* src_reg == ctx in one branch and
* src_reg == stack|map in some other branch.
* Reject it.
*/
verbose(env, "same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_STX) {
enum bpf_reg_type *prev_dst_type, dst_reg_type;
if (BPF_MODE(insn->code) == BPF_XADD) {
err = check_xadd(env, insn_idx, insn);
if (err)
return err;
insn_idx++;
continue;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
dst_reg_type = regs[insn->dst_reg].type;
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE,
insn->src_reg);
if (err)
return err;
prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
if (*prev_dst_type == NOT_INIT) {
*prev_dst_type = dst_reg_type;
} else if (dst_reg_type != *prev_dst_type &&
(dst_reg_type == PTR_TO_CTX ||
*prev_dst_type == PTR_TO_CTX)) {
verbose(env, "same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_ST) {
if (BPF_MODE(insn->code) != BPF_MEM ||
insn->src_reg != BPF_REG_0) {
verbose(env, "BPF_ST uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE,
-1);
if (err)
return err;
} else if (class == BPF_JMP) {
u8 opcode = BPF_OP(insn->code);
if (opcode == BPF_CALL) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->off != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_CALL uses reserved fields\n");
return -EINVAL;
}
err = check_call(env, insn->imm, insn_idx);
if (err)
return err;
} else if (opcode == BPF_JA) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_JA uses reserved fields\n");
return -EINVAL;
}
insn_idx += insn->off + 1;
continue;
} else if (opcode == BPF_EXIT) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_EXIT uses reserved fields\n");
return -EINVAL;
}
/* eBPF calling convetion is such that R0 is used
* to return the value from eBPF program.
* Make sure that it's readable at this time
* of bpf_exit, which means that program wrote
* something into it earlier
*/
err = check_reg_arg(env, BPF_REG_0, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, BPF_REG_0)) {
verbose(env, "R0 leaks addr as return value\n");
return -EACCES;
}
err = check_return_code(env);
if (err)
return err;
process_bpf_exit:
err = pop_stack(env, &prev_insn_idx, &insn_idx);
if (err < 0) {
if (err != -ENOENT)
return err;
break;
} else {
do_print_state = true;
continue;
}
} else {
err = check_cond_jmp_op(env, insn, &insn_idx);
if (err)
return err;
}
} else if (class == BPF_LD) {
u8 mode = BPF_MODE(insn->code);
if (mode == BPF_ABS || mode == BPF_IND) {
err = check_ld_abs(env, insn);
if (err)
return err;
} else if (mode == BPF_IMM) {
err = check_ld_imm(env, insn);
if (err)
return err;
insn_idx++;
env->insn_aux_data[insn_idx].seen = true;
} else {
verbose(env, "invalid BPF_LD mode\n");
return -EINVAL;
}
} else {
verbose(env, "unknown insn class %d\n", class);
return -EINVAL;
}
insn_idx++;
}
verbose(env, "processed %d insns, stack depth %d\n", insn_processed,
env->prog->aux->stack_depth);
return 0;
}
static int check_map_prealloc(struct bpf_map *map)
{
return (map->map_type != BPF_MAP_TYPE_HASH &&
map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
!(map->map_flags & BPF_F_NO_PREALLOC);
}
static int check_map_prog_compatibility(struct bpf_verifier_env *env,
struct bpf_map *map,
struct bpf_prog *prog)
{
/* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
* preallocated hash maps, since doing memory allocation
* in overflow_handler can crash depending on where nmi got
* triggered.
*/
if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
if (!check_map_prealloc(map)) {
verbose(env, "perf_event programs can only use preallocated hash map\n");
return -EINVAL;
}
if (map->inner_map_meta &&
!check_map_prealloc(map->inner_map_meta)) {
verbose(env, "perf_event programs can only use preallocated inner hash map\n");
return -EINVAL;
}
}
return 0;
}
/* look for pseudo eBPF instructions that access map FDs and
* replace them with actual map pointers
*/
static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
{
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
int i, j, err;
err = bpf_prog_calc_tag(env->prog);
if (err)
return err;
for (i = 0; i < insn_cnt; i++, insn++) {
if (BPF_CLASS(insn->code) == BPF_LDX &&
(BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
verbose(env, "BPF_LDX uses reserved fields\n");
return -EINVAL;
}
if (BPF_CLASS(insn->code) == BPF_STX &&
((BPF_MODE(insn->code) != BPF_MEM &&
BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
verbose(env, "BPF_STX uses reserved fields\n");
return -EINVAL;
}
if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
struct bpf_map *map;
struct fd f;
if (i == insn_cnt - 1 || insn[1].code != 0 ||
insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
insn[1].off != 0) {
verbose(env, "invalid bpf_ld_imm64 insn\n");
return -EINVAL;
}
if (insn->src_reg == 0)
/* valid generic load 64-bit imm */
goto next_insn;
if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
verbose(env,
"unrecognized bpf_ld_imm64 insn\n");
return -EINVAL;
}
f = fdget(insn->imm);
map = __bpf_map_get(f);
if (IS_ERR(map)) {
verbose(env, "fd %d is not pointing to valid bpf_map\n",
insn->imm);
return PTR_ERR(map);
}
err = check_map_prog_compatibility(env, map, env->prog);
if (err) {
fdput(f);
return err;
}
/* store map pointer inside BPF_LD_IMM64 instruction */
insn[0].imm = (u32) (unsigned long) map;
insn[1].imm = ((u64) (unsigned long) map) >> 32;
/* check whether we recorded this map already */
for (j = 0; j < env->used_map_cnt; j++)
if (env->used_maps[j] == map) {
fdput(f);
goto next_insn;
}
if (env->used_map_cnt >= MAX_USED_MAPS) {
fdput(f);
return -E2BIG;
}
/* hold the map. If the program is rejected by verifier,
* the map will be released by release_maps() or it
* will be used by the valid program until it's unloaded
* and all maps are released in free_bpf_prog_info()
*/
map = bpf_map_inc(map, false);
if (IS_ERR(map)) {
fdput(f);
return PTR_ERR(map);
}
env->used_maps[env->used_map_cnt++] = map;
fdput(f);
next_insn:
insn++;
i++;
}
}
/* now all pseudo BPF_LD_IMM64 instructions load valid
* 'struct bpf_map *' into a register instead of user map_fd.
* These pointers will be used later by verifier to validate map access.
*/
return 0;
}
/* drop refcnt of maps used by the rejected program */
static void release_maps(struct bpf_verifier_env *env)
{
int i;
for (i = 0; i < env->used_map_cnt; i++)
bpf_map_put(env->used_maps[i]);
}
/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
{
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
int i;
for (i = 0; i < insn_cnt; i++, insn++)
if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
insn->src_reg = 0;
}
/* single env->prog->insni[off] instruction was replaced with the range
* insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
* [0, off) and [off, end) to new locations, so the patched range stays zero
*/
static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
u32 off, u32 cnt)
{
struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
int i;
if (cnt == 1)
return 0;
new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
if (!new_data)
return -ENOMEM;
memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
memcpy(new_data + off + cnt - 1, old_data + off,
sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
for (i = off; i < off + cnt - 1; i++)
new_data[i].seen = true;
env->insn_aux_data = new_data;
vfree(old_data);
return 0;
}
static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
const struct bpf_insn *patch, u32 len)
{
struct bpf_prog *new_prog;
new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
if (!new_prog)
return NULL;
if (adjust_insn_aux_data(env, new_prog->len, off, len))
return NULL;
return new_prog;
}
/* The verifier does more data flow analysis than llvm and will not explore
* branches that are dead at run time. Malicious programs can have dead code
* too. Therefore replace all dead at-run-time code with nops.
*/
static void sanitize_dead_code(struct bpf_verifier_env *env)
{
struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0);
struct bpf_insn *insn = env->prog->insnsi;
const int insn_cnt = env->prog->len;
int i;
for (i = 0; i < insn_cnt; i++) {
if (aux_data[i].seen)
continue;
memcpy(insn + i, &nop, sizeof(nop));
}
}
/* convert load instructions that access fields of 'struct __sk_buff'
* into sequence of instructions that access fields of 'struct sk_buff'
*/
static int convert_ctx_accesses(struct bpf_verifier_env *env)
{
const struct bpf_verifier_ops *ops = env->ops;
int i, cnt, size, ctx_field_size, delta = 0;
const int insn_cnt = env->prog->len;
struct bpf_insn insn_buf[16], *insn;
struct bpf_prog *new_prog;
enum bpf_access_type type;
bool is_narrower_load;
u32 target_size;
if (ops->gen_prologue) {
cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
env->prog);
if (cnt >= ARRAY_SIZE(insn_buf)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
} else if (cnt) {
new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
env->prog = new_prog;
delta += cnt - 1;
}
}
if (!ops->convert_ctx_access)
return 0;
insn = env->prog->insnsi + delta;
for (i = 0; i < insn_cnt; i++, insn++) {
if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
type = BPF_READ;
else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
insn->code == (BPF_STX | BPF_MEM | BPF_DW))
type = BPF_WRITE;
else
continue;
if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
continue;
ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
size = BPF_LDST_BYTES(insn);
/* If the read access is a narrower load of the field,
* convert to a 4/8-byte load, to minimum program type specific
* convert_ctx_access changes. If conversion is successful,
* we will apply proper mask to the result.
*/
is_narrower_load = size < ctx_field_size;
if (is_narrower_load) {
u32 off = insn->off;
u8 size_code;
if (type == BPF_WRITE) {
verbose(env, "bpf verifier narrow ctx access misconfigured\n");
return -EINVAL;
}
size_code = BPF_H;
if (ctx_field_size == 4)
size_code = BPF_W;
else if (ctx_field_size == 8)
size_code = BPF_DW;
insn->off = off & ~(ctx_field_size - 1);
insn->code = BPF_LDX | BPF_MEM | size_code;
}
target_size = 0;
cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
&target_size);
if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
(ctx_field_size && !target_size)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
}
if (is_narrower_load && size < target_size) {
if (ctx_field_size <= 4)
insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
(1 << size * 8) - 1);
else
insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
(1 << size * 8) - 1);
}
new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
/* keep walking new program and skip insns we just inserted */
env->prog = new_prog;
insn = new_prog->insnsi + i + delta;
}
return 0;
}
/* fixup insn->imm field of bpf_call instructions
* and inline eligible helpers as explicit sequence of BPF instructions
*
* this function is called after eBPF program passed verification
*/
static int fixup_bpf_calls(struct bpf_verifier_env *env)
{
struct bpf_prog *prog = env->prog;
struct bpf_insn *insn = prog->insnsi;
const struct bpf_func_proto *fn;
const int insn_cnt = prog->len;
struct bpf_insn insn_buf[16];
struct bpf_prog *new_prog;
struct bpf_map *map_ptr;
int i, cnt, delta = 0;
for (i = 0; i < insn_cnt; i++, insn++) {
if (insn->code != (BPF_JMP | BPF_CALL))
continue;
if (insn->imm == BPF_FUNC_get_route_realm)
prog->dst_needed = 1;
if (insn->imm == BPF_FUNC_get_prandom_u32)
bpf_user_rnd_init_once();
if (insn->imm == BPF_FUNC_tail_call) {
/* If we tail call into other programs, we
* cannot make any assumptions since they can
* be replaced dynamically during runtime in
* the program array.
*/
prog->cb_access = 1;
env->prog->aux->stack_depth = MAX_BPF_STACK;
/* mark bpf_tail_call as different opcode to avoid
* conditional branch in the interpeter for every normal
* call and to prevent accidental JITing by JIT compiler
* that doesn't support bpf_tail_call yet
*/
insn->imm = 0;
insn->code = BPF_JMP | BPF_TAIL_CALL;
continue;
}
/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
* handlers are currently limited to 64 bit only.
*/
if (ebpf_jit_enabled() && BITS_PER_LONG == 64 &&
insn->imm == BPF_FUNC_map_lookup_elem) {
map_ptr = env->insn_aux_data[i + delta].map_ptr;
if (map_ptr == BPF_MAP_PTR_POISON ||
!map_ptr->ops->map_gen_lookup)
goto patch_call_imm;
cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
}
new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
/* keep walking new program and skip insns we just inserted */
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
continue;
}
if (insn->imm == BPF_FUNC_redirect_map) {
/* Note, we cannot use prog directly as imm as subsequent
* rewrites would still change the prog pointer. The only
* stable address we can use is aux, which also works with
* prog clones during blinding.
*/
u64 addr = (unsigned long)prog->aux;
struct bpf_insn r4_ld[] = {
BPF_LD_IMM64(BPF_REG_4, addr),
*insn,
};
cnt = ARRAY_SIZE(r4_ld);
new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
}
patch_call_imm:
fn = env->ops->get_func_proto(insn->imm);
/* all functions that have prototype and verifier allowed
* programs to call them, must be real in-kernel functions
*/
if (!fn->func) {
verbose(env,
"kernel subsystem misconfigured func %s#%d\n",
func_id_name(insn->imm), insn->imm);
return -EFAULT;
}
insn->imm = fn->func - __bpf_call_base;
}
return 0;
}
static void free_states(struct bpf_verifier_env *env)
{
struct bpf_verifier_state_list *sl, *sln;
int i;
if (!env->explored_states)
return;
for (i = 0; i < env->prog->len; i++) {
sl = env->explored_states[i];
if (sl)
while (sl != STATE_LIST_MARK) {
sln = sl->next;
free_verifier_state(&sl->state, false);
kfree(sl);
sl = sln;
}
}
kfree(env->explored_states);
}
int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
{
struct bpf_verifier_env *env;
struct bpf_verifer_log *log;
int ret = -EINVAL;
/* no program is valid */
if (ARRAY_SIZE(bpf_verifier_ops) == 0)
return -EINVAL;
/* 'struct bpf_verifier_env' can be global, but since it's not small,
* allocate/free it every time bpf_check() is called
*/
env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
if (!env)
return -ENOMEM;
log = &env->log;
env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
(*prog)->len);
ret = -ENOMEM;
if (!env->insn_aux_data)
goto err_free_env;
env->prog = *prog;
env->ops = bpf_verifier_ops[env->prog->type];
/* grab the mutex to protect few globals used by verifier */
mutex_lock(&bpf_verifier_lock);
if (attr->log_level || attr->log_buf || attr->log_size) {
/* user requested verbose verifier output
* and supplied buffer to store the verification trace
*/
log->level = attr->log_level;
log->ubuf = (char __user *) (unsigned long) attr->log_buf;
log->len_total = attr->log_size;
ret = -EINVAL;
/* log attributes have to be sane */
if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
!log->level || !log->ubuf)
goto err_unlock;
}
env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
env->strict_alignment = true;
if (env->prog->aux->offload) {
ret = bpf_prog_offload_verifier_prep(env);
if (ret)
goto err_unlock;
}
ret = replace_map_fd_with_map_ptr(env);
if (ret < 0)
goto skip_full_check;
env->explored_states = kcalloc(env->prog->len,
sizeof(struct bpf_verifier_state_list *),
GFP_USER);
ret = -ENOMEM;
if (!env->explored_states)
goto skip_full_check;
ret = check_cfg(env);
if (ret < 0)
goto skip_full_check;
env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
ret = do_check(env);
if (env->cur_state) {
free_verifier_state(env->cur_state, true);
env->cur_state = NULL;
}
skip_full_check:
while (!pop_stack(env, NULL, NULL));
free_states(env);
if (ret == 0)
sanitize_dead_code(env);
if (ret == 0)
/* program is valid, convert *(u32*)(ctx + off) accesses */
ret = convert_ctx_accesses(env);
if (ret == 0)
ret = fixup_bpf_calls(env);
if (log->level && bpf_verifier_log_full(log))
ret = -ENOSPC;
if (log->level && !log->ubuf) {
ret = -EFAULT;
goto err_release_maps;
}
if (ret == 0 && env->used_map_cnt) {
/* if program passed verifier, update used_maps in bpf_prog_info */
env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
sizeof(env->used_maps[0]),
GFP_KERNEL);
if (!env->prog->aux->used_maps) {
ret = -ENOMEM;
goto err_release_maps;
}
memcpy(env->prog->aux->used_maps, env->used_maps,
sizeof(env->used_maps[0]) * env->used_map_cnt);
env->prog->aux->used_map_cnt = env->used_map_cnt;
/* program is valid. Convert pseudo bpf_ld_imm64 into generic
* bpf_ld_imm64 instructions
*/
convert_pseudo_ld_imm64(env);
}
err_release_maps:
if (!env->prog->aux->used_maps)
/* if we didn't copy map pointers into bpf_prog_info, release
* them now. Otherwise free_bpf_prog_info() will release them.
*/
release_maps(env);
*prog = env->prog;
err_unlock:
mutex_unlock(&bpf_verifier_lock);
vfree(env->insn_aux_data);
err_free_env:
kfree(env);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2989_1 |
crossvul-cpp_data_bad_1221_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% SSSSS V V GGGG %
% SS V V G %
% SSS V V G GG %
% SS V V G G %
% SSSSS V GGG %
% %
% %
% Read/Write Scalable Vector Graphics Format %
% %
% Software Design %
% Cristy %
% William Radcliffe %
% March 2000 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/annotate.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/constitute.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/delegate.h"
#include "MagickCore/delegate-private.h"
#include "MagickCore/draw.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/resource_.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/token.h"
#include "MagickCore/utility.h"
#if defined(MAGICKCORE_XML_DELEGATE)
# if defined(MAGICKCORE_WINDOWS_SUPPORT)
# if !defined(__MINGW32__)
# include <win32config.h>
# endif
# endif
# include <libxml/xmlmemory.h>
# include <libxml/parserInternals.h>
# include <libxml/xmlerror.h>
#endif
#if defined(MAGICKCORE_AUTOTRACE_DELEGATE)
#include "autotrace/autotrace.h"
#endif
#if defined(MAGICKCORE_RSVG_DELEGATE)
#include "librsvg/rsvg.h"
#if !defined(LIBRSVG_CHECK_VERSION)
#include "librsvg/rsvg-cairo.h"
#include "librsvg/librsvg-features.h"
#elif !LIBRSVG_CHECK_VERSION(2,36,2)
#include "librsvg/rsvg-cairo.h"
#include "librsvg/librsvg-features.h"
#endif
#endif
/*
Define declarations.
*/
#define DefaultSVGDensity 96.0
/*
Typedef declarations.
*/
typedef struct _BoundingBox
{
double
x,
y,
width,
height;
} BoundingBox;
typedef struct _ElementInfo
{
double
cx,
cy,
major,
minor,
angle;
} ElementInfo;
typedef struct _SVGInfo
{
FILE
*file;
ExceptionInfo
*exception;
Image
*image;
const ImageInfo
*image_info;
AffineMatrix
affine;
size_t
width,
height;
char
*size,
*title,
*comment;
int
n;
double
*scale,
pointsize;
ElementInfo
element;
SegmentInfo
segment;
BoundingBox
bounds,
text_offset,
view_box;
PointInfo
radius;
char
*stop_color,
*offset,
*text,
*vertices,
*url;
#if defined(MAGICKCORE_XML_DELEGATE)
xmlParserCtxtPtr
parser;
xmlDocPtr
document;
#endif
ssize_t
svgDepth;
} SVGInfo;
/*
Static declarations.
*/
static char
SVGDensityGeometry[] = "96.0x96.0";
/*
Forward declarations.
*/
static MagickBooleanType
WriteSVGImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s S V G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsSVG()() returns MagickTrue if the image format type, identified by the
% magick string, is SVG.
%
% The format of the IsSVG method is:
%
% MagickBooleanType IsSVG(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsSVG(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((const char *) magick+1,"svg",3) == 0)
return(MagickTrue);
if (length < 5)
return(MagickFalse);
if (LocaleNCompare((const char *) magick+1,"?xml",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d S V G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadSVGImage() reads a Scalable Vector Gaphics file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadSVGImage method is:
%
% Image *ReadSVGImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *RenderSVGImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
background[MagickPathExtent],
command[MagickPathExtent],
*density,
input_filename[MagickPathExtent],
opacity[MagickPathExtent],
output_filename[MagickPathExtent],
unique[MagickPathExtent];
const DelegateInfo
*delegate_info;
Image
*next;
int
status;
struct stat
attributes;
/*
Our best hope for compliance with the SVG standard.
*/
delegate_info=GetDelegateInfo("svg:decode",(char *) NULL,exception);
if (delegate_info == (const DelegateInfo *) NULL)
return((Image *) NULL);
status=AcquireUniqueSymbolicLink(image->filename,input_filename);
(void) AcquireUniqueFilename(output_filename);
(void) AcquireUniqueFilename(unique);
density=AcquireString("");
(void) FormatLocaleString(density,MagickPathExtent,"%.20g,%.20g",
image->resolution.x,image->resolution.y);
(void) FormatLocaleString(background,MagickPathExtent,
"rgb(%.20g%%,%.20g%%,%.20g%%)",
100.0*QuantumScale*image->background_color.red,
100.0*QuantumScale*image->background_color.green,
100.0*QuantumScale*image->background_color.blue);
(void) FormatLocaleString(opacity,MagickPathExtent,"%.20g",QuantumScale*
image->background_color.alpha);
(void) FormatLocaleString(command,MagickPathExtent,
GetDelegateCommands(delegate_info),input_filename,output_filename,density,
background,opacity,unique);
density=DestroyString(density);
status=ExternalDelegateCommand(MagickFalse,image_info->verbose,command,
(char *) NULL,exception);
(void) RelinquishUniqueFileResource(unique);
(void) RelinquishUniqueFileResource(input_filename);
if ((status == 0) && (stat(output_filename,&attributes) == 0) &&
(attributes.st_size > 0))
{
Image
*svg_image;
ImageInfo
*read_info;
read_info=CloneImageInfo(image_info);
(void) CopyMagickString(read_info->filename,output_filename,
MagickPathExtent);
svg_image=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
if (svg_image != (Image *) NULL)
{
(void) RelinquishUniqueFileResource(output_filename);
for (next=GetFirstImageInList(svg_image); next != (Image *) NULL; )
{
(void) CopyMagickString(next->filename,image->filename,
MaxTextExtent);
(void) CopyMagickString(next->magick,image->magick,MaxTextExtent);
next=GetNextImageInList(next);
}
return(svg_image);
}
}
(void) RelinquishUniqueFileResource(output_filename);
return((Image *) NULL);
}
#if defined(MAGICKCORE_XML_DELEGATE)
static SVGInfo *AcquireSVGInfo(void)
{
SVGInfo
*svg_info;
svg_info=(SVGInfo *) AcquireMagickMemory(sizeof(*svg_info));
if (svg_info == (SVGInfo *) NULL)
return((SVGInfo *) NULL);
(void) memset(svg_info,0,sizeof(*svg_info));
svg_info->text=AcquireString("");
svg_info->scale=(double *) AcquireCriticalMemory(sizeof(*svg_info->scale));
GetAffineMatrix(&svg_info->affine);
svg_info->scale[0]=ExpandAffine(&svg_info->affine);
return(svg_info);
}
static SVGInfo *DestroySVGInfo(SVGInfo *svg_info)
{
if (svg_info->text != (char *) NULL)
svg_info->text=DestroyString(svg_info->text);
if (svg_info->scale != (double *) NULL)
svg_info->scale=(double *) RelinquishMagickMemory(svg_info->scale);
if (svg_info->title != (char *) NULL)
svg_info->title=DestroyString(svg_info->title);
if (svg_info->comment != (char *) NULL)
svg_info->comment=DestroyString(svg_info->comment);
return((SVGInfo *) RelinquishMagickMemory(svg_info));
}
static double GetUserSpaceCoordinateValue(const SVGInfo *svg_info,int type,
const char *string)
{
char
*next_token,
token[MagickPathExtent];
const char
*p;
double
value;
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",string);
assert(string != (const char *) NULL);
p=(const char *) string;
(void) GetNextToken(p,&p,MagickPathExtent,token);
value=StringToDouble(token,&next_token);
if (strchr(token,'%') != (char *) NULL)
{
double
alpha,
beta;
if (type > 0)
{
if (svg_info->view_box.width == 0.0)
return(0.0);
return(svg_info->view_box.width*value/100.0);
}
if (type < 0)
{
if (svg_info->view_box.height == 0.0)
return(0.0);
return(svg_info->view_box.height*value/100.0);
}
alpha=value-svg_info->view_box.width;
beta=value-svg_info->view_box.height;
return(hypot(alpha,beta)/sqrt(2.0)/100.0);
}
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (LocaleNCompare(token,"cm",2) == 0)
return(DefaultSVGDensity*svg_info->scale[0]/2.54*value);
if (LocaleNCompare(token,"em",2) == 0)
return(svg_info->pointsize*value);
if (LocaleNCompare(token,"ex",2) == 0)
return(svg_info->pointsize*value/2.0);
if (LocaleNCompare(token,"in",2) == 0)
return(DefaultSVGDensity*svg_info->scale[0]*value);
if (LocaleNCompare(token,"mm",2) == 0)
return(DefaultSVGDensity*svg_info->scale[0]/25.4*value);
if (LocaleNCompare(token,"pc",2) == 0)
return(DefaultSVGDensity*svg_info->scale[0]/6.0*value);
if (LocaleNCompare(token,"pt",2) == 0)
return(svg_info->scale[0]*value);
if (LocaleNCompare(token,"px",2) == 0)
return(value);
return(value);
}
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int SVGIsStandalone(void *context)
{
SVGInfo
*svg_info;
/*
Is this document tagged standalone?
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.SVGIsStandalone()");
svg_info=(SVGInfo *) context;
return(svg_info->document->standalone == 1);
}
static int SVGHasInternalSubset(void *context)
{
SVGInfo
*svg_info;
/*
Does this document has an internal subset?
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.SVGHasInternalSubset()");
svg_info=(SVGInfo *) context;
return(svg_info->document->intSubset != NULL);
}
static int SVGHasExternalSubset(void *context)
{
SVGInfo
*svg_info;
/*
Does this document has an external subset?
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.SVGHasExternalSubset()");
svg_info=(SVGInfo *) context;
return(svg_info->document->extSubset != NULL);
}
static void SVGInternalSubset(void *context,const xmlChar *name,
const xmlChar *external_id,const xmlChar *system_id)
{
SVGInfo
*svg_info;
/*
Does this document has an internal subset?
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.internalSubset(%s, %s, %s)",(const char *) name,
(external_id != (const xmlChar *) NULL ? (const char *) external_id : "none"),
(system_id != (const xmlChar *) NULL ? (const char *) system_id : "none"));
svg_info=(SVGInfo *) context;
(void) xmlCreateIntSubset(svg_info->document,name,external_id,system_id);
}
static xmlParserInputPtr SVGResolveEntity(void *context,
const xmlChar *public_id,const xmlChar *system_id)
{
SVGInfo
*svg_info;
xmlParserInputPtr
stream;
/*
Special entity resolver, better left to the parser, it has more
context than the application layer. The default behaviour is to
not resolve the entities, in that case the ENTITY_REF nodes are
built in the structure (and the parameter values).
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.resolveEntity(%s, %s)",
(public_id != (const xmlChar *) NULL ? (const char *) public_id : "none"),
(system_id != (const xmlChar *) NULL ? (const char *) system_id : "none"));
svg_info=(SVGInfo *) context;
stream=xmlLoadExternalEntity((const char *) system_id,(const char *)
public_id,svg_info->parser);
return(stream);
}
static xmlEntityPtr SVGGetEntity(void *context,const xmlChar *name)
{
SVGInfo
*svg_info;
/*
Get an entity by name.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.SVGGetEntity(%s)",
name);
svg_info=(SVGInfo *) context;
return(xmlGetDocEntity(svg_info->document,name));
}
static xmlEntityPtr SVGGetParameterEntity(void *context,const xmlChar *name)
{
SVGInfo
*svg_info;
/*
Get a parameter entity by name.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.getParameterEntity(%s)",name);
svg_info=(SVGInfo *) context;
return(xmlGetParameterEntity(svg_info->document,name));
}
static void SVGEntityDeclaration(void *context,const xmlChar *name,int type,
const xmlChar *public_id,const xmlChar *system_id,xmlChar *content)
{
SVGInfo
*svg_info;
/*
An entity definition has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.entityDecl(%s, %d, %s, %s, %s)",name,type,
public_id != (xmlChar *) NULL ? (const char *) public_id : "none",
system_id != (xmlChar *) NULL ? (const char *) system_id : "none",content);
svg_info=(SVGInfo *) context;
if (svg_info->parser->inSubset == 1)
(void) xmlAddDocEntity(svg_info->document,name,type,public_id,system_id,
content);
else
if (svg_info->parser->inSubset == 2)
(void) xmlAddDtdEntity(svg_info->document,name,type,public_id,system_id,
content);
}
static void SVGAttributeDeclaration(void *context,const xmlChar *element,
const xmlChar *name,int type,int value,const xmlChar *default_value,
xmlEnumerationPtr tree)
{
SVGInfo
*svg_info;
xmlChar
*fullname,
*prefix;
xmlParserCtxtPtr
parser;
/*
An attribute definition has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.attributeDecl(%s, %s, %d, %d, %s, ...)",element,name,type,value,
default_value);
svg_info=(SVGInfo *) context;
fullname=(xmlChar *) NULL;
prefix=(xmlChar *) NULL;
parser=svg_info->parser;
fullname=(xmlChar *) xmlSplitQName(parser,name,&prefix);
if (parser->inSubset == 1)
(void) xmlAddAttributeDecl(&parser->vctxt,svg_info->document->intSubset,
element,fullname,prefix,(xmlAttributeType) type,
(xmlAttributeDefault) value,default_value,tree);
else
if (parser->inSubset == 2)
(void) xmlAddAttributeDecl(&parser->vctxt,svg_info->document->extSubset,
element,fullname,prefix,(xmlAttributeType) type,
(xmlAttributeDefault) value,default_value,tree);
if (prefix != (xmlChar *) NULL)
xmlFree(prefix);
if (fullname != (xmlChar *) NULL)
xmlFree(fullname);
}
static void SVGElementDeclaration(void *context,const xmlChar *name,int type,
xmlElementContentPtr content)
{
SVGInfo
*svg_info;
xmlParserCtxtPtr
parser;
/*
An element definition has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.elementDecl(%s, %d, ...)",name,type);
svg_info=(SVGInfo *) context;
parser=svg_info->parser;
if (parser->inSubset == 1)
(void) xmlAddElementDecl(&parser->vctxt,svg_info->document->intSubset,
name,(xmlElementTypeVal) type,content);
else
if (parser->inSubset == 2)
(void) xmlAddElementDecl(&parser->vctxt,svg_info->document->extSubset,
name,(xmlElementTypeVal) type,content);
}
static void SVGStripString(const MagickBooleanType trim,char *message)
{
register char
*p,
*q;
size_t
length;
assert(message != (char *) NULL);
if (*message == '\0')
return;
/*
Remove comment.
*/
q=message;
for (p=message; *p != '\0'; p++)
{
if ((*p == '/') && (*(p+1) == '*'))
{
for ( ; *p != '\0'; p++)
if ((*p == '*') && (*(p+1) == '/'))
{
p+=2;
break;
}
if (*p == '\0')
break;
}
*q++=(*p);
}
*q='\0';
length=strlen(message);
if ((trim != MagickFalse) && (length != 0))
{
/*
Remove whitespace.
*/
p=message;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if ((*p == '\'') || (*p == '"'))
p++;
q=message+length-1;
while ((isspace((int) ((unsigned char) *q)) != 0) && (q > p))
q--;
if (q > p)
if ((*q == '\'') || (*q == '"'))
q--;
(void) memmove(message,p,(size_t) (q-p+1));
message[q-p+1]='\0';
}
/*
Convert newlines to a space.
*/
for (p=message; *p != '\0'; p++)
if (*p == '\n')
*p=' ';
}
static char **SVGKeyValuePairs(void *context,const int key_sentinel,
const int value_sentinel,const char *text,size_t *number_tokens)
{
char
**tokens;
register const char
*p,
*q;
register ssize_t
i;
size_t
extent;
SVGInfo
*svg_info;
svg_info=(SVGInfo *) context;
*number_tokens=0;
if (text == (const char *) NULL)
return((char **) NULL);
extent=8;
tokens=(char **) AcquireQuantumMemory(extent+2UL,sizeof(*tokens));
if (tokens == (char **) NULL)
{
(void) ThrowMagickException(svg_info->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",text);
return((char **) NULL);
}
/*
Convert string to an ASCII list.
*/
i=0;
p=text;
for (q=p; *q != '\0'; q++)
{
if ((*q != key_sentinel) && (*q != value_sentinel) && (*q != '\0'))
continue;
if (i == (ssize_t) extent)
{
extent<<=1;
tokens=(char **) ResizeQuantumMemory(tokens,extent+2,sizeof(*tokens));
if (tokens == (char **) NULL)
{
(void) ThrowMagickException(svg_info->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",text);
return((char **) NULL);
}
}
tokens[i]=AcquireString(p);
(void) CopyMagickString(tokens[i],p,(size_t) (q-p+1));
SVGStripString(MagickTrue,tokens[i]);
i++;
p=q+1;
}
tokens[i]=AcquireString(p);
(void) CopyMagickString(tokens[i],p,(size_t) (q-p+1));
SVGStripString(MagickTrue,tokens[i++]);
tokens[i]=(char *) NULL;
*number_tokens=(size_t) i;
return(tokens);
}
static void SVGNotationDeclaration(void *context,const xmlChar *name,
const xmlChar *public_id,const xmlChar *system_id)
{
SVGInfo
*svg_info;
xmlParserCtxtPtr
parser;
/*
What to do when a notation declaration has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.notationDecl(%s, %s, %s)",name,
public_id != (const xmlChar *) NULL ? (const char *) public_id : "none",
system_id != (const xmlChar *) NULL ? (const char *) system_id : "none");
svg_info=(SVGInfo *) context;
parser=svg_info->parser;
if (parser->inSubset == 1)
(void) xmlAddNotationDecl(&parser->vctxt,svg_info->document->intSubset,
name,public_id,system_id);
else
if (parser->inSubset == 2)
(void) xmlAddNotationDecl(&parser->vctxt,svg_info->document->intSubset,
name,public_id,system_id);
}
static void SVGProcessStyleElement(void *context,const xmlChar *name,
const char *style)
{
char
background[MagickPathExtent],
*color,
*keyword,
*units,
*value;
char
**tokens;
register ssize_t
i;
size_t
number_tokens;
SVGInfo
*svg_info;
(void) LogMagickEvent(CoderEvent,GetMagickModule()," ");
svg_info=(SVGInfo *) context;
tokens=SVGKeyValuePairs(context,':',';',style,&number_tokens);
if (tokens == (char **) NULL)
return;
for (i=0; i < (ssize_t) (number_tokens-1); i+=2)
{
keyword=(char *) tokens[i];
value=(char *) tokens[i+1];
if (LocaleCompare(keyword,"font-size") != 0)
continue;
svg_info->pointsize=GetUserSpaceCoordinateValue(svg_info,0,value);
(void) FormatLocaleFile(svg_info->file,"font-size %g\n",
svg_info->pointsize);
}
color=AcquireString("none");
units=AcquireString("userSpaceOnUse");
for (i=0; i < (ssize_t) (number_tokens-1); i+=2)
{
keyword=(char *) tokens[i];
value=(char *) tokens[i+1];
(void) LogMagickEvent(CoderEvent,GetMagickModule()," %s: %s",keyword,
value);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare((const char *) name,"background") == 0)
{
if (LocaleCompare((const char *) name,"svg") == 0)
(void) CopyMagickString(background,value,MagickPathExtent);
break;
}
break;
}
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"clip-path") == 0)
{
(void) FormatLocaleFile(svg_info->file,"clip-path \"%s\"\n",value);
break;
}
if (LocaleCompare(keyword,"clip-rule") == 0)
{
(void) FormatLocaleFile(svg_info->file,"clip-rule \"%s\"\n",value);
break;
}
if (LocaleCompare(keyword,"clipPathUnits") == 0)
{
(void) CloneString(&units,value);
(void) FormatLocaleFile(svg_info->file,"clip-units \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"color") == 0)
{
(void) CloneString(&color,value);
break;
}
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fill") == 0)
{
if (LocaleCompare(value,"currentColor") == 0)
{
(void) FormatLocaleFile(svg_info->file,"fill \"%s\"\n",color);
break;
}
if (LocaleCompare(value,"#000000ff") == 0)
(void) FormatLocaleFile(svg_info->file,"fill '#000000'\n");
else
(void) FormatLocaleFile(svg_info->file,"fill \"%s\"\n",value);
break;
}
if (LocaleCompare(keyword,"fillcolor") == 0)
{
(void) FormatLocaleFile(svg_info->file,"fill \"%s\"\n",value);
break;
}
if (LocaleCompare(keyword,"fill-rule") == 0)
{
(void) FormatLocaleFile(svg_info->file,"fill-rule \"%s\"\n",value);
break;
}
if (LocaleCompare(keyword,"fill-opacity") == 0)
{
(void) FormatLocaleFile(svg_info->file,"fill-opacity \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"font") == 0)
{
char
family[MagickPathExtent],
size[MagickPathExtent],
style[MagickPathExtent];
if (sscanf(value,"%2048s %2048s %2048s",style,size,family) != 3)
break;
if (GetUserSpaceCoordinateValue(svg_info,0,style) == 0)
(void) FormatLocaleFile(svg_info->file,"font-style \"%s\"\n",
style);
else
if (sscanf(value,"%2048s %2048s",size,family) != 2)
break;
(void) FormatLocaleFile(svg_info->file,"font-size \"%s\"\n",size);
(void) FormatLocaleFile(svg_info->file,"font-family \"%s\"\n",
family);
break;
}
if (LocaleCompare(keyword,"font-family") == 0)
{
(void) FormatLocaleFile(svg_info->file,"font-family \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"font-stretch") == 0)
{
(void) FormatLocaleFile(svg_info->file,"font-stretch \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"font-style") == 0)
{
(void) FormatLocaleFile(svg_info->file,"font-style \"%s\"\n",value);
break;
}
if (LocaleCompare(keyword,"font-size") == 0)
{
svg_info->pointsize=GetUserSpaceCoordinateValue(svg_info,0,value);
(void) FormatLocaleFile(svg_info->file,"font-size %g\n",
svg_info->pointsize);
break;
}
if (LocaleCompare(keyword,"font-weight") == 0)
{
(void) FormatLocaleFile(svg_info->file,"font-weight \"%s\"\n",
value);
break;
}
break;
}
case 'K':
case 'k':
{
if (LocaleCompare(keyword,"kerning") == 0)
{
(void) FormatLocaleFile(svg_info->file,"kerning \"%s\"\n",value);
break;
}
break;
}
case 'L':
case 'l':
{
if (LocaleCompare(keyword,"letter-spacing") == 0)
{
(void) FormatLocaleFile(svg_info->file,"letter-spacing \"%s\"\n",
value);
break;
}
break;
}
case 'M':
case 'm':
{
if (LocaleCompare(keyword,"mask") == 0)
{
(void) FormatLocaleFile(svg_info->file,"mask \"%s\"\n",value);
break;
}
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"offset") == 0)
{
(void) FormatLocaleFile(svg_info->file,"offset %g\n",
GetUserSpaceCoordinateValue(svg_info,1,value));
break;
}
if (LocaleCompare(keyword,"opacity") == 0)
{
(void) FormatLocaleFile(svg_info->file,"opacity \"%s\"\n",value);
break;
}
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"stop-color") == 0)
{
(void) CloneString(&svg_info->stop_color,value);
break;
}
if (LocaleCompare(keyword,"stroke") == 0)
{
if (LocaleCompare(value,"currentColor") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke \"%s\"\n",color);
break;
}
if (LocaleCompare(value,"#000000ff") == 0)
(void) FormatLocaleFile(svg_info->file,"fill '#000000'\n");
else
(void) FormatLocaleFile(svg_info->file,
"stroke \"%s\"\n",value);
break;
}
if (LocaleCompare(keyword,"stroke-antialiasing") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke-antialias %d\n",
LocaleCompare(value,"true") == 0);
break;
}
if (LocaleCompare(keyword,"stroke-dasharray") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke-dasharray %s\n",
value);
break;
}
if (LocaleCompare(keyword,"stroke-dashoffset") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke-dashoffset %g\n",
GetUserSpaceCoordinateValue(svg_info,1,value));
break;
}
if (LocaleCompare(keyword,"stroke-linecap") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke-linecap \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"stroke-linejoin") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke-linejoin \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"stroke-miterlimit") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke-miterlimit \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"stroke-opacity") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke-opacity \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"stroke-width") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke-width %g\n",
GetUserSpaceCoordinateValue(svg_info,1,value));
break;
}
break;
}
case 't':
case 'T':
{
if (LocaleCompare(keyword,"text-align") == 0)
{
(void) FormatLocaleFile(svg_info->file,"text-align \"%s\"\n",value);
break;
}
if (LocaleCompare(keyword,"text-anchor") == 0)
{
(void) FormatLocaleFile(svg_info->file,"text-anchor \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"text-decoration") == 0)
{
if (LocaleCompare(value,"underline") == 0)
(void) FormatLocaleFile(svg_info->file,"decorate underline\n");
if (LocaleCompare(value,"line-through") == 0)
(void) FormatLocaleFile(svg_info->file,"decorate line-through\n");
if (LocaleCompare(value,"overline") == 0)
(void) FormatLocaleFile(svg_info->file,"decorate overline\n");
break;
}
if (LocaleCompare(keyword,"text-antialiasing") == 0)
{
(void) FormatLocaleFile(svg_info->file,"text-antialias %d\n",
LocaleCompare(value,"true") == 0);
break;
}
break;
}
default:
break;
}
}
if (units != (char *) NULL)
units=DestroyString(units);
if (color != (char *) NULL)
color=DestroyString(color);
for (i=0; tokens[i] != (char *) NULL; i++)
tokens[i]=DestroyString(tokens[i]);
tokens=(char **) RelinquishMagickMemory(tokens);
}
static void SVGUnparsedEntityDeclaration(void *context,const xmlChar *name,
const xmlChar *public_id,const xmlChar *system_id,const xmlChar *notation)
{
SVGInfo
*svg_info;
/*
What to do when an unparsed entity declaration is parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.unparsedEntityDecl(%s, %s, %s, %s)",name,
public_id != (xmlChar *) NULL ? (const char *) public_id : "none",
system_id != (xmlChar *) NULL ? (const char *) system_id : "none",notation);
svg_info=(SVGInfo *) context;
(void) xmlAddDocEntity(svg_info->document,name,
XML_EXTERNAL_GENERAL_UNPARSED_ENTITY,public_id,system_id,notation);
}
static void SVGSetDocumentLocator(void *context,xmlSAXLocatorPtr location)
{
SVGInfo
*svg_info;
/*
Receive the document locator at startup, actually xmlDefaultSAXLocator.
*/
(void) location;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.setDocumentLocator()");
svg_info=(SVGInfo *) context;
(void) svg_info;
}
static void SVGStartDocument(void *context)
{
SVGInfo
*svg_info;
xmlParserCtxtPtr
parser;
/*
Called when the document start being processed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.startDocument()");
svg_info=(SVGInfo *) context;
parser=svg_info->parser;
svg_info->document=xmlNewDoc(parser->version);
if (svg_info->document == (xmlDocPtr) NULL)
return;
if (parser->encoding == NULL)
svg_info->document->encoding=(const xmlChar *) NULL;
else
svg_info->document->encoding=xmlStrdup(parser->encoding);
svg_info->document->standalone=parser->standalone;
}
static void SVGEndDocument(void *context)
{
SVGInfo
*svg_info;
/*
Called when the document end has been detected.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.endDocument()");
svg_info=(SVGInfo *) context;
if (svg_info->offset != (char *) NULL)
svg_info->offset=DestroyString(svg_info->offset);
if (svg_info->stop_color != (char *) NULL)
svg_info->stop_color=DestroyString(svg_info->stop_color);
if (svg_info->scale != (double *) NULL)
svg_info->scale=(double *) RelinquishMagickMemory(svg_info->scale);
if (svg_info->text != (char *) NULL)
svg_info->text=DestroyString(svg_info->text);
if (svg_info->vertices != (char *) NULL)
svg_info->vertices=DestroyString(svg_info->vertices);
if (svg_info->url != (char *) NULL)
svg_info->url=DestroyString(svg_info->url);
#if defined(MAGICKCORE_XML_DELEGATE)
if (svg_info->document != (xmlDocPtr) NULL)
{
xmlFreeDoc(svg_info->document);
svg_info->document=(xmlDocPtr) NULL;
}
#endif
}
static void SVGStartElement(void *context,const xmlChar *name,
const xmlChar **attributes)
{
#define PushGraphicContext(id) \
{ \
if (*id == '\0') \
(void) FormatLocaleFile(svg_info->file,"push graphic-context\n"); \
else \
(void) FormatLocaleFile(svg_info->file,"push graphic-context \"%s\"\n", \
id); \
}
char
*color,
background[MagickPathExtent],
id[MagickPathExtent],
*next_token,
token[MagickPathExtent],
**tokens,
*units;
const char
*keyword,
*p,
*value;
register ssize_t
i,
j;
size_t
number_tokens;
SVGInfo
*svg_info;
/*
Called when an opening tag has been processed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.startElement(%s",
name);
svg_info=(SVGInfo *) context;
svg_info->n++;
svg_info->scale=(double *) ResizeQuantumMemory(svg_info->scale,
svg_info->n+1UL,sizeof(*svg_info->scale));
if (svg_info->scale == (double *) NULL)
{
(void) ThrowMagickException(svg_info->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",name);
return;
}
svg_info->scale[svg_info->n]=svg_info->scale[svg_info->n-1];
color=AcquireString("none");
units=AcquireString("userSpaceOnUse");
*id='\0';
*token='\0';
*background='\0';
value=(const char *) NULL;
if ((LocaleCompare((char *) name,"image") == 0) ||
(LocaleCompare((char *) name,"pattern") == 0) ||
(LocaleCompare((char *) name,"rect") == 0) ||
(LocaleCompare((char *) name,"text") == 0) ||
(LocaleCompare((char *) name,"use") == 0))
{
svg_info->bounds.x=0.0;
svg_info->bounds.y=0.0;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i+=2)
{
keyword=(const char *) attributes[i];
value=(const char *) attributes[i+1];
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"cx") == 0)
{
svg_info->element.cx=
GetUserSpaceCoordinateValue(svg_info,1,value);
break;
}
if (LocaleCompare(keyword,"cy") == 0)
{
svg_info->element.cy=
GetUserSpaceCoordinateValue(svg_info,-1,value);
break;
}
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fx") == 0)
{
svg_info->element.major=
GetUserSpaceCoordinateValue(svg_info,1,value);
break;
}
if (LocaleCompare(keyword,"fy") == 0)
{
svg_info->element.minor=
GetUserSpaceCoordinateValue(svg_info,-1,value);
break;
}
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
svg_info->bounds.height=
GetUserSpaceCoordinateValue(svg_info,-1,value);
break;
}
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"id") == 0)
{
(void) CopyMagickString(id,value,MagickPathExtent);
break;
}
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"r") == 0)
{
svg_info->element.angle=
GetUserSpaceCoordinateValue(svg_info,0,value);
break;
}
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
svg_info->bounds.width=
GetUserSpaceCoordinateValue(svg_info,1,value);
break;
}
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
svg_info->bounds.x=GetUserSpaceCoordinateValue(svg_info,1,value);
break;
}
if (LocaleCompare(keyword,"x1") == 0)
{
svg_info->segment.x1=GetUserSpaceCoordinateValue(svg_info,1,
value);
break;
}
if (LocaleCompare(keyword,"x2") == 0)
{
svg_info->segment.x2=GetUserSpaceCoordinateValue(svg_info,1,
value);
break;
}
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
svg_info->bounds.y=GetUserSpaceCoordinateValue(svg_info,-1,value);
break;
}
if (LocaleCompare(keyword,"y1") == 0)
{
svg_info->segment.y1=GetUserSpaceCoordinateValue(svg_info,-1,
value);
break;
}
if (LocaleCompare(keyword,"y2") == 0)
{
svg_info->segment.y2=GetUserSpaceCoordinateValue(svg_info,-1,
value);
break;
}
break;
}
default:
break;
}
}
if (strchr((char *) name,':') != (char *) NULL)
{
/*
Skip over namespace.
*/
for ( ; *name != ':'; name++) ;
name++;
}
switch (*name)
{
case 'C':
case 'c':
{
if (LocaleCompare((const char *) name,"circle") == 0)
{
PushGraphicContext(id);
break;
}
if (LocaleCompare((const char *) name,"clipPath") == 0)
{
(void) FormatLocaleFile(svg_info->file,"push clip-path \"%s\"\n",id);
break;
}
break;
}
case 'D':
case 'd':
{
if (LocaleCompare((const char *) name,"defs") == 0)
{
(void) FormatLocaleFile(svg_info->file,"push defs\n");
break;
}
break;
}
case 'E':
case 'e':
{
if (LocaleCompare((const char *) name,"ellipse") == 0)
{
PushGraphicContext(id);
break;
}
break;
}
case 'F':
case 'f':
{
if (LocaleCompare((const char *) name,"foreignObject") == 0)
{
PushGraphicContext(id);
break;
}
break;
}
case 'G':
case 'g':
{
if (LocaleCompare((const char *) name,"g") == 0)
{
PushGraphicContext(id);
break;
}
break;
}
case 'I':
case 'i':
{
if (LocaleCompare((const char *) name,"image") == 0)
{
PushGraphicContext(id);
break;
}
break;
}
case 'L':
case 'l':
{
if (LocaleCompare((const char *) name,"line") == 0)
{
PushGraphicContext(id);
break;
}
if (LocaleCompare((const char *) name,"linearGradient") == 0)
{
(void) FormatLocaleFile(svg_info->file,
"push gradient \"%s\" linear %g,%g %g,%g\n",id,
svg_info->segment.x1,svg_info->segment.y1,svg_info->segment.x2,
svg_info->segment.y2);
break;
}
break;
}
case 'M':
case 'm':
{
if (LocaleCompare((const char *) name,"mask") == 0)
{
(void) FormatLocaleFile(svg_info->file,"push mask \"%s\"\n",id);
break;
}
break;
}
case 'P':
case 'p':
{
if (LocaleCompare((const char *) name,"path") == 0)
{
PushGraphicContext(id);
break;
}
if (LocaleCompare((const char *) name,"pattern") == 0)
{
(void) FormatLocaleFile(svg_info->file,
"push pattern \"%s\" %g,%g %g,%g\n",id,
svg_info->bounds.x,svg_info->bounds.y,svg_info->bounds.width,
svg_info->bounds.height);
break;
}
if (LocaleCompare((const char *) name,"polygon") == 0)
{
PushGraphicContext(id);
break;
}
if (LocaleCompare((const char *) name,"polyline") == 0)
{
PushGraphicContext(id);
break;
}
break;
}
case 'R':
case 'r':
{
if (LocaleCompare((const char *) name,"radialGradient") == 0)
{
(void) FormatLocaleFile(svg_info->file,
"push gradient \"%s\" radial %g,%g %g,%g %g\n",
id,svg_info->element.cx,svg_info->element.cy,
svg_info->element.major,svg_info->element.minor,
svg_info->element.angle);
break;
}
if (LocaleCompare((const char *) name,"rect") == 0)
{
PushGraphicContext(id);
break;
}
break;
}
case 'S':
case 's':
{
if (LocaleCompare((char *) name,"style") == 0)
break;
if (LocaleCompare((const char *) name,"svg") == 0)
{
svg_info->svgDepth++;
PushGraphicContext(id);
(void) FormatLocaleFile(svg_info->file,"compliance \"SVG\"\n");
(void) FormatLocaleFile(svg_info->file,"fill \"black\"\n");
(void) FormatLocaleFile(svg_info->file,"fill-opacity 1\n");
(void) FormatLocaleFile(svg_info->file,"stroke \"none\"\n");
(void) FormatLocaleFile(svg_info->file,"stroke-width 1\n");
(void) FormatLocaleFile(svg_info->file,"stroke-opacity 1\n");
(void) FormatLocaleFile(svg_info->file,"fill-rule nonzero\n");
break;
}
if (LocaleCompare((const char *) name,"symbol") == 0)
{
(void) FormatLocaleFile(svg_info->file,"push symbol\n");
break;
}
break;
}
case 'T':
case 't':
{
if (LocaleCompare((const char *) name,"text") == 0)
{
PushGraphicContext(id);
(void) FormatLocaleFile(svg_info->file,"class \"text\"\n");
svg_info->text_offset.x=svg_info->bounds.x;
svg_info->text_offset.y=svg_info->bounds.y;
svg_info->bounds.x=0.0;
svg_info->bounds.y=0.0;
svg_info->bounds.width=0.0;
svg_info->bounds.height=0.0;
break;
}
if (LocaleCompare((const char *) name,"tspan") == 0)
{
if (*svg_info->text != '\0')
{
char
*text;
text=EscapeString(svg_info->text,'\"');
(void) FormatLocaleFile(svg_info->file,"text %g,%g \"%s\"\n",
svg_info->text_offset.x,svg_info->text_offset.y,text);
text=DestroyString(text);
*svg_info->text='\0';
}
PushGraphicContext(id);
break;
}
break;
}
case 'U':
case 'u':
{
if (LocaleCompare((char *) name,"use") == 0)
{
PushGraphicContext(id);
break;
}
break;
}
default:
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i+=2)
{
keyword=(const char *) attributes[i];
value=(const char *) attributes[i+1];
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %s = %s",keyword,value);
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"angle") == 0)
{
(void) FormatLocaleFile(svg_info->file,"angle %g\n",
GetUserSpaceCoordinateValue(svg_info,0,value));
break;
}
break;
}
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"class") == 0)
{
const char
*p;
for (p=value; ; )
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token != '\0')
{
(void) FormatLocaleFile(svg_info->file,"class \"%s\"\n",
value);
break;
}
}
break;
}
if (LocaleCompare(keyword,"clip-path") == 0)
{
(void) FormatLocaleFile(svg_info->file,"clip-path \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"clip-rule") == 0)
{
(void) FormatLocaleFile(svg_info->file,"clip-rule \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"clipPathUnits") == 0)
{
(void) CloneString(&units,value);
(void) FormatLocaleFile(svg_info->file,"clip-units \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"color") == 0)
{
(void) CloneString(&color,value);
break;
}
if (LocaleCompare(keyword,"cx") == 0)
{
svg_info->element.cx=
GetUserSpaceCoordinateValue(svg_info,1,value);
break;
}
if (LocaleCompare(keyword,"cy") == 0)
{
svg_info->element.cy=
GetUserSpaceCoordinateValue(svg_info,-1,value);
break;
}
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"d") == 0)
{
(void) CloneString(&svg_info->vertices,value);
break;
}
if (LocaleCompare(keyword,"dx") == 0)
{
double
dx;
dx=GetUserSpaceCoordinateValue(svg_info,1,value);
svg_info->bounds.x+=dx;
svg_info->text_offset.x+=dx;
if (LocaleCompare((char *) name,"text") == 0)
(void) FormatLocaleFile(svg_info->file,"translate %g,0.0\n",dx);
break;
}
if (LocaleCompare(keyword,"dy") == 0)
{
double
dy;
dy=GetUserSpaceCoordinateValue(svg_info,-1,value);
svg_info->bounds.y+=dy;
svg_info->text_offset.y+=dy;
if (LocaleCompare((char *) name,"text") == 0)
(void) FormatLocaleFile(svg_info->file,"translate 0.0,%g\n",dy);
break;
}
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fill") == 0)
{
if (LocaleCompare(value,"currentColor") == 0)
{
(void) FormatLocaleFile(svg_info->file,"fill \"%s\"\n",color);
break;
}
(void) FormatLocaleFile(svg_info->file,"fill \"%s\"\n",value);
break;
}
if (LocaleCompare(keyword,"fillcolor") == 0)
{
(void) FormatLocaleFile(svg_info->file,"fill \"%s\"\n",value);
break;
}
if (LocaleCompare(keyword,"fill-rule") == 0)
{
(void) FormatLocaleFile(svg_info->file,"fill-rule \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"fill-opacity") == 0)
{
(void) FormatLocaleFile(svg_info->file,"fill-opacity \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"font-family") == 0)
{
(void) FormatLocaleFile(svg_info->file,"font-family \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"font-stretch") == 0)
{
(void) FormatLocaleFile(svg_info->file,"font-stretch \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"font-style") == 0)
{
(void) FormatLocaleFile(svg_info->file,"font-style \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"font-size") == 0)
{
if (LocaleCompare(value,"xx-small") == 0)
svg_info->pointsize=6.144;
else if (LocaleCompare(value,"x-small") == 0)
svg_info->pointsize=7.68;
else if (LocaleCompare(value,"small") == 0)
svg_info->pointsize=9.6;
else if (LocaleCompare(value,"medium") == 0)
svg_info->pointsize=12.0;
else if (LocaleCompare(value,"large") == 0)
svg_info->pointsize=14.4;
else if (LocaleCompare(value,"x-large") == 0)
svg_info->pointsize=17.28;
else if (LocaleCompare(value,"xx-large") == 0)
svg_info->pointsize=20.736;
else
svg_info->pointsize=GetUserSpaceCoordinateValue(svg_info,0,
value);
(void) FormatLocaleFile(svg_info->file,"font-size %g\n",
svg_info->pointsize);
break;
}
if (LocaleCompare(keyword,"font-weight") == 0)
{
(void) FormatLocaleFile(svg_info->file,"font-weight \"%s\"\n",
value);
break;
}
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gradientTransform") == 0)
{
AffineMatrix
affine,
current,
transform;
GetAffineMatrix(&transform);
(void) LogMagickEvent(CoderEvent,GetMagickModule()," ");
tokens=SVGKeyValuePairs(context,'(',')',value,&number_tokens);
if (tokens == (char **) NULL)
break;
for (j=0; j < (ssize_t) (number_tokens-1); j+=2)
{
keyword=(char *) tokens[j];
if (keyword == (char *) NULL)
continue;
value=(char *) tokens[j+1];
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %s: %s",keyword,value);
current=transform;
GetAffineMatrix(&affine);
switch (*keyword)
{
case 'M':
case 'm':
{
if (LocaleCompare(keyword,"matrix") == 0)
{
p=(const char *) value;
(void) GetNextToken(p,&p,MagickPathExtent,token);
affine.sx=StringToDouble(value,(char **) NULL);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
affine.rx=StringToDouble(token,&next_token);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
affine.ry=StringToDouble(token,&next_token);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
affine.sy=StringToDouble(token,&next_token);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
affine.tx=StringToDouble(token,&next_token);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
affine.ty=StringToDouble(token,&next_token);
break;
}
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"rotate") == 0)
{
double
angle;
angle=GetUserSpaceCoordinateValue(svg_info,0,value);
affine.sx=cos(DegreesToRadians(fmod(angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod(angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"scale") == 0)
{
for (p=(const char *) value; *p != '\0'; p++)
if ((isspace((int) ((unsigned char) *p)) != 0) ||
(*p == ','))
break;
affine.sx=GetUserSpaceCoordinateValue(svg_info,1,value);
affine.sy=affine.sx;
if (*p != '\0')
affine.sy=
GetUserSpaceCoordinateValue(svg_info,-1,p+1);
svg_info->scale[svg_info->n]=ExpandAffine(&affine);
break;
}
if (LocaleCompare(keyword,"skewX") == 0)
{
affine.sx=svg_info->affine.sx;
affine.ry=tan(DegreesToRadians(fmod(
GetUserSpaceCoordinateValue(svg_info,1,value),
360.0)));
affine.sy=svg_info->affine.sy;
break;
}
if (LocaleCompare(keyword,"skewY") == 0)
{
affine.sx=svg_info->affine.sx;
affine.rx=tan(DegreesToRadians(fmod(
GetUserSpaceCoordinateValue(svg_info,-1,value),
360.0)));
affine.sy=svg_info->affine.sy;
break;
}
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"translate") == 0)
{
for (p=(const char *) value; *p != '\0'; p++)
if ((isspace((int) ((unsigned char) *p)) != 0) ||
(*p == ','))
break;
affine.tx=GetUserSpaceCoordinateValue(svg_info,1,value);
affine.ty=affine.tx;
if (*p != '\0')
affine.ty=
GetUserSpaceCoordinateValue(svg_info,-1,p+1);
break;
}
break;
}
default:
break;
}
transform.sx=affine.sx*current.sx+affine.ry*current.rx;
transform.rx=affine.rx*current.sx+affine.sy*current.rx;
transform.ry=affine.sx*current.ry+affine.ry*current.sy;
transform.sy=affine.rx*current.ry+affine.sy*current.sy;
transform.tx=affine.tx*current.sx+affine.ty*current.ry+
current.tx;
transform.ty=affine.tx*current.rx+affine.ty*current.sy+
current.ty;
}
(void) FormatLocaleFile(svg_info->file,
"affine %g %g %g %g %g %g\n",transform.sx,
transform.rx,transform.ry,transform.sy,transform.tx,
transform.ty);
for (j=0; tokens[j] != (char *) NULL; j++)
tokens[j]=DestroyString(tokens[j]);
tokens=(char **) RelinquishMagickMemory(tokens);
break;
}
if (LocaleCompare(keyword,"gradientUnits") == 0)
{
(void) CloneString(&units,value);
(void) FormatLocaleFile(svg_info->file,"gradient-units \"%s\"\n",
value);
break;
}
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
svg_info->bounds.height=
GetUserSpaceCoordinateValue(svg_info,-1,value);
break;
}
if (LocaleCompare(keyword,"href") == 0)
{
(void) CloneString(&svg_info->url,value);
break;
}
break;
}
case 'K':
case 'k':
{
if (LocaleCompare(keyword,"kerning") == 0)
{
(void) FormatLocaleFile(svg_info->file,"kerning \"%s\"\n",
value);
break;
}
break;
}
case 'L':
case 'l':
{
if (LocaleCompare(keyword,"letter-spacing") == 0)
{
(void) FormatLocaleFile(svg_info->file,"letter-spacing \"%s\"\n",
value);
break;
}
break;
}
case 'M':
case 'm':
{
if (LocaleCompare(keyword,"major") == 0)
{
svg_info->element.major=
GetUserSpaceCoordinateValue(svg_info,1,value);
break;
}
if (LocaleCompare(keyword,"mask") == 0)
{
(void) FormatLocaleFile(svg_info->file,"mask \"%s\"\n",value);
break;
}
if (LocaleCompare(keyword,"minor") == 0)
{
svg_info->element.minor=
GetUserSpaceCoordinateValue(svg_info,-1,value);
break;
}
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"offset") == 0)
{
(void) CloneString(&svg_info->offset,value);
break;
}
if (LocaleCompare(keyword,"opacity") == 0)
{
(void) FormatLocaleFile(svg_info->file,"opacity \"%s\"\n",value);
break;
}
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"path") == 0)
{
(void) CloneString(&svg_info->url,value);
break;
}
if (LocaleCompare(keyword,"points") == 0)
{
(void) CloneString(&svg_info->vertices,value);
break;
}
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"r") == 0)
{
svg_info->element.major=
GetUserSpaceCoordinateValue(svg_info,1,value);
svg_info->element.minor=
GetUserSpaceCoordinateValue(svg_info,-1,value);
break;
}
if (LocaleCompare(keyword,"rotate") == 0)
{
double
angle;
angle=GetUserSpaceCoordinateValue(svg_info,0,value);
(void) FormatLocaleFile(svg_info->file,"translate %g,%g\n",
svg_info->bounds.x,svg_info->bounds.y);
svg_info->bounds.x=0;
svg_info->bounds.y=0;
(void) FormatLocaleFile(svg_info->file,"rotate %g\n",angle);
break;
}
if (LocaleCompare(keyword,"rx") == 0)
{
if (LocaleCompare((const char *) name,"ellipse") == 0)
svg_info->element.major=
GetUserSpaceCoordinateValue(svg_info,1,value);
else
svg_info->radius.x=
GetUserSpaceCoordinateValue(svg_info,1,value);
break;
}
if (LocaleCompare(keyword,"ry") == 0)
{
if (LocaleCompare((const char *) name,"ellipse") == 0)
svg_info->element.minor=
GetUserSpaceCoordinateValue(svg_info,-1,value);
else
svg_info->radius.y=
GetUserSpaceCoordinateValue(svg_info,-1,value);
break;
}
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"stop-color") == 0)
{
(void) CloneString(&svg_info->stop_color,value);
break;
}
if (LocaleCompare(keyword,"stroke") == 0)
{
if (LocaleCompare(value,"currentColor") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke \"%s\"\n",
color);
break;
}
(void) FormatLocaleFile(svg_info->file,"stroke \"%s\"\n",value);
break;
}
if (LocaleCompare(keyword,"stroke-antialiasing") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke-antialias %d\n",
LocaleCompare(value,"true") == 0);
break;
}
if (LocaleCompare(keyword,"stroke-dasharray") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke-dasharray %s\n",
value);
break;
}
if (LocaleCompare(keyword,"stroke-dashoffset") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke-dashoffset %g\n",
GetUserSpaceCoordinateValue(svg_info,1,value));
break;
}
if (LocaleCompare(keyword,"stroke-linecap") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke-linecap \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"stroke-linejoin") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke-linejoin \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"stroke-miterlimit") == 0)
{
(void) FormatLocaleFile(svg_info->file,
"stroke-miterlimit \"%s\"\n",value);
break;
}
if (LocaleCompare(keyword,"stroke-opacity") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke-opacity \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"stroke-width") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stroke-width %g\n",
GetUserSpaceCoordinateValue(svg_info,1,value));
break;
}
if (LocaleCompare(keyword,"style") == 0)
{
SVGProcessStyleElement(context,name,value);
break;
}
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"text-align") == 0)
{
(void) FormatLocaleFile(svg_info->file,"text-align \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"text-anchor") == 0)
{
(void) FormatLocaleFile(svg_info->file,"text-anchor \"%s\"\n",
value);
break;
}
if (LocaleCompare(keyword,"text-decoration") == 0)
{
if (LocaleCompare(value,"underline") == 0)
(void) FormatLocaleFile(svg_info->file,"decorate underline\n");
if (LocaleCompare(value,"line-through") == 0)
(void) FormatLocaleFile(svg_info->file,
"decorate line-through\n");
if (LocaleCompare(value,"overline") == 0)
(void) FormatLocaleFile(svg_info->file,"decorate overline\n");
break;
}
if (LocaleCompare(keyword,"text-antialiasing") == 0)
{
(void) FormatLocaleFile(svg_info->file,"text-antialias %d\n",
LocaleCompare(value,"true") == 0);
break;
}
if (LocaleCompare(keyword,"transform") == 0)
{
AffineMatrix
affine,
current,
transform;
GetAffineMatrix(&transform);
(void) LogMagickEvent(CoderEvent,GetMagickModule()," ");
tokens=SVGKeyValuePairs(context,'(',')',value,&number_tokens);
if (tokens == (char **) NULL)
break;
for (j=0; j < (ssize_t) (number_tokens-1); j+=2)
{
keyword=(char *) tokens[j];
value=(char *) tokens[j+1];
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %s: %s",keyword,value);
current=transform;
GetAffineMatrix(&affine);
switch (*keyword)
{
case 'M':
case 'm':
{
if (LocaleCompare(keyword,"matrix") == 0)
{
p=(const char *) value;
(void) GetNextToken(p,&p,MagickPathExtent,token);
affine.sx=StringToDouble(value,(char **) NULL);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
affine.rx=StringToDouble(token,&next_token);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
affine.ry=StringToDouble(token,&next_token);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
affine.sy=StringToDouble(token,&next_token);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
affine.tx=StringToDouble(token,&next_token);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
affine.ty=StringToDouble(token,&next_token);
break;
}
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"rotate") == 0)
{
double
angle,
x,
y;
p=(const char *) value;
(void) GetNextToken(p,&p,MagickPathExtent,token);
angle=StringToDouble(value,(char **) NULL);
affine.sx=cos(DegreesToRadians(fmod(angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod(angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod(angle,360.0)));
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
affine.tx=svg_info->bounds.x+x*
cos(DegreesToRadians(fmod(angle,360.0)))+y*
sin(DegreesToRadians(fmod(angle,360.0)));
affine.ty=svg_info->bounds.y-x*
sin(DegreesToRadians(fmod(angle,360.0)))+y*
cos(DegreesToRadians(fmod(angle,360.0)));
affine.tx-=x;
affine.ty-=y;
break;
}
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"scale") == 0)
{
for (p=(const char *) value; *p != '\0'; p++)
if ((isspace((int) ((unsigned char) *p)) != 0) ||
(*p == ','))
break;
affine.sx=GetUserSpaceCoordinateValue(svg_info,1,value);
affine.sy=affine.sx;
if (*p != '\0')
affine.sy=GetUserSpaceCoordinateValue(svg_info,-1,
p+1);
svg_info->scale[svg_info->n]=ExpandAffine(&affine);
break;
}
if (LocaleCompare(keyword,"skewX") == 0)
{
affine.sx=svg_info->affine.sx;
affine.ry=tan(DegreesToRadians(fmod(
GetUserSpaceCoordinateValue(svg_info,1,value),
360.0)));
affine.sy=svg_info->affine.sy;
break;
}
if (LocaleCompare(keyword,"skewY") == 0)
{
affine.sx=svg_info->affine.sx;
affine.rx=tan(DegreesToRadians(fmod(
GetUserSpaceCoordinateValue(svg_info,-1,value),
360.0)));
affine.sy=svg_info->affine.sy;
break;
}
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"translate") == 0)
{
for (p=(const char *) value; *p != '\0'; p++)
if ((isspace((int) ((unsigned char) *p)) != 0) ||
(*p == ','))
break;
affine.tx=GetUserSpaceCoordinateValue(svg_info,1,value);
affine.ty=0;
if (*p != '\0')
affine.ty=GetUserSpaceCoordinateValue(svg_info,-1,
p+1);
break;
}
break;
}
default:
break;
}
transform.sx=affine.sx*current.sx+affine.ry*current.rx;
transform.rx=affine.rx*current.sx+affine.sy*current.rx;
transform.ry=affine.sx*current.ry+affine.ry*current.sy;
transform.sy=affine.rx*current.ry+affine.sy*current.sy;
transform.tx=affine.tx*current.sx+affine.ty*current.ry+
current.tx;
transform.ty=affine.tx*current.rx+affine.ty*current.sy+
current.ty;
}
(void) FormatLocaleFile(svg_info->file,
"affine %g %g %g %g %g %g\n",transform.sx,transform.rx,
transform.ry,transform.sy,transform.tx,transform.ty);
for (j=0; tokens[j] != (char *) NULL; j++)
tokens[j]=DestroyString(tokens[j]);
tokens=(char **) RelinquishMagickMemory(tokens);
break;
}
break;
}
case 'V':
case 'v':
{
if (LocaleCompare(keyword,"verts") == 0)
{
(void) CloneString(&svg_info->vertices,value);
break;
}
if (LocaleCompare(keyword,"viewBox") == 0)
{
p=(const char *) value;
(void) GetNextToken(p,&p,MagickPathExtent,token);
svg_info->view_box.x=StringToDouble(token,&next_token);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
svg_info->view_box.y=StringToDouble(token,&next_token);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
svg_info->view_box.width=StringToDouble(token,
(char **) NULL);
if (svg_info->bounds.width == 0)
svg_info->bounds.width=svg_info->view_box.width;
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
svg_info->view_box.height=StringToDouble(token,
(char **) NULL);
if (svg_info->bounds.height == 0)
svg_info->bounds.height=svg_info->view_box.height;
break;
}
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
svg_info->bounds.width=
GetUserSpaceCoordinateValue(svg_info,1,value);
break;
}
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
svg_info->bounds.x=GetUserSpaceCoordinateValue(svg_info,1,value);
break;
}
if (LocaleCompare(keyword,"xlink:href") == 0)
{
(void) CloneString(&svg_info->url,value);
break;
}
if (LocaleCompare(keyword,"x1") == 0)
{
svg_info->segment.x1=
GetUserSpaceCoordinateValue(svg_info,1,value);
break;
}
if (LocaleCompare(keyword,"x2") == 0)
{
svg_info->segment.x2=
GetUserSpaceCoordinateValue(svg_info,1,value);
break;
}
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
svg_info->bounds.y=GetUserSpaceCoordinateValue(svg_info,-1,value);
break;
}
if (LocaleCompare(keyword,"y1") == 0)
{
svg_info->segment.y1=
GetUserSpaceCoordinateValue(svg_info,-1,value);
break;
}
if (LocaleCompare(keyword,"y2") == 0)
{
svg_info->segment.y2=
GetUserSpaceCoordinateValue(svg_info,-1,value);
break;
}
break;
}
default:
break;
}
}
if (LocaleCompare((const char *) name,"svg") == 0)
{
if (svg_info->document->encoding != (const xmlChar *) NULL)
(void) FormatLocaleFile(svg_info->file,"encoding \"%s\"\n",
(const char *) svg_info->document->encoding);
if (attributes != (const xmlChar **) NULL)
{
double
sx,
sy,
tx,
ty;
if ((svg_info->view_box.width == 0.0) ||
(svg_info->view_box.height == 0.0))
svg_info->view_box=svg_info->bounds;
svg_info->width=0;
if (svg_info->bounds.width > 0.0)
svg_info->width=(size_t) floor(svg_info->bounds.width+0.5);
svg_info->height=0;
if (svg_info->bounds.height > 0.0)
svg_info->height=(size_t) floor(svg_info->bounds.height+0.5);
(void) FormatLocaleFile(svg_info->file,"viewbox 0 0 %.20g %.20g\n",
(double) svg_info->width,(double) svg_info->height);
sx=PerceptibleReciprocal(svg_info->view_box.width)*svg_info->width;
sy=PerceptibleReciprocal(svg_info->view_box.height)*svg_info->height;
tx=svg_info->view_box.x != 0.0 ? (double) -sx*svg_info->view_box.x :
0.0;
ty=svg_info->view_box.y != 0.0 ? (double) -sy*svg_info->view_box.y :
0.0;
(void) FormatLocaleFile(svg_info->file,"affine %g 0 0 %g %g %g\n",
sx,sy,tx,ty);
if ((svg_info->svgDepth == 1) && (*background != '\0'))
{
PushGraphicContext(id);
(void) FormatLocaleFile(svg_info->file,"fill %s\n",background);
(void) FormatLocaleFile(svg_info->file,
"rectangle 0,0 %g,%g\n",svg_info->view_box.width,
svg_info->view_box.height);
(void) FormatLocaleFile(svg_info->file,"pop graphic-context\n");
}
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule()," )");
if (units != (char *) NULL)
units=DestroyString(units);
if (color != (char *) NULL)
color=DestroyString(color);
}
static void SVGEndElement(void *context,const xmlChar *name)
{
SVGInfo
*svg_info;
/*
Called when the end of an element has been detected.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.endElement(%s)",name);
svg_info=(SVGInfo *) context;
if (strchr((char *) name,':') != (char *) NULL)
{
/*
Skip over namespace.
*/
for ( ; *name != ':'; name++) ;
name++;
}
switch (*name)
{
case 'C':
case 'c':
{
if (LocaleCompare((const char *) name,"circle") == 0)
{
(void) FormatLocaleFile(svg_info->file,"class \"circle\"\n");
(void) FormatLocaleFile(svg_info->file,"circle %g,%g %g,%g\n",
svg_info->element.cx,svg_info->element.cy,svg_info->element.cx,
svg_info->element.cy+svg_info->element.minor);
(void) FormatLocaleFile(svg_info->file,"pop graphic-context\n");
break;
}
if (LocaleCompare((const char *) name,"clipPath") == 0)
{
(void) FormatLocaleFile(svg_info->file,"pop clip-path\n");
break;
}
break;
}
case 'D':
case 'd':
{
if (LocaleCompare((const char *) name,"defs") == 0)
{
(void) FormatLocaleFile(svg_info->file,"pop defs\n");
break;
}
if (LocaleCompare((const char *) name,"desc") == 0)
{
register char
*p;
if (*svg_info->text == '\0')
break;
(void) fputc('#',svg_info->file);
for (p=svg_info->text; *p != '\0'; p++)
{
(void) fputc(*p,svg_info->file);
if (*p == '\n')
(void) fputc('#',svg_info->file);
}
(void) fputc('\n',svg_info->file);
*svg_info->text='\0';
break;
}
break;
}
case 'E':
case 'e':
{
if (LocaleCompare((const char *) name,"ellipse") == 0)
{
double
angle;
(void) FormatLocaleFile(svg_info->file,"class \"ellipse\"\n");
angle=svg_info->element.angle;
(void) FormatLocaleFile(svg_info->file,"ellipse %g,%g %g,%g 0,360\n",
svg_info->element.cx,svg_info->element.cy,
angle == 0.0 ? svg_info->element.major : svg_info->element.minor,
angle == 0.0 ? svg_info->element.minor : svg_info->element.major);
(void) FormatLocaleFile(svg_info->file,"pop graphic-context\n");
break;
}
break;
}
case 'F':
case 'f':
{
if (LocaleCompare((const char *) name,"foreignObject") == 0)
{
(void) FormatLocaleFile(svg_info->file,"pop graphic-context\n");
break;
}
break;
}
case 'G':
case 'g':
{
if (LocaleCompare((const char *) name,"g") == 0)
{
(void) FormatLocaleFile(svg_info->file,"pop graphic-context\n");
break;
}
break;
}
case 'I':
case 'i':
{
if (LocaleCompare((const char *) name,"image") == 0)
{
(void) FormatLocaleFile(svg_info->file,
"image Over %g,%g %g,%g \"%s\"\n",svg_info->bounds.x,
svg_info->bounds.y,svg_info->bounds.width,svg_info->bounds.height,
svg_info->url);
(void) FormatLocaleFile(svg_info->file,"pop graphic-context\n");
break;
}
break;
}
case 'L':
case 'l':
{
if (LocaleCompare((const char *) name,"line") == 0)
{
(void) FormatLocaleFile(svg_info->file,"class \"line\"\n");
(void) FormatLocaleFile(svg_info->file,"line %g,%g %g,%g\n",
svg_info->segment.x1,svg_info->segment.y1,svg_info->segment.x2,
svg_info->segment.y2);
(void) FormatLocaleFile(svg_info->file,"pop graphic-context\n");
break;
}
if (LocaleCompare((const char *) name,"linearGradient") == 0)
{
(void) FormatLocaleFile(svg_info->file,"pop gradient\n");
break;
}
break;
}
case 'M':
case 'm':
{
if (LocaleCompare((const char *) name,"mask") == 0)
{
(void) FormatLocaleFile(svg_info->file,"pop mask\n");
break;
}
break;
}
case 'P':
case 'p':
{
if (LocaleCompare((const char *) name,"pattern") == 0)
{
(void) FormatLocaleFile(svg_info->file,"pop pattern\n");
break;
}
if (LocaleCompare((const char *) name,"path") == 0)
{
(void) FormatLocaleFile(svg_info->file,"class \"path\"\n");
(void) FormatLocaleFile(svg_info->file,"path \"%s\"\n",
svg_info->vertices);
(void) FormatLocaleFile(svg_info->file,"pop graphic-context\n");
break;
}
if (LocaleCompare((const char *) name,"polygon") == 0)
{
(void) FormatLocaleFile(svg_info->file,"class \"polygon\"\n");
(void) FormatLocaleFile(svg_info->file,"polygon %s\n",
svg_info->vertices);
(void) FormatLocaleFile(svg_info->file,"pop graphic-context\n");
break;
}
if (LocaleCompare((const char *) name,"polyline") == 0)
{
(void) FormatLocaleFile(svg_info->file,"class \"polyline\"\n");
(void) FormatLocaleFile(svg_info->file,"polyline %s\n",
svg_info->vertices);
(void) FormatLocaleFile(svg_info->file,"pop graphic-context\n");
break;
}
break;
}
case 'R':
case 'r':
{
if (LocaleCompare((const char *) name,"radialGradient") == 0)
{
(void) FormatLocaleFile(svg_info->file,"pop gradient\n");
break;
}
if (LocaleCompare((const char *) name,"rect") == 0)
{
if ((svg_info->radius.x == 0.0) && (svg_info->radius.y == 0.0))
{
(void) FormatLocaleFile(svg_info->file,"class \"rect\"\n");
if ((fabs(svg_info->bounds.width-1.0) < MagickEpsilon) &&
(fabs(svg_info->bounds.height-1.0) < MagickEpsilon))
(void) FormatLocaleFile(svg_info->file,"point %g,%g\n",
svg_info->bounds.x,svg_info->bounds.y);
else
(void) FormatLocaleFile(svg_info->file,
"rectangle %g,%g %g,%g\n",svg_info->bounds.x,
svg_info->bounds.y,svg_info->bounds.x+svg_info->bounds.width,
svg_info->bounds.y+svg_info->bounds.height);
(void) FormatLocaleFile(svg_info->file,"pop graphic-context\n");
break;
}
if (svg_info->radius.x == 0.0)
svg_info->radius.x=svg_info->radius.y;
if (svg_info->radius.y == 0.0)
svg_info->radius.y=svg_info->radius.x;
(void) FormatLocaleFile(svg_info->file,
"roundRectangle %g,%g %g,%g %g,%g\n",
svg_info->bounds.x,svg_info->bounds.y,svg_info->bounds.x+
svg_info->bounds.width,svg_info->bounds.y+svg_info->bounds.height,
svg_info->radius.x,svg_info->radius.y);
svg_info->radius.x=0.0;
svg_info->radius.y=0.0;
(void) FormatLocaleFile(svg_info->file,"pop graphic-context\n");
break;
}
break;
}
case 'S':
case 's':
{
if (LocaleCompare((const char *) name,"stop") == 0)
{
(void) FormatLocaleFile(svg_info->file,"stop-color \"%s\" %s\n",
svg_info->stop_color,svg_info->offset);
break;
}
if (LocaleCompare((char *) name,"style") == 0)
{
char
*keyword,
**tokens,
*value;
register ssize_t
j;
size_t
number_tokens;
/*
Find style definitions in svg_info->text.
*/
tokens=SVGKeyValuePairs(context,'{','}',svg_info->text,
&number_tokens);
if (tokens == (char **) NULL)
break;
for (j=0; j < (ssize_t) (number_tokens-1); j+=2)
{
keyword=(char *) tokens[j];
value=(char *) tokens[j+1];
(void) FormatLocaleFile(svg_info->file,"push class \"%s\"\n",
*keyword == '.' ? keyword+1 : keyword);
SVGProcessStyleElement(context,name,value);
(void) FormatLocaleFile(svg_info->file,"pop class\n");
}
for (j=0; tokens[j] != (char *) NULL; j++)
tokens[j]=DestroyString(tokens[j]);
tokens=(char **) RelinquishMagickMemory(tokens);
break;
}
if (LocaleCompare((const char *) name,"svg") == 0)
{
(void) FormatLocaleFile(svg_info->file,"pop graphic-context\n");
svg_info->svgDepth--;
break;
}
if (LocaleCompare((const char *) name,"symbol") == 0)
{
(void) FormatLocaleFile(svg_info->file,"pop symbol\n");
break;
}
break;
}
case 'T':
case 't':
{
if (LocaleCompare((const char *) name,"text") == 0)
{
if (*svg_info->text != '\0')
{
char
*text;
SVGStripString(MagickTrue,svg_info->text);
text=EscapeString(svg_info->text,'\"');
(void) FormatLocaleFile(svg_info->file,"text %g,%g \"%s\"\n",
svg_info->text_offset.x,svg_info->text_offset.y,text);
text=DestroyString(text);
*svg_info->text='\0';
}
(void) FormatLocaleFile(svg_info->file,"pop graphic-context\n");
break;
}
if (LocaleCompare((const char *) name,"tspan") == 0)
{
if (*svg_info->text != '\0')
{
char
*text;
(void) FormatLocaleFile(svg_info->file,"class \"tspan\"\n");
text=EscapeString(svg_info->text,'\"');
(void) FormatLocaleFile(svg_info->file,"text %g,%g \"%s\"\n",
svg_info->bounds.x,svg_info->bounds.y,text);
text=DestroyString(text);
*svg_info->text='\0';
}
(void) FormatLocaleFile(svg_info->file,"pop graphic-context\n");
break;
}
if (LocaleCompare((const char *) name,"title") == 0)
{
if (*svg_info->text == '\0')
break;
(void) CloneString(&svg_info->title,svg_info->text);
*svg_info->text='\0';
break;
}
break;
}
case 'U':
case 'u':
{
if (LocaleCompare((char *) name,"use") == 0)
{
if ((svg_info->bounds.x != 0.0) || (svg_info->bounds.y != 0.0))
(void) FormatLocaleFile(svg_info->file,"translate %g,%g\n",
svg_info->bounds.x,svg_info->bounds.y);
(void) FormatLocaleFile(svg_info->file,"use \"url(%s)\"\n",
svg_info->url);
(void) FormatLocaleFile(svg_info->file,"pop graphic-context\n");
break;
}
break;
}
default:
break;
}
*svg_info->text='\0';
(void) memset(&svg_info->element,0,sizeof(svg_info->element));
(void) memset(&svg_info->segment,0,sizeof(svg_info->segment));
svg_info->n--;
}
static void SVGCharacters(void *context,const xmlChar *c,int length)
{
char
*text;
register char
*p;
register ssize_t
i;
SVGInfo
*svg_info;
/*
Receiving some characters from the parser.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.characters(%s,%.20g)",c,(double) length);
svg_info=(SVGInfo *) context;
text=(char *) AcquireQuantumMemory(length+1,sizeof(*text));
if (text == (char *) NULL)
return;
p=text;
for (i=0; i < (ssize_t) length; i++)
*p++=c[i];
*p='\0';
SVGStripString(MagickFalse,text);
if (svg_info->text == (char *) NULL)
svg_info->text=text;
else
{
(void) ConcatenateString(&svg_info->text,text);
text=DestroyString(text);
}
}
static void SVGReference(void *context,const xmlChar *name)
{
SVGInfo
*svg_info;
xmlParserCtxtPtr
parser;
/*
Called when an entity reference is detected.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.reference(%s)",
name);
svg_info=(SVGInfo *) context;
parser=svg_info->parser;
if (parser == (xmlParserCtxtPtr) NULL)
return;
if (parser->node == (xmlNodePtr) NULL)
return;
if (*name == '#')
(void) xmlAddChild(parser->node,xmlNewCharRef(svg_info->document,name));
else
(void) xmlAddChild(parser->node,xmlNewReference(svg_info->document,name));
}
static void SVGIgnorableWhitespace(void *context,const xmlChar *c,int length)
{
SVGInfo
*svg_info;
/*
Receiving some ignorable whitespaces from the parser.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.ignorableWhitespace(%.30s, %d)",c,length);
svg_info=(SVGInfo *) context;
(void) svg_info;
}
static void SVGProcessingInstructions(void *context,const xmlChar *target,
const xmlChar *data)
{
SVGInfo
*svg_info;
/*
A processing instruction has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.processingInstruction(%s, %s)",target,data);
svg_info=(SVGInfo *) context;
(void) svg_info;
}
static void SVGComment(void *context,const xmlChar *value)
{
SVGInfo
*svg_info;
/*
A comment has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.comment(%s)",
value);
svg_info=(SVGInfo *) context;
if (svg_info->comment != (char *) NULL)
(void) ConcatenateString(&svg_info->comment,"\n");
(void) ConcatenateString(&svg_info->comment,(const char *) value);
}
static void SVGWarning(void *,const char *,...)
magick_attribute((__format__ (__printf__,2,3)));
static void SVGWarning(void *context,const char *format,...)
{
char
*message,
reason[MagickPathExtent];
SVGInfo
*svg_info;
va_list
operands;
/**
Display and format a warning messages, gives file, line, position and
extra parameters.
*/
va_start(operands,format);
svg_info=(SVGInfo *) context;
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.warning: ");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),format,operands);
#if !defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsprintf(reason,format,operands);
#else
(void) vsnprintf(reason,MagickPathExtent,format,operands);
#endif
message=GetExceptionMessage(errno);
(void) ThrowMagickException(svg_info->exception,GetMagickModule(),
DelegateWarning,reason,"`%s`",message);
message=DestroyString(message);
va_end(operands);
}
static void SVGError(void *,const char *,...)
magick_attribute((__format__ (__printf__,2,3)));
static void SVGError(void *context,const char *format,...)
{
char
*message,
reason[MagickPathExtent];
SVGInfo
*svg_info;
va_list
operands;
/*
Display and format a error formats, gives file, line, position and
extra parameters.
*/
va_start(operands,format);
svg_info=(SVGInfo *) context;
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.error: ");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),format,operands);
#if !defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsprintf(reason,format,operands);
#else
(void) vsnprintf(reason,MagickPathExtent,format,operands);
#endif
message=GetExceptionMessage(errno);
(void) ThrowMagickException(svg_info->exception,GetMagickModule(),CoderError,
reason,"`%s`",message);
message=DestroyString(message);
va_end(operands);
}
static void SVGCDataBlock(void *context,const xmlChar *value,int length)
{
SVGInfo
*svg_info;
xmlNodePtr
child;
xmlParserCtxtPtr
parser;
/*
Called when a pcdata block has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.pcdata(%s, %d)",
value,length);
svg_info=(SVGInfo *) context;
parser=svg_info->parser;
child=xmlGetLastChild(parser->node);
if ((child != (xmlNodePtr) NULL) && (child->type == XML_CDATA_SECTION_NODE))
{
xmlTextConcat(child,value,length);
return;
}
(void) xmlAddChild(parser->node,xmlNewCDataBlock(parser->myDoc,value,length));
}
static void SVGExternalSubset(void *context,const xmlChar *name,
const xmlChar *external_id,const xmlChar *system_id)
{
SVGInfo
*svg_info;
xmlParserCtxt
parser_context;
xmlParserCtxtPtr
parser;
xmlParserInputPtr
input;
/*
Does this document has an external subset?
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.externalSubset(%s, %s, %s)",name,
(external_id != (const xmlChar *) NULL ? (const char *) external_id : "none"),
(system_id != (const xmlChar *) NULL ? (const char *) system_id : "none"));
svg_info=(SVGInfo *) context;
parser=svg_info->parser;
if (((external_id == NULL) && (system_id == NULL)) ||
((parser->validate == 0) || (parser->wellFormed == 0) ||
(svg_info->document == 0)))
return;
input=SVGResolveEntity(context,external_id,system_id);
if (input == NULL)
return;
(void) xmlNewDtd(svg_info->document,name,external_id,system_id);
parser_context=(*parser);
parser->inputTab=(xmlParserInputPtr *) xmlMalloc(5*sizeof(*parser->inputTab));
if (parser->inputTab == (xmlParserInputPtr *) NULL)
{
parser->errNo=XML_ERR_NO_MEMORY;
parser->input=parser_context.input;
parser->inputNr=parser_context.inputNr;
parser->inputMax=parser_context.inputMax;
parser->inputTab=parser_context.inputTab;
return;
}
parser->inputNr=0;
parser->inputMax=5;
parser->input=NULL;
xmlPushInput(parser,input);
(void) xmlSwitchEncoding(parser,xmlDetectCharEncoding(parser->input->cur,4));
if (input->filename == (char *) NULL)
input->filename=(char *) xmlStrdup(system_id);
input->line=1;
input->col=1;
input->base=parser->input->cur;
input->cur=parser->input->cur;
input->free=NULL;
xmlParseExternalSubset(parser,external_id,system_id);
while (parser->inputNr > 1)
(void) xmlPopInput(parser);
xmlFreeInputStream(parser->input);
xmlFree(parser->inputTab);
parser->input=parser_context.input;
parser->inputNr=parser_context.inputNr;
parser->inputMax=parser_context.inputMax;
parser->inputTab=parser_context.inputTab;
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static Image *ReadSVGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
filename[MagickPathExtent];
FILE
*file;
Image
*image,
*next;
int
status,
unique_file;
ssize_t
n;
SVGInfo
*svg_info;
unsigned char
message[MagickPathExtent];
xmlSAXHandler
sax_modules;
xmlSAXHandlerPtr
sax_handler;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if ((fabs(image->resolution.x) < MagickEpsilon) ||
(fabs(image->resolution.y) < MagickEpsilon))
{
GeometryInfo
geometry_info;
int
flags;
flags=ParseGeometry(SVGDensityGeometry,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
}
if (LocaleCompare(image_info->magick,"MSVG") != 0)
{
Image
*svg_image;
svg_image=RenderSVGImage(image_info,image,exception);
if (svg_image != (Image *) NULL)
{
image=DestroyImageList(image);
return(svg_image);
}
{
#if defined(MAGICKCORE_RSVG_DELEGATE)
#if defined(MAGICKCORE_CAIRO_DELEGATE)
cairo_surface_t
*cairo_surface;
cairo_t
*cairo_image;
MagickBooleanType
apply_density;
MemoryInfo
*pixel_info;
register unsigned char
*p;
RsvgDimensionData
dimension_info;
unsigned char
*pixels;
#else
GdkPixbuf
*pixel_buffer;
register const guchar
*p;
#endif
GError
*error;
PixelInfo
fill_color;
register ssize_t
x;
register Quantum
*q;
RsvgHandle
*svg_handle;
ssize_t
y;
svg_handle=rsvg_handle_new();
if (svg_handle == (RsvgHandle *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
rsvg_handle_set_base_uri(svg_handle,image_info->filename);
if ((fabs(image->resolution.x) > MagickEpsilon) &&
(fabs(image->resolution.y) > MagickEpsilon))
rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x,
image->resolution.y);
while ((n=ReadBlob(image,MagickPathExtent-1,message)) != 0)
{
message[n]='\0';
error=(GError *) NULL;
(void) rsvg_handle_write(svg_handle,message,n,&error);
if (error != (GError *) NULL)
g_error_free(error);
}
error=(GError *) NULL;
rsvg_handle_close(svg_handle,&error);
if (error != (GError *) NULL)
g_error_free(error);
#if defined(MAGICKCORE_CAIRO_DELEGATE)
apply_density=MagickTrue;
rsvg_handle_get_dimensions(svg_handle,&dimension_info);
if ((image->resolution.x > 0.0) && (image->resolution.y > 0.0))
{
RsvgDimensionData
dpi_dimension_info;
/*
We should not apply the density when the internal 'factor' is 'i'.
This can be checked by using the trick below.
*/
rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x*256,
image->resolution.y*256);
rsvg_handle_get_dimensions(svg_handle,&dpi_dimension_info);
if ((dpi_dimension_info.width != dimension_info.width) ||
(dpi_dimension_info.height != dimension_info.height))
apply_density=MagickFalse;
rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x,
image->resolution.y);
}
if (image_info->size != (char *) NULL)
{
(void) GetGeometry(image_info->size,(ssize_t *) NULL,
(ssize_t *) NULL,&image->columns,&image->rows);
if ((image->columns != 0) || (image->rows != 0))
{
image->resolution.x=DefaultSVGDensity*image->columns/
dimension_info.width;
image->resolution.y=DefaultSVGDensity*image->rows/
dimension_info.height;
if (fabs(image->resolution.x) < MagickEpsilon)
image->resolution.x=image->resolution.y;
else
if (fabs(image->resolution.y) < MagickEpsilon)
image->resolution.y=image->resolution.x;
else
image->resolution.x=image->resolution.y=MagickMin(
image->resolution.x,image->resolution.y);
apply_density=MagickTrue;
}
}
if (apply_density != MagickFalse)
{
image->columns=image->resolution.x*dimension_info.width/
DefaultSVGDensity;
image->rows=image->resolution.y*dimension_info.height/
DefaultSVGDensity;
}
else
{
image->columns=dimension_info.width;
image->rows=dimension_info.height;
}
pixel_info=(MemoryInfo *) NULL;
#else
pixel_buffer=rsvg_handle_get_pixbuf(svg_handle);
rsvg_handle_free(svg_handle);
image->columns=gdk_pixbuf_get_width(pixel_buffer);
image->rows=gdk_pixbuf_get_height(pixel_buffer);
#endif
image->alpha_trait=BlendPixelTrait;
if (image_info->ping == MagickFalse)
{
#if defined(MAGICKCORE_CAIRO_DELEGATE)
size_t
stride;
#endif
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
{
#if !defined(MAGICKCORE_CAIRO_DELEGATE)
g_object_unref(G_OBJECT(pixel_buffer));
#endif
g_object_unref(svg_handle);
ThrowReaderException(MissingDelegateError,
"NoDecodeDelegateForThisImageFormat");
}
#if defined(MAGICKCORE_CAIRO_DELEGATE)
stride=4*image->columns;
#if defined(MAGICKCORE_PANGOCAIRO_DELEGATE)
stride=(size_t) cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32,
(int) image->columns);
#endif
pixel_info=AcquireVirtualMemory(stride,image->rows*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
g_object_unref(svg_handle);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
#endif
(void) SetImageBackgroundColor(image,exception);
#if defined(MAGICKCORE_CAIRO_DELEGATE)
cairo_surface=cairo_image_surface_create_for_data(pixels,
CAIRO_FORMAT_ARGB32,(int) image->columns,(int) image->rows,(int)
stride);
if ((cairo_surface == (cairo_surface_t *) NULL) ||
(cairo_surface_status(cairo_surface) != CAIRO_STATUS_SUCCESS))
{
if (cairo_surface != (cairo_surface_t *) NULL)
cairo_surface_destroy(cairo_surface);
pixel_info=RelinquishVirtualMemory(pixel_info);
g_object_unref(svg_handle);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
cairo_image=cairo_create(cairo_surface);
cairo_set_operator(cairo_image,CAIRO_OPERATOR_CLEAR);
cairo_paint(cairo_image);
cairo_set_operator(cairo_image,CAIRO_OPERATOR_OVER);
if (apply_density != MagickFalse)
cairo_scale(cairo_image,image->resolution.x/DefaultSVGDensity,
image->resolution.y/DefaultSVGDensity);
rsvg_handle_render_cairo(svg_handle,cairo_image);
cairo_destroy(cairo_image);
cairo_surface_destroy(cairo_surface);
g_object_unref(svg_handle);
p=pixels;
#else
p=gdk_pixbuf_get_pixels(pixel_buffer);
#endif
GetPixelInfo(image,&fill_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
#if defined(MAGICKCORE_CAIRO_DELEGATE)
fill_color.blue=ScaleCharToQuantum(*p++);
fill_color.green=ScaleCharToQuantum(*p++);
fill_color.red=ScaleCharToQuantum(*p++);
#else
fill_color.red=ScaleCharToQuantum(*p++);
fill_color.green=ScaleCharToQuantum(*p++);
fill_color.blue=ScaleCharToQuantum(*p++);
#endif
fill_color.alpha=ScaleCharToQuantum(*p++);
#if defined(MAGICKCORE_CAIRO_DELEGATE)
{
double
gamma;
gamma=QuantumScale*fill_color.alpha;
gamma=PerceptibleReciprocal(gamma);
fill_color.blue*=gamma;
fill_color.green*=gamma;
fill_color.red*=gamma;
}
#endif
CompositePixelOver(image,&fill_color,fill_color.alpha,q,(double)
GetPixelAlpha(image,q),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
#if defined(MAGICKCORE_CAIRO_DELEGATE)
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
#else
g_object_unref(G_OBJECT(pixel_buffer));
#endif
(void) CloseBlob(image);
for (next=GetFirstImageInList(image); next != (Image *) NULL; )
{
(void) CopyMagickString(next->filename,image->filename,MaxTextExtent);
(void) CopyMagickString(next->magick,image->magick,MaxTextExtent);
next=GetNextImageInList(next);
}
return(GetFirstImageInList(image));
#endif
}
}
/*
Open draw file.
*/
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"w");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
(void) CopyMagickString(image->filename,filename,MagickPathExtent);
ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Parse SVG file.
*/
svg_info=AcquireSVGInfo();
if (svg_info == (SVGInfo *) NULL)
{
(void) fclose(file);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
svg_info->file=file;
svg_info->exception=exception;
svg_info->image=image;
svg_info->image_info=image_info;
svg_info->bounds.width=image->columns;
svg_info->bounds.height=image->rows;
svg_info->svgDepth=0;
if (image_info->size != (char *) NULL)
(void) CloneString(&svg_info->size,image_info->size);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"begin SAX");
xmlInitParser();
(void) xmlSubstituteEntitiesDefault(1);
(void) memset(&sax_modules,0,sizeof(sax_modules));
sax_modules.internalSubset=SVGInternalSubset;
sax_modules.isStandalone=SVGIsStandalone;
sax_modules.hasInternalSubset=SVGHasInternalSubset;
sax_modules.hasExternalSubset=SVGHasExternalSubset;
sax_modules.resolveEntity=SVGResolveEntity;
sax_modules.getEntity=SVGGetEntity;
sax_modules.entityDecl=SVGEntityDeclaration;
sax_modules.notationDecl=SVGNotationDeclaration;
sax_modules.attributeDecl=SVGAttributeDeclaration;
sax_modules.elementDecl=SVGElementDeclaration;
sax_modules.unparsedEntityDecl=SVGUnparsedEntityDeclaration;
sax_modules.setDocumentLocator=SVGSetDocumentLocator;
sax_modules.startDocument=SVGStartDocument;
sax_modules.endDocument=SVGEndDocument;
sax_modules.startElement=SVGStartElement;
sax_modules.endElement=SVGEndElement;
sax_modules.reference=SVGReference;
sax_modules.characters=SVGCharacters;
sax_modules.ignorableWhitespace=SVGIgnorableWhitespace;
sax_modules.processingInstruction=SVGProcessingInstructions;
sax_modules.comment=SVGComment;
sax_modules.warning=SVGWarning;
sax_modules.error=SVGError;
sax_modules.fatalError=SVGError;
sax_modules.getParameterEntity=SVGGetParameterEntity;
sax_modules.cdataBlock=SVGCDataBlock;
sax_modules.externalSubset=SVGExternalSubset;
sax_handler=(&sax_modules);
n=ReadBlob(image,MagickPathExtent-1,message);
message[n]='\0';
if (n > 0)
{
svg_info->parser=xmlCreatePushParserCtxt(sax_handler,svg_info,(char *)
message,n,image->filename);
(void) xmlCtxtUseOptions(svg_info->parser,XML_PARSE_HUGE);
while ((n=ReadBlob(image,MagickPathExtent-1,message)) != 0)
{
message[n]='\0';
status=xmlParseChunk(svg_info->parser,(char *) message,(int) n,0);
if (status != 0)
break;
}
}
(void) xmlParseChunk(svg_info->parser,(char *) message,0,1);
SVGEndDocument(svg_info);
xmlFreeParserCtxt(svg_info->parser);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"end SAX");
(void) fclose(file);
(void) CloseBlob(image);
image->columns=svg_info->width;
image->rows=svg_info->height;
if (exception->severity >= ErrorException)
{
svg_info=DestroySVGInfo(svg_info);
(void) RelinquishUniqueFileResource(filename);
image=DestroyImage(image);
return((Image *) NULL);
}
if (image_info->ping == MagickFalse)
{
ImageInfo
*read_info;
/*
Draw image.
*/
image=DestroyImage(image);
image=(Image *) NULL;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) FormatLocaleString(read_info->filename,MagickPathExtent,"mvg:%s",
filename);
image=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
}
/*
Relinquish resources.
*/
if (image != (Image *) NULL)
{
if (svg_info->title != (char *) NULL)
(void) SetImageProperty(image,"svg:title",svg_info->title,exception);
if (svg_info->comment != (char *) NULL)
(void) SetImageProperty(image,"svg:comment",svg_info->comment,
exception);
}
for (next=GetFirstImageInList(image); next != (Image *) NULL; )
{
(void) CopyMagickString(next->filename,image->filename,MaxTextExtent);
(void) CopyMagickString(next->magick,image->magick,MaxTextExtent);
next=GetNextImageInList(next);
}
svg_info=DestroySVGInfo(svg_info);
(void) RelinquishUniqueFileResource(filename);
return(GetFirstImageInList(image));
}
#else
static Image *ReadSVGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image,
*svg_image;
MagickBooleanType
status;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if ((fabs(image->resolution.x) < MagickEpsilon) ||
(fabs(image->resolution.y) < MagickEpsilon))
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(SVGDensityGeometry,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
}
svg_image=RenderSVGImage(image_info,image,exception);
image=DestroyImage(image);
return(svg_image);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r S V G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterSVGImage() adds attributes for the SVG image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterSVGImage method is:
%
% size_t RegisterSVGImage(void)
%
*/
ModuleExport size_t RegisterSVGImage(void)
{
char
version[MagickPathExtent];
MagickInfo
*entry;
*version='\0';
#if defined(LIBXML_DOTTED_VERSION)
(void) CopyMagickString(version,"XML " LIBXML_DOTTED_VERSION,
MagickPathExtent);
#endif
#if defined(MAGICKCORE_RSVG_DELEGATE)
#if !GLIB_CHECK_VERSION(2,35,0)
g_type_init();
#endif
(void) FormatLocaleString(version,MagickPathExtent,"RSVG %d.%d.%d",
LIBRSVG_MAJOR_VERSION,LIBRSVG_MINOR_VERSION,LIBRSVG_MICRO_VERSION);
#endif
entry=AcquireMagickInfo("SVG","SVG","Scalable Vector Graphics");
entry->decoder=(DecodeImageHandler *) ReadSVGImage;
entry->encoder=(EncodeImageHandler *) WriteSVGImage;
entry->flags^=CoderBlobSupportFlag;
#if defined(MAGICKCORE_RSVG_DELEGATE)
entry->flags^=CoderDecoderThreadSupportFlag;
#endif
entry->mime_type=ConstantString("image/svg+xml");
if (*version != '\0')
entry->version=ConstantString(version);
entry->magick=(IsImageFormatHandler *) IsSVG;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("SVG","SVGZ","Compressed Scalable Vector Graphics");
#if defined(MAGICKCORE_XML_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadSVGImage;
#endif
entry->encoder=(EncodeImageHandler *) WriteSVGImage;
entry->flags^=CoderBlobSupportFlag;
#if defined(MAGICKCORE_RSVG_DELEGATE)
entry->flags^=CoderDecoderThreadSupportFlag;
#endif
entry->mime_type=ConstantString("image/svg+xml");
if (*version != '\0')
entry->version=ConstantString(version);
entry->magick=(IsImageFormatHandler *) IsSVG;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("SVG","MSVG",
"ImageMagick's own SVG internal renderer");
#if defined(MAGICKCORE_XML_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadSVGImage;
#endif
entry->encoder=(EncodeImageHandler *) WriteSVGImage;
entry->flags^=CoderBlobSupportFlag;
#if defined(MAGICKCORE_RSVG_DELEGATE)
entry->flags^=CoderDecoderThreadSupportFlag;
#endif
entry->magick=(IsImageFormatHandler *) IsSVG;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r S V G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterSVGImage() removes format registrations made by the
% SVG module from the list of supported formats.
%
% The format of the UnregisterSVGImage method is:
%
% UnregisterSVGImage(void)
%
*/
ModuleExport void UnregisterSVGImage(void)
{
(void) UnregisterMagickInfo("SVGZ");
(void) UnregisterMagickInfo("SVG");
(void) UnregisterMagickInfo("MSVG");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e S V G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteSVGImage() writes a image in the SVG - XML based W3C standard
% format.
%
% The format of the WriteSVGImage method is:
%
% MagickBooleanType WriteSVGImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static void AffineToTransform(Image *image,AffineMatrix *affine)
{
char
transform[MagickPathExtent];
if ((fabs(affine->tx) < MagickEpsilon) && (fabs(affine->ty) < MagickEpsilon))
{
if ((fabs(affine->rx) < MagickEpsilon) &&
(fabs(affine->ry) < MagickEpsilon))
{
if ((fabs(affine->sx-1.0) < MagickEpsilon) &&
(fabs(affine->sy-1.0) < MagickEpsilon))
{
(void) WriteBlobString(image,"\">\n");
return;
}
(void) FormatLocaleString(transform,MagickPathExtent,
"\" transform=\"scale(%g,%g)\">\n",affine->sx,affine->sy);
(void) WriteBlobString(image,transform);
return;
}
else
{
if ((fabs(affine->sx-affine->sy) < MagickEpsilon) &&
(fabs(affine->rx+affine->ry) < MagickEpsilon) &&
(fabs(affine->sx*affine->sx+affine->rx*affine->rx-1.0) <
2*MagickEpsilon))
{
double
theta;
theta=(180.0/MagickPI)*atan2(affine->rx,affine->sx);
(void) FormatLocaleString(transform,MagickPathExtent,
"\" transform=\"rotate(%g)\">\n",theta);
(void) WriteBlobString(image,transform);
return;
}
}
}
else
{
if ((fabs(affine->sx-1.0) < MagickEpsilon) &&
(fabs(affine->rx) < MagickEpsilon) &&
(fabs(affine->ry) < MagickEpsilon) &&
(fabs(affine->sy-1.0) < MagickEpsilon))
{
(void) FormatLocaleString(transform,MagickPathExtent,
"\" transform=\"translate(%g,%g)\">\n",affine->tx,affine->ty);
(void) WriteBlobString(image,transform);
return;
}
}
(void) FormatLocaleString(transform,MagickPathExtent,
"\" transform=\"matrix(%g %g %g %g %g %g)\">\n",
affine->sx,affine->rx,affine->ry,affine->sy,affine->tx,affine->ty);
(void) WriteBlobString(image,transform);
}
static MagickBooleanType IsPoint(const char *point)
{
char
*p;
ssize_t
value;
value=(ssize_t) strtol(point,&p,10);
(void) value;
return(p != point ? MagickTrue : MagickFalse);
}
static MagickBooleanType TraceSVGImage(Image *image,ExceptionInfo *exception)
{
#if defined(MAGICKCORE_AUTOTRACE_DELEGATE)
{
at_bitmap_type
*trace;
at_fitting_opts_type
*fitting_options;
at_output_opts_type
*output_options;
at_splines_type
*splines;
ImageType
type;
register const Quantum
*p;
register ssize_t
i,
x;
size_t
number_planes;
ssize_t
y;
/*
Trace image and write as SVG.
*/
fitting_options=at_fitting_opts_new();
output_options=at_output_opts_new();
(void) SetImageGray(image,exception);
type=GetImageType(image);
number_planes=3;
if ((type == BilevelType) || (type == GrayscaleType))
number_planes=1;
trace=at_bitmap_new(image->columns,image->rows,number_planes);
i=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
trace->bitmap[i++]=GetPixelRed(image,p);
if (number_planes == 3)
{
trace->bitmap[i++]=GetPixelGreen(image,p);
trace->bitmap[i++]=GetPixelBlue(image,p);
}
p+=GetPixelChannels(image);
}
}
splines=at_splines_new_full(trace,fitting_options,NULL,NULL,NULL,NULL,NULL,
NULL);
at_splines_write(at_output_get_handler_by_suffix((char *) "svg"),
GetBlobFileHandle(image),image->filename,output_options,splines,NULL,
NULL);
/*
Free resources.
*/
at_splines_free(splines);
at_bitmap_free(trace);
at_output_opts_free(output_options);
at_fitting_opts_free(fitting_options);
}
#else
{
char
*base64,
filename[MagickPathExtent],
message[MagickPathExtent];
const DelegateInfo
*delegate_info;
Image
*clone_image;
ImageInfo
*image_info;
MagickBooleanType
status;
register char
*p;
size_t
blob_length,
encode_length;
ssize_t
i;
unsigned char
*blob;
delegate_info=GetDelegateInfo((char *) NULL,"TRACE",exception);
if (delegate_info != (DelegateInfo *) NULL)
{
/*
Trace SVG with tracing delegate.
*/
image_info=AcquireImageInfo();
(void) CopyMagickString(image_info->magick,"TRACE",MagickPathExtent);
(void) FormatLocaleString(filename,MagickPathExtent,"trace:%s",
image_info->filename);
(void) CopyMagickString(image_info->filename,filename,MagickPathExtent);
status=WriteImage(image_info,image,exception);
image_info=DestroyImageInfo(image_info);
return(status);
}
(void) WriteBlobString(image,
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
(void) WriteBlobString(image,
"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"");
(void) WriteBlobString(image,
" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
(void) FormatLocaleString(message,MagickPathExtent,
"<svg version=\"1.1\" id=\"Layer_1\" "
"xmlns=\"http://www.w3.org/2000/svg\" "
"xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\" "
"width=\"%.20gpx\" height=\"%.20gpx\" viewBox=\"0 0 %.20g %.20g\" "
"enable-background=\"new 0 0 %.20g %.20g\" xml:space=\"preserve\">",
(double) image->columns,(double) image->rows,
(double) image->columns,(double) image->rows,
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,message);
clone_image=CloneImage(image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
return(MagickFalse);
image_info=AcquireImageInfo();
(void) CopyMagickString(image_info->magick,"PNG",MagickPathExtent);
blob_length=2048;
blob=(unsigned char *) ImageToBlob(image_info,clone_image,&blob_length,
exception);
clone_image=DestroyImage(clone_image);
image_info=DestroyImageInfo(image_info);
if (blob == (unsigned char *) NULL)
return(MagickFalse);
encode_length=0;
base64=Base64Encode(blob,blob_length,&encode_length);
blob=(unsigned char *) RelinquishMagickMemory(blob);
(void) FormatLocaleString(message,MagickPathExtent,
" <image id=\"image%.20g\" width=\"%.20g\" height=\"%.20g\" "
"x=\"%.20g\" y=\"%.20g\"\n href=\"data:image/png;base64,",
(double) image->scene,(double) image->columns,(double) image->rows,
(double) image->page.x,(double) image->page.y);
(void) WriteBlobString(image,message);
p=base64;
for (i=(ssize_t) encode_length; i > 0; i-=76)
{
(void) FormatLocaleString(message,MagickPathExtent,"%.76s",p);
(void) WriteBlobString(image,message);
p+=76;
if (i > 76)
(void) WriteBlobString(image,"\n");
}
base64=DestroyString(base64);
(void) WriteBlobString(image,"\" />\n");
(void) WriteBlobString(image,"</svg>\n");
}
#endif
(void) CloseBlob(image);
return(MagickTrue);
}
static MagickBooleanType WriteSVGImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
#define BezierQuantum 200
AffineMatrix
affine;
char
keyword[MagickPathExtent],
message[MagickPathExtent],
name[MagickPathExtent],
*next_token,
*token,
type[MagickPathExtent];
const char
*p,
*q,
*value;
int
n;
ssize_t
j;
MagickBooleanType
active,
status;
PointInfo
point;
PrimitiveInfo
*primitive_info;
PrimitiveType
primitive_type;
register ssize_t
x;
register ssize_t
i;
size_t
extent,
length,
number_points;
SVGInfo
svg_info;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
value=GetImageArtifact(image,"SVG");
if (value != (char *) NULL)
{
(void) WriteBlobString(image,value);
(void) CloseBlob(image);
return(MagickTrue);
}
value=GetImageArtifact(image,"mvg:vector-graphics");
if (value == (char *) NULL)
return(TraceSVGImage(image,exception));
/*
Write SVG header.
*/
(void) WriteBlobString(image,"<?xml version=\"1.0\" standalone=\"no\"?>\n");
(void) WriteBlobString(image,
"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 20010904//EN\"\n");
(void) WriteBlobString(image,
" \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n");
(void) FormatLocaleString(message,MagickPathExtent,
"<svg width=\"%.20g\" height=\"%.20g\">\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,message);
/*
Allocate primitive info memory.
*/
number_points=2047;
primitive_info=(PrimitiveInfo *) AcquireQuantumMemory(number_points,
sizeof(*primitive_info));
if (primitive_info == (PrimitiveInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
GetAffineMatrix(&affine);
token=AcquireString(value);
extent=strlen(token)+MagickPathExtent;
active=MagickFalse;
n=0;
status=MagickTrue;
for (q=(const char *) value; *q != '\0'; )
{
/*
Interpret graphic primitive.
*/
(void) GetNextToken(q,&q,MagickPathExtent,keyword);
if (*keyword == '\0')
break;
if (*keyword == '#')
{
/*
Comment.
*/
if (active != MagickFalse)
{
AffineToTransform(image,&affine);
active=MagickFalse;
}
(void) WriteBlobString(image,"<desc>");
(void) WriteBlobString(image,keyword+1);
for ( ; (*q != '\n') && (*q != '\0'); q++)
switch (*q)
{
case '<': (void) WriteBlobString(image,"<"); break;
case '>': (void) WriteBlobString(image,">"); break;
case '&': (void) WriteBlobString(image,"&"); break;
default: (void) WriteBlobByte(image,(unsigned char) *q); break;
}
(void) WriteBlobString(image,"</desc>\n");
continue;
}
primitive_type=UndefinedPrimitive;
switch (*keyword)
{
case ';':
break;
case 'a':
case 'A':
{
if (LocaleCompare("affine",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
affine.sx=StringToDouble(token,&next_token);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
affine.rx=StringToDouble(token,&next_token);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
affine.ry=StringToDouble(token,&next_token);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
affine.sy=StringToDouble(token,&next_token);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
affine.tx=StringToDouble(token,&next_token);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
affine.ty=StringToDouble(token,&next_token);
break;
}
if (LocaleCompare("alpha",keyword) == 0)
{
primitive_type=AlphaPrimitive;
break;
}
if (LocaleCompare("angle",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
affine.rx=StringToDouble(token,&next_token);
affine.ry=StringToDouble(token,&next_token);
break;
}
if (LocaleCompare("arc",keyword) == 0)
{
primitive_type=ArcPrimitive;
break;
}
status=MagickFalse;
break;
}
case 'b':
case 'B':
{
if (LocaleCompare("bezier",keyword) == 0)
{
primitive_type=BezierPrimitive;
break;
}
status=MagickFalse;
break;
}
case 'c':
case 'C':
{
if (LocaleCompare("clip-path",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"clip-path:url(#%s);",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("clip-rule",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,"clip-rule:%s;",
token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("clip-units",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"clipPathUnits=%s;",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("circle",keyword) == 0)
{
primitive_type=CirclePrimitive;
break;
}
if (LocaleCompare("color",keyword) == 0)
{
primitive_type=ColorPrimitive;
break;
}
status=MagickFalse;
break;
}
case 'd':
case 'D':
{
if (LocaleCompare("decorate",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"text-decoration:%s;",token);
(void) WriteBlobString(image,message);
break;
}
status=MagickFalse;
break;
}
case 'e':
case 'E':
{
if (LocaleCompare("ellipse",keyword) == 0)
{
primitive_type=EllipsePrimitive;
break;
}
status=MagickFalse;
break;
}
case 'f':
case 'F':
{
if (LocaleCompare("fill",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,"fill:%s;",
token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("fill-rule",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"fill-rule:%s;",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("fill-opacity",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"fill-opacity:%s;",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("font-family",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"font-family:%s;",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("font-stretch",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"font-stretch:%s;",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("font-style",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"font-style:%s;",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("font-size",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"font-size:%s;",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("font-weight",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"font-weight:%s;",token);
(void) WriteBlobString(image,message);
break;
}
status=MagickFalse;
break;
}
case 'g':
case 'G':
{
if (LocaleCompare("gradient-units",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("text-align",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"text-align %s ",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("text-anchor",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"text-anchor %s ",token);
(void) WriteBlobString(image,message);
break;
}
status=MagickFalse;
break;
}
case 'i':
case 'I':
{
if (LocaleCompare("image",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
primitive_type=ImagePrimitive;
break;
}
status=MagickFalse;
break;
}
case 'k':
case 'K':
{
if (LocaleCompare("kerning",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,"kerning:%s;",
token);
(void) WriteBlobString(image,message);
}
break;
}
case 'l':
case 'L':
{
if (LocaleCompare("letter-spacing",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"letter-spacing:%s;",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("line",keyword) == 0)
{
primitive_type=LinePrimitive;
break;
}
status=MagickFalse;
break;
}
case 'o':
case 'O':
{
if (LocaleCompare("opacity",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,"opacity %s ",
token);
(void) WriteBlobString(image,message);
break;
}
status=MagickFalse;
break;
}
case 'p':
case 'P':
{
if (LocaleCompare("path",keyword) == 0)
{
primitive_type=PathPrimitive;
break;
}
if (LocaleCompare("point",keyword) == 0)
{
primitive_type=PointPrimitive;
break;
}
if (LocaleCompare("polyline",keyword) == 0)
{
primitive_type=PolylinePrimitive;
break;
}
if (LocaleCompare("polygon",keyword) == 0)
{
primitive_type=PolygonPrimitive;
break;
}
if (LocaleCompare("pop",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
if (LocaleCompare("clip-path",token) == 0)
{
(void) WriteBlobString(image,"</clipPath>\n");
break;
}
if (LocaleCompare("defs",token) == 0)
{
(void) WriteBlobString(image,"</defs>\n");
break;
}
if (LocaleCompare("gradient",token) == 0)
{
(void) FormatLocaleString(message,MagickPathExtent,
"</%sGradient>\n",type);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("graphic-context",token) == 0)
{
n--;
if (n < 0)
ThrowWriterException(DrawError,
"UnbalancedGraphicContextPushPop");
(void) WriteBlobString(image,"</g>\n");
}
if (LocaleCompare("pattern",token) == 0)
{
(void) WriteBlobString(image,"</pattern>\n");
break;
}
if (LocaleCompare("symbol",token) == 0)
{
(void) WriteBlobString(image,"</symbol>\n");
break;
}
if ((LocaleCompare("defs",token) == 0) ||
(LocaleCompare("symbol",token) == 0))
(void) WriteBlobString(image,"</g>\n");
break;
}
if (LocaleCompare("push",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
if (LocaleCompare("clip-path",token) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"<clipPath id=\"%s\">\n",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("defs",token) == 0)
{
(void) WriteBlobString(image,"<defs>\n");
break;
}
if (LocaleCompare("gradient",token) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) CopyMagickString(name,token,MagickPathExtent);
(void) GetNextToken(q,&q,extent,token);
(void) CopyMagickString(type,token,MagickPathExtent);
(void) GetNextToken(q,&q,extent,token);
svg_info.segment.x1=StringToDouble(token,&next_token);
svg_info.element.cx=StringToDouble(token,&next_token);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
svg_info.segment.y1=StringToDouble(token,&next_token);
svg_info.element.cy=StringToDouble(token,&next_token);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
svg_info.segment.x2=StringToDouble(token,&next_token);
svg_info.element.major=StringToDouble(token,
(char **) NULL);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
svg_info.segment.y2=StringToDouble(token,&next_token);
svg_info.element.minor=StringToDouble(token,
(char **) NULL);
(void) FormatLocaleString(message,MagickPathExtent,
"<%sGradient id=\"%s\" x1=\"%g\" y1=\"%g\" x2=\"%g\" "
"y2=\"%g\">\n",type,name,svg_info.segment.x1,
svg_info.segment.y1,svg_info.segment.x2,svg_info.segment.y2);
if (LocaleCompare(type,"radial") == 0)
{
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
svg_info.element.angle=StringToDouble(token,
(char **) NULL);
(void) FormatLocaleString(message,MagickPathExtent,
"<%sGradient id=\"%s\" cx=\"%g\" cy=\"%g\" r=\"%g\" "
"fx=\"%g\" fy=\"%g\">\n",type,name,
svg_info.element.cx,svg_info.element.cy,
svg_info.element.angle,svg_info.element.major,
svg_info.element.minor);
}
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("graphic-context",token) == 0)
{
n++;
if (active)
{
AffineToTransform(image,&affine);
active=MagickFalse;
}
(void) WriteBlobString(image,"<g style=\"");
active=MagickTrue;
}
if (LocaleCompare("pattern",token) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) CopyMagickString(name,token,MagickPathExtent);
(void) GetNextToken(q,&q,extent,token);
svg_info.bounds.x=StringToDouble(token,&next_token);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
svg_info.bounds.y=StringToDouble(token,&next_token);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
svg_info.bounds.width=StringToDouble(token,
(char **) NULL);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
svg_info.bounds.height=StringToDouble(token,(char **) NULL);
(void) FormatLocaleString(message,MagickPathExtent,
"<pattern id=\"%s\" x=\"%g\" y=\"%g\" width=\"%g\" "
"height=\"%g\">\n",name,svg_info.bounds.x,svg_info.bounds.y,
svg_info.bounds.width,svg_info.bounds.height);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("symbol",token) == 0)
{
(void) WriteBlobString(image,"<symbol>\n");
break;
}
break;
}
status=MagickFalse;
break;
}
case 'r':
case 'R':
{
if (LocaleCompare("rectangle",keyword) == 0)
{
primitive_type=RectanglePrimitive;
break;
}
if (LocaleCompare("roundRectangle",keyword) == 0)
{
primitive_type=RoundRectanglePrimitive;
break;
}
if (LocaleCompare("rotate",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,"rotate(%s) ",
token);
(void) WriteBlobString(image,message);
break;
}
status=MagickFalse;
break;
}
case 's':
case 'S':
{
if (LocaleCompare("scale",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
affine.sx=StringToDouble(token,&next_token);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
affine.sy=StringToDouble(token,&next_token);
break;
}
if (LocaleCompare("skewX",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,"skewX(%s) ",
token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("skewY",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,"skewY(%s) ",
token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("stop-color",keyword) == 0)
{
char
color[MagickPathExtent];
(void) GetNextToken(q,&q,extent,token);
(void) CopyMagickString(color,token,MagickPathExtent);
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
" <stop offset=\"%s\" stop-color=\"%s\" />\n",token,color);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("stroke",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,"stroke:%s;",
token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("stroke-antialias",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"stroke-antialias:%s;",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("stroke-dasharray",keyword) == 0)
{
if (IsPoint(q))
{
ssize_t
k;
p=q;
(void) GetNextToken(p,&p,extent,token);
for (k=0; IsPoint(token); k++)
(void) GetNextToken(p,&p,extent,token);
(void) WriteBlobString(image,"stroke-dasharray:");
for (j=0; j < k; j++)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,"%s ",
token);
(void) WriteBlobString(image,message);
}
(void) WriteBlobString(image,";");
break;
}
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"stroke-dasharray:%s;",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("stroke-dashoffset",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"stroke-dashoffset:%s;",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("stroke-linecap",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"stroke-linecap:%s;",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("stroke-linejoin",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"stroke-linejoin:%s;",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("stroke-miterlimit",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"stroke-miterlimit:%s;",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("stroke-opacity",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"stroke-opacity:%s;",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("stroke-width",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"stroke-width:%s;",token);
(void) WriteBlobString(image,message);
continue;
}
status=MagickFalse;
break;
}
case 't':
case 'T':
{
if (LocaleCompare("text",keyword) == 0)
{
primitive_type=TextPrimitive;
break;
}
if (LocaleCompare("text-antialias",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
"text-antialias:%s;",token);
(void) WriteBlobString(image,message);
break;
}
if (LocaleCompare("tspan",keyword) == 0)
{
primitive_type=TextPrimitive;
break;
}
if (LocaleCompare("translate",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
affine.tx=StringToDouble(token,&next_token);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
affine.ty=StringToDouble(token,&next_token);
break;
}
status=MagickFalse;
break;
}
case 'v':
case 'V':
{
if (LocaleCompare("viewbox",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
(void) GetNextToken(q,&q,extent,token);
break;
}
status=MagickFalse;
break;
}
default:
{
status=MagickFalse;
break;
}
}
if (status == MagickFalse)
break;
if (primitive_type == UndefinedPrimitive)
continue;
/*
Parse the primitive attributes.
*/
i=0;
j=0;
for (x=0; *q != '\0'; x++)
{
/*
Define points.
*/
if (IsPoint(q) == MagickFalse)
break;
(void) GetNextToken(q,&q,extent,token);
point.x=StringToDouble(token,&next_token);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
point.y=StringToDouble(token,&next_token);
(void) GetNextToken(q,(const char **) NULL,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
primitive_info[i].primitive=primitive_type;
primitive_info[i].point=point;
primitive_info[i].coordinates=0;
primitive_info[i].method=FloodfillMethod;
i++;
if (i < (ssize_t) (number_points-6*BezierQuantum-360))
continue;
number_points+=6*BezierQuantum+360;
primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,
number_points,sizeof(*primitive_info));
if (primitive_info == (PrimitiveInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
break;
}
}
primitive_info[j].primitive=primitive_type;
primitive_info[j].coordinates=(size_t) x;
primitive_info[j].method=FloodfillMethod;
primitive_info[j].text=(char *) NULL;
if (active)
{
AffineToTransform(image,&affine);
active=MagickFalse;
}
active=MagickFalse;
switch (primitive_type)
{
case PointPrimitive:
default:
{
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
break;
}
case LinePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
(void) FormatLocaleString(message,MagickPathExtent,
" <line x1=\"%g\" y1=\"%g\" x2=\"%g\" y2=\"%g\"/>\n",
primitive_info[j].point.x,primitive_info[j].point.y,
primitive_info[j+1].point.x,primitive_info[j+1].point.y);
(void) WriteBlobString(image,message);
break;
}
case RectanglePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
(void) FormatLocaleString(message,MagickPathExtent,
" <rect x=\"%g\" y=\"%g\" width=\"%g\" height=\"%g\"/>\n",
primitive_info[j].point.x,primitive_info[j].point.y,
primitive_info[j+1].point.x-primitive_info[j].point.x,
primitive_info[j+1].point.y-primitive_info[j].point.y);
(void) WriteBlobString(image,message);
break;
}
case RoundRectanglePrimitive:
{
if (primitive_info[j].coordinates != 3)
{
status=MagickFalse;
break;
}
(void) FormatLocaleString(message,MagickPathExtent,
" <rect x=\"%g\" y=\"%g\" width=\"%g\" height=\"%g\" rx=\"%g\" "
"ry=\"%g\"/>\n",primitive_info[j].point.x,
primitive_info[j].point.y,primitive_info[j+1].point.x-
primitive_info[j].point.x,primitive_info[j+1].point.y-
primitive_info[j].point.y,primitive_info[j+2].point.x,
primitive_info[j+2].point.y);
(void) WriteBlobString(image,message);
break;
}
case ArcPrimitive:
{
if (primitive_info[j].coordinates != 3)
{
status=MagickFalse;
break;
}
break;
}
case EllipsePrimitive:
{
if (primitive_info[j].coordinates != 3)
{
status=MagickFalse;
break;
}
(void) FormatLocaleString(message,MagickPathExtent,
" <ellipse cx=\"%g\" cy=\"%g\" rx=\"%g\" ry=\"%g\"/>\n",
primitive_info[j].point.x,primitive_info[j].point.y,
primitive_info[j+1].point.x,primitive_info[j+1].point.y);
(void) WriteBlobString(image,message);
break;
}
case CirclePrimitive:
{
double
alpha,
beta;
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
alpha=primitive_info[j+1].point.x-primitive_info[j].point.x;
beta=primitive_info[j+1].point.y-primitive_info[j].point.y;
(void) FormatLocaleString(message,MagickPathExtent,
" <circle cx=\"%g\" cy=\"%g\" r=\"%g\"/>\n",
primitive_info[j].point.x,primitive_info[j].point.y,
hypot(alpha,beta));
(void) WriteBlobString(image,message);
break;
}
case PolylinePrimitive:
{
if (primitive_info[j].coordinates < 2)
{
status=MagickFalse;
break;
}
(void) CopyMagickString(message," <polyline points=\"",
MagickPathExtent);
(void) WriteBlobString(image,message);
length=strlen(message);
for ( ; j < i; j++)
{
(void) FormatLocaleString(message,MagickPathExtent,"%g,%g ",
primitive_info[j].point.x,primitive_info[j].point.y);
length+=strlen(message);
if (length >= 80)
{
(void) WriteBlobString(image,"\n ");
length=strlen(message)+5;
}
(void) WriteBlobString(image,message);
}
(void) WriteBlobString(image,"\"/>\n");
break;
}
case PolygonPrimitive:
{
if (primitive_info[j].coordinates < 3)
{
status=MagickFalse;
break;
}
primitive_info[i]=primitive_info[j];
primitive_info[i].coordinates=0;
primitive_info[j].coordinates++;
i++;
(void) CopyMagickString(message," <polygon points=\"",
MagickPathExtent);
(void) WriteBlobString(image,message);
length=strlen(message);
for ( ; j < i; j++)
{
(void) FormatLocaleString(message,MagickPathExtent,"%g,%g ",
primitive_info[j].point.x,primitive_info[j].point.y);
length+=strlen(message);
if (length >= 80)
{
(void) WriteBlobString(image,"\n ");
length=strlen(message)+5;
}
(void) WriteBlobString(image,message);
}
(void) WriteBlobString(image,"\"/>\n");
break;
}
case BezierPrimitive:
{
if (primitive_info[j].coordinates < 3)
{
status=MagickFalse;
break;
}
break;
}
case PathPrimitive:
{
int
number_attributes;
(void) GetNextToken(q,&q,extent,token);
number_attributes=1;
for (p=token; *p != '\0'; p++)
if (isalpha((int) ((unsigned char) *p)) != 0)
number_attributes++;
if (i > (ssize_t) (number_points-6*BezierQuantum*number_attributes-1))
{
number_points+=6*BezierQuantum*number_attributes;
primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,
number_points,sizeof(*primitive_info));
if (primitive_info == (PrimitiveInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
}
(void) WriteBlobString(image," <path d=\"");
(void) WriteBlobString(image,token);
(void) WriteBlobString(image,"\"/>\n");
break;
}
case AlphaPrimitive:
case ColorPrimitive:
{
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
(void) GetNextToken(q,&q,extent,token);
if (LocaleCompare("point",token) == 0)
primitive_info[j].method=PointMethod;
if (LocaleCompare("replace",token) == 0)
primitive_info[j].method=ReplaceMethod;
if (LocaleCompare("floodfill",token) == 0)
primitive_info[j].method=FloodfillMethod;
if (LocaleCompare("filltoborder",token) == 0)
primitive_info[j].method=FillToBorderMethod;
if (LocaleCompare("reset",token) == 0)
primitive_info[j].method=ResetMethod;
break;
}
case TextPrimitive:
{
register char
*p;
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
" <text x=\"%g\" y=\"%g\">",primitive_info[j].point.x,
primitive_info[j].point.y);
(void) WriteBlobString(image,message);
for (p=token; *p != '\0'; p++)
switch (*p)
{
case '<': (void) WriteBlobString(image,"<"); break;
case '>': (void) WriteBlobString(image,">"); break;
case '&': (void) WriteBlobString(image,"&"); break;
default: (void) WriteBlobByte(image,(unsigned char) *p); break;
}
(void) WriteBlobString(image,"</text>\n");
break;
}
case ImagePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
(void) GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(message,MagickPathExtent,
" <image x=\"%g\" y=\"%g\" width=\"%g\" height=\"%g\" "
"href=\"%s\"/>\n",primitive_info[j].point.x,
primitive_info[j].point.y,primitive_info[j+1].point.x,
primitive_info[j+1].point.y,token);
(void) WriteBlobString(image,message);
break;
}
}
if (primitive_info == (PrimitiveInfo *) NULL)
break;
primitive_info[i].primitive=UndefinedPrimitive;
if (status == MagickFalse)
break;
}
(void) WriteBlobString(image,"</svg>\n");
/*
Relinquish resources.
*/
token=DestroyString(token);
if (primitive_info != (PrimitiveInfo *) NULL)
primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info);
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1221_0 |
crossvul-cpp_data_good_3443_0 | /*
* ebtables
*
* Author:
* Bart De Schuymer <bdschuym@pandora.be>
*
* ebtables.c,v 2.0, July, 2002
*
* This code is stongly inspired on the iptables code which is
* Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kmod.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_bridge/ebtables.h>
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <linux/smp.h>
#include <linux/cpumask.h>
#include <net/sock.h>
/* needed for logical [in,out]-dev filtering */
#include "../br_private.h"
#define BUGPRINT(format, args...) printk("kernel msg: ebtables bug: please "\
"report to author: "format, ## args)
/* #define BUGPRINT(format, args...) */
/*
* Each cpu has its own set of counters, so there is no need for write_lock in
* the softirq
* For reading or updating the counters, the user context needs to
* get a write_lock
*/
/* The size of each set of counters is altered to get cache alignment */
#define SMP_ALIGN(x) (((x) + SMP_CACHE_BYTES-1) & ~(SMP_CACHE_BYTES-1))
#define COUNTER_OFFSET(n) (SMP_ALIGN(n * sizeof(struct ebt_counter)))
#define COUNTER_BASE(c, n, cpu) ((struct ebt_counter *)(((char *)c) + \
COUNTER_OFFSET(n) * cpu))
static DEFINE_MUTEX(ebt_mutex);
#ifdef CONFIG_COMPAT
static void ebt_standard_compat_from_user(void *dst, const void *src)
{
int v = *(compat_int_t *)src;
if (v >= 0)
v += xt_compat_calc_jump(NFPROTO_BRIDGE, v);
memcpy(dst, &v, sizeof(v));
}
static int ebt_standard_compat_to_user(void __user *dst, const void *src)
{
compat_int_t cv = *(int *)src;
if (cv >= 0)
cv -= xt_compat_calc_jump(NFPROTO_BRIDGE, cv);
return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0;
}
#endif
static struct xt_target ebt_standard_target = {
.name = "standard",
.revision = 0,
.family = NFPROTO_BRIDGE,
.targetsize = sizeof(int),
#ifdef CONFIG_COMPAT
.compatsize = sizeof(compat_int_t),
.compat_from_user = ebt_standard_compat_from_user,
.compat_to_user = ebt_standard_compat_to_user,
#endif
};
static inline int
ebt_do_watcher(const struct ebt_entry_watcher *w, struct sk_buff *skb,
struct xt_action_param *par)
{
par->target = w->u.watcher;
par->targinfo = w->data;
w->u.watcher->target(skb, par);
/* watchers don't give a verdict */
return 0;
}
static inline int
ebt_do_match(struct ebt_entry_match *m, const struct sk_buff *skb,
struct xt_action_param *par)
{
par->match = m->u.match;
par->matchinfo = m->data;
return m->u.match->match(skb, par) ? EBT_MATCH : EBT_NOMATCH;
}
static inline int
ebt_dev_check(const char *entry, const struct net_device *device)
{
int i = 0;
const char *devname;
if (*entry == '\0')
return 0;
if (!device)
return 1;
devname = device->name;
/* 1 is the wildcard token */
while (entry[i] != '\0' && entry[i] != 1 && entry[i] == devname[i])
i++;
return (devname[i] != entry[i] && entry[i] != 1);
}
#define FWINV2(bool,invflg) ((bool) ^ !!(e->invflags & invflg))
/* process standard matches */
static inline int
ebt_basic_match(const struct ebt_entry *e, const struct sk_buff *skb,
const struct net_device *in, const struct net_device *out)
{
const struct ethhdr *h = eth_hdr(skb);
const struct net_bridge_port *p;
__be16 ethproto;
int verdict, i;
if (vlan_tx_tag_present(skb))
ethproto = htons(ETH_P_8021Q);
else
ethproto = h->h_proto;
if (e->bitmask & EBT_802_3) {
if (FWINV2(ntohs(ethproto) >= 1536, EBT_IPROTO))
return 1;
} else if (!(e->bitmask & EBT_NOPROTO) &&
FWINV2(e->ethproto != ethproto, EBT_IPROTO))
return 1;
if (FWINV2(ebt_dev_check(e->in, in), EBT_IIN))
return 1;
if (FWINV2(ebt_dev_check(e->out, out), EBT_IOUT))
return 1;
/* rcu_read_lock()ed by nf_hook_slow */
if (in && (p = br_port_get_rcu(in)) != NULL &&
FWINV2(ebt_dev_check(e->logical_in, p->br->dev), EBT_ILOGICALIN))
return 1;
if (out && (p = br_port_get_rcu(out)) != NULL &&
FWINV2(ebt_dev_check(e->logical_out, p->br->dev), EBT_ILOGICALOUT))
return 1;
if (e->bitmask & EBT_SOURCEMAC) {
verdict = 0;
for (i = 0; i < 6; i++)
verdict |= (h->h_source[i] ^ e->sourcemac[i]) &
e->sourcemsk[i];
if (FWINV2(verdict != 0, EBT_ISOURCE) )
return 1;
}
if (e->bitmask & EBT_DESTMAC) {
verdict = 0;
for (i = 0; i < 6; i++)
verdict |= (h->h_dest[i] ^ e->destmac[i]) &
e->destmsk[i];
if (FWINV2(verdict != 0, EBT_IDEST) )
return 1;
}
return 0;
}
static inline __pure
struct ebt_entry *ebt_next_entry(const struct ebt_entry *entry)
{
return (void *)entry + entry->next_offset;
}
/* Do some firewalling */
unsigned int ebt_do_table (unsigned int hook, struct sk_buff *skb,
const struct net_device *in, const struct net_device *out,
struct ebt_table *table)
{
int i, nentries;
struct ebt_entry *point;
struct ebt_counter *counter_base, *cb_base;
const struct ebt_entry_target *t;
int verdict, sp = 0;
struct ebt_chainstack *cs;
struct ebt_entries *chaininfo;
const char *base;
const struct ebt_table_info *private;
struct xt_action_param acpar;
acpar.family = NFPROTO_BRIDGE;
acpar.in = in;
acpar.out = out;
acpar.hotdrop = false;
acpar.hooknum = hook;
read_lock_bh(&table->lock);
private = table->private;
cb_base = COUNTER_BASE(private->counters, private->nentries,
smp_processor_id());
if (private->chainstack)
cs = private->chainstack[smp_processor_id()];
else
cs = NULL;
chaininfo = private->hook_entry[hook];
nentries = private->hook_entry[hook]->nentries;
point = (struct ebt_entry *)(private->hook_entry[hook]->data);
counter_base = cb_base + private->hook_entry[hook]->counter_offset;
/* base for chain jumps */
base = private->entries;
i = 0;
while (i < nentries) {
if (ebt_basic_match(point, skb, in, out))
goto letscontinue;
if (EBT_MATCH_ITERATE(point, ebt_do_match, skb, &acpar) != 0)
goto letscontinue;
if (acpar.hotdrop) {
read_unlock_bh(&table->lock);
return NF_DROP;
}
/* increase counter */
(*(counter_base + i)).pcnt++;
(*(counter_base + i)).bcnt += skb->len;
/* these should only watch: not modify, nor tell us
what to do with the packet */
EBT_WATCHER_ITERATE(point, ebt_do_watcher, skb, &acpar);
t = (struct ebt_entry_target *)
(((char *)point) + point->target_offset);
/* standard target */
if (!t->u.target->target)
verdict = ((struct ebt_standard_target *)t)->verdict;
else {
acpar.target = t->u.target;
acpar.targinfo = t->data;
verdict = t->u.target->target(skb, &acpar);
}
if (verdict == EBT_ACCEPT) {
read_unlock_bh(&table->lock);
return NF_ACCEPT;
}
if (verdict == EBT_DROP) {
read_unlock_bh(&table->lock);
return NF_DROP;
}
if (verdict == EBT_RETURN) {
letsreturn:
#ifdef CONFIG_NETFILTER_DEBUG
if (sp == 0) {
BUGPRINT("RETURN on base chain");
/* act like this is EBT_CONTINUE */
goto letscontinue;
}
#endif
sp--;
/* put all the local variables right */
i = cs[sp].n;
chaininfo = cs[sp].chaininfo;
nentries = chaininfo->nentries;
point = cs[sp].e;
counter_base = cb_base +
chaininfo->counter_offset;
continue;
}
if (verdict == EBT_CONTINUE)
goto letscontinue;
#ifdef CONFIG_NETFILTER_DEBUG
if (verdict < 0) {
BUGPRINT("bogus standard verdict\n");
read_unlock_bh(&table->lock);
return NF_DROP;
}
#endif
/* jump to a udc */
cs[sp].n = i + 1;
cs[sp].chaininfo = chaininfo;
cs[sp].e = ebt_next_entry(point);
i = 0;
chaininfo = (struct ebt_entries *) (base + verdict);
#ifdef CONFIG_NETFILTER_DEBUG
if (chaininfo->distinguisher) {
BUGPRINT("jump to non-chain\n");
read_unlock_bh(&table->lock);
return NF_DROP;
}
#endif
nentries = chaininfo->nentries;
point = (struct ebt_entry *)chaininfo->data;
counter_base = cb_base + chaininfo->counter_offset;
sp++;
continue;
letscontinue:
point = ebt_next_entry(point);
i++;
}
/* I actually like this :) */
if (chaininfo->policy == EBT_RETURN)
goto letsreturn;
if (chaininfo->policy == EBT_ACCEPT) {
read_unlock_bh(&table->lock);
return NF_ACCEPT;
}
read_unlock_bh(&table->lock);
return NF_DROP;
}
/* If it succeeds, returns element and locks mutex */
static inline void *
find_inlist_lock_noload(struct list_head *head, const char *name, int *error,
struct mutex *mutex)
{
struct {
struct list_head list;
char name[EBT_FUNCTION_MAXNAMELEN];
} *e;
*error = mutex_lock_interruptible(mutex);
if (*error != 0)
return NULL;
list_for_each_entry(e, head, list) {
if (strcmp(e->name, name) == 0)
return e;
}
*error = -ENOENT;
mutex_unlock(mutex);
return NULL;
}
static void *
find_inlist_lock(struct list_head *head, const char *name, const char *prefix,
int *error, struct mutex *mutex)
{
return try_then_request_module(
find_inlist_lock_noload(head, name, error, mutex),
"%s%s", prefix, name);
}
static inline struct ebt_table *
find_table_lock(struct net *net, const char *name, int *error,
struct mutex *mutex)
{
return find_inlist_lock(&net->xt.tables[NFPROTO_BRIDGE], name,
"ebtable_", error, mutex);
}
static inline int
ebt_check_match(struct ebt_entry_match *m, struct xt_mtchk_param *par,
unsigned int *cnt)
{
const struct ebt_entry *e = par->entryinfo;
struct xt_match *match;
size_t left = ((char *)e + e->watchers_offset) - (char *)m;
int ret;
if (left < sizeof(struct ebt_entry_match) ||
left - sizeof(struct ebt_entry_match) < m->match_size)
return -EINVAL;
match = xt_request_find_match(NFPROTO_BRIDGE, m->u.name, 0);
if (IS_ERR(match))
return PTR_ERR(match);
m->u.match = match;
par->match = match;
par->matchinfo = m->data;
ret = xt_check_match(par, m->match_size,
e->ethproto, e->invflags & EBT_IPROTO);
if (ret < 0) {
module_put(match->me);
return ret;
}
(*cnt)++;
return 0;
}
static inline int
ebt_check_watcher(struct ebt_entry_watcher *w, struct xt_tgchk_param *par,
unsigned int *cnt)
{
const struct ebt_entry *e = par->entryinfo;
struct xt_target *watcher;
size_t left = ((char *)e + e->target_offset) - (char *)w;
int ret;
if (left < sizeof(struct ebt_entry_watcher) ||
left - sizeof(struct ebt_entry_watcher) < w->watcher_size)
return -EINVAL;
watcher = xt_request_find_target(NFPROTO_BRIDGE, w->u.name, 0);
if (IS_ERR(watcher))
return PTR_ERR(watcher);
w->u.watcher = watcher;
par->target = watcher;
par->targinfo = w->data;
ret = xt_check_target(par, w->watcher_size,
e->ethproto, e->invflags & EBT_IPROTO);
if (ret < 0) {
module_put(watcher->me);
return ret;
}
(*cnt)++;
return 0;
}
static int ebt_verify_pointers(const struct ebt_replace *repl,
struct ebt_table_info *newinfo)
{
unsigned int limit = repl->entries_size;
unsigned int valid_hooks = repl->valid_hooks;
unsigned int offset = 0;
int i;
for (i = 0; i < NF_BR_NUMHOOKS; i++)
newinfo->hook_entry[i] = NULL;
newinfo->entries_size = repl->entries_size;
newinfo->nentries = repl->nentries;
while (offset < limit) {
size_t left = limit - offset;
struct ebt_entry *e = (void *)newinfo->entries + offset;
if (left < sizeof(unsigned int))
break;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if ((valid_hooks & (1 << i)) == 0)
continue;
if ((char __user *)repl->hook_entry[i] ==
repl->entries + offset)
break;
}
if (i != NF_BR_NUMHOOKS || !(e->bitmask & EBT_ENTRY_OR_ENTRIES)) {
if (e->bitmask != 0) {
/* we make userspace set this right,
so there is no misunderstanding */
BUGPRINT("EBT_ENTRY_OR_ENTRIES shouldn't be set "
"in distinguisher\n");
return -EINVAL;
}
if (i != NF_BR_NUMHOOKS)
newinfo->hook_entry[i] = (struct ebt_entries *)e;
if (left < sizeof(struct ebt_entries))
break;
offset += sizeof(struct ebt_entries);
} else {
if (left < sizeof(struct ebt_entry))
break;
if (left < e->next_offset)
break;
if (e->next_offset < sizeof(struct ebt_entry))
return -EINVAL;
offset += e->next_offset;
}
}
if (offset != limit) {
BUGPRINT("entries_size too small\n");
return -EINVAL;
}
/* check if all valid hooks have a chain */
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if (!newinfo->hook_entry[i] &&
(valid_hooks & (1 << i))) {
BUGPRINT("Valid hook without chain\n");
return -EINVAL;
}
}
return 0;
}
/*
* this one is very careful, as it is the first function
* to parse the userspace data
*/
static inline int
ebt_check_entry_size_and_hooks(const struct ebt_entry *e,
const struct ebt_table_info *newinfo,
unsigned int *n, unsigned int *cnt,
unsigned int *totalcnt, unsigned int *udc_cnt)
{
int i;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if ((void *)e == (void *)newinfo->hook_entry[i])
break;
}
/* beginning of a new chain
if i == NF_BR_NUMHOOKS it must be a user defined chain */
if (i != NF_BR_NUMHOOKS || !e->bitmask) {
/* this checks if the previous chain has as many entries
as it said it has */
if (*n != *cnt) {
BUGPRINT("nentries does not equal the nr of entries "
"in the chain\n");
return -EINVAL;
}
if (((struct ebt_entries *)e)->policy != EBT_DROP &&
((struct ebt_entries *)e)->policy != EBT_ACCEPT) {
/* only RETURN from udc */
if (i != NF_BR_NUMHOOKS ||
((struct ebt_entries *)e)->policy != EBT_RETURN) {
BUGPRINT("bad policy\n");
return -EINVAL;
}
}
if (i == NF_BR_NUMHOOKS) /* it's a user defined chain */
(*udc_cnt)++;
if (((struct ebt_entries *)e)->counter_offset != *totalcnt) {
BUGPRINT("counter_offset != totalcnt");
return -EINVAL;
}
*n = ((struct ebt_entries *)e)->nentries;
*cnt = 0;
return 0;
}
/* a plain old entry, heh */
if (sizeof(struct ebt_entry) > e->watchers_offset ||
e->watchers_offset > e->target_offset ||
e->target_offset >= e->next_offset) {
BUGPRINT("entry offsets not in right order\n");
return -EINVAL;
}
/* this is not checked anywhere else */
if (e->next_offset - e->target_offset < sizeof(struct ebt_entry_target)) {
BUGPRINT("target size too small\n");
return -EINVAL;
}
(*cnt)++;
(*totalcnt)++;
return 0;
}
struct ebt_cl_stack
{
struct ebt_chainstack cs;
int from;
unsigned int hookmask;
};
/*
* we need these positions to check that the jumps to a different part of the
* entries is a jump to the beginning of a new chain.
*/
static inline int
ebt_get_udc_positions(struct ebt_entry *e, struct ebt_table_info *newinfo,
unsigned int *n, struct ebt_cl_stack *udc)
{
int i;
/* we're only interested in chain starts */
if (e->bitmask)
return 0;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if (newinfo->hook_entry[i] == (struct ebt_entries *)e)
break;
}
/* only care about udc */
if (i != NF_BR_NUMHOOKS)
return 0;
udc[*n].cs.chaininfo = (struct ebt_entries *)e;
/* these initialisations are depended on later in check_chainloops() */
udc[*n].cs.n = 0;
udc[*n].hookmask = 0;
(*n)++;
return 0;
}
static inline int
ebt_cleanup_match(struct ebt_entry_match *m, struct net *net, unsigned int *i)
{
struct xt_mtdtor_param par;
if (i && (*i)-- == 0)
return 1;
par.net = net;
par.match = m->u.match;
par.matchinfo = m->data;
par.family = NFPROTO_BRIDGE;
if (par.match->destroy != NULL)
par.match->destroy(&par);
module_put(par.match->me);
return 0;
}
static inline int
ebt_cleanup_watcher(struct ebt_entry_watcher *w, struct net *net, unsigned int *i)
{
struct xt_tgdtor_param par;
if (i && (*i)-- == 0)
return 1;
par.net = net;
par.target = w->u.watcher;
par.targinfo = w->data;
par.family = NFPROTO_BRIDGE;
if (par.target->destroy != NULL)
par.target->destroy(&par);
module_put(par.target->me);
return 0;
}
static inline int
ebt_cleanup_entry(struct ebt_entry *e, struct net *net, unsigned int *cnt)
{
struct xt_tgdtor_param par;
struct ebt_entry_target *t;
if (e->bitmask == 0)
return 0;
/* we're done */
if (cnt && (*cnt)-- == 0)
return 1;
EBT_WATCHER_ITERATE(e, ebt_cleanup_watcher, net, NULL);
EBT_MATCH_ITERATE(e, ebt_cleanup_match, net, NULL);
t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
par.net = net;
par.target = t->u.target;
par.targinfo = t->data;
par.family = NFPROTO_BRIDGE;
if (par.target->destroy != NULL)
par.target->destroy(&par);
module_put(par.target->me);
return 0;
}
static inline int
ebt_check_entry(struct ebt_entry *e, struct net *net,
const struct ebt_table_info *newinfo,
const char *name, unsigned int *cnt,
struct ebt_cl_stack *cl_s, unsigned int udc_cnt)
{
struct ebt_entry_target *t;
struct xt_target *target;
unsigned int i, j, hook = 0, hookmask = 0;
size_t gap;
int ret;
struct xt_mtchk_param mtpar;
struct xt_tgchk_param tgpar;
/* don't mess with the struct ebt_entries */
if (e->bitmask == 0)
return 0;
if (e->bitmask & ~EBT_F_MASK) {
BUGPRINT("Unknown flag for bitmask\n");
return -EINVAL;
}
if (e->invflags & ~EBT_INV_MASK) {
BUGPRINT("Unknown flag for inv bitmask\n");
return -EINVAL;
}
if ( (e->bitmask & EBT_NOPROTO) && (e->bitmask & EBT_802_3) ) {
BUGPRINT("NOPROTO & 802_3 not allowed\n");
return -EINVAL;
}
/* what hook do we belong to? */
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if (!newinfo->hook_entry[i])
continue;
if ((char *)newinfo->hook_entry[i] < (char *)e)
hook = i;
else
break;
}
/* (1 << NF_BR_NUMHOOKS) tells the check functions the rule is on
a base chain */
if (i < NF_BR_NUMHOOKS)
hookmask = (1 << hook) | (1 << NF_BR_NUMHOOKS);
else {
for (i = 0; i < udc_cnt; i++)
if ((char *)(cl_s[i].cs.chaininfo) > (char *)e)
break;
if (i == 0)
hookmask = (1 << hook) | (1 << NF_BR_NUMHOOKS);
else
hookmask = cl_s[i - 1].hookmask;
}
i = 0;
mtpar.net = tgpar.net = net;
mtpar.table = tgpar.table = name;
mtpar.entryinfo = tgpar.entryinfo = e;
mtpar.hook_mask = tgpar.hook_mask = hookmask;
mtpar.family = tgpar.family = NFPROTO_BRIDGE;
ret = EBT_MATCH_ITERATE(e, ebt_check_match, &mtpar, &i);
if (ret != 0)
goto cleanup_matches;
j = 0;
ret = EBT_WATCHER_ITERATE(e, ebt_check_watcher, &tgpar, &j);
if (ret != 0)
goto cleanup_watchers;
t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
gap = e->next_offset - e->target_offset;
target = xt_request_find_target(NFPROTO_BRIDGE, t->u.name, 0);
if (IS_ERR(target)) {
ret = PTR_ERR(target);
goto cleanup_watchers;
}
t->u.target = target;
if (t->u.target == &ebt_standard_target) {
if (gap < sizeof(struct ebt_standard_target)) {
BUGPRINT("Standard target size too big\n");
ret = -EFAULT;
goto cleanup_watchers;
}
if (((struct ebt_standard_target *)t)->verdict <
-NUM_STANDARD_TARGETS) {
BUGPRINT("Invalid standard target\n");
ret = -EFAULT;
goto cleanup_watchers;
}
} else if (t->target_size > gap - sizeof(struct ebt_entry_target)) {
module_put(t->u.target->me);
ret = -EFAULT;
goto cleanup_watchers;
}
tgpar.target = target;
tgpar.targinfo = t->data;
ret = xt_check_target(&tgpar, t->target_size,
e->ethproto, e->invflags & EBT_IPROTO);
if (ret < 0) {
module_put(target->me);
goto cleanup_watchers;
}
(*cnt)++;
return 0;
cleanup_watchers:
EBT_WATCHER_ITERATE(e, ebt_cleanup_watcher, net, &j);
cleanup_matches:
EBT_MATCH_ITERATE(e, ebt_cleanup_match, net, &i);
return ret;
}
/*
* checks for loops and sets the hook mask for udc
* the hook mask for udc tells us from which base chains the udc can be
* accessed. This mask is a parameter to the check() functions of the extensions
*/
static int check_chainloops(const struct ebt_entries *chain, struct ebt_cl_stack *cl_s,
unsigned int udc_cnt, unsigned int hooknr, char *base)
{
int i, chain_nr = -1, pos = 0, nentries = chain->nentries, verdict;
const struct ebt_entry *e = (struct ebt_entry *)chain->data;
const struct ebt_entry_target *t;
while (pos < nentries || chain_nr != -1) {
/* end of udc, go back one 'recursion' step */
if (pos == nentries) {
/* put back values of the time when this chain was called */
e = cl_s[chain_nr].cs.e;
if (cl_s[chain_nr].from != -1)
nentries =
cl_s[cl_s[chain_nr].from].cs.chaininfo->nentries;
else
nentries = chain->nentries;
pos = cl_s[chain_nr].cs.n;
/* make sure we won't see a loop that isn't one */
cl_s[chain_nr].cs.n = 0;
chain_nr = cl_s[chain_nr].from;
if (pos == nentries)
continue;
}
t = (struct ebt_entry_target *)
(((char *)e) + e->target_offset);
if (strcmp(t->u.name, EBT_STANDARD_TARGET))
goto letscontinue;
if (e->target_offset + sizeof(struct ebt_standard_target) >
e->next_offset) {
BUGPRINT("Standard target size too big\n");
return -1;
}
verdict = ((struct ebt_standard_target *)t)->verdict;
if (verdict >= 0) { /* jump to another chain */
struct ebt_entries *hlp2 =
(struct ebt_entries *)(base + verdict);
for (i = 0; i < udc_cnt; i++)
if (hlp2 == cl_s[i].cs.chaininfo)
break;
/* bad destination or loop */
if (i == udc_cnt) {
BUGPRINT("bad destination\n");
return -1;
}
if (cl_s[i].cs.n) {
BUGPRINT("loop\n");
return -1;
}
if (cl_s[i].hookmask & (1 << hooknr))
goto letscontinue;
/* this can't be 0, so the loop test is correct */
cl_s[i].cs.n = pos + 1;
pos = 0;
cl_s[i].cs.e = ebt_next_entry(e);
e = (struct ebt_entry *)(hlp2->data);
nentries = hlp2->nentries;
cl_s[i].from = chain_nr;
chain_nr = i;
/* this udc is accessible from the base chain for hooknr */
cl_s[i].hookmask |= (1 << hooknr);
continue;
}
letscontinue:
e = ebt_next_entry(e);
pos++;
}
return 0;
}
/* do the parsing of the table/chains/entries/matches/watchers/targets, heh */
static int translate_table(struct net *net, const char *name,
struct ebt_table_info *newinfo)
{
unsigned int i, j, k, udc_cnt;
int ret;
struct ebt_cl_stack *cl_s = NULL; /* used in the checking for chain loops */
i = 0;
while (i < NF_BR_NUMHOOKS && !newinfo->hook_entry[i])
i++;
if (i == NF_BR_NUMHOOKS) {
BUGPRINT("No valid hooks specified\n");
return -EINVAL;
}
if (newinfo->hook_entry[i] != (struct ebt_entries *)newinfo->entries) {
BUGPRINT("Chains don't start at beginning\n");
return -EINVAL;
}
/* make sure chains are ordered after each other in same order
as their corresponding hooks */
for (j = i + 1; j < NF_BR_NUMHOOKS; j++) {
if (!newinfo->hook_entry[j])
continue;
if (newinfo->hook_entry[j] <= newinfo->hook_entry[i]) {
BUGPRINT("Hook order must be followed\n");
return -EINVAL;
}
i = j;
}
/* do some early checkings and initialize some things */
i = 0; /* holds the expected nr. of entries for the chain */
j = 0; /* holds the up to now counted entries for the chain */
k = 0; /* holds the total nr. of entries, should equal
newinfo->nentries afterwards */
udc_cnt = 0; /* will hold the nr. of user defined chains (udc) */
ret = EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_check_entry_size_and_hooks, newinfo,
&i, &j, &k, &udc_cnt);
if (ret != 0)
return ret;
if (i != j) {
BUGPRINT("nentries does not equal the nr of entries in the "
"(last) chain\n");
return -EINVAL;
}
if (k != newinfo->nentries) {
BUGPRINT("Total nentries is wrong\n");
return -EINVAL;
}
/* get the location of the udc, put them in an array
while we're at it, allocate the chainstack */
if (udc_cnt) {
/* this will get free'd in do_replace()/ebt_register_table()
if an error occurs */
newinfo->chainstack =
vmalloc(nr_cpu_ids * sizeof(*(newinfo->chainstack)));
if (!newinfo->chainstack)
return -ENOMEM;
for_each_possible_cpu(i) {
newinfo->chainstack[i] =
vmalloc(udc_cnt * sizeof(*(newinfo->chainstack[0])));
if (!newinfo->chainstack[i]) {
while (i)
vfree(newinfo->chainstack[--i]);
vfree(newinfo->chainstack);
newinfo->chainstack = NULL;
return -ENOMEM;
}
}
cl_s = vmalloc(udc_cnt * sizeof(*cl_s));
if (!cl_s)
return -ENOMEM;
i = 0; /* the i'th udc */
EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_get_udc_positions, newinfo, &i, cl_s);
/* sanity check */
if (i != udc_cnt) {
BUGPRINT("i != udc_cnt\n");
vfree(cl_s);
return -EFAULT;
}
}
/* Check for loops */
for (i = 0; i < NF_BR_NUMHOOKS; i++)
if (newinfo->hook_entry[i])
if (check_chainloops(newinfo->hook_entry[i],
cl_s, udc_cnt, i, newinfo->entries)) {
vfree(cl_s);
return -EINVAL;
}
/* we now know the following (along with E=mc²):
- the nr of entries in each chain is right
- the size of the allocated space is right
- all valid hooks have a corresponding chain
- there are no loops
- wrong data can still be on the level of a single entry
- could be there are jumps to places that are not the
beginning of a chain. This can only occur in chains that
are not accessible from any base chains, so we don't care. */
/* used to know what we need to clean up if something goes wrong */
i = 0;
ret = EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_check_entry, net, newinfo, name, &i, cl_s, udc_cnt);
if (ret != 0) {
EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_cleanup_entry, net, &i);
}
vfree(cl_s);
return ret;
}
/* called under write_lock */
static void get_counters(const struct ebt_counter *oldcounters,
struct ebt_counter *counters, unsigned int nentries)
{
int i, cpu;
struct ebt_counter *counter_base;
/* counters of cpu 0 */
memcpy(counters, oldcounters,
sizeof(struct ebt_counter) * nentries);
/* add other counters to those of cpu 0 */
for_each_possible_cpu(cpu) {
if (cpu == 0)
continue;
counter_base = COUNTER_BASE(oldcounters, nentries, cpu);
for (i = 0; i < nentries; i++) {
counters[i].pcnt += counter_base[i].pcnt;
counters[i].bcnt += counter_base[i].bcnt;
}
}
}
static int do_replace_finish(struct net *net, struct ebt_replace *repl,
struct ebt_table_info *newinfo)
{
int ret, i;
struct ebt_counter *counterstmp = NULL;
/* used to be able to unlock earlier */
struct ebt_table_info *table;
struct ebt_table *t;
/* the user wants counters back
the check on the size is done later, when we have the lock */
if (repl->num_counters) {
unsigned long size = repl->num_counters * sizeof(*counterstmp);
counterstmp = vmalloc(size);
if (!counterstmp)
return -ENOMEM;
}
newinfo->chainstack = NULL;
ret = ebt_verify_pointers(repl, newinfo);
if (ret != 0)
goto free_counterstmp;
ret = translate_table(net, repl->name, newinfo);
if (ret != 0)
goto free_counterstmp;
t = find_table_lock(net, repl->name, &ret, &ebt_mutex);
if (!t) {
ret = -ENOENT;
goto free_iterate;
}
/* the table doesn't like it */
if (t->check && (ret = t->check(newinfo, repl->valid_hooks)))
goto free_unlock;
if (repl->num_counters && repl->num_counters != t->private->nentries) {
BUGPRINT("Wrong nr. of counters requested\n");
ret = -EINVAL;
goto free_unlock;
}
/* we have the mutex lock, so no danger in reading this pointer */
table = t->private;
/* make sure the table can only be rmmod'ed if it contains no rules */
if (!table->nentries && newinfo->nentries && !try_module_get(t->me)) {
ret = -ENOENT;
goto free_unlock;
} else if (table->nentries && !newinfo->nentries)
module_put(t->me);
/* we need an atomic snapshot of the counters */
write_lock_bh(&t->lock);
if (repl->num_counters)
get_counters(t->private->counters, counterstmp,
t->private->nentries);
t->private = newinfo;
write_unlock_bh(&t->lock);
mutex_unlock(&ebt_mutex);
/* so, a user can change the chains while having messed up her counter
allocation. Only reason why this is done is because this way the lock
is held only once, while this doesn't bring the kernel into a
dangerous state. */
if (repl->num_counters &&
copy_to_user(repl->counters, counterstmp,
repl->num_counters * sizeof(struct ebt_counter))) {
ret = -EFAULT;
}
else
ret = 0;
/* decrease module count and free resources */
EBT_ENTRY_ITERATE(table->entries, table->entries_size,
ebt_cleanup_entry, net, NULL);
vfree(table->entries);
if (table->chainstack) {
for_each_possible_cpu(i)
vfree(table->chainstack[i]);
vfree(table->chainstack);
}
vfree(table);
vfree(counterstmp);
return ret;
free_unlock:
mutex_unlock(&ebt_mutex);
free_iterate:
EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_cleanup_entry, net, NULL);
free_counterstmp:
vfree(counterstmp);
/* can be initialized in translate_table() */
if (newinfo->chainstack) {
for_each_possible_cpu(i)
vfree(newinfo->chainstack[i]);
vfree(newinfo->chainstack);
}
return ret;
}
/* replace the table */
static int do_replace(struct net *net, const void __user *user,
unsigned int len)
{
int ret, countersize;
struct ebt_table_info *newinfo;
struct ebt_replace tmp;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
if (len != sizeof(tmp) + tmp.entries_size) {
BUGPRINT("Wrong len argument\n");
return -EINVAL;
}
if (tmp.entries_size == 0) {
BUGPRINT("Entries_size never zero\n");
return -EINVAL;
}
/* overflow check */
if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) /
NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter))
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter))
return -ENOMEM;
tmp.name[sizeof(tmp.name) - 1] = 0;
countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
if (!newinfo)
return -ENOMEM;
if (countersize)
memset(newinfo->counters, 0, countersize);
newinfo->entries = vmalloc(tmp.entries_size);
if (!newinfo->entries) {
ret = -ENOMEM;
goto free_newinfo;
}
if (copy_from_user(
newinfo->entries, tmp.entries, tmp.entries_size) != 0) {
BUGPRINT("Couldn't copy entries from userspace\n");
ret = -EFAULT;
goto free_entries;
}
ret = do_replace_finish(net, &tmp, newinfo);
if (ret == 0)
return ret;
free_entries:
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
return ret;
}
struct ebt_table *
ebt_register_table(struct net *net, const struct ebt_table *input_table)
{
struct ebt_table_info *newinfo;
struct ebt_table *t, *table;
struct ebt_replace_kernel *repl;
int ret, i, countersize;
void *p;
if (input_table == NULL || (repl = input_table->table) == NULL ||
repl->entries == NULL || repl->entries_size == 0 ||
repl->counters != NULL || input_table->private != NULL) {
BUGPRINT("Bad table data for ebt_register_table!!!\n");
return ERR_PTR(-EINVAL);
}
/* Don't add one table to multiple lists. */
table = kmemdup(input_table, sizeof(struct ebt_table), GFP_KERNEL);
if (!table) {
ret = -ENOMEM;
goto out;
}
countersize = COUNTER_OFFSET(repl->nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
ret = -ENOMEM;
if (!newinfo)
goto free_table;
p = vmalloc(repl->entries_size);
if (!p)
goto free_newinfo;
memcpy(p, repl->entries, repl->entries_size);
newinfo->entries = p;
newinfo->entries_size = repl->entries_size;
newinfo->nentries = repl->nentries;
if (countersize)
memset(newinfo->counters, 0, countersize);
/* fill in newinfo and parse the entries */
newinfo->chainstack = NULL;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if ((repl->valid_hooks & (1 << i)) == 0)
newinfo->hook_entry[i] = NULL;
else
newinfo->hook_entry[i] = p +
((char *)repl->hook_entry[i] - repl->entries);
}
ret = translate_table(net, repl->name, newinfo);
if (ret != 0) {
BUGPRINT("Translate_table failed\n");
goto free_chainstack;
}
if (table->check && table->check(newinfo, table->valid_hooks)) {
BUGPRINT("The table doesn't like its own initial data, lol\n");
return ERR_PTR(-EINVAL);
}
table->private = newinfo;
rwlock_init(&table->lock);
ret = mutex_lock_interruptible(&ebt_mutex);
if (ret != 0)
goto free_chainstack;
list_for_each_entry(t, &net->xt.tables[NFPROTO_BRIDGE], list) {
if (strcmp(t->name, table->name) == 0) {
ret = -EEXIST;
BUGPRINT("Table name already exists\n");
goto free_unlock;
}
}
/* Hold a reference count if the chains aren't empty */
if (newinfo->nentries && !try_module_get(table->me)) {
ret = -ENOENT;
goto free_unlock;
}
list_add(&table->list, &net->xt.tables[NFPROTO_BRIDGE]);
mutex_unlock(&ebt_mutex);
return table;
free_unlock:
mutex_unlock(&ebt_mutex);
free_chainstack:
if (newinfo->chainstack) {
for_each_possible_cpu(i)
vfree(newinfo->chainstack[i]);
vfree(newinfo->chainstack);
}
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
free_table:
kfree(table);
out:
return ERR_PTR(ret);
}
void ebt_unregister_table(struct net *net, struct ebt_table *table)
{
int i;
if (!table) {
BUGPRINT("Request to unregister NULL table!!!\n");
return;
}
mutex_lock(&ebt_mutex);
list_del(&table->list);
mutex_unlock(&ebt_mutex);
EBT_ENTRY_ITERATE(table->private->entries, table->private->entries_size,
ebt_cleanup_entry, net, NULL);
if (table->private->nentries)
module_put(table->me);
vfree(table->private->entries);
if (table->private->chainstack) {
for_each_possible_cpu(i)
vfree(table->private->chainstack[i]);
vfree(table->private->chainstack);
}
vfree(table->private);
kfree(table);
}
/* userspace just supplied us with counters */
static int do_update_counters(struct net *net, const char *name,
struct ebt_counter __user *counters,
unsigned int num_counters,
const void __user *user, unsigned int len)
{
int i, ret;
struct ebt_counter *tmp;
struct ebt_table *t;
if (num_counters == 0)
return -EINVAL;
tmp = vmalloc(num_counters * sizeof(*tmp));
if (!tmp)
return -ENOMEM;
t = find_table_lock(net, name, &ret, &ebt_mutex);
if (!t)
goto free_tmp;
if (num_counters != t->private->nentries) {
BUGPRINT("Wrong nr of counters\n");
ret = -EINVAL;
goto unlock_mutex;
}
if (copy_from_user(tmp, counters, num_counters * sizeof(*counters))) {
ret = -EFAULT;
goto unlock_mutex;
}
/* we want an atomic add of the counters */
write_lock_bh(&t->lock);
/* we add to the counters of the first cpu */
for (i = 0; i < num_counters; i++) {
t->private->counters[i].pcnt += tmp[i].pcnt;
t->private->counters[i].bcnt += tmp[i].bcnt;
}
write_unlock_bh(&t->lock);
ret = 0;
unlock_mutex:
mutex_unlock(&ebt_mutex);
free_tmp:
vfree(tmp);
return ret;
}
static int update_counters(struct net *net, const void __user *user,
unsigned int len)
{
struct ebt_replace hlp;
if (copy_from_user(&hlp, user, sizeof(hlp)))
return -EFAULT;
if (len != sizeof(hlp) + hlp.num_counters * sizeof(struct ebt_counter))
return -EINVAL;
return do_update_counters(net, hlp.name, hlp.counters,
hlp.num_counters, user, len);
}
static inline int ebt_make_matchname(const struct ebt_entry_match *m,
const char *base, char __user *ubase)
{
char __user *hlp = ubase + ((char *)m - base);
if (copy_to_user(hlp, m->u.match->name, EBT_FUNCTION_MAXNAMELEN))
return -EFAULT;
return 0;
}
static inline int ebt_make_watchername(const struct ebt_entry_watcher *w,
const char *base, char __user *ubase)
{
char __user *hlp = ubase + ((char *)w - base);
if (copy_to_user(hlp , w->u.watcher->name, EBT_FUNCTION_MAXNAMELEN))
return -EFAULT;
return 0;
}
static inline int
ebt_make_names(struct ebt_entry *e, const char *base, char __user *ubase)
{
int ret;
char __user *hlp;
const struct ebt_entry_target *t;
if (e->bitmask == 0)
return 0;
hlp = ubase + (((char *)e + e->target_offset) - base);
t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
ret = EBT_MATCH_ITERATE(e, ebt_make_matchname, base, ubase);
if (ret != 0)
return ret;
ret = EBT_WATCHER_ITERATE(e, ebt_make_watchername, base, ubase);
if (ret != 0)
return ret;
if (copy_to_user(hlp, t->u.target->name, EBT_FUNCTION_MAXNAMELEN))
return -EFAULT;
return 0;
}
static int copy_counters_to_user(struct ebt_table *t,
const struct ebt_counter *oldcounters,
void __user *user, unsigned int num_counters,
unsigned int nentries)
{
struct ebt_counter *counterstmp;
int ret = 0;
/* userspace might not need the counters */
if (num_counters == 0)
return 0;
if (num_counters != nentries) {
BUGPRINT("Num_counters wrong\n");
return -EINVAL;
}
counterstmp = vmalloc(nentries * sizeof(*counterstmp));
if (!counterstmp)
return -ENOMEM;
write_lock_bh(&t->lock);
get_counters(oldcounters, counterstmp, nentries);
write_unlock_bh(&t->lock);
if (copy_to_user(user, counterstmp,
nentries * sizeof(struct ebt_counter)))
ret = -EFAULT;
vfree(counterstmp);
return ret;
}
/* called with ebt_mutex locked */
static int copy_everything_to_user(struct ebt_table *t, void __user *user,
const int *len, int cmd)
{
struct ebt_replace tmp;
const struct ebt_counter *oldcounters;
unsigned int entries_size, nentries;
int ret;
char *entries;
if (cmd == EBT_SO_GET_ENTRIES) {
entries_size = t->private->entries_size;
nentries = t->private->nentries;
entries = t->private->entries;
oldcounters = t->private->counters;
} else {
entries_size = t->table->entries_size;
nentries = t->table->nentries;
entries = t->table->entries;
oldcounters = t->table->counters;
}
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
if (*len != sizeof(struct ebt_replace) + entries_size +
(tmp.num_counters? nentries * sizeof(struct ebt_counter): 0))
return -EINVAL;
if (tmp.nentries != nentries) {
BUGPRINT("Nentries wrong\n");
return -EINVAL;
}
if (tmp.entries_size != entries_size) {
BUGPRINT("Wrong size\n");
return -EINVAL;
}
ret = copy_counters_to_user(t, oldcounters, tmp.counters,
tmp.num_counters, nentries);
if (ret)
return ret;
if (copy_to_user(tmp.entries, entries, entries_size)) {
BUGPRINT("Couldn't copy entries to userspace\n");
return -EFAULT;
}
/* set the match/watcher/target names right */
return EBT_ENTRY_ITERATE(entries, entries_size,
ebt_make_names, entries, tmp.entries);
}
static int do_ebt_set_ctl(struct sock *sk,
int cmd, void __user *user, unsigned int len)
{
int ret;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
switch(cmd) {
case EBT_SO_SET_ENTRIES:
ret = do_replace(sock_net(sk), user, len);
break;
case EBT_SO_SET_COUNTERS:
ret = update_counters(sock_net(sk), user, len);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int do_ebt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
int ret;
struct ebt_replace tmp;
struct ebt_table *t;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
t = find_table_lock(sock_net(sk), tmp.name, &ret, &ebt_mutex);
if (!t)
return ret;
switch(cmd) {
case EBT_SO_GET_INFO:
case EBT_SO_GET_INIT_INFO:
if (*len != sizeof(struct ebt_replace)){
ret = -EINVAL;
mutex_unlock(&ebt_mutex);
break;
}
if (cmd == EBT_SO_GET_INFO) {
tmp.nentries = t->private->nentries;
tmp.entries_size = t->private->entries_size;
tmp.valid_hooks = t->valid_hooks;
} else {
tmp.nentries = t->table->nentries;
tmp.entries_size = t->table->entries_size;
tmp.valid_hooks = t->table->valid_hooks;
}
mutex_unlock(&ebt_mutex);
if (copy_to_user(user, &tmp, *len) != 0){
BUGPRINT("c2u Didn't work\n");
ret = -EFAULT;
break;
}
ret = 0;
break;
case EBT_SO_GET_ENTRIES:
case EBT_SO_GET_INIT_ENTRIES:
ret = copy_everything_to_user(t, user, len, cmd);
mutex_unlock(&ebt_mutex);
break;
default:
mutex_unlock(&ebt_mutex);
ret = -EINVAL;
}
return ret;
}
#ifdef CONFIG_COMPAT
/* 32 bit-userspace compatibility definitions. */
struct compat_ebt_replace {
char name[EBT_TABLE_MAXNAMELEN];
compat_uint_t valid_hooks;
compat_uint_t nentries;
compat_uint_t entries_size;
/* start of the chains */
compat_uptr_t hook_entry[NF_BR_NUMHOOKS];
/* nr of counters userspace expects back */
compat_uint_t num_counters;
/* where the kernel will put the old counters. */
compat_uptr_t counters;
compat_uptr_t entries;
};
/* struct ebt_entry_match, _target and _watcher have same layout */
struct compat_ebt_entry_mwt {
union {
char name[EBT_FUNCTION_MAXNAMELEN];
compat_uptr_t ptr;
} u;
compat_uint_t match_size;
compat_uint_t data[0];
};
/* account for possible padding between match_size and ->data */
static int ebt_compat_entry_padsize(void)
{
BUILD_BUG_ON(XT_ALIGN(sizeof(struct ebt_entry_match)) <
COMPAT_XT_ALIGN(sizeof(struct compat_ebt_entry_mwt)));
return (int) XT_ALIGN(sizeof(struct ebt_entry_match)) -
COMPAT_XT_ALIGN(sizeof(struct compat_ebt_entry_mwt));
}
static int ebt_compat_match_offset(const struct xt_match *match,
unsigned int userlen)
{
/*
* ebt_among needs special handling. The kernel .matchsize is
* set to -1 at registration time; at runtime an EBT_ALIGN()ed
* value is expected.
* Example: userspace sends 4500, ebt_among.c wants 4504.
*/
if (unlikely(match->matchsize == -1))
return XT_ALIGN(userlen) - COMPAT_XT_ALIGN(userlen);
return xt_compat_match_offset(match);
}
static int compat_match_to_user(struct ebt_entry_match *m, void __user **dstptr,
unsigned int *size)
{
const struct xt_match *match = m->u.match;
struct compat_ebt_entry_mwt __user *cm = *dstptr;
int off = ebt_compat_match_offset(match, m->match_size);
compat_uint_t msize = m->match_size - off;
BUG_ON(off >= m->match_size);
if (copy_to_user(cm->u.name, match->name,
strlen(match->name) + 1) || put_user(msize, &cm->match_size))
return -EFAULT;
if (match->compat_to_user) {
if (match->compat_to_user(cm->data, m->data))
return -EFAULT;
} else if (copy_to_user(cm->data, m->data, msize))
return -EFAULT;
*size -= ebt_compat_entry_padsize() + off;
*dstptr = cm->data;
*dstptr += msize;
return 0;
}
static int compat_target_to_user(struct ebt_entry_target *t,
void __user **dstptr,
unsigned int *size)
{
const struct xt_target *target = t->u.target;
struct compat_ebt_entry_mwt __user *cm = *dstptr;
int off = xt_compat_target_offset(target);
compat_uint_t tsize = t->target_size - off;
BUG_ON(off >= t->target_size);
if (copy_to_user(cm->u.name, target->name,
strlen(target->name) + 1) || put_user(tsize, &cm->match_size))
return -EFAULT;
if (target->compat_to_user) {
if (target->compat_to_user(cm->data, t->data))
return -EFAULT;
} else if (copy_to_user(cm->data, t->data, tsize))
return -EFAULT;
*size -= ebt_compat_entry_padsize() + off;
*dstptr = cm->data;
*dstptr += tsize;
return 0;
}
static int compat_watcher_to_user(struct ebt_entry_watcher *w,
void __user **dstptr,
unsigned int *size)
{
return compat_target_to_user((struct ebt_entry_target *)w,
dstptr, size);
}
static int compat_copy_entry_to_user(struct ebt_entry *e, void __user **dstptr,
unsigned int *size)
{
struct ebt_entry_target *t;
struct ebt_entry __user *ce;
u32 watchers_offset, target_offset, next_offset;
compat_uint_t origsize;
int ret;
if (e->bitmask == 0) {
if (*size < sizeof(struct ebt_entries))
return -EINVAL;
if (copy_to_user(*dstptr, e, sizeof(struct ebt_entries)))
return -EFAULT;
*dstptr += sizeof(struct ebt_entries);
*size -= sizeof(struct ebt_entries);
return 0;
}
if (*size < sizeof(*ce))
return -EINVAL;
ce = (struct ebt_entry __user *)*dstptr;
if (copy_to_user(ce, e, sizeof(*ce)))
return -EFAULT;
origsize = *size;
*dstptr += sizeof(*ce);
ret = EBT_MATCH_ITERATE(e, compat_match_to_user, dstptr, size);
if (ret)
return ret;
watchers_offset = e->watchers_offset - (origsize - *size);
ret = EBT_WATCHER_ITERATE(e, compat_watcher_to_user, dstptr, size);
if (ret)
return ret;
target_offset = e->target_offset - (origsize - *size);
t = (struct ebt_entry_target *) ((char *) e + e->target_offset);
ret = compat_target_to_user(t, dstptr, size);
if (ret)
return ret;
next_offset = e->next_offset - (origsize - *size);
if (put_user(watchers_offset, &ce->watchers_offset) ||
put_user(target_offset, &ce->target_offset) ||
put_user(next_offset, &ce->next_offset))
return -EFAULT;
*size -= sizeof(*ce);
return 0;
}
static int compat_calc_match(struct ebt_entry_match *m, int *off)
{
*off += ebt_compat_match_offset(m->u.match, m->match_size);
*off += ebt_compat_entry_padsize();
return 0;
}
static int compat_calc_watcher(struct ebt_entry_watcher *w, int *off)
{
*off += xt_compat_target_offset(w->u.watcher);
*off += ebt_compat_entry_padsize();
return 0;
}
static int compat_calc_entry(const struct ebt_entry *e,
const struct ebt_table_info *info,
const void *base,
struct compat_ebt_replace *newinfo)
{
const struct ebt_entry_target *t;
unsigned int entry_offset;
int off, ret, i;
if (e->bitmask == 0)
return 0;
off = 0;
entry_offset = (void *)e - base;
EBT_MATCH_ITERATE(e, compat_calc_match, &off);
EBT_WATCHER_ITERATE(e, compat_calc_watcher, &off);
t = (const struct ebt_entry_target *) ((char *) e + e->target_offset);
off += xt_compat_target_offset(t->u.target);
off += ebt_compat_entry_padsize();
newinfo->entries_size -= off;
ret = xt_compat_add_offset(NFPROTO_BRIDGE, entry_offset, off);
if (ret)
return ret;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
const void *hookptr = info->hook_entry[i];
if (info->hook_entry[i] &&
(e < (struct ebt_entry *)(base - hookptr))) {
newinfo->hook_entry[i] -= off;
pr_debug("0x%08X -> 0x%08X\n",
newinfo->hook_entry[i] + off,
newinfo->hook_entry[i]);
}
}
return 0;
}
static int compat_table_info(const struct ebt_table_info *info,
struct compat_ebt_replace *newinfo)
{
unsigned int size = info->entries_size;
const void *entries = info->entries;
newinfo->entries_size = size;
xt_compat_init_offsets(AF_INET, info->nentries);
return EBT_ENTRY_ITERATE(entries, size, compat_calc_entry, info,
entries, newinfo);
}
static int compat_copy_everything_to_user(struct ebt_table *t,
void __user *user, int *len, int cmd)
{
struct compat_ebt_replace repl, tmp;
struct ebt_counter *oldcounters;
struct ebt_table_info tinfo;
int ret;
void __user *pos;
memset(&tinfo, 0, sizeof(tinfo));
if (cmd == EBT_SO_GET_ENTRIES) {
tinfo.entries_size = t->private->entries_size;
tinfo.nentries = t->private->nentries;
tinfo.entries = t->private->entries;
oldcounters = t->private->counters;
} else {
tinfo.entries_size = t->table->entries_size;
tinfo.nentries = t->table->nentries;
tinfo.entries = t->table->entries;
oldcounters = t->table->counters;
}
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
if (tmp.nentries != tinfo.nentries ||
(tmp.num_counters && tmp.num_counters != tinfo.nentries))
return -EINVAL;
memcpy(&repl, &tmp, sizeof(repl));
if (cmd == EBT_SO_GET_ENTRIES)
ret = compat_table_info(t->private, &repl);
else
ret = compat_table_info(&tinfo, &repl);
if (ret)
return ret;
if (*len != sizeof(tmp) + repl.entries_size +
(tmp.num_counters? tinfo.nentries * sizeof(struct ebt_counter): 0)) {
pr_err("wrong size: *len %d, entries_size %u, replsz %d\n",
*len, tinfo.entries_size, repl.entries_size);
return -EINVAL;
}
/* userspace might not need the counters */
ret = copy_counters_to_user(t, oldcounters, compat_ptr(tmp.counters),
tmp.num_counters, tinfo.nentries);
if (ret)
return ret;
pos = compat_ptr(tmp.entries);
return EBT_ENTRY_ITERATE(tinfo.entries, tinfo.entries_size,
compat_copy_entry_to_user, &pos, &tmp.entries_size);
}
struct ebt_entries_buf_state {
char *buf_kern_start; /* kernel buffer to copy (translated) data to */
u32 buf_kern_len; /* total size of kernel buffer */
u32 buf_kern_offset; /* amount of data copied so far */
u32 buf_user_offset; /* read position in userspace buffer */
};
static int ebt_buf_count(struct ebt_entries_buf_state *state, unsigned int sz)
{
state->buf_kern_offset += sz;
return state->buf_kern_offset >= sz ? 0 : -EINVAL;
}
static int ebt_buf_add(struct ebt_entries_buf_state *state,
void *data, unsigned int sz)
{
if (state->buf_kern_start == NULL)
goto count_only;
BUG_ON(state->buf_kern_offset + sz > state->buf_kern_len);
memcpy(state->buf_kern_start + state->buf_kern_offset, data, sz);
count_only:
state->buf_user_offset += sz;
return ebt_buf_count(state, sz);
}
static int ebt_buf_add_pad(struct ebt_entries_buf_state *state, unsigned int sz)
{
char *b = state->buf_kern_start;
BUG_ON(b && state->buf_kern_offset > state->buf_kern_len);
if (b != NULL && sz > 0)
memset(b + state->buf_kern_offset, 0, sz);
/* do not adjust ->buf_user_offset here, we added kernel-side padding */
return ebt_buf_count(state, sz);
}
enum compat_mwt {
EBT_COMPAT_MATCH,
EBT_COMPAT_WATCHER,
EBT_COMPAT_TARGET,
};
static int compat_mtw_from_user(struct compat_ebt_entry_mwt *mwt,
enum compat_mwt compat_mwt,
struct ebt_entries_buf_state *state,
const unsigned char *base)
{
char name[EBT_FUNCTION_MAXNAMELEN];
struct xt_match *match;
struct xt_target *wt;
void *dst = NULL;
int off, pad = 0, ret = 0;
unsigned int size_kern, entry_offset, match_size = mwt->match_size;
strlcpy(name, mwt->u.name, sizeof(name));
if (state->buf_kern_start)
dst = state->buf_kern_start + state->buf_kern_offset;
entry_offset = (unsigned char *) mwt - base;
switch (compat_mwt) {
case EBT_COMPAT_MATCH:
match = try_then_request_module(xt_find_match(NFPROTO_BRIDGE,
name, 0), "ebt_%s", name);
if (match == NULL)
return -ENOENT;
if (IS_ERR(match))
return PTR_ERR(match);
off = ebt_compat_match_offset(match, match_size);
if (dst) {
if (match->compat_from_user)
match->compat_from_user(dst, mwt->data);
else
memcpy(dst, mwt->data, match_size);
}
size_kern = match->matchsize;
if (unlikely(size_kern == -1))
size_kern = match_size;
module_put(match->me);
break;
case EBT_COMPAT_WATCHER: /* fallthrough */
case EBT_COMPAT_TARGET:
wt = try_then_request_module(xt_find_target(NFPROTO_BRIDGE,
name, 0), "ebt_%s", name);
if (wt == NULL)
return -ENOENT;
if (IS_ERR(wt))
return PTR_ERR(wt);
off = xt_compat_target_offset(wt);
if (dst) {
if (wt->compat_from_user)
wt->compat_from_user(dst, mwt->data);
else
memcpy(dst, mwt->data, match_size);
}
size_kern = wt->targetsize;
module_put(wt->me);
break;
}
if (!dst) {
ret = xt_compat_add_offset(NFPROTO_BRIDGE, entry_offset,
off + ebt_compat_entry_padsize());
if (ret < 0)
return ret;
}
state->buf_kern_offset += match_size + off;
state->buf_user_offset += match_size;
pad = XT_ALIGN(size_kern) - size_kern;
if (pad > 0 && dst) {
BUG_ON(state->buf_kern_len <= pad);
BUG_ON(state->buf_kern_offset - (match_size + off) + size_kern > state->buf_kern_len - pad);
memset(dst + size_kern, 0, pad);
}
return off + match_size;
}
/*
* return size of all matches, watchers or target, including necessary
* alignment and padding.
*/
static int ebt_size_mwt(struct compat_ebt_entry_mwt *match32,
unsigned int size_left, enum compat_mwt type,
struct ebt_entries_buf_state *state, const void *base)
{
int growth = 0;
char *buf;
if (size_left == 0)
return 0;
buf = (char *) match32;
while (size_left >= sizeof(*match32)) {
struct ebt_entry_match *match_kern;
int ret;
match_kern = (struct ebt_entry_match *) state->buf_kern_start;
if (match_kern) {
char *tmp;
tmp = state->buf_kern_start + state->buf_kern_offset;
match_kern = (struct ebt_entry_match *) tmp;
}
ret = ebt_buf_add(state, buf, sizeof(*match32));
if (ret < 0)
return ret;
size_left -= sizeof(*match32);
/* add padding before match->data (if any) */
ret = ebt_buf_add_pad(state, ebt_compat_entry_padsize());
if (ret < 0)
return ret;
if (match32->match_size > size_left)
return -EINVAL;
size_left -= match32->match_size;
ret = compat_mtw_from_user(match32, type, state, base);
if (ret < 0)
return ret;
BUG_ON(ret < match32->match_size);
growth += ret - match32->match_size;
growth += ebt_compat_entry_padsize();
buf += sizeof(*match32);
buf += match32->match_size;
if (match_kern)
match_kern->match_size = ret;
WARN_ON(type == EBT_COMPAT_TARGET && size_left);
match32 = (struct compat_ebt_entry_mwt *) buf;
}
return growth;
}
#define EBT_COMPAT_WATCHER_ITERATE(e, fn, args...) \
({ \
unsigned int __i; \
int __ret = 0; \
struct compat_ebt_entry_mwt *__watcher; \
\
for (__i = e->watchers_offset; \
__i < (e)->target_offset; \
__i += __watcher->watcher_size + \
sizeof(struct compat_ebt_entry_mwt)) { \
__watcher = (void *)(e) + __i; \
__ret = fn(__watcher , ## args); \
if (__ret != 0) \
break; \
} \
if (__ret == 0) { \
if (__i != (e)->target_offset) \
__ret = -EINVAL; \
} \
__ret; \
})
#define EBT_COMPAT_MATCH_ITERATE(e, fn, args...) \
({ \
unsigned int __i; \
int __ret = 0; \
struct compat_ebt_entry_mwt *__match; \
\
for (__i = sizeof(struct ebt_entry); \
__i < (e)->watchers_offset; \
__i += __match->match_size + \
sizeof(struct compat_ebt_entry_mwt)) { \
__match = (void *)(e) + __i; \
__ret = fn(__match , ## args); \
if (__ret != 0) \
break; \
} \
if (__ret == 0) { \
if (__i != (e)->watchers_offset) \
__ret = -EINVAL; \
} \
__ret; \
})
/* called for all ebt_entry structures. */
static int size_entry_mwt(struct ebt_entry *entry, const unsigned char *base,
unsigned int *total,
struct ebt_entries_buf_state *state)
{
unsigned int i, j, startoff, new_offset = 0;
/* stores match/watchers/targets & offset of next struct ebt_entry: */
unsigned int offsets[4];
unsigned int *offsets_update = NULL;
int ret;
char *buf_start;
if (*total < sizeof(struct ebt_entries))
return -EINVAL;
if (!entry->bitmask) {
*total -= sizeof(struct ebt_entries);
return ebt_buf_add(state, entry, sizeof(struct ebt_entries));
}
if (*total < sizeof(*entry) || entry->next_offset < sizeof(*entry))
return -EINVAL;
startoff = state->buf_user_offset;
/* pull in most part of ebt_entry, it does not need to be changed. */
ret = ebt_buf_add(state, entry,
offsetof(struct ebt_entry, watchers_offset));
if (ret < 0)
return ret;
offsets[0] = sizeof(struct ebt_entry); /* matches come first */
memcpy(&offsets[1], &entry->watchers_offset,
sizeof(offsets) - sizeof(offsets[0]));
if (state->buf_kern_start) {
buf_start = state->buf_kern_start + state->buf_kern_offset;
offsets_update = (unsigned int *) buf_start;
}
ret = ebt_buf_add(state, &offsets[1],
sizeof(offsets) - sizeof(offsets[0]));
if (ret < 0)
return ret;
buf_start = (char *) entry;
/*
* 0: matches offset, always follows ebt_entry.
* 1: watchers offset, from ebt_entry structure
* 2: target offset, from ebt_entry structure
* 3: next ebt_entry offset, from ebt_entry structure
*
* offsets are relative to beginning of struct ebt_entry (i.e., 0).
*/
for (i = 0, j = 1 ; j < 4 ; j++, i++) {
struct compat_ebt_entry_mwt *match32;
unsigned int size;
char *buf = buf_start;
buf = buf_start + offsets[i];
if (offsets[i] > offsets[j])
return -EINVAL;
match32 = (struct compat_ebt_entry_mwt *) buf;
size = offsets[j] - offsets[i];
ret = ebt_size_mwt(match32, size, i, state, base);
if (ret < 0)
return ret;
new_offset += ret;
if (offsets_update && new_offset) {
pr_debug("change offset %d to %d\n",
offsets_update[i], offsets[j] + new_offset);
offsets_update[i] = offsets[j] + new_offset;
}
}
startoff = state->buf_user_offset - startoff;
BUG_ON(*total < startoff);
*total -= startoff;
return 0;
}
/*
* repl->entries_size is the size of the ebt_entry blob in userspace.
* It might need more memory when copied to a 64 bit kernel in case
* userspace is 32-bit. So, first task: find out how much memory is needed.
*
* Called before validation is performed.
*/
static int compat_copy_entries(unsigned char *data, unsigned int size_user,
struct ebt_entries_buf_state *state)
{
unsigned int size_remaining = size_user;
int ret;
ret = EBT_ENTRY_ITERATE(data, size_user, size_entry_mwt, data,
&size_remaining, state);
if (ret < 0)
return ret;
WARN_ON(size_remaining);
return state->buf_kern_offset;
}
static int compat_copy_ebt_replace_from_user(struct ebt_replace *repl,
void __user *user, unsigned int len)
{
struct compat_ebt_replace tmp;
int i;
if (len < sizeof(tmp))
return -EINVAL;
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
if (len != sizeof(tmp) + tmp.entries_size)
return -EINVAL;
if (tmp.entries_size == 0)
return -EINVAL;
if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) /
NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter))
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter))
return -ENOMEM;
memcpy(repl, &tmp, offsetof(struct ebt_replace, hook_entry));
/* starting with hook_entry, 32 vs. 64 bit structures are different */
for (i = 0; i < NF_BR_NUMHOOKS; i++)
repl->hook_entry[i] = compat_ptr(tmp.hook_entry[i]);
repl->num_counters = tmp.num_counters;
repl->counters = compat_ptr(tmp.counters);
repl->entries = compat_ptr(tmp.entries);
return 0;
}
static int compat_do_replace(struct net *net, void __user *user,
unsigned int len)
{
int ret, i, countersize, size64;
struct ebt_table_info *newinfo;
struct ebt_replace tmp;
struct ebt_entries_buf_state state;
void *entries_tmp;
ret = compat_copy_ebt_replace_from_user(&tmp, user, len);
if (ret) {
/* try real handler in case userland supplied needed padding */
if (ret == -EINVAL && do_replace(net, user, len) == 0)
ret = 0;
return ret;
}
countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
if (!newinfo)
return -ENOMEM;
if (countersize)
memset(newinfo->counters, 0, countersize);
memset(&state, 0, sizeof(state));
newinfo->entries = vmalloc(tmp.entries_size);
if (!newinfo->entries) {
ret = -ENOMEM;
goto free_newinfo;
}
if (copy_from_user(
newinfo->entries, tmp.entries, tmp.entries_size) != 0) {
ret = -EFAULT;
goto free_entries;
}
entries_tmp = newinfo->entries;
xt_compat_lock(NFPROTO_BRIDGE);
ret = compat_copy_entries(entries_tmp, tmp.entries_size, &state);
if (ret < 0)
goto out_unlock;
pr_debug("tmp.entries_size %d, kern off %d, user off %d delta %d\n",
tmp.entries_size, state.buf_kern_offset, state.buf_user_offset,
xt_compat_calc_jump(NFPROTO_BRIDGE, tmp.entries_size));
size64 = ret;
newinfo->entries = vmalloc(size64);
if (!newinfo->entries) {
vfree(entries_tmp);
ret = -ENOMEM;
goto out_unlock;
}
memset(&state, 0, sizeof(state));
state.buf_kern_start = newinfo->entries;
state.buf_kern_len = size64;
ret = compat_copy_entries(entries_tmp, tmp.entries_size, &state);
BUG_ON(ret < 0); /* parses same data again */
vfree(entries_tmp);
tmp.entries_size = size64;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
char __user *usrptr;
if (tmp.hook_entry[i]) {
unsigned int delta;
usrptr = (char __user *) tmp.hook_entry[i];
delta = usrptr - tmp.entries;
usrptr += xt_compat_calc_jump(NFPROTO_BRIDGE, delta);
tmp.hook_entry[i] = (struct ebt_entries __user *)usrptr;
}
}
xt_compat_flush_offsets(NFPROTO_BRIDGE);
xt_compat_unlock(NFPROTO_BRIDGE);
ret = do_replace_finish(net, &tmp, newinfo);
if (ret == 0)
return ret;
free_entries:
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
return ret;
out_unlock:
xt_compat_flush_offsets(NFPROTO_BRIDGE);
xt_compat_unlock(NFPROTO_BRIDGE);
goto free_entries;
}
static int compat_update_counters(struct net *net, void __user *user,
unsigned int len)
{
struct compat_ebt_replace hlp;
if (copy_from_user(&hlp, user, sizeof(hlp)))
return -EFAULT;
/* try real handler in case userland supplied needed padding */
if (len != sizeof(hlp) + hlp.num_counters * sizeof(struct ebt_counter))
return update_counters(net, user, len);
return do_update_counters(net, hlp.name, compat_ptr(hlp.counters),
hlp.num_counters, user, len);
}
static int compat_do_ebt_set_ctl(struct sock *sk,
int cmd, void __user *user, unsigned int len)
{
int ret;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case EBT_SO_SET_ENTRIES:
ret = compat_do_replace(sock_net(sk), user, len);
break;
case EBT_SO_SET_COUNTERS:
ret = compat_update_counters(sock_net(sk), user, len);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int compat_do_ebt_get_ctl(struct sock *sk, int cmd,
void __user *user, int *len)
{
int ret;
struct compat_ebt_replace tmp;
struct ebt_table *t;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
/* try real handler in case userland supplied needed padding */
if ((cmd == EBT_SO_GET_INFO ||
cmd == EBT_SO_GET_INIT_INFO) && *len != sizeof(tmp))
return do_ebt_get_ctl(sk, cmd, user, len);
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
t = find_table_lock(sock_net(sk), tmp.name, &ret, &ebt_mutex);
if (!t)
return ret;
xt_compat_lock(NFPROTO_BRIDGE);
switch (cmd) {
case EBT_SO_GET_INFO:
tmp.nentries = t->private->nentries;
ret = compat_table_info(t->private, &tmp);
if (ret)
goto out;
tmp.valid_hooks = t->valid_hooks;
if (copy_to_user(user, &tmp, *len) != 0) {
ret = -EFAULT;
break;
}
ret = 0;
break;
case EBT_SO_GET_INIT_INFO:
tmp.nentries = t->table->nentries;
tmp.entries_size = t->table->entries_size;
tmp.valid_hooks = t->table->valid_hooks;
if (copy_to_user(user, &tmp, *len) != 0) {
ret = -EFAULT;
break;
}
ret = 0;
break;
case EBT_SO_GET_ENTRIES:
case EBT_SO_GET_INIT_ENTRIES:
/*
* try real handler first in case of userland-side padding.
* in case we are dealing with an 'ordinary' 32 bit binary
* without 64bit compatibility padding, this will fail right
* after copy_from_user when the *len argument is validated.
*
* the compat_ variant needs to do one pass over the kernel
* data set to adjust for size differences before it the check.
*/
if (copy_everything_to_user(t, user, len, cmd) == 0)
ret = 0;
else
ret = compat_copy_everything_to_user(t, user, len, cmd);
break;
default:
ret = -EINVAL;
}
out:
xt_compat_flush_offsets(NFPROTO_BRIDGE);
xt_compat_unlock(NFPROTO_BRIDGE);
mutex_unlock(&ebt_mutex);
return ret;
}
#endif
static struct nf_sockopt_ops ebt_sockopts =
{
.pf = PF_INET,
.set_optmin = EBT_BASE_CTL,
.set_optmax = EBT_SO_SET_MAX + 1,
.set = do_ebt_set_ctl,
#ifdef CONFIG_COMPAT
.compat_set = compat_do_ebt_set_ctl,
#endif
.get_optmin = EBT_BASE_CTL,
.get_optmax = EBT_SO_GET_MAX + 1,
.get = do_ebt_get_ctl,
#ifdef CONFIG_COMPAT
.compat_get = compat_do_ebt_get_ctl,
#endif
.owner = THIS_MODULE,
};
static int __init ebtables_init(void)
{
int ret;
ret = xt_register_target(&ebt_standard_target);
if (ret < 0)
return ret;
ret = nf_register_sockopt(&ebt_sockopts);
if (ret < 0) {
xt_unregister_target(&ebt_standard_target);
return ret;
}
printk(KERN_INFO "Ebtables v2.0 registered\n");
return 0;
}
static void __exit ebtables_fini(void)
{
nf_unregister_sockopt(&ebt_sockopts);
xt_unregister_target(&ebt_standard_target);
printk(KERN_INFO "Ebtables v2.0 unregistered\n");
}
EXPORT_SYMBOL(ebt_register_table);
EXPORT_SYMBOL(ebt_unregister_table);
EXPORT_SYMBOL(ebt_do_table);
module_init(ebtables_init);
module_exit(ebtables_fini);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3443_0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.