예제 #1
0
/*
   Any time an access gets denied this callback will be called
   with the audit data.  We then need to just copy the audit data into the msgbuf.
*/
static int audit_callback(
                void *auditdata,
                security_class_t cls,
                char *msgbuf,
                size_t msgbufsize) {

        const struct audit_info *audit = auditdata;
        uid_t uid = 0, login_uid = 0;
        gid_t gid = 0;
        char login_uid_buf[DECIMAL_STR_MAX(uid_t) + 1] = "n/a";
        char uid_buf[DECIMAL_STR_MAX(uid_t) + 1] = "n/a";
        char gid_buf[DECIMAL_STR_MAX(gid_t) + 1] = "n/a";

        if (sd_bus_creds_get_audit_login_uid(audit->creds, &login_uid) >= 0)
                xsprintf(login_uid_buf, UID_FMT, login_uid);
        if (sd_bus_creds_get_euid(audit->creds, &uid) >= 0)
                xsprintf(uid_buf, UID_FMT, uid);
        if (sd_bus_creds_get_egid(audit->creds, &gid) >= 0)
                xsprintf(gid_buf, GID_FMT, gid);

        snprintf(msgbuf, msgbufsize,
                 "auid=%s uid=%s gid=%s%s%s%s%s%s%s",
                 login_uid_buf, uid_buf, gid_buf,
                 audit->path ? " path=\"" : "", strempty(audit->path), audit->path ? "\"" : "",
                 audit->cmdline ? " cmdline=\"" : "", strempty(audit->cmdline), audit->cmdline ? "\"" : "");

        return 0;
}
예제 #2
0
파일: filter.c 프로젝트: Ethylix/child
int match_rules (struct ruleset *rule, struct ruleset *packet)
{
    int param = REG_EXTENDED|REG_NOSUB;

    if (rule->rule != packet->rule || rule->direction != packet->direction)
        return 0;

    if (!strempty(rule->from)) {
        if (Strcmp(rule->from, packet->from))
            return 0;
    }

    if (!strempty(rule->to)) {
        if (Strcmp(rule->to, packet->to))
            return 0;
    }

    if (!strempty(rule->action)) {
        if (Strcmp(rule->action, packet->action))
            return 0;
    }

    if (!strempty(rule->data)) {
        if (rule->icase)
            param |= REG_ICASE;
        if (!__match_regex(rule->data, packet->data, param))
            return 0;
    }

    return 1;
}
예제 #3
0
void bus_match_dump(struct bus_match_node *node, unsigned level) {
        struct bus_match_node *c;
        _cleanup_free_ char *pfx = NULL;
        char buf[32];

        if (!node)
                return;

        pfx = strrep("  ", level);
        printf("%s[%s]", strempty(pfx), bus_match_node_type_to_string(node->type, buf, sizeof(buf)));

        if (node->type == BUS_MATCH_VALUE) {
                if (node->parent->type == BUS_MATCH_MESSAGE_TYPE)
                        printf(" <%u>\n", node->value.u8);
                else
                        printf(" <%s>\n", node->value.str);
        } else if (node->type == BUS_MATCH_ROOT)
                puts(" root");
        else if (node->type == BUS_MATCH_LEAF)
                printf(" %p/%p\n", node->leaf.callback, node->leaf.userdata);
        else
                putchar('\n');

        if (BUS_MATCH_CAN_HASH(node->type)) {
                Iterator i;

                HASHMAP_FOREACH(c, node->compare.children, i)
                        bus_match_dump(c, level + 1);
        }

        for (c = node->child; c; c = c->next)
                bus_match_dump(c, level + 1);
}
예제 #4
0
static int load_env_file_push(const char *filename, unsigned line,
                              const char *key, char *value, void *userdata) {
    char ***m = userdata;
    char *p;
    int r;

    if (!utf8_is_valid(key)) {
        log_error("%s:%u: invalid UTF-8 for key '%s', ignoring.",
                  filename, line, key);
        return -EINVAL;
    }

    if (value && !utf8_is_valid(value)) {
        /* FIXME: filter UTF-8 */
        log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.",
                  filename, line, key, value);
        return -EINVAL;
    }

    p = strjoin(key, "=", strempty(value), NULL);
    if (!p)
        return -ENOMEM;

    r = strv_push(m, p);
    if (r < 0) {
        free(p);
        return r;
    }

    free(value);
    return 0;
}
예제 #5
0
파일: db.cpp 프로젝트: nyaxt/ptnk
DB::DB(const char* filename, ptnk_opts_t opts, int mode)
{
	if(opts & OHELPERTHREAD)
	{
		m_helper.reset(new Helper);	
	}

	if(! strempty(filename) && (opts & OPARTITIONED))
	{
		PartitionedPageIO* ppio;
		m_pio.reset((ppio = new PartitionedPageIO(filename, opts, mode)));
		if(m_helper)
		{
			ppio->attachHelper(m_helper.get());
			ppio->setHookAddNewPartition([this] () {
				m_helper->enq([this] () {
					this->handleHookAddNewPartition();
				});
			});
		}
	}
	else
	{
		m_pio.reset(new PageIOMem(filename, opts, mode));
	}

	m_tpio.reset(new TPIO(m_pio, opts));
	initCommon();
}
예제 #6
0
static int load_env_file_push(
                const char *filename, unsigned line,
                const char *key, char *value,
                void *userdata) {
        char ***m = userdata;
        char *p;
        int r;

        if (!utf8_is_valid(key)) {
                _cleanup_free_ char *t = utf8_escape_invalid(key);

                log_error("%s:%u: invalid UTF-8 for key '%s', ignoring.", strna(filename), line, t);
                return -EINVAL;
        }

        if (value && !utf8_is_valid(value)) {
                _cleanup_free_ char *t = utf8_escape_invalid(value);

                log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, t);
                return -EINVAL;
        }

        p = strjoin(key, "=", strempty(value), NULL);
        if (!p)
                return -ENOMEM;

        r = strv_consume(m, p);
        if (r < 0)
                return r;

        free(value);
        return 0;
}
예제 #7
0
static int warn_wall(Manager *m, usec_t n) {
        char date[FORMAT_TIMESTAMP_MAX] = {};
        _cleanup_free_ char *l = NULL;
        usec_t left;
        int r;

        assert(m);

        if (!m->enable_wall_messages)
                return 0;

        left = m->scheduled_shutdown_timeout > n;

        r = asprintf(&l, "%s%sThe system is going down for %s %s%s!",
                     strempty(m->wall_message),
                     isempty(m->wall_message) ? "" : "\n",
                     m->scheduled_shutdown_type,
                     left ? "at " : "NOW",
                     left ? format_timestamp(date, sizeof(date), m->scheduled_shutdown_timeout) : "");
        if (r < 0) {
                log_oom();
                return 0;
        }

        utmp_wall(l, uid_to_name(m->scheduled_shutdown_uid),
                  m->scheduled_shutdown_tty, logind_wall_tty_filter, m);

        return 1;
}
예제 #8
0
int introspect_write_interface(struct introspect *i, const char *interface, const sd_bus_vtable *v) {
        assert(i);
        assert(interface);
        assert(v);

        fprintf(i->f, " <interface name=\"%s\">\n", interface);

        for (; v->type != _SD_BUS_VTABLE_END; v++) {

                switch (v->type) {

                case _SD_BUS_VTABLE_START:
                        if (v->flags & SD_BUS_VTABLE_DEPRECATED)
                                fputs("  <annotation name=\"org.freedesktop.DBus.Deprecated\" value=\"true\"/>\n", i->f);
                        break;

                case _SD_BUS_VTABLE_METHOD:
                        fprintf(i->f, "  <method name=\"%s\">\n", v->x.method.member);
                        introspect_write_arguments(i, strempty(v->x.method.signature), "in");
                        introspect_write_arguments(i, strempty(v->x.method.result), "out");
                        introspect_write_flags(i, v->type, v->flags);
                        fputs("  </method>\n", i->f);
                        break;

                case _SD_BUS_VTABLE_PROPERTY:
                case _SD_BUS_VTABLE_WRITABLE_PROPERTY:
                        fprintf(i->f, "  <property name=\"%s\" type=\"%s\" access=\"%s\">\n",
                                v->x.property.member,
                                v->x.property.signature,
                                v->type == _SD_BUS_VTABLE_WRITABLE_PROPERTY ? "readwrite" : "read");
                        introspect_write_flags(i, v->type, v->flags);
                        fputs("  </property>\n", i->f);
                        break;

                case _SD_BUS_VTABLE_SIGNAL:
                        fprintf(i->f, "  <signal name=\"%s\">\n", v->x.signal.member);
                        introspect_write_arguments(i, strempty(v->x.signal.signature), NULL);
                        introspect_write_flags(i, v->type, v->flags);
                        fputs("  </signal>\n", i->f);
                        break;
                }

        }

        fputs(" </interface>\n", i->f);
        return 0;
}
예제 #9
0
파일: scan.c 프로젝트: apc-llc/cernlib
/***********************************************************************
 *                                                                     *
 *   Copy selected items from the left list to the right list.         *
 *                                                                     *
 ***********************************************************************/
static void copy_cb(Widget w, XtPointer cd, XmAnyCallbackStruct *cbs)
{
   int         icnt, pos, pcnt, *posl;
   XmString   *items;

   if (XmListGetSelectedPos(var2NtSList, &posl, &pcnt)) {
      pos = posl[pcnt-1] + 1;
      XtFree((char *)posl);
   } else
      pos = 0;
   XmListDeselectAllItems(var2NtSList);

   if (w == exprNtSText) {

      char     *expr = XmTextGetString(w);

      if (!strempty(expr)) {
         XmString xms = XmStringCreateSimple(expr);

         XmListAddItem(var2NtSList, xms, pos);

         XmStringFree(xms);
      }
      XtFree(expr);

      /*
       * ugly... I don't want to show the scanner after hitting the
       * KActivate in the text widget
       */
      no_scan = True;

   } else if (w == copyNtSButton) {

      XtVaGetValues(var1NtSList, XmNselectedItemCount, &icnt,
                                 XmNselectedItems,     &items,
                                 NULL);

      XmListAddItems(var2NtSList, items, icnt, pos);

   } else if (w == copyAllNtSButton) {

      XtVaGetValues(var1NtSList, XmNitemCount, &icnt,
                                 XmNitems,     &items,
                                 NULL);

      clear_selector_columns(2);
      XmListAddItems(var2NtSList, items, icnt, pos);

   } else if (w == var1NtSList) {

      XmListCallbackStruct *cbsl = (XmListCallbackStruct *) cbs;
      if (cbsl->event->type == ButtonRelease)
         XmListAddItem(var2NtSList, cbsl->item, pos);

   }
   XmListSelectPos(var2NtSList, pos, False);
}
예제 #10
0
/* handle "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
int util_resolve_subsys_kernel(const char *string, char *result, size_t maxsize, bool read_value) {
        char temp[UTIL_PATH_SIZE], *subsys, *sysname, *attr;
        _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
        const char *val;
        int r;

        if (string[0] != '[')
                return -EINVAL;

        strscpy(temp, sizeof(temp), string);

        subsys = &temp[1];

        sysname = strchr(subsys, '/');
        if (!sysname)
                return -EINVAL;
        sysname[0] = '\0';
        sysname = &sysname[1];

        attr = strchr(sysname, ']');
        if (!attr)
                return -EINVAL;
        attr[0] = '\0';
        attr = &attr[1];
        if (attr[0] == '/')
                attr = &attr[1];
        if (attr[0] == '\0')
                attr = NULL;

        if (read_value && !attr)
                return -EINVAL;

        r = sd_device_new_from_subsystem_sysname(&dev, subsys, sysname);
        if (r < 0)
                return r;

        if (read_value) {
                r = sd_device_get_sysattr_value(dev, attr, &val);
                if (r < 0 && r != -ENOENT)
                        return r;
                if (r == -ENOENT)
                        result[0] = '\0';
                else
                        strscpy(result, maxsize, val);
                log_debug("value '[%s/%s]%s' is '%s'", subsys, sysname, attr, result);
        } else {
                r = sd_device_get_syspath(dev, &val);
                if (r < 0)
                        return r;

                strscpyl(result, maxsize, val, attr ? "/" : NULL, attr ?: NULL, NULL);
                log_debug("path '[%s/%s]%s' is '%s'", subsys, sysname, strempty(attr), result);
        }
        return 0;
}
예제 #11
0
static void test_conf_files_insert(const char *root) {
        _cleanup_strv_free_ char **s = NULL;

        log_info("/* %s root=%s */", __func__, strempty(root));

        char **dirs = STRV_MAKE("/dir1", "/dir2", "/dir3");

        _cleanup_free_ const char
                *foo1 = prefix_root(root, "/dir1/foo.conf"),
                *foo2 = prefix_root(root, "/dir2/foo.conf"),
                *bar2 = prefix_root(root, "/dir2/bar.conf"),
                *zzz3 = prefix_root(root, "/dir3/zzz.conf"),
                *whatever = prefix_root(root, "/whatever.conf");

        assert_se(conf_files_insert(&s, root, dirs, "/dir2/foo.conf") == 0);
        assert_se(strv_equal(s, STRV_MAKE(foo2)));

        /* The same file again, https://github.com/systemd/systemd/issues/11124 */
        assert_se(conf_files_insert(&s, root, dirs, "/dir2/foo.conf") == 0);
        assert_se(strv_equal(s, STRV_MAKE(foo2)));

        /* Lower priority → new entry is ignored */
        assert_se(conf_files_insert(&s, root, dirs, "/dir3/foo.conf") == 0);
        assert_se(strv_equal(s, STRV_MAKE(foo2)));

        /* Higher priority → new entry replaces */
        assert_se(conf_files_insert(&s, root, dirs, "/dir1/foo.conf") == 0);
        assert_se(strv_equal(s, STRV_MAKE(foo1)));

        /* Earlier basename */
        assert_se(conf_files_insert(&s, root, dirs, "/dir2/bar.conf") == 0);
        assert_se(strv_equal(s, STRV_MAKE(bar2, foo1)));

        /* Later basename */
        assert_se(conf_files_insert(&s, root, dirs, "/dir3/zzz.conf") == 0);
        assert_se(strv_equal(s, STRV_MAKE(bar2, foo1, zzz3)));

        /* All lower priority → all ignored */
        assert_se(conf_files_insert(&s, root, dirs, "/dir3/zzz.conf") == 0);
        assert_se(conf_files_insert(&s, root, dirs, "/dir2/bar.conf") == 0);
        assert_se(conf_files_insert(&s, root, dirs, "/dir3/bar.conf") == 0);
        assert_se(conf_files_insert(&s, root, dirs, "/dir2/foo.conf") == 0);
        assert_se(strv_equal(s, STRV_MAKE(bar2, foo1, zzz3)));

        /* Two entries that don't match any of the directories, but match basename */
        assert_se(conf_files_insert(&s, root, dirs, "/dir4/zzz.conf") == 0);
        assert_se(conf_files_insert(&s, root, dirs, "/zzz.conf") == 0);
        assert_se(strv_equal(s, STRV_MAKE(bar2, foo1, zzz3)));

        /* An entry that doesn't match any of the directories, no match at all */
        assert_se(conf_files_insert(&s, root, dirs, "/whatever.conf") == 0);
        assert_se(strv_equal(s, STRV_MAKE(bar2, foo1, whatever, zzz3)));
}
예제 #12
0
_public_ int sd_bus_set_property(
                sd_bus *bus,
                const char *destination,
                const char *path,
                const char *interface,
                const char *member,
                sd_bus_error *error,
                const char *type, ...) {

        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
        va_list ap;
        int r;

        bus_assert_return(bus, -EINVAL, error);
        bus_assert_return(isempty(interface) || interface_name_is_valid(interface), -EINVAL, error);
        bus_assert_return(member_name_is_valid(member), -EINVAL, error);
        bus_assert_return(signature_is_single(type, false), -EINVAL, error);
        bus_assert_return(!bus_pid_changed(bus), -ECHILD, error);

        if (!BUS_IS_OPEN(bus->state)) {
                r = -ENOTCONN;
                goto fail;
        }

        r = sd_bus_message_new_method_call(bus, &m, destination, path, "org.freedesktop.DBus.Properties", "Set");
        if (r < 0)
                goto fail;

        r = sd_bus_message_append(m, "ss", strempty(interface), member);
        if (r < 0)
                goto fail;

        r = sd_bus_message_open_container(m, 'v', type);
        if (r < 0)
                goto fail;

        va_start(ap, type);
        r = sd_bus_message_appendv(m, type, ap);
        va_end(ap);
        if (r < 0)
                goto fail;

        r = sd_bus_message_close_container(m);
        if (r < 0)
                goto fail;

        return sd_bus_call(bus, m, 0, error, NULL);

fail:
        return sd_bus_error_set_errno(error, r);
}
예제 #13
0
파일: HttpHelper.cpp 프로젝트: azalpy/sdk
void HttpHelper::SetStatus(int status, const char* reason)
{
	m_status = status;
	if(strempty(reason))
	{
		THttpStatus::const_iterator it = sm_status.find(status);
		if(it != sm_status.end())
		{
			m_reason = it->second;
			return;
		}
	}
	m_reason = reason;
}
예제 #14
0
static int pppoe_send_initiation(sd_pppoe *ppp) {
        int r;

        r = pppoe_send(ppp, PADI_CODE);
        if (r < 0)
                return r;

        log_debug("PPPoE: sent DISCOVER (Service-Name: %s)",
                  strempty(ppp->service_name));

        pppoe_arm_timeout(ppp);

        return r;
}
예제 #15
0
파일: filter.c 프로젝트: Ethylix/child
int filter_check (char *line, int direction)
{
    if (rule_list.enabled == 0)
        return -1;

    struct ruleset *rule, *last = NULL, packet;
    memset(&packet, 0, sizeof(packet));

    char *from, *action, *to, *data;
    char temp[1024];
    strncpy(temp, line, 1023);

    from = temp;
    action = SeperateWord(from);
    to = SeperateWord(action);
    data = SeperateWord(to);

    if (strempty(from))
        return -1;

    if (*from == ':')
        from++;

    packet.direction = direction;
    strncpy(packet.from, from, NICKLEN);
    if (action)
        strncpy(packet.action, action, 128);
    if (to)
        strncpy(packet.to, to, NICKLEN);
    if (data) {
        if (*data == ':')
            data++;
        strncpy(packet.data, data, 1023);
    }

    for (rule = rule_list.ltail; rule; rule = rule->lprev) {
        packet.rule = rule->rule;
        if ((match_rules(rule, &packet)) == 1) {
            last = rule;
            if (rule->quick == 1)
                return rule->rule;
        }
    }

    if (last)
        return last->rule;

    return -1;
}
예제 #16
0
파일: kill.c 프로젝트: dankor/systemd
void kill_context_dump(KillContext *c, FILE *f, const char *prefix) {
        assert(c);

        prefix = strempty(prefix);

        fprintf(f,
                "%sKillMode: %s\n"
                "%sKillSignal: SIG%s\n"
                "%sSendSIGKILL: %s\n"
                "%sSendSIGHUP:  %s\n",
                prefix, kill_mode_to_string(c->kill_mode),
                prefix, signal_to_string(c->kill_signal),
                prefix, yes_no(c->send_sigkill),
                prefix, yes_no(c->send_sighup));
}
예제 #17
0
/*
   Any time an access gets denied this callback will be called
   with the aduit data.  We then need to just copy the audit data into the msgbuf.
*/
static int audit_callback(
                void *auditdata,
                security_class_t cls,
                char *msgbuf,
                size_t msgbufsize) {

        const struct audit_info *audit = auditdata;
        uid_t uid = 0, login_uid = 0;
        gid_t gid = 0;

        sd_bus_creds_get_audit_login_uid(audit->creds, &login_uid);
        sd_bus_creds_get_uid(audit->creds, &uid);
        sd_bus_creds_get_gid(audit->creds, &gid);

        snprintf(msgbuf, msgbufsize,
                 "auid=%d uid=%d gid=%d%s%s%s%s%s%s",
                 login_uid, uid, gid,
                 audit->path ? " path=\"" : "", strempty(audit->path), audit->path ? "\"" : "",
                 audit->cmdline ? " cmdline=\"" : "", strempty(audit->cmdline), audit->cmdline ? "\"" : "");

        msgbuf[msgbufsize-1] = 0;

        return 0;
}
예제 #18
0
int sysctl_write_ip_property(int af, const char *ifname, const char *property, const char *value) {
        const char *p;

        assert(IN_SET(af, AF_INET, AF_INET6));
        assert(property);
        assert(value);

        p = strjoina("/proc/sys/net/ipv", af == AF_INET ? "4" : "6",
                     ifname ? "/conf/" : "", strempty(ifname),
                     property[0] == '/' ? "" : "/", property);

        log_debug("Setting '%s' to '%s'", p, value);

        return write_string_file(p, value, WRITE_STRING_FILE_VERIFY_ON_FAILURE | WRITE_STRING_FILE_DISABLE_BUFFER);
}
예제 #19
0
/*
   Any time an access gets denied this callback will be called
   with the aduit data.  We then need to just copy the audit data into the msgbuf.
*/
static int audit_callback(
                void *auditdata,
                security_class_t cls,
                char *msgbuf,
                size_t msgbufsize) {

        struct auditstruct *audit = (struct auditstruct *) auditdata;

        snprintf(msgbuf, msgbufsize,
                 "auid=%d uid=%d gid=%d%s%s%s%s%s%s",
                 audit->loginuid,
                 audit->uid,
                 audit->gid,
                 (audit->path ? " path=\"" : ""),
                 strempty(audit->path),
                 (audit->path ? "\"" : ""),
                 (audit->cmdline ? " cmdline=\"" : ""),
                 strempty(audit->cmdline),
                 (audit->cmdline ? "\"" : ""));

        msgbuf[msgbufsize-1] = 0;

        return 0;
}
예제 #20
0
static void test_mount_points_list(const char *fname) {
        _cleanup_(mount_points_list_free) LIST_HEAD(MountPoint, mp_list_head);
        MountPoint *m;

        log_info("/* %s(\"%s\") */", __func__, fname ?: "/proc/self/mountinfo");

        LIST_HEAD_INIT(mp_list_head);
        assert_se(mount_points_list_get(fname, &mp_list_head) >= 0);

        LIST_FOREACH(mount_point, m, mp_list_head)
                log_debug("path=%s o=%s f=0x%lx try-ro=%s dev=%u:%u",
                          m->path,
                          strempty(m->remount_options),
                          m->remount_flags,
                          yes_no(m->try_remount_ro),
                          major(m->devnum), minor(m->devnum));
}
예제 #21
0
static int mount_legacy_cgroup_hierarchy(
                const char *dest,
                const char *controller,
                const char *hierarchy,
                bool read_only) {

        const char *to, *fstype, *opts;
        int r;

        to = strjoina(strempty(dest), "/sys/fs/cgroup/", hierarchy);

        r = path_is_mount_point(to, dest, 0);
        if (r < 0 && r != -ENOENT)
                return log_error_errno(r, "Failed to determine if %s is mounted already: %m", to);
        if (r > 0)
                return 0;

        mkdir_p(to, 0755);

        /* The superblock mount options of the mount point need to be
         * identical to the hosts', and hence writable... */
        if (streq(controller, SYSTEMD_CGROUP_CONTROLLER_HYBRID)) {
                fstype = "cgroup2";
                opts = NULL;
        } else if (streq(controller, SYSTEMD_CGROUP_CONTROLLER_LEGACY)) {
                fstype = "cgroup";
                opts = "none,name=systemd,xattr";
        } else {
                fstype = "cgroup";
                opts = controller;
        }

        r = mount_verbose(LOG_ERR, "cgroup", to, fstype, MS_NOSUID|MS_NOEXEC|MS_NODEV, opts);
        if (r < 0)
                return r;

        /* ... hence let's only make the bind mount read-only, not the superblock. */
        if (read_only) {
                r = mount_verbose(LOG_ERR, NULL, to, NULL,
                                  MS_BIND|MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY, NULL);
                if (r < 0)
                        return r;
        }

        return 1;
}
예제 #22
0
static void test_unhexmem_one(const char *s, size_t l, int retval) {
        _cleanup_free_ char *hex = NULL;
        _cleanup_free_ void *mem = NULL;
        size_t len;

        assert_se(unhexmem(s, l, &mem, &len) == retval);
        if (retval == 0) {
                char *answer;

                if (l == (size_t) -1)
                        l = strlen(s);

                assert_se(hex = hexmem(mem, len));
                answer = strndupa(strempty(s), l);
                assert_se(streq(delete_chars(answer, WHITESPACE), hex));
        }
}
예제 #23
0
파일: fileio.c 프로젝트: Miss6yka/systemd
static int load_env_file_push(const char *key, char *value, void *userdata) {
        char ***m = userdata;
        char *p;
        int r;

        p = strjoin(key, "=", strempty(value), NULL);
        if (!p)
                return -ENOMEM;

        r = strv_push(m, p);
        if (r < 0) {
                free(p);
                return r;
        }

        free(value);
        return 0;
}
예제 #24
0
void server_forward_wall(
                Server *s,
                int priority,
                const char *identifier,
                const char *message,
                const struct ucred *ucred) {

        _cleanup_free_ char *ident_buf = NULL, *l_buf = NULL;
        const char *l;
        int r;

        assert(s);
        assert(message);

        if (LOG_PRI(priority) > s->max_level_wall)
                return;

        if (ucred) {
                if (!identifier) {
                        get_process_comm(ucred->pid, &ident_buf);
                        identifier = ident_buf;
                }

                if (asprintf(&l_buf, "%s["PID_FMT"]: %s", strempty(identifier), ucred->pid, message) < 0) {
                        log_oom();
                        return;
                }

                l = l_buf;

        } else if (identifier) {

                l = l_buf = strjoin(identifier, ": ", message, NULL);
                if (!l_buf) {
                        log_oom();
                        return;
                }
        } else
                l = message;

        r = utmp_wall(l, "systemd-journald", NULL, NULL, NULL);
        if (r < 0)
                log_debug_errno(r, "Failed to send wall message: %m");
}
예제 #25
0
static int specifier_instance(char specifier, void *data, void *userdata, char **ret) {
        const UnitFileInstallInfo *i = userdata;
        char *instance;
        int r;

        assert(i);

        r = unit_name_to_instance(i->name, &instance);
        if (r < 0)
                return r;

        if (isempty(instance)) {
                r = free_and_strdup(&instance, strempty(i->default_instance));
                if (r < 0)
                        return r;
        }

        *ret = instance;
        return 0;
}
예제 #26
0
int sysctl_read_ip_property(int af, const char *ifname, const char *property, char **ret) {
        _cleanup_free_ char *value = NULL;
        const char *p;
        int r;

        assert(IN_SET(af, AF_INET, AF_INET6));
        assert(property);

        p = strjoina("/proc/sys/net/ipv", af == AF_INET ? "4" : "6",
                     ifname ? "/conf/" : "", strempty(ifname),
                     property[0] == '/' ? "" : "/", property);

        r = read_one_line_file(p, &value);
        if (r < 0)
                return r;

        if (ret)
                *ret = TAKE_PTR(value);

        return r;
}
static int setup_monitor(MonitorNetlinkGroup sender, sd_event *event, sd_device_monitor **ret) {
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
        const char *subsystem, *devtype, *tag;
        Iterator i;
        int r;

        r = device_monitor_new_full(&monitor, sender, -1);
        if (r < 0)
                return log_error_errno(r, "Failed to create netlink socket: %m");

        (void) sd_device_monitor_set_receive_buffer_size(monitor, 128*1024*1024);

        r = sd_device_monitor_attach_event(monitor, event);
        if (r < 0)
                return log_error_errno(r, "Failed to attach event: %m");

        HASHMAP_FOREACH_KEY(devtype, subsystem, arg_subsystem_filter, i) {
                r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, subsystem, devtype);
                if (r < 0)
                        return log_error_errno(r, "Failed to apply subsystem filter '%s%s%s': %m",
                                               subsystem, devtype ? "/" : "", strempty(devtype));
        }
예제 #28
0
/*
	Get()
*/
LPCSTR CUrlService::Get(	UINT		nID,
					LPSTR	lpszUrl,
					int		nUrlSize,
					LPSTR	lpszParentUrl,
					int		nParentUrlSize,
					CUrlStatus::URL_STATUS& nStat
					)
{
	char* p = NULL;
	nStat = CUrlStatus::URL_STATUS_UNKNOWN;
	memset(lpszUrl,'\0',nUrlSize);
	memset(lpszParentUrl,'\0',nParentUrlSize);

	if(m_bIsValid)
	{
		// sincronizza l'accesso alla tabella
		if(m_mutexTable.Lock())
		{
			// cerca il valore richesto
			if(m_pUrlTable->Seek((int)nID,URL_IDX_ID))
			{
				m_pUrlTable->ScatterMemvars();
				
				strcpyn(lpszUrl,(char*)m_pUrlTable->GetField_Url(),nUrlSize);
				if(!strempty(lpszUrl))
				{
					strcpyn(lpszParentUrl,(char*)m_pUrlTable->GetField_ParentUrl(),nParentUrlSize);
					p = lpszUrl;
					nStat = (CUrlStatus::URL_STATUS)m_pUrlTable->GetField_Stat();
				}
			}

			m_mutexTable.Unlock();
		}
	}

	return(p);
}
예제 #29
0
파일: ini.c 프로젝트: alanrogers/ldpsiz
/**
 * Open and read an initialization file, putting the information
 * therein into a newly-allocated object of type Ini.
 *
 * @param[in] ifname Name of input file
 *
 * @returns Newly-allocate Ini object containing info from input file.
 */
Ini        *Ini_new(const char *ifname) {
    FILE       *ifp = fopen(ifname, "r");
    int         inPopHist = 0;

    if(ifp == NULL)
        return NULL;

    Ini        *ini = malloc(sizeof(Ini));

    checkmem(ini, __FILE__, __LINE__);
    memset(ini, 0, sizeof(Ini));
    ini->a = NULL;
    ini->epochList = NULL;

    Tokenizer  *tkz = Tokenizer_new(100);
    char        buff[1000];
    int         lineno = 0, ntokens;

    while(fgets(buff, sizeof(buff), ifp) != NULL) {

        ++lineno;

        if(!strchr(buff, '\n') && !feof(ifp))
            eprintf("ERR@%s:%d: Buffer overflow. buff=\"%s\"\n",
                    __FILE__, __LINE__, buff);

        /* skip blank lines and comments */
        stripComment(buff);
        if(strempty(buff))
            continue;

        if(inPopHist) {
            Tokenizer_split(tkz, buff, " \t");  /* tokenize */
            ntokens = Tokenizer_strip(tkz, " \t\n");    /* strip extraneous */
            if(ntokens != 2)
                break;

            double      t = strtod(Tokenizer_token(tkz, 0), NULL);
            double      twoN = strtod(Tokenizer_token(tkz, 1), NULL);

            ini->epochList = EpochLink_new(ini->epochList, t, twoN);
            if(!isfinite(t))
                break;
        } else if(strchr(buff, '=')) {
            Tokenizer_split(tkz, buff, "=");    /* tokenize */
            ntokens = Tokenizer_strip(tkz, " \t\n");    /* strip extraneous */
            if(ntokens != 2)
                eprintf("ERR@:%s:%d:"
                        "Broken assignment @ line %u"
                        " of initialization file",
                        __FILE__, __LINE__, lineno);

            ini->a = Assignment_new(ini->a,
                                    Tokenizer_token(tkz, 0),
                                    Tokenizer_token(tkz, 1));

        } else {
            Tokenizer_split(tkz, buff, " \t");  /* tokenize */
            ntokens = Tokenizer_strip(tkz, " \t\n");    /* strip
                                                         * extraneous */
            if(ntokens == 0)
                continue;
            if(ntokens != 1)
                eprintf("ERR@:%s:%d:"
                        "Broken command @ line %u"
                        " of initialization file."
                        " inPopHist=%d; ntokens=%d\n",
                        __FILE__, __LINE__, lineno, inPopHist, ntokens);
            if(!strcmp("PopHist", Tokenizer_token(tkz, 0)))
                inPopHist = 1;
            else
                ini->a = Assignment_new(ini->a, Tokenizer_token(tkz, 0), "1");
        }
    }

    Tokenizer_free(tkz);
    fclose(ifp);
    return ini;
}
예제 #30
0
int main(int argc, char *argv[])
{ 
	int n;         /* Ранг исходного массива */
	int nrank;     /* Общее количество процессов */
	int myrank;    /* Номер текущего процесса */ 
	long *prev = NULL;  /* массивов элементов */
	long *next = NULL;  /* массивов элементов */
	int *intermedian = NULL;    /* Массив промежуточных точек */
	int i, j;

	MPI_Status status; 

	/* Иницилизация MPI */ 
	MPI_Init(&argc, &argv); 
	MPI_Comm_size(MPI_COMM_WORLD, &nrank); 
	MPI_Comm_rank(MPI_COMM_WORLD, &myrank); 

	if (myrank == 0 && argc < 4) {
		printf("Usage :\t%s <inputfilename> <outputfilename> <intermedianfilename>\n", argv[0]); fflush(stdout);
		printf("\tinputfilename - source matrix of path prices or empty\n"); fflush(stdout);
		printf("\toutputfilename - output floyd's matrix of path prices\n"); fflush(stdout);
		printf("\tintermedianfilename - output matrix of intermedian points or empty\n"); fflush(stdout);
		exit(-1);
	}

	char *inputFileName = argv[1];
	char *outputFileName = argv[2];
	char *intermedianFileName = argv[3];

	if (myrank == 0) {

		printf("Title :\t%s\n", title); fflush(stdout);
		printf("Number Of Process :\t%d\n", nrank);	fflush(stdout);
		printf("Input File Name :\t%s\n", inputFileName); fflush(stdout);
		printf("Output File Name :\t%s\n", outputFileName); fflush(stdout);
		printf("Intermedian File Name :\t%s\n", intermedianFileName); fflush(stdout);

		char buffer[4096];
		char *tok;
		char *p;


		FILE *fs = fopen(inputFileName, "r");
		if (fs == NULL) {
			fprintf(stderr, "File open error (%s)\n", inputFileName); fflush(stderr);
			exit(-1);
		}

		n = 0;

		/* Заполняем массив числами из файла */ 
		/* Операция выполняетя только на хост процессе */
		/* Операция выполняетя в два прохода по файлу */
		/* На первом проходе определяется ранг матрицы */
		/* На втором проходе считываются данные */
		for (i = 0; (tok = fgets(buffer, sizeof(buffer), fs)) != NULL; i++)
		{
			 j = 0;
			 for (tok = mystrtok(&p, tok, ';'); tok != NULL; tok = mystrtok(&p, NULL, ';'))
			 {
				 j++;
			 }
			 n = max(n, j);
		}
		n = max(n, i);

		prev = (long *)malloc(n*n*sizeof(long));
		next = (long *)malloc(n*n*sizeof(long));

		fseek(fs, 0, SEEK_SET);

		for (i = 0; (tok = fgets(buffer, sizeof(buffer), fs)) != NULL; i++)
		{
			j = 0;
			for (tok = mystrtok(&p, tok, ';'); tok != NULL; tok = mystrtok(&p, NULL, ';'))
			{
				/* Пустые элементы - это запрещённые пути */
				prev[n*i + j++] = strempty(tok) ? LONG_MAX : atol(tok);
			}
			for (; j < n; j++) prev[n*i + j] = LONG_MAX;
		}
		for (i = 0; i < n; i++) prev[n*i + i] = LONG_MAX; /* Запрещаем петли */

		fclose(fs);

		printf("Matrix rank :\t%d\n", n);
		for (i = 0; i < n; i++){
			for (j = 0; j < n; j++){
				printf("%ld%s", prev[i*n+j], ((j == n-1) ? "\n" : "\t"));
			}
		}
	}

	/* Копируем брэдкастом ранг матрицы в дочерние процессы */
	MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);

	if (myrank != 0) {
		prev = (long *)malloc(n*n*sizeof(long));
		next = (long *)malloc(n*n*sizeof(long));
	}

	/* Копируем брэдкастом исходную матрицу в дочерние процессы */
	MPI_Bcast(prev, n*n, MPI_LONG, 0, MPI_COMM_WORLD);

	intermedian = (int *)malloc(n*n*sizeof(int));

	_mpi_init(prev, next, intermedian, -1, n, myrank, nrank, &status);

	for(int m = 0; m < n ; m++){
		_mpi_floyd(prev, next, intermedian, m, n, myrank, nrank, &status);
		if (myrank == 0) {
			for (int i = 0; i < n; i++){
				for (int j = 0; j < n; j++){
					printf("%ld%s", next[i*n + j], ((j == n - 1) ? "\n" : ";"));
				}
			}
			printf("\n");
		}
		long * t = prev; prev = next; next = t;
	}

	/* Bыводим результаты */
	if (myrank == 0) {
		FILE *fs = fopen(outputFileName, "w");
		if (fs == NULL) {
			fprintf(stderr, "File open error (%s)\n", outputFileName); fflush(stderr);
			exit(-1);
		}
		for (i = 0; i < n; i++){
			for (j = 0; j < n; j++){
				if (prev[i*n + j] != LONG_MAX)
					fprintf(fs, "%ld%s", prev[i*n + j], ((j == n - 1) ? "\n" : ";"));
				else
					fprintf(fs, "%s", ((j == n - 1) ? "\n" : ";"));
			}
		}
		fclose(fs);
	}

	/* Bыводим результаты */
	if (myrank == 0) {
		FILE *fs = fopen(intermedianFileName, "w");
		if (fs == NULL) {
			fprintf(stderr, "File open error (%s)\n", intermedianFileName); fflush(stderr);
			exit(-1);
		}
		for (i = 0; i < n; i++){
			for (j = 0; j < n; j++){
				if (intermedian[i*n + j] >= 0)
					fprintf(fs, "%d%s", intermedian[i*n + j], ((j == n - 1) ? "\n" : ";"));
				else
					fprintf(fs, "%s", ((j == n - 1) ? "\n" : ";"));
			}
		}
		fclose(fs);
	}

	/* Освобождаем ранее выделенные ресурсы */
	free(prev);
	free(next);
	free(intermedian);

	MPI_Finalize(); 

	exit(0);
}