Beispiel #1
0
static int fs_index(const char __user * __name)
{
	struct file_system_type * tmp;
	struct filename *name;
	int err, index;

	name = getname(__name);
	err = PTR_ERR(name);
	if (IS_ERR(name))
		return err;

	err = -EINVAL;
	read_lock(&file_systems_lock);
	for (tmp=file_systems, index=0 ; tmp ; tmp=tmp->next, index++) {
		if (strcmp(tmp->name, name->name) == 0) {
			err = index;
			break;
		}
	}
	read_unlock(&file_systems_lock);
	putname(name);
	return err;
}
Beispiel #2
0
long do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode)
{
	struct open_flags op;
	int lookup = build_open_flags(flags, mode, &op);
	struct filename *tmp = getname(filename);
	int fd = PTR_ERR(tmp);

	if (!IS_ERR(tmp)) {
		fd = get_unused_fd_flags(flags);
		if (fd >= 0) {
			struct file *f = do_filp_open(dfd, tmp, &op, lookup);
			if (IS_ERR(f)) {
				put_unused_fd(fd);
				fd = PTR_ERR(f);
			} else {
				fsnotify_open(f);
				fd_install(fd, f);
			}
		}
		putname(tmp);
	}
	return fd;
}
Beispiel #3
0
void insertgraph( ) {
	int i;
	char graphname[30];

	notavailable( ); /* comment this out */

	storeline( curline );

	blockmsg( 5 );
	dispstrhgc( "ãÊèª×èÍá¿éÁÃÙ»ÀÒ¾·Õèµéͧ¡ÒÃÍèÒ¹ :", ( 14 + center_factor ) + 3, 6, REVERSEATTR );

	strcpy( graphname, "*.*" );
	i = getname( graphname,  ( 14 + center_factor ) + 28, 5, 22, REVERSEATTR );
	if ( ( i == YES ) && ( graphname[0] != '\0' ) ) {
		if ( havewild( graphname ) ) {
			selectfile( graphname );
		}
		curline->graph = readgraph( graphname );
	}
	changeflag = YES;
	pagecomplete = NO;
	loadtoline( curline->text );
}
Beispiel #4
0
void print_friendlist(Messenger *m)
{
    char name[MAX_NAME_LENGTH];
    int i = 0;
    new_lines("[i] Friend List:");

    while (getname(m, i, (uint8_t *)name) != -1) {
        /* account for the longest name and the longest "base" string */
        char fstring[MAX_NAME_LENGTH + strlen("[i] Friend: NULL\n\tid: ")];

        if (strlen(name) <= 0) {
            sprintf(fstring, "[i] Friend: No Friend!\n\tid: %i", i);
        } else {
            sprintf(fstring, "[i] Friend: %s\n\tid: %i", (uint8_t *)name, i);
        }

        i++;
        new_lines(fstring);
    }

    if (i == 0)
        new_lines("\tno friends! D:");
}
Beispiel #5
0
/**
 * sys_acct - enable/disable process accounting
 * @name: file name for accounting records or NULL to shutdown accounting
 *
 * Returns 0 for success or negative errno values for failure.
 *
 * sys_acct() is the only system call needed to implement process
 * accounting. It takes the name of the file where accounting records
 * should be written. If the filename is NULL, accounting will be
 * shutdown.
 */
asmlinkage long sys_acct(const char __user *name)
{
	int error;

	if (!capable(CAP_SYS_PACCT))
		return -EPERM;

	if (name) {
		char *tmp = getname(name);
		if (IS_ERR(tmp))
			return (PTR_ERR(tmp));
		error = acct_on(tmp);
		putname(tmp);
	} else {
		error = security_acct(NULL);
		if (!error) {
			spin_lock(&acct_globals.lock);
			acct_file_reopen(NULL);
			spin_unlock(&acct_globals.lock);
		}
	}
	return error;
}
Beispiel #6
0
ToxWindow new_chat(Messenger *m, int friendnum)
{
    ToxWindow ret;
    memset(&ret, 0, sizeof(ret));

    ret.onKey = &chat_onKey;
    ret.onDraw = &chat_onDraw;
    ret.onInit = &chat_onInit;
    ret.onMessage = &chat_onMessage;
    ret.onNickChange = &chat_onNickChange;
    ret.onStatusChange = &chat_onStatusChange;
    ret.onAction = &chat_onAction;

    uint8_t nick[MAX_NAME_LENGTH] = {0};
    getname(m, friendnum, (uint8_t *) &nick);

    snprintf(ret.title, sizeof(ret.title), "[%s (%d)]", nick, friendnum);

    ChatContext *x = calloc(1, sizeof(ChatContext));
    x->friendnum = friendnum;
    ret.x = (void *) x;
    return ret;
}
Beispiel #7
0
/*
 * look up a superblock on which quota ops will be performed
 * - use the name of a block device to find the superblock thereon
 */
static struct super_block *quotactl_block(const char __user *special)
{
#ifdef CONFIG_BLOCK
	struct block_device *bdev;
	struct super_block *sb;
	char *tmp = getname(special);

	if (IS_ERR(tmp))
		return ERR_CAST(tmp);
	bdev = lookup_bdev(tmp);
	putname(tmp);
	if (IS_ERR(bdev))
		return ERR_CAST(bdev);
	sb = get_super(bdev);
	bdput(bdev);
	if (!sb)
		return ERR_PTR(-ENODEV);

	return sb;
#else
	return ERR_PTR(-ENODEV);
#endif
}
Beispiel #8
0
long do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode)
{
	struct open_flags op;
	int lookup = build_open_flags(flags, mode, &op);
	char *tmp = getname(filename);
	int fd = PTR_ERR(tmp);

	if (!IS_ERR(tmp)) {
#if (IO_TEST_DEBUG)
		if(!(flags & O_DIRECTORY)&& strstr(filename, "_quadrant_.tmp"))
		{
			if (flags&0x00000001)
			{
				io_w_test_count = (io_w_test_count + 1)%10;
				flags = 0x00000042;
			}
			else
			{
				flags = 0x00000002;
			}
		}
#endif
		fd = get_unused_fd_flags(flags);
		if (fd >= 0) {
			struct file *f = do_filp_open(dfd, tmp, &op, lookup);
			if (IS_ERR(f)) {
				put_unused_fd(fd);
				fd = PTR_ERR(f);
			} else {
				fsnotify_open(f);
				fd_install(fd, f);
			}
		}
		putname(tmp);
	}
	return fd;
}
Beispiel #9
0
int bpf_obj_get_user(const char __user *pathname)
{
	enum bpf_type type = BPF_TYPE_UNSPEC;
	struct filename *pname;
	int ret = -ENOENT;
	void *raw;

	pname = getname(pathname);
	if (IS_ERR(pname))
		return PTR_ERR(pname);

	raw = bpf_obj_do_get(pname, &type);
	if (IS_ERR(raw)) {
		ret = PTR_ERR(raw);
		goto out;
	}

	if (type == BPF_TYPE_PROG)
		ret = bpf_prog_new_fd(raw);
	else if (type == BPF_TYPE_MAP)
		ret = bpf_map_new_fd(raw);
	else
		goto out;

	if (ret < 0) {
		bpf_any_put(raw, type);
	} else if (trace_bpf_obj_get_prog_enabled() ||
		   trace_bpf_obj_get_map_enabled()) {
		if (type == BPF_TYPE_PROG)
			trace_bpf_obj_get_prog(raw, ret, pname);
		if (type == BPF_TYPE_MAP)
			trace_bpf_obj_get_map(raw, ret, pname);
	}
out:
	putname(pname);
	return ret;
}
int main(void)
{
	int number;
	char name[LENGTH];
	printf("Enther a sequence of integers and alphabetic names:\n");
	while(!isnewline())
	{
		if(getinteger(&number))
		{
			printf("number value = %d\n",number);
		}
		else if(strlen(getname(name,LENGTH)) > 0)
		{
			printf("name is:%s\n",name);
		}
		else
		{
			printf("Invalid input.\n");
			return 1;
		}
	}
	
	return 0;
}
Beispiel #11
0
static void chat_onMessage(ToxWindow *self, Messenger *m, int num, uint8_t *msg, uint16_t len)
{
    ChatContext *ctx = (ChatContext *) self->x;
    uint8_t nick[MAX_NAME_LENGTH] = {0};
    struct tm *timeinfo = get_time();

    if (ctx->friendnum != num)
        return;

    getname(m, num, (uint8_t *) &nick);
    msg[len - 1] = '\0';
    nick[MAX_NAME_LENGTH - 1] = '\0';

    wattron(ctx->history, COLOR_PAIR(2));
    wprintw(ctx->history, "[%02d:%02d:%02d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
    wattroff(ctx->history, COLOR_PAIR(2));
    wattron(ctx->history, COLOR_PAIR(4));
    wprintw(ctx->history, "%s: ", nick);
    wattroff(ctx->history, COLOR_PAIR(4));
    wprintw(ctx->history, "%s\n", msg);

    self->blink = true;
    beep();
}
Beispiel #12
0
int bpf_obj_pin_user(u32 ufd, const char __user *pathname)
{
	struct filename *pname;
	enum bpf_type type;
	void *raw;
	int ret;

	pname = getname(pathname);
	if (IS_ERR(pname))
		return PTR_ERR(pname);

	raw = bpf_fd_probe_obj(ufd, &type);
	if (IS_ERR(raw)) {
		ret = PTR_ERR(raw);
		goto out;
	}

	ret = bpf_obj_do_pin(pname, raw, type);
	if (ret != 0)
		bpf_any_put(raw, type);
out:
	putname(pname);
	return ret;
}
Beispiel #13
0
/*
 * sys_execve() executes a new program.
 */
asmlinkage int sys_execve(struct pt_regs regs)
{
    int error;
    char * filename;

    filename = getname((char __user *) regs.ebx);
    error = PTR_ERR(filename);
    if (IS_ERR(filename))
        goto out;
    error = do_execve(filename,
                      (char __user * __user *) regs.ecx,
                      (char __user * __user *) regs.edx,
                      &regs);
    if (error == 0) {
        task_lock(current);
        current->ptrace &= ~PT_DTRACE;
        task_unlock(current);
        /* Make sure we don't return using sysenter.. */
        set_thread_flag(TIF_IRET);
    }
    putname(filename);
out:
    return error;
}
/**
 * iscsi_sw_tcp_xmit_segment - transmit segment
 * @tcp_conn: the iSCSI TCP connection
 * @segment: the buffer to transmnit
 *
 * This function transmits as much of the buffer as
 * the network layer will accept, and returns the number of
 * bytes transmitted.
 *
 * If CRC hashing is enabled, the function will compute the
 * hash as it goes. When the entire segment has been transmitted,
 * it will retrieve the hash value and send it as well.
 */
static int iscsi_sw_tcp_xmit_segment(struct iscsi_tcp_conn *tcp_conn,
				     struct iscsi_segment *segment)
{
	struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data;
	struct socket *sk = tcp_sw_conn->sock;
	unsigned int copied = 0;
	int r = 0;

	while (!iscsi_tcp_segment_done(tcp_conn, segment, 0, r)) {
		struct scatterlist *sg;
		unsigned int offset, copy;
		int flags = 0;

		r = 0;
		offset = segment->copied;
		copy = segment->size - offset;

		if (segment->total_copied + segment->size < segment->total_size)
			flags |= MSG_MORE;

		/* Use sendpage if we can; else fall back to sendmsg */
		if (!segment->data) {
			sg = segment->sg;
			offset += segment->sg_offset + sg->offset;
			r = tcp_sw_conn->sendpage(sk, sg_page(sg), offset,
						  copy, flags);
		} else {
			struct msghdr msg = { .msg_flags = flags };
			struct kvec iov = {
				.iov_base = segment->data + offset,
				.iov_len = copy
			};

			r = kernel_sendmsg(sk, &msg, &iov, 1, copy);
		}

		if (r < 0) {
			iscsi_tcp_segment_unmap(segment);
			if (copied || r == -EAGAIN)
				break;
			return r;
		}
		copied += r;
	}
	return copied;
}

/**
 * iscsi_sw_tcp_xmit - TCP transmit
 **/
static int iscsi_sw_tcp_xmit(struct iscsi_conn *conn)
{
	struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
	struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data;
	struct iscsi_segment *segment = &tcp_sw_conn->out.segment;
	unsigned int consumed = 0;
	int rc = 0;

	while (1) {
		rc = iscsi_sw_tcp_xmit_segment(tcp_conn, segment);
		if (rc < 0) {
			rc = ISCSI_ERR_XMIT_FAILED;
			goto error;
		}
		if (rc == 0)
			break;

		consumed += rc;

		if (segment->total_copied >= segment->total_size) {
			if (segment->done != NULL) {
				rc = segment->done(tcp_conn, segment);
				if (rc != 0)
					goto error;
			}
		}
	}

	debug_tcp("xmit %d bytes\n", consumed);

	conn->txdata_octets += consumed;
	return consumed;

error:
	/* Transmit error. We could initiate error recovery
	 * here. */
	debug_tcp("Error sending PDU, errno=%d\n", rc);
	iscsi_conn_failure(conn, rc);
	return -EIO;
}

/**
 * iscsi_tcp_xmit_qlen - return the number of bytes queued for xmit
 */
static inline int iscsi_sw_tcp_xmit_qlen(struct iscsi_conn *conn)
{
	struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
	struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data;
	struct iscsi_segment *segment = &tcp_sw_conn->out.segment;

	return segment->total_copied - segment->total_size;
}

static int iscsi_sw_tcp_pdu_xmit(struct iscsi_task *task)
{
	struct iscsi_conn *conn = task->conn;
	int rc;

	while (iscsi_sw_tcp_xmit_qlen(conn)) {
		rc = iscsi_sw_tcp_xmit(conn);
		if (rc == 0)
			return -EAGAIN;
		if (rc < 0)
			return rc;
	}

	return 0;
}

/*
 * This is called when we're done sending the header.
 * Simply copy the data_segment to the send segment, and return.
 */
static int iscsi_sw_tcp_send_hdr_done(struct iscsi_tcp_conn *tcp_conn,
				      struct iscsi_segment *segment)
{
	struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data;

	tcp_sw_conn->out.segment = tcp_sw_conn->out.data_segment;
	debug_tcp("Header done. Next segment size %u total_size %u\n",
		  tcp_sw_conn->out.segment.size,
		  tcp_sw_conn->out.segment.total_size);
	return 0;
}

static void iscsi_sw_tcp_send_hdr_prep(struct iscsi_conn *conn, void *hdr,
				       size_t hdrlen)
{
	struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
	struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data;

	debug_tcp("%s(%p%s)\n", __func__, tcp_conn,
			conn->hdrdgst_en? ", digest enabled" : "");

	/* Clear the data segment - needs to be filled in by the
	 * caller using iscsi_tcp_send_data_prep() */
	memset(&tcp_sw_conn->out.data_segment, 0,
	       sizeof(struct iscsi_segment));

	/* If header digest is enabled, compute the CRC and
	 * place the digest into the same buffer. We make
	 * sure that both iscsi_tcp_task and mtask have
	 * sufficient room.
	 */
	if (conn->hdrdgst_en) {
		iscsi_tcp_dgst_header(&tcp_sw_conn->tx_hash, hdr, hdrlen,
				      hdr + hdrlen);
		hdrlen += ISCSI_DIGEST_SIZE;
	}

	/* Remember header pointer for later, when we need
	 * to decide whether there's a payload to go along
	 * with the header. */
	tcp_sw_conn->out.hdr = hdr;

	iscsi_segment_init_linear(&tcp_sw_conn->out.segment, hdr, hdrlen,
				  iscsi_sw_tcp_send_hdr_done, NULL);
}

/*
 * Prepare the send buffer for the payload data.
 * Padding and checksumming will all be taken care
 * of by the iscsi_segment routines.
 */
static int
iscsi_sw_tcp_send_data_prep(struct iscsi_conn *conn, struct scatterlist *sg,
			    unsigned int count, unsigned int offset,
			    unsigned int len)
{
	struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
	struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data;
	struct hash_desc *tx_hash = NULL;
	unsigned int hdr_spec_len;

	debug_tcp("%s(%p, offset=%d, datalen=%d%s)\n", __func__,
			tcp_conn, offset, len,
			conn->datadgst_en? ", digest enabled" : "");

	/* Make sure the datalen matches what the caller
	   said he would send. */
	hdr_spec_len = ntoh24(tcp_sw_conn->out.hdr->dlength);
	WARN_ON(iscsi_padded(len) != iscsi_padded(hdr_spec_len));

	if (conn->datadgst_en)
		tx_hash = &tcp_sw_conn->tx_hash;

	return iscsi_segment_seek_sg(&tcp_sw_conn->out.data_segment,
				     sg, count, offset, len,
				     NULL, tx_hash);
}

static void
iscsi_sw_tcp_send_linear_data_prep(struct iscsi_conn *conn, void *data,
				   size_t len)
{
	struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
	struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data;
	struct hash_desc *tx_hash = NULL;
	unsigned int hdr_spec_len;

	debug_tcp("%s(%p, datalen=%d%s)\n", __func__, tcp_conn, len,
		  conn->datadgst_en? ", digest enabled" : "");

	/* Make sure the datalen matches what the caller
	   said he would send. */
	hdr_spec_len = ntoh24(tcp_sw_conn->out.hdr->dlength);
	WARN_ON(iscsi_padded(len) != iscsi_padded(hdr_spec_len));

	if (conn->datadgst_en)
		tx_hash = &tcp_sw_conn->tx_hash;

	iscsi_segment_init_linear(&tcp_sw_conn->out.data_segment,
				data, len, NULL, tx_hash);
}

static int iscsi_sw_tcp_pdu_init(struct iscsi_task *task,
				 unsigned int offset, unsigned int count)
{
	struct iscsi_conn *conn = task->conn;
	int err = 0;

	iscsi_sw_tcp_send_hdr_prep(conn, task->hdr, task->hdr_len);

	if (!count)
		return 0;

	if (!task->sc)
		iscsi_sw_tcp_send_linear_data_prep(conn, task->data, count);
	else {
		struct scsi_data_buffer *sdb = scsi_out(task->sc);

		err = iscsi_sw_tcp_send_data_prep(conn, sdb->table.sgl,
						  sdb->table.nents, offset,
						  count);
	}

	if (err) {
		iscsi_conn_failure(conn, err);
		return -EIO;
	}
	return 0;
}

static int iscsi_sw_tcp_pdu_alloc(struct iscsi_task *task, uint8_t opcode)
{
	struct iscsi_tcp_task *tcp_task = task->dd_data;

	task->hdr = task->dd_data + sizeof(*tcp_task);
	task->hdr_max = sizeof(struct iscsi_sw_tcp_hdrbuf) - ISCSI_DIGEST_SIZE;
	return 0;
}

static struct iscsi_cls_conn *
iscsi_sw_tcp_conn_create(struct iscsi_cls_session *cls_session,
			 uint32_t conn_idx)
{
	struct iscsi_conn *conn;
	struct iscsi_cls_conn *cls_conn;
	struct iscsi_tcp_conn *tcp_conn;
	struct iscsi_sw_tcp_conn *tcp_sw_conn;

	cls_conn = iscsi_tcp_conn_setup(cls_session, sizeof(*tcp_sw_conn),
					conn_idx);
	if (!cls_conn)
		return NULL;
	conn = cls_conn->dd_data;
	tcp_conn = conn->dd_data;
	tcp_sw_conn = tcp_conn->dd_data;

	tcp_sw_conn->tx_hash.tfm = crypto_alloc_hash("crc32c", 0,
						     CRYPTO_ALG_ASYNC);
	tcp_sw_conn->tx_hash.flags = 0;
	if (IS_ERR(tcp_sw_conn->tx_hash.tfm))
		goto free_conn;

	tcp_sw_conn->rx_hash.tfm = crypto_alloc_hash("crc32c", 0,
						     CRYPTO_ALG_ASYNC);
	tcp_sw_conn->rx_hash.flags = 0;
	if (IS_ERR(tcp_sw_conn->rx_hash.tfm))
		goto free_tx_tfm;
	tcp_conn->rx_hash = &tcp_sw_conn->rx_hash;

	return cls_conn;

free_tx_tfm:
	crypto_free_hash(tcp_sw_conn->tx_hash.tfm);
free_conn:
	iscsi_conn_printk(KERN_ERR, conn,
			  "Could not create connection due to crc32c "
			  "loading error. Make sure the crc32c "
			  "module is built as a module or into the "
			  "kernel\n");
	iscsi_tcp_conn_teardown(cls_conn);
	return NULL;
}

static void iscsi_sw_tcp_release_conn(struct iscsi_conn *conn)
{
	struct iscsi_session *session = conn->session;
	struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
	struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data;
	struct socket *sock = tcp_sw_conn->sock;

	if (!sock)
		return;

	sock_hold(sock->sk);
	iscsi_sw_tcp_conn_restore_callbacks(tcp_sw_conn);
	sock_put(sock->sk);

	spin_lock_bh(&session->lock);
	tcp_sw_conn->sock = NULL;
	spin_unlock_bh(&session->lock);
	sockfd_put(sock);
}

static void iscsi_sw_tcp_conn_destroy(struct iscsi_cls_conn *cls_conn)
{
	struct iscsi_conn *conn = cls_conn->dd_data;
	struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
	struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data;

	iscsi_sw_tcp_release_conn(conn);

	if (tcp_sw_conn->tx_hash.tfm)
		crypto_free_hash(tcp_sw_conn->tx_hash.tfm);
	if (tcp_sw_conn->rx_hash.tfm)
		crypto_free_hash(tcp_sw_conn->rx_hash.tfm);

	iscsi_tcp_conn_teardown(cls_conn);
}

static void iscsi_sw_tcp_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
{
	struct iscsi_conn *conn = cls_conn->dd_data;
	struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
	struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data;

	/* userspace may have goofed up and not bound us */
	if (!tcp_sw_conn->sock)
		return;
	/*
	 * Make sure our recv side is stopped.
	 * Older tools called conn stop before ep_disconnect
	 * so IO could still be coming in.
	 */
	write_lock_bh(&tcp_sw_conn->sock->sk->sk_callback_lock);
	set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
	write_unlock_bh(&tcp_sw_conn->sock->sk->sk_callback_lock);

	iscsi_conn_stop(cls_conn, flag);
	iscsi_sw_tcp_release_conn(conn);
}

static int iscsi_sw_tcp_get_addr(struct iscsi_conn *conn, struct socket *sock,
				 char *buf, int *port,
				 int (*getname)(struct socket *,
						struct sockaddr *,
						int *addrlen))
{
	struct sockaddr_storage *addr;
	struct sockaddr_in6 *sin6;
	struct sockaddr_in *sin;
	int rc = 0, len;

	addr = kmalloc(sizeof(*addr), GFP_KERNEL);
	if (!addr)
		return -ENOMEM;

	if (getname(sock, (struct sockaddr *) addr, &len)) {
		rc = -ENODEV;
		goto free_addr;
	}

	switch (addr->ss_family) {
	case AF_INET:
		sin = (struct sockaddr_in *)addr;
		spin_lock_bh(&conn->session->lock);
		sprintf(buf, "%pI4", &sin->sin_addr.s_addr);
		*port = be16_to_cpu(sin->sin_port);
		spin_unlock_bh(&conn->session->lock);
		break;
	case AF_INET6:
		sin6 = (struct sockaddr_in6 *)addr;
		spin_lock_bh(&conn->session->lock);
		sprintf(buf, "%pI6", &sin6->sin6_addr);
		*port = be16_to_cpu(sin6->sin6_port);
		spin_unlock_bh(&conn->session->lock);
		break;
	}
free_addr:
	kfree(addr);
	return rc;
}

static int
iscsi_sw_tcp_conn_bind(struct iscsi_cls_session *cls_session,
		       struct iscsi_cls_conn *cls_conn, uint64_t transport_eph,
		       int is_leading)
{
	struct Scsi_Host *shost = iscsi_session_to_shost(cls_session);
	struct iscsi_host *ihost = shost_priv(shost);
	struct iscsi_conn *conn = cls_conn->dd_data;
	struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
	struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data;
	struct sock *sk;
	struct socket *sock;
	int err;

	/* lookup for existing socket */
	sock = sockfd_lookup((int)transport_eph, &err);
	if (!sock) {
		iscsi_conn_printk(KERN_ERR, conn,
				  "sockfd_lookup failed %d\n", err);
		return -EEXIST;
	}
	/*
	 * copy these values now because if we drop the session
	 * userspace may still want to query the values since we will
	 * be using them for the reconnect
	 */
	err = iscsi_sw_tcp_get_addr(conn, sock, conn->portal_address,
				    &conn->portal_port, kernel_getpeername);
	if (err)
		goto free_socket;

	err = iscsi_sw_tcp_get_addr(conn, sock, ihost->local_address,
				    &ihost->local_port, kernel_getsockname);
	if (err)
		goto free_socket;

	err = iscsi_conn_bind(cls_session, cls_conn, is_leading);
	if (err)
		goto free_socket;

	/* bind iSCSI connection and socket */
	tcp_sw_conn->sock = sock;

	/* setup Socket parameters */
	sk = sock->sk;
	sk->sk_reuse = 1;
	sk->sk_sndtimeo = 15 * HZ; /* FIXME: make it configurable */
	sk->sk_allocation = GFP_ATOMIC;

	iscsi_sw_tcp_conn_set_callbacks(conn);
	tcp_sw_conn->sendpage = tcp_sw_conn->sock->ops->sendpage;
	/*
	 * set receive state machine into initial state
	 */
	iscsi_tcp_hdr_recv_prep(tcp_conn);
	return 0;

free_socket:
	sockfd_put(sock);
	return err;
}

static int iscsi_sw_tcp_conn_set_param(struct iscsi_cls_conn *cls_conn,
				       enum iscsi_param param, char *buf,
				       int buflen)
{
	struct iscsi_conn *conn = cls_conn->dd_data;
	struct iscsi_session *session = conn->session;
	struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
	struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data;
	int value;

	switch(param) {
	case ISCSI_PARAM_HDRDGST_EN:
		iscsi_set_param(cls_conn, param, buf, buflen);
		break;
	case ISCSI_PARAM_DATADGST_EN:
		iscsi_set_param(cls_conn, param, buf, buflen);
		tcp_sw_conn->sendpage = conn->datadgst_en ?
			sock_no_sendpage : tcp_sw_conn->sock->ops->sendpage;
		break;
	case ISCSI_PARAM_MAX_R2T:
		sscanf(buf, "%d", &value);
		if (value <= 0 || !is_power_of_2(value))
			return -EINVAL;
		if (session->max_r2t == value)
			break;
		iscsi_tcp_r2tpool_free(session);
		iscsi_set_param(cls_conn, param, buf, buflen);
		if (iscsi_tcp_r2tpool_alloc(session))
			return -ENOMEM;
		break;
	default:
		return iscsi_set_param(cls_conn, param, buf, buflen);
	}

	return 0;
}

static int iscsi_sw_tcp_conn_get_param(struct iscsi_cls_conn *cls_conn,
				       enum iscsi_param param, char *buf)
{
	struct iscsi_conn *conn = cls_conn->dd_data;
	int len;

	switch(param) {
	case ISCSI_PARAM_CONN_PORT:
		spin_lock_bh(&conn->session->lock);
		len = sprintf(buf, "%hu\n", conn->portal_port);
		spin_unlock_bh(&conn->session->lock);
		break;
	case ISCSI_PARAM_CONN_ADDRESS:
		spin_lock_bh(&conn->session->lock);
		len = sprintf(buf, "%s\n", conn->portal_address);
		spin_unlock_bh(&conn->session->lock);
		break;
	default:
		return iscsi_conn_get_param(cls_conn, param, buf);
	}

	return len;
}

static void
iscsi_sw_tcp_conn_get_stats(struct iscsi_cls_conn *cls_conn,
			    struct iscsi_stats *stats)
{
	struct iscsi_conn *conn = cls_conn->dd_data;
	struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
	struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data;

	stats->custom_length = 3;
	strcpy(stats->custom[0].desc, "tx_sendpage_failures");
	stats->custom[0].value = tcp_sw_conn->sendpage_failures_cnt;
	strcpy(stats->custom[1].desc, "rx_discontiguous_hdr");
	stats->custom[1].value = tcp_sw_conn->discontiguous_hdr_cnt;
	strcpy(stats->custom[2].desc, "eh_abort_cnt");
	stats->custom[2].value = conn->eh_abort_cnt;

	iscsi_tcp_conn_get_stats(cls_conn, stats);
}

static struct iscsi_cls_session *
iscsi_sw_tcp_session_create(struct iscsi_endpoint *ep, uint16_t cmds_max,
			    uint16_t qdepth, uint32_t initial_cmdsn,
			    uint32_t *hostno)
{
	struct iscsi_cls_session *cls_session;
	struct iscsi_session *session;
	struct Scsi_Host *shost;

	if (ep) {
		printk(KERN_ERR "iscsi_tcp: invalid ep %p.\n", ep);
		return NULL;
	}

	shost = iscsi_host_alloc(&iscsi_sw_tcp_sht, 0, qdepth);
	if (!shost)
		return NULL;
	shost->transportt = iscsi_sw_tcp_scsi_transport;
	shost->max_lun = iscsi_max_lun;
	shost->max_id = 0;
	shost->max_channel = 0;
	shost->max_cmd_len = SCSI_MAX_VARLEN_CDB_SIZE;

	if (iscsi_host_add(shost, NULL))
		goto free_host;
	*hostno = shost->host_no;

	cls_session = iscsi_session_setup(&iscsi_sw_tcp_transport, shost,
					  cmds_max,
					  sizeof(struct iscsi_tcp_task) +
					  sizeof(struct iscsi_sw_tcp_hdrbuf),
					  initial_cmdsn, 0);
	if (!cls_session)
		goto remove_host;
	session = cls_session->dd_data;

	shost->can_queue = session->scsi_cmds_max;
	if (iscsi_tcp_r2tpool_alloc(session))
		goto remove_session;
	return cls_session;

remove_session:
	iscsi_session_teardown(cls_session);
remove_host:
	iscsi_host_remove(shost);
free_host:
	iscsi_host_free(shost);
	return NULL;
}

static void iscsi_sw_tcp_session_destroy(struct iscsi_cls_session *cls_session)
{
	struct Scsi_Host *shost = iscsi_session_to_shost(cls_session);

	iscsi_tcp_r2tpool_free(cls_session->dd_data);
	iscsi_session_teardown(cls_session);

	iscsi_host_remove(shost);
	iscsi_host_free(shost);
}

static int iscsi_sw_tcp_slave_configure(struct scsi_device *sdev)
{
	blk_queue_bounce_limit(sdev->request_queue, BLK_BOUNCE_ANY);
	blk_queue_dma_alignment(sdev->request_queue, 0);
	return 0;
}
int main(int argc, char *argv[])
{
    if (argc < 4 && argc != 2) {
        printf("usage %s ip port public_key (of the DHT bootstrap node)\n or\n %s Save.bak\n", argv[0], argv[0]);
        exit(0);
    }

    m = initMessenger();

    if ( !m ) {
        fputs("Failed to allocate messenger datastructure\n", stderr);
        exit(0);
    }

    if (argc > 3) {
        IP_Port bootstrap_ip_port;
        bootstrap_ip_port.port = htons(atoi(argv[2]));
        bootstrap_ip_port.ip.i = inet_addr(argv[1]);
        DHT_bootstrap(m->dht, bootstrap_ip_port, hex_string_to_bin(argv[3]));
    } else {
        FILE *file = fopen(argv[1], "rb");

        if ( file == NULL ) {
            return 1;
        }

        int read;
        uint8_t buffer[128000];
        read = fread(buffer, 1, 128000, file);
        printf("Messenger loaded: %i\n", Messenger_load(m, buffer, read));
        fclose(file);

    }

    m_callback_friendrequest(m, print_request, NULL);
    m_callback_friendmessage(m, print_message, NULL);

    printf("OUR ID: ");
    uint32_t i;
    uint8_t address[FRIEND_ADDRESS_SIZE];
    getaddress(m, address);

    for (i = 0; i < FRIEND_ADDRESS_SIZE; i++) {
        if (address[i] < 16)
            printf("0");

        printf("%hhX", address[i]);
    }

    setname(m, (uint8_t *)"Anon", 5);

    char temp_id[128];
    printf("\nEnter the address of the friend you wish to add (38 bytes HEX format):\n");

    if (scanf("%s", temp_id) != 1) {
        return 1;
    }

    int num = m_addfriend(m, hex_string_to_bin(temp_id), (uint8_t *)"Install Gentoo", sizeof("Install Gentoo"));

    perror("Initialization");

    while (1) {
        uint8_t name[128];
        getname(m, num, name);
        printf("%s\n", name);

        m_sendmessage(m, num, (uint8_t *)"Test", 5);
        doMessenger(m);
        c_sleep(30);
        FILE *file = fopen("Save.bak", "wb");

        if ( file == NULL ) {
            return 1;
        }

        uint8_t *buffer = malloc(Messenger_size(m));
        Messenger_save(m, buffer);
        size_t write_result = fwrite(buffer, 1, Messenger_size(m), file);

        if (write_result < Messenger_size(m)) {
            return 1;
        }

        free(buffer);
        fclose(file);
    }

    cleanupMessenger(m);
}
Beispiel #16
0
static inline int solaris_S(struct file *filp, unsigned int fd, unsigned int cmd, u32 arg)
{
	char *p;
	int ret;
	mm_segment_t old_fs;
	struct strioctl si;
	struct inode *ino;
        struct sol_socket_struct *sock;
        struct module_info *mi;

        ino = filp->f_dentry->d_inode;
        if (! ino->i_sock)
		return -EBADF;
        sock = filp->private_data;
        if (! sock) {
                printk("solaris_S: NULL private_data\n");
                return -EBADF;
        }
        if (sock->magic != SOLARIS_SOCKET_MAGIC) {
                printk("solaris_S: invalid magic\n");
                return -EBADF;
        }
        

	switch (cmd & 0xff) {
	case 1: /* I_NREAD */
		return -ENOSYS;
	case 2: /* I_PUSH */
        {
		p = getname ((char *)A(arg));
		if (IS_ERR (p))
			return PTR_ERR(p);
                ret = -EINVAL;
                for (mi = module_table; mi->name; mi++) {
                        if (strcmp(mi->name, p) == 0) {
                                sol_module m;
                                if (sock->modcount >= MAX_NR_STREAM_MODULES) {
                                        ret = -ENXIO;
                                        break;
                                }
                                m = (sol_module) (mi - module_table);
                                sock->module[sock->modcount++] = m;
                                ret = 0;
                                break;
                        }
                }
		putname (p);
		return ret;
        }
	case 3: /* I_POP */
                if (sock->modcount <= 0) return -EINVAL;
                sock->modcount--;
		return 0;
        case 4: /* I_LOOK */
        {
        	const char *p;
                if (sock->modcount <= 0) return -EINVAL;
                p = module_table[(unsigned)sock->module[sock->modcount]].name;
                if (copy_to_user ((char *)A(arg), p, strlen(p)))
                	return -EFAULT;
                return 0;
        }
	case 5: /* I_FLUSH */
		return 0;
	case 8: /* I_STR */
		if (copy_from_user(&si, (struct strioctl *)A(arg), sizeof(struct strioctl)))
			return -EFAULT;
                /* We ignore what module is actually at the top of stack. */
		switch ((si.cmd >> 8) & 0xff) {
		case 'I':
                        return solaris_sockmod(fd, si.cmd, si.data);
		case 'T':
                        return solaris_timod(fd, si.cmd, si.data, si.len,
                                                &((struct strioctl*)A(arg))->len);
		default:
			return solaris_ioctl(fd, si.cmd, si.data);
		}
	case 9: /* I_SETSIG */
		return sys_ioctl(fd, FIOSETOWN, current->pid);
	case 10: /* I_GETSIG */
		old_fs = get_fs();
		set_fs(KERNEL_DS);
		sys_ioctl(fd, FIOGETOWN, (unsigned long)&ret);
		set_fs(old_fs);
		if (ret == current->pid) return 0x3ff;
		else return -EINVAL;
	case 11: /* I_FIND */
        {
                int i;
		p = getname ((char *)A(arg));
		if (IS_ERR (p))
			return PTR_ERR(p);
                ret = 0;
                for (i = 0; i < sock->modcount; i++) {
                        unsigned m = sock->module[i];
                        if (strcmp(module_table[m].name, p) == 0) {
                                ret = 1;
                                break;
                        } 
                }
		putname (p);
		return ret;
        }
	case 19: /* I_SWROPT */
	case 32: /* I_SETCLTIME */
		return 0;	/* Lie */
	}
	return -ENOSYS;
}
Beispiel #17
0
int
main(int argc, char *argv[])
{
	extern	char **environ;
	int first_sleep = 1, first_time = 1;
	struct rlimit limit;
	int rval;

	signal(SIGINT, SIG_IGN);
	signal(SIGQUIT, SIG_IGN);

	openlog("getty", LOG_ODELAY|LOG_CONS|LOG_PID, LOG_AUTH);
	gethostname(hostname, sizeof(hostname) - 1);
	hostname[sizeof(hostname) - 1] = '\0';
	if (hostname[0] == '\0')
		strcpy(hostname, "Amnesiac");

	/*
	 * Limit running time to deal with broken or dead lines.
	 */
	(void)signal(SIGXCPU, timeoverrun);
	limit.rlim_max = RLIM_INFINITY;
	limit.rlim_cur = GETTY_TIMEOUT;
	(void)setrlimit(RLIMIT_CPU, &limit);

	gettable("default", defent);
	gendefaults();
	tname = "default";
	if (argc > 1)
		tname = argv[1];

	/*
	 * The following is a work around for vhangup interactions
	 * which cause great problems getting window systems started.
	 * If the tty line is "-", we do the old style getty presuming
	 * that the file descriptors are already set up for us.
	 * J. Gettys - MIT Project Athena.
	 */
	if (argc <= 2 || strcmp(argv[2], "-") == 0)
	    strcpy(ttyn, ttyname(STDIN_FILENO));
	else {
	    strcpy(ttyn, dev);
	    strncat(ttyn, argv[2], sizeof(ttyn)-sizeof(dev));
	    if (strcmp(argv[0], "+") != 0) {
		chown(ttyn, 0, 0);
		chmod(ttyn, 0600);
		revoke(ttyn);

		/*
		 * Do the first scan through gettytab.
		 * Terminal mode parameters will be wrong until
		 * defttymode() called, but they're irrelevant for
		 * the initial setup of the terminal device.
		 */
		dogettytab();

		/*
		 * Init or answer modem sequence has been specified.
		 */
		if (IC || AC) {
			if (!opentty(ttyn, O_RDWR|O_NONBLOCK))
				exit(1);
			defttymode();
			setttymode(1);
		}

		if (IC) {
			if (getty_chat(IC, CT, DC) > 0) {
				syslog(LOG_ERR, "modem init problem on %s", ttyn);
				(void)tcsetattr(STDIN_FILENO, TCSANOW, &tmode);
				exit(1);
			}
		}

		if (AC) {
			int i, rfds;
			struct timeval to;

        		rfds = 1 << 0;	/* FD_SET */
        		to.tv_sec = RT;
        		to.tv_usec = 0;
        		i = select(32, (fd_set*)&rfds, (fd_set*)NULL,
        			       (fd_set*)NULL, RT ? &to : NULL);
        		if (i < 0) {
				syslog(LOG_ERR, "select %s: %m", ttyn);
			} else if (i == 0) {
				syslog(LOG_NOTICE, "recycle tty %s", ttyn);
				(void)tcsetattr(STDIN_FILENO, TCSANOW, &tmode);
				exit(0);  /* recycle for init */
			}
			i = getty_chat(AC, CT, DC);
			if (i > 0) {
				syslog(LOG_ERR, "modem answer problem on %s", ttyn);
				(void)tcsetattr(STDIN_FILENO, TCSANOW, &tmode);
				exit(1);
			}
		} else { /* maybe blocking open */
			if (!opentty(ttyn, O_RDWR | (NC ? O_NONBLOCK : 0 )))
				exit(1);
		}
	    }
	}

	defttymode();
	for (;;) {

		/*
		 * if a delay was specified then sleep for that 
		 * number of seconds before writing the initial prompt
		 */
		if (first_sleep && DE) {
		    sleep(DE);
		    /* remove any noise */
		    (void)tcflush(STDIN_FILENO, TCIOFLUSH);
		}
		first_sleep = 0;

		setttymode(0);
		if (AB) {
			tname = autobaud();
			dogettytab();
			continue;
		}
		if (PS) {
			tname = portselector();
			dogettytab();
			continue;
		}
		if (CL && *CL)
			putpad(CL);
		edithost(HE);

		/* if this is the first time through this, and an
		   issue file has been given, then send it */
		if (first_time && IF) {
			int fd;

			if ((fd = open(IF, O_RDONLY)) != -1) {
				char * cp;

				while ((cp = getline(fd)) != NULL) {
					  putf(cp);
				}
				close(fd);
			}
		}
		first_time = 0;

		if (IM && *IM && !(PL && PP))
			putf(IM);
		if (setjmp(timeout)) {
			cfsetispeed(&tmode, B0);
			cfsetospeed(&tmode, B0);
			(void)tcsetattr(STDIN_FILENO, TCSANOW, &tmode);
			exit(1);
		}
		if (TO) {
			signal(SIGALRM, dingdong);
			alarm(TO);
		}

		rval = 0;
		if (AL) {
			const char *p = AL;
			char *q = name;

			while (*p && q < &name[sizeof name - 1]) {
				if (isupper(*p))
					upper = 1;
				else if (islower(*p))
					lower = 1;
				else if (isdigit(*p))
					digit = 1;
				*q++ = *p++;
			}
		} else if (!(PL && PP))
			rval = getname();
		if (rval == 2 || (PL && PP)) {
			oflush();
			alarm(0);
			limit.rlim_max = RLIM_INFINITY;
			limit.rlim_cur = RLIM_INFINITY;
			(void)setrlimit(RLIMIT_CPU, &limit);
			execle(PP, "ppplogin", ttyn, (char *) 0, env);
			syslog(LOG_ERR, "%s: %m", PP);
			exit(1);
		} else if (rval || AL) {
			int i;

			oflush();
			alarm(0);
			signal(SIGALRM, SIG_DFL);
			if (name[0] == '\0')
				continue;
			if (name[0] == '-') {
				puts("user names may not start with '-'.");
				continue;
			}
			if (!(upper || lower || digit)) {
				if (AL) {
					syslog(LOG_ERR,
					    "invalid auto-login name: %s", AL);
					exit(1);
				} else
					continue;
			}
			set_flags(2);
			if (crmod) {
				tmode.c_iflag |= ICRNL;
				tmode.c_oflag |= ONLCR;
			}
#if REALLY_OLD_TTYS
			if (upper || UC)
				tmode.sg_flags |= LCASE;
			if (lower || LC)
				tmode.sg_flags &= ~LCASE;
#endif
			if (tcsetattr(STDIN_FILENO, TCSANOW, &tmode) < 0) {
				syslog(LOG_ERR, "tcsetattr %s: %m", ttyn);
				exit(1);
			}
			signal(SIGINT, SIG_DFL);
			for (i = 0; environ[i] != (char *)0; i++)
				env[i] = environ[i];
			makeenv(&env[i]);

			limit.rlim_max = RLIM_INFINITY;
			limit.rlim_cur = RLIM_INFINITY;
			(void)setrlimit(RLIMIT_CPU, &limit);
			execle(LO, "login", AL ? "-fp" : "-p", name,
			    (char *) 0, env);
			syslog(LOG_ERR, "%s: %m", LO);
			exit(1);
		}
		alarm(0);
		signal(SIGALRM, SIG_DFL);
		signal(SIGINT, SIG_IGN);
		if (NX && *NX) {
			tname = NX;
			dogettytab();
		}
	}
}
Beispiel #18
0
void line_eval(char* line)
{
    if(line[0] == '/') {
        char inpt_command = line[1];
        /* Add friend */
        if(inpt_command == 'f') {
            int i;
            char temp_id[128];
            for (i = 0; i < 128; i++) 
                temp_id[i] = line[i+3];
            int num = m_addfriend(hex_string_to_bin(temp_id), (uint8_t*)"Install Gentoo", sizeof("Install Gentoo"));
            if (num >= 0) {
                char numstring[100];
                sprintf(numstring, "\n[i] Friend request sent. Wait to be accepted. Friend id: %d\n\n", num);
                printf(numstring);
            }
            else if (num == -1) 
                printf("\n[i] Message is too long.\n\n");
            else if (num == -2)
                printf("\n[i] Please add a message to your friend request.\n\n");
            else if (num == -3)
                printf("\n[i] That appears to be your own ID.\n\n");
            else if (num == -4)
                printf("\n[i] Friend request already sent.\n\n");
            else if (num == -5)
                printf("\n[i] Undefined error when adding friend\n\n");
        }

        else if (inpt_command == 'r') {
            do_header();
            printf("\n\n");
        }

        else if (inpt_command == 'l') {
            int activefriends = 0;
            int i;

            for (i = 0; i <= getnumfriends(); i++)
            {
                if (m_friendstatus(i) == 4)
                    activefriends++;
            }

            printf("\n[i] Friend List | Total: %d\n\n", activefriends);

            for (i = 0; i <= getnumfriends(); i++) {
                char name[MAX_NAME_LENGTH];
                getname(i, (uint8_t*)name);
                if (m_friendstatus(i) == 4)    
                    printf("[%d] %s\n\n", i, (uint8_t*)name);
            }
        }

        else if (inpt_command == 'd') {
            size_t len = strlen(line);
            char numstring[len-3];
            int i;
            for (i = 0; i < len; i++) {
                if (line[i+3] != ' ') {
                    numstring[i] = line[i+3];
                }
            }
            int num = atoi(numstring);
            m_delfriend(num);
            printf("\n\n");
        }
        /* Send message to friend */
        else if (inpt_command == 'm') {
            size_t len = strlen(line);
            char numstring[len-3];
            char message[len-3];
            int i;
            for (i = 0; i < len; i++) {
                if (line[i+3] != ' ') {
                    numstring[i] = line[i+3];
                } else {
                    int j;
                    for (j = (i+1); j < len; j++)
                        message[j-i-1] = line[j+3];
                    break;
                }
            }
            int num = atoi(numstring);
            if(m_sendmessage(num, (uint8_t*) message, sizeof(message)) != 1) {
                printf("\n[i] could not send message (they may be offline): %s\n", message);
            } else {
                //simply for aesthetics
                printf("\n");
            }
        }

        else if (inpt_command == 'n') {
            uint8_t name[MAX_NAME_LENGTH];
            int i = 0;
            size_t len = strlen(line);
            for (i = 3; i < len; i++) {
                if (line[i] == 0 || line[i] == '\n') break;
                name[i-3] = line[i];
            }
            name[i-3] = 0;
            setname(name, i);
            char numstring[100];
            sprintf(numstring, "\n[i] changed nick to %s\n\n", (char*)name);
            printf(numstring);

            FILE *name_file = NULL;
            name_file = fopen("namefile.txt", "w");
            fprintf(name_file, "%s", (char*)name);
            fclose(name_file);
        }

        else if (inpt_command == 's') {
            uint8_t status[MAX_USERSTATUS_LENGTH];
            int i = 0;
            size_t len = strlen(line);
            for (i = 3; i < len; i++) {
                if (line[i] == 0 || line[i] == '\n') break;
                status[i-3] = line[i];
            }
            status[i-3] = 0;
            m_set_userstatus(status, strlen((char*)status));
            char numstring[100];
            sprintf(numstring, "\n[i] changed status to %s\n\n", (char*)status);
            printf(numstring);

            FILE* status_file = NULL;
            status_file = fopen("statusfile.txt", "w");
            fprintf(status_file, "%s", (char*)status);
            fclose(status_file);
        }

        else if (inpt_command == 'a') {
            uint8_t numf = atoi(line + 3);
            char numchar[100];
            sprintf(numchar, "\n[i] friend request %u accepted\n\n", numf);
            printf(numchar);
            int num = m_addfriend_norequest(pending_requests[numf]);
            sprintf(numchar, "\n[i] added friendnumber %d\n\n", num);
            printf(numchar);
        }
        /* EXIT */
        else if (inpt_command == 'q') { 
            uint8_t status[MAX_USERSTATUS_LENGTH] = "Offline";
            m_set_userstatus(status, strlen((char*)status));
            exit(EXIT_SUCCESS);
        }
    } else {
        //nothing atm
    }
}
Beispiel #19
0
void load_file ()
    {
    struct place_obj *	place;
    struct matrix *	m_p;
    struct matrix *	prev_m_p=NULL;
    char		linebuf[LINEMAX], c;
    float		ftemp;
    int                 group_num, i, knd, noar, mark, nomp, norp;

#define VBAR '|'

#ifdef DEBUG
  fprintf(stderr,"  Start of load_file\n");
#endif
    /* skip first line containing '|0|' */
    fgets(linebuf, LINEMAX, nfp);

    /* skip comment */
    for ( ; ; ) {
	fgets(linebuf, LINEMAX, nfp);
	if ( linebuf[0] == VBAR ) break;
    }

    /* read number of objects in the net */

    fscanf(nfp,"f %d %d %d",&nomp,&place_num,&norp);
    fscanf(nfp,"%d %d",&trans_num,&group_num);
    if ( testplace > place_num ) {
      fprintf(stderr,"ERROR: place %d does not exist !\n",testplace);
	exit(1);
      }
    while ( (c=getc(nfp)) != '\n' );
    p_list = (struct place_obj *)emalloc((unsigned)(place_num*POB_SIZE));
    row_size = (unsigned)( 2 * (place_num + trans_num + 1) * ITM_SIZE );
    newrow = (ROWP)emalloc( row_size );
    row_size = (unsigned)( 2 * (trans_num + 2) * ITM_SIZE );
    elim_trans = (int *)emalloc((unsigned)(sizeof(int)*(1+trans_num)));
    poss_trans = (int *)emalloc((unsigned)(sizeof(int)*(1+trans_num)));
    n_pos = (int *)emalloc((unsigned)(sizeof(int)*(1+trans_num)));
    n_neg = (int *)emalloc((unsigned)(sizeof(int)*(1+trans_num)));
    { register int * ii, * jj, * ip, * in;
      for ( i=0, ii=elim_trans, jj=poss_trans, ip=n_pos, in=n_neg;
	    i++ < trans_num ;
	    *(++jj) = FALSE, *(++ii) = FALSE, *(++ip) = 0, *(++in) = 0 );
    }

    /* skip marking parameters */
    i = 1;
    while ( i++ <= nomp ) {
	getname( linebuf );
	fscanf(nfp,"%d",&mark);
	while ( (c=getc(nfp)) != '\n' );
    }

    /* read places */
    i = 1; place = p_list;
    while ( i <= place_num ) {
	place->covered = FALSE;
	getname( place -> tag );
	m_p = (struct matrix *) emalloc(MAT_SIZE);
	m_p -> rowp = (ROWP) emalloc( row_size );
	{ register int j; register ROWP p = m_p->rowp;
	  *(p++) = 1; *(p++) = i; *(p++) = 1;
	  for ( j = 0 ; j++ < trans_num ; *(p++) = 0, *(p++) = 0 );
	  *p = 0;
	}
	fscanf(nfp,"%d",&mark);
	while ( (c=getc(nfp)) != '\n' );
	if ( i == 1 ) {
	    mat = m_p;
	  }
	else {
	    prev_m_p -> next = m_p;
	  }
	prev_m_p = m_p;
	if ( i++ == place_num ) {
	    m_p -> next = NULL;
	  }
	place++;
      }
    oldmp = oldmm = NULL;

    /* skip rate parameters */
    i = 1;
    while ( i++ <= norp ) {
	getname( linebuf );
	fscanf(nfp,"%f",&ftemp);
	while ( (c=getc(nfp)) != '\n' );
    }

    /* skip groups */
    i = 1;
    while ( i++ <= group_num ) {
	getname( linebuf );
	while ( (c=getc(nfp)) != '\n' );
    }

    /* read transitions */
    for ( i = 0 ; i++ < trans_num ; ) {
	getname( linebuf );
	fscanf(nfp,"%f %d %d %d",
		 &ftemp,&mark,&knd,&noar);
	while ( (c=getc(nfp)) != '\n' );
	if ( mark < 0 ) {
	  int ii;
	    ii = mark = -mark;
	    while ( --ii ) {
		while ( getc(nfp) != '\n' );
	      }
	  }
	getarcs(TO_TRANS,i,noar);
	fscanf(nfp,"%d\n",&noar);
	getarcs(TO_PLACE,i,noar);
	fscanf(nfp,"%d\n",&noar);
	getarcs(INHIBITOR,i,noar);
      }
    /* compact rows */
    for ( m_p = mat ; m_p != NULL ; m_p = m_p->next ) {
	register ROWP pp, np; register int i;
	for ( pp = np = (m_p->rowp + 3), i = trans_num ; i-- > 0 ; np += 2 )
	    if ( ((short)(*np) != (short)0)
		  && ((short)(*(np+1)) != (short)0) ) {
		*(pp++) = *np;
		if ( (int)( *(pp++) = *(np+1) ) > 0 )
		    ++(n_pos[(int)(*np)]);
		else
		    ++(n_neg[(int)(*np)]);
	      }
	*pp = 0;
      }
#ifdef DEBUG
  fprintf(stderr,"  End of load_file\n");
#endif
}
Beispiel #20
0
/* XXXXXXXXXXXXXXXXXXXX */
asmlinkage int
sunos_mount(char *type, char *dir, int flags, void *data)
{
	int linux_flags = 0;
	int ret = -EINVAL;
	char *dev_fname = 0;
	char *dir_page, *type_page;

	if (!capable (CAP_SYS_ADMIN))
		return -EPERM;

	/* We don't handle the integer fs type */
	if ((flags & SMNT_NEWTYPE) == 0)
		goto out;

	/* Do not allow for those flags we don't support */
	if (flags & (SMNT_GRPID|SMNT_NOSUB|SMNT_MULTI|SMNT_SYS5))
		goto out;

	if(flags & SMNT_REMOUNT)
		linux_flags |= MS_REMOUNT;
	if(flags & SMNT_RDONLY)
		linux_flags |= MS_RDONLY;
	if(flags & SMNT_NOSUID)
		linux_flags |= MS_NOSUID;

	dir_page = getname(dir);
	ret = PTR_ERR(dir_page);
	if (IS_ERR(dir_page))
		goto out;

	type_page = getname(type);
	ret = PTR_ERR(type_page);
	if (IS_ERR(type_page))
		goto out1;

	if(strcmp(type_page, "ext2") == 0) {
		dev_fname = getname(data);
	} else if(strcmp(type_page, "iso9660") == 0) {
		dev_fname = getname(data);
	} else if(strcmp(type_page, "minix") == 0) {
		dev_fname = getname(data);
	} else if(strcmp(type_page, "nfs") == 0) {
		ret = sunos_nfs_mount (dir_page, flags, data);
		goto out2;
        } else if(strcmp(type_page, "ufs") == 0) {
		printk("Warning: UFS filesystem mounts unsupported.\n");
		ret = -ENODEV;
		goto out2;
	} else if(strcmp(type_page, "proc")) {
		ret = -ENODEV;
		goto out2;
	}
	ret = PTR_ERR(dev_fname);
	if (IS_ERR(dev_fname))
		goto out2;
	lock_kernel();
	ret = do_mount(dev_fname, dir_page, type_page, linux_flags, NULL);
	unlock_kernel();
	if (dev_fname)
		putname(dev_fname);
out2:
	putname(type_page);
out1:
	putname(dir_page);
out:
	return ret;
}
Beispiel #21
0
			NULL, NULL);
}

/*
 * sys_execve() executes a new program.
 */
asmlinkage int sys_execve(const char __user *ufilename,
			  const char __user *const __user *uargv,
			  const char __user *const __user *uenvp,
			  unsigned long r3, unsigned long r4, unsigned long r5,
			  unsigned long r6, struct pt_regs regs)
{
	int error;
	char *filename;

	filename = getname(ufilename);
	error = PTR_ERR(filename);
	if (IS_ERR(filename))
		goto out;

	error = do_execve(filename, uargv, uenvp, &regs);
	putname(filename);
out:
	return error;
}

/*
 * These bracket the sleeping functions..
 */
#define first_sched	((unsigned long) scheduling_functions_start_here)
#define last_sched	((unsigned long) scheduling_functions_end_here)
Beispiel #22
0
	return 0;
}

/*
 * sys_execve() executes a new program.
 */

asmlinkage int sys_execve(char __user *name, char __user * __user *argv, char __user * __user *envp)
{
	int error;
	char *filename;
	struct pt_regs *regs = (struct pt_regs *)((&name) + 6);

	lock_kernel();
	filename = getname(name);
	error = PTR_ERR(filename);
	if (IS_ERR(filename))
		goto out;
	error = do_execve(filename, argv, envp, regs);
	putname(filename);
 out:
	unlock_kernel();
	return error;
}

unsigned long get_wchan(struct task_struct *p)
{
	unsigned long fp, pc;
	unsigned long stack_page;
	int count = 0;
Beispiel #23
0
int unionfs_ioctl_addbranch(struct inode *inode, unsigned int cmd,
			    unsigned long arg)
{
	int err;
	struct unionfs_addbranch_args *addargs = NULL;
	struct nameidata nd;
	char *path = NULL;
	int gen;
	int i;
	int count;

	int pobjects;

	struct vfsmount **new_hidden_mnt = NULL;
	struct inode **new_uii_inode = NULL;
	struct dentry **new_udi_dentry = NULL;
	struct super_block **new_usi_sb = NULL;
	int *new_branchperms = NULL;
	atomic_t *new_counts = NULL;

	print_entry_location();

	err = -ENOMEM;
	addargs = KMALLOC(sizeof(struct unionfs_addbranch_args), GFP_UNIONFS);
	if (!addargs)
		goto out;

	err = -EFAULT;
	if (copy_from_user
	    (addargs, (void *)arg, sizeof(struct unionfs_addbranch_args)))
		goto out;

	err = -EINVAL;
	if (addargs->ab_perms & ~(MAY_READ | MAY_WRITE))
		goto out;
	if (!(addargs->ab_perms & MAY_READ))
		goto out;

	err = -E2BIG;
	if (sbend(inode->i_sb) > FD_SETSIZE)
		goto out;

	err = -ENOMEM;
	if (!(path = getname(addargs->ab_path)))
		goto out;

	err = path_lookup(path, LOOKUP_FOLLOW, &nd);

	RECORD_PATH_LOOKUP(&nd);
	if (err)
		goto out;
	if ((err = check_branch(&nd))) {
		path_release(&nd);
		RECORD_PATH_RELEASE(&nd);
		goto out;
	}

	unionfs_write_lock(inode->i_sb);
	lock_dentry(inode->i_sb->s_root);

	err = -EINVAL;
	if (addargs->ab_branch < 0
	    || (addargs->ab_branch > (sbend(inode->i_sb) + 1)))
		goto out;

	if ((err = newputmap(inode->i_sb)))
		goto out;

	stopd(inode->i_sb)->b_end++;
	dtopd(inode->i_sb->s_root)->udi_bcount++;
	set_dbend(inode->i_sb->s_root, dbend(inode->i_sb->s_root) + 1);
	itopd(inode->i_sb->s_root->d_inode)->b_end++;

	atomic_inc(&stopd(inode->i_sb)->usi_generation);
	gen = atomic_read(&stopd(inode->i_sb)->usi_generation);

	pobjects = (sbend(inode->i_sb) + 1) - UNIONFS_INLINE_OBJECTS;
	if (pobjects > 0) {
		/* Reallocate the dynamic structures. */
		new_hidden_mnt =
		    KMALLOC(sizeof(struct vfsmount *) * pobjects, GFP_UNIONFS);
		new_udi_dentry =
		    KMALLOC(sizeof(struct dentry *) * pobjects, GFP_UNIONFS);
		new_uii_inode =
		    KMALLOC(sizeof(struct inode *) * pobjects, GFP_UNIONFS);
		new_usi_sb =
		    KMALLOC(sizeof(struct super_block *) * pobjects,
			    GFP_UNIONFS);
		new_counts = KMALLOC(sizeof(atomic_t) * pobjects, GFP_UNIONFS);
		new_branchperms = KMALLOC(sizeof(int) * pobjects, GFP_UNIONFS);
		if (!new_hidden_mnt || !new_udi_dentry || !new_uii_inode
		    || !new_counts || !new_usi_sb || !new_branchperms) {
			err = -ENOMEM;
			goto out;
		}
		memset(new_hidden_mnt, 0, sizeof(struct vfsmount *) * pobjects);
		memset(new_udi_dentry, 0, sizeof(struct dentry *) * pobjects);
		memset(new_uii_inode, 0, sizeof(struct inode *) * pobjects);
		memset(new_usi_sb, 0, sizeof(struct super_block *) * pobjects);
		memset(new_branchperms, 0, sizeof(int) * pobjects);
	}

	/* Copy the in-place values to our new structure. */
	for (i = UNIONFS_INLINE_OBJECTS; i < addargs->ab_branch; i++) {
		int j = i - UNIONFS_INLINE_OBJECTS;

		count = branch_count(inode->i_sb, i);
		atomic_set(&(new_counts[j]), count);

		new_branchperms[j] = branchperms(inode->i_sb, i);
		new_hidden_mnt[j] = stohiddenmnt_index(inode->i_sb, i);

		new_usi_sb[j] = stohs_index(inode->i_sb, i);
		new_udi_dentry[j] = dtohd_index(inode->i_sb->s_root, i);
		new_uii_inode[j] = itohi_index(inode->i_sb->s_root->d_inode, i);
	}

	/* Shift the ends to the right (only handle reallocated bits). */
	for (i = sbend(inode->i_sb) - 1; i >= (int)addargs->ab_branch; i--) {
		int j = i + 1;
		int perms;
		struct vfsmount *hm;
		struct super_block *hs;
		struct dentry *hd;
		struct inode *hi;
		int pmindex;

		count = branch_count(inode->i_sb, i);
		perms = branchperms(inode->i_sb, i);
		hm = stohiddenmnt_index(inode->i_sb, i);
		hs = stohs_index(inode->i_sb, i);
		hd = dtohd_index(inode->i_sb->s_root, i);
		hi = itohi_index(inode->i_sb->s_root->d_inode, i);

		/* Update the newest putmap, so it is correct for later. */
		pmindex = stopd(inode->i_sb)->usi_lastputmap;
		pmindex -= stopd(inode->i_sb)->usi_firstputmap;
		stopd(inode->i_sb)->usi_putmaps[pmindex]->map[i] = j;

		if (j >= UNIONFS_INLINE_OBJECTS) {
			j -= UNIONFS_INLINE_OBJECTS;
			atomic_set(&(new_counts[j]), count);
			new_branchperms[j] = perms;
			new_hidden_mnt[j] = hm;
			new_usi_sb[j] = hs;
			new_udi_dentry[j] = hd;
			new_uii_inode[j] = hi;
		} else {
			set_branch_count(inode->i_sb, j, count);
			set_branchperms(inode->i_sb, j, perms);
			set_stohiddenmnt_index(inode->i_sb, j, hm);
			set_stohs_index(inode->i_sb, j, hs);
			set_dtohd_index(inode->i_sb->s_root, j, hd);
			set_itohi_index(inode->i_sb->s_root->d_inode, j, hi);
		}
	}

	/* Now we can free the old ones. */
	KFREE(dtopd(inode->i_sb->s_root)->udi_dentry_p);
	KFREE(itopd(inode->i_sb->s_root->d_inode)->uii_inode_p);
	KFREE(stopd(inode->i_sb)->usi_hidden_mnt_p);
	KFREE(stopd(inode->i_sb)->usi_sb_p);
	KFREE(stopd(inode->i_sb)->usi_sbcount_p);
	KFREE(stopd(inode->i_sb)->usi_branchperms_p);

	/* Update the real pointers. */
	dtohd_ptr(inode->i_sb->s_root) = new_udi_dentry;
	itohi_ptr(inode->i_sb->s_root->d_inode) = new_uii_inode;
	stohiddenmnt_ptr(inode->i_sb) = new_hidden_mnt;
	stohs_ptr(inode->i_sb) = new_usi_sb;
	stopd(inode->i_sb)->usi_sbcount_p = new_counts;
	stopd(inode->i_sb)->usi_branchperms_p = new_branchperms;

	/* Re-NULL the new ones so we don't try to free them. */
	new_hidden_mnt = NULL;
	new_udi_dentry = NULL;
	new_usi_sb = NULL;
	new_uii_inode = NULL;
	new_counts = NULL;
	new_branchperms = NULL;

	/* Put the new dentry information into it's slot. */
	set_dtohd_index(inode->i_sb->s_root, addargs->ab_branch, nd.dentry);
	set_itohi_index(inode->i_sb->s_root->d_inode, addargs->ab_branch,
			igrab(nd.dentry->d_inode));
	set_branchperms(inode->i_sb, addargs->ab_branch, addargs->ab_perms);
	set_branch_count(inode->i_sb, addargs->ab_branch, 0);
	set_stohiddenmnt_index(inode->i_sb, addargs->ab_branch, nd.mnt);
	set_stohs_index(inode->i_sb, addargs->ab_branch, nd.dentry->d_sb);

	atomic_set(&dtopd(inode->i_sb->s_root)->udi_generation, gen);
	atomic_set(&itopd(inode->i_sb->s_root->d_inode)->uii_generation, gen);

	fixputmaps(inode->i_sb);

      out:
	unlock_dentry(inode->i_sb->s_root);
	unionfs_write_unlock(inode->i_sb);

	KFREE(new_hidden_mnt);
	KFREE(new_udi_dentry);
	KFREE(new_uii_inode);
	KFREE(new_usi_sb);
	KFREE(new_counts);
	KFREE(new_branchperms);
	KFREE(addargs);
	if (path)
		putname(path);

	print_exit_status(err);

	return err;
}
Beispiel #24
0
int argout(int dtype, int dval, int optype)
{
  char *s;

  if (dtype&AGT_VAR) dtype=AGT_VAR;

  if ((optype&3)==1) /* variable */
    dtype=AGT_VAR;
  if (optype&2) {/* NOUN or OBJECT */
    if (dtype>=64 && dtype!=AGT_NUM) 
      dbgprintf("ILL:");
    if (optype==2)
      print_special_obj(0); /* NOUN */
    else 
      print_special_obj(1);  /* OBJECT */
    return 0;
  }

  if (!interp_arg) 
    dbgprintf("%d",dval);
  else {
    if (dtype<64) {
      if (dval==-1) 
	print_special_obj(2); /* NAME */
      else {
	s=getname(dval);
	if (dtype&(AGT_ITEM|AGT_CREAT|AGT_SELF|AGT_WORN)) 
	  dbgprintf("<%d:%s>",dval,s);
	else 
	  dbgprintf("{%d:%s}",dval,s);
	rfree(s);	
      }
    } else if ( (dtype&AGT_VAR)!=0) {
      if (dval==-1) 
	print_tos();
      else
	printval("Var",dval,dbgvarptr);
    } else switch(dtype) 
      {
      case AGT_TIME:
	dbgprintf("%2d:%2d",dval/100,dval%100);break;
      case AGT_NUM:  /* Numeric */
        dbgprintf("%d",dval);break;
      case AGT_FLAG:  /* Flag */
	printval("Flg",dval,dbgflagptr);break;
      case AGT_ROOMFLAG: /* Roomflag */
        dbgprintf("RoomFlag%d",dval);break;
      case AGT_QUEST:  /* Question */
	if (dval<=MaxQuestion && dval>=1 && question!=NULL) {
	  dbgprintf("\nQ%d:%s\n",dval,question[dval-1]);
	  dbgprintf("[A:%s]",answer[dval-1]);      
	} else if (quest_ptr!=NULL) {
	  dbgprintf("\nQ%d: ",dval);
	  print_msg(quest_ptr[dval-1]);
	  dbgprintf("[A:");
	  print_msg(ans_ptr[dval-1]);
	}
	break;
      case AGT_MSG: /* Message */
	if (dval>last_message || dval<1 || msg_ptr==NULL) 
	  dbgprintf("ILLEGAL MESSAGE");
	else {
	  dbgprintf("(Msg%d)",dval);
	  if (!dbg_nomsg)
	    print_msg(msg_ptr[dval-1]);
	}
	break;
      case AGT_ERR: /* Message */
	if (dval>NUM_ERR || dval<1 || err_ptr==NULL) 
	  dbgprintf("ILLEGAL MESSAGE");
	else {
	  dbgprintf("(Std%d)",dval);
	  if (!dbg_nomsg) 
	    print_msg(err_ptr[dval-1]);
	}
	break;
      case AGT_STR: /* String */
	if (dval-1>=MAX_USTR || userstr==NULL) 
	  dbgprintf("ILLEGAL STRING");
	else 
	  dbgprintf("\nStr%d:%s",dval,userstr[dval]);
	break;
      case AGT_CNT: /* Counter */
	printval("Cnt",dval,dbgcntptr);break;
      case AGT_DIR: /* Direction */
	if (dval>=1 && dval<=13) 
	  dbgprintf("%s",exitname[dval-1]);
	else dbgprintf("ILL_DIR(%d)",dval);
	break;
      case AGT_SUB: /* Subroutine */
	dbgprintf("Subroutine %d",dval);break;
      case AGT_PIC: /* Picture */
      case AGT_PIX:
	dbgprintf("Picture #%d",dval);break;
      case AGT_FONT: /* Font */
	dbgprintf("Font #%d",dval);break;
      case AGT_SONG:  /* Song */
	dbgprintf("Song #%d",dval);break;
      case AGT_OBJFLAG: 
	dbgprintf("ObjFlag%d",dval);break;
      case AGT_OBJPROP: 
	dbgprintf("ObjProp%d",dval);break;
      case AGT_ATTR:
	if (dval<0 || dval>=NUM_ATTR) 
	  dbgprintf("UnkownAttr%d",dval);
	else 
	  dbgprintf("%s",attrlist[dval].name);
	break;
      case AGT_PROP:
	if (dval<0 || dval>=NUM_PROP)
	  dbgprintf("UnknownProp%d",dval);
	else 
	  dbgprintf("%s",proplist[dval].name);
	break;
      case AGT_EXIT:
	if (dval>=exitmsg_base) 
	  argout(AGT_MSG,dval-exitmsg_base,0);
	else 
	  argout(AGT_ROOM,dval,0);
	break;
      default:
	dbgprintf("?+%d",dval);
      }
  }
  return 1;
}
Beispiel #25
0
void do_eventlog(FILE *output, int maxcount, int maxminutes, char *fromtime, char *totime, 
		char *pageregex, char *expageregex,
		char *hostregex, char *exhostregex,
		char *testregex, char *extestregex,
		char *colrregex, int ignoredialups,
		f_hostcheck hostcheck,
		event_t **eventlist, countlist_t **hostcounts, countlist_t **servicecounts,
		countsummary_t counttype, eventsummary_t sumtype, char *periodstring)
{
	FILE *eventlog;
	char eventlogfilename[PATH_MAX];
	time_t firstevent = 0;
	time_t lastevent = getcurrenttime(NULL);
	event_t	*eventhead = NULL;
	struct stat st;
	char l[MAX_LINE_LEN];
	char title[200];

	/* For the PCRE matching */
	const char *errmsg = NULL;
	int errofs = 0;
	pcre *pageregexp = NULL;
	pcre *expageregexp = NULL;
	pcre *hostregexp = NULL;
	pcre *exhostregexp = NULL;
	pcre *testregexp = NULL;
	pcre *extestregexp = NULL;
	pcre *colrregexp = NULL;
	countlist_t *hostcounthead = NULL, *svccounthead = NULL;

	if (eventlist) *eventlist = NULL;
	if (hostcounts) *hostcounts = NULL;
	if (servicecounts) *servicecounts = NULL;

	havedoneeventlog = 1;

	if ((maxminutes > 0) && (fromtime || totime)) {
		fprintf(output, "<B>Only one time interval type is allowed!</B>");
		return;
	}

	if (fromtime) {
		firstevent = eventreport_time(fromtime);
		if(firstevent < 0) {
			if (output) fprintf(output,"<B>Invalid 'from' time: %s</B>", htmlquoted(fromtime));
			return;
		}
	}
	else if (maxminutes == -1) {
		/* Unlimited number of minutes */
		firstevent = 0;
	}
	else if (maxminutes > 0) {
		firstevent = getcurrenttime(NULL) - maxminutes*60;
	}
	else {
		firstevent = getcurrenttime(NULL) - 86400;
	}

	if (totime) {
		lastevent = eventreport_time(totime);
		if (lastevent < 0) {
			if (output) fprintf(output,"<B>Invalid 'to' time: %s</B>", htmlquoted(totime));
			return;
		}
		if (lastevent < firstevent) {
			if (output) fprintf(output,"<B>'to' time must be after 'from' time.</B>");
			return;
		}
	}

	if (!maxcount) maxcount = 100;

	if (pageregex && *pageregex) pageregexp = pcre_compile(pageregex, PCRE_CASELESS, &errmsg, &errofs, NULL);
	if (expageregex && *expageregex) expageregexp = pcre_compile(expageregex, PCRE_CASELESS, &errmsg, &errofs, NULL);
	if (hostregex && *hostregex) hostregexp = pcre_compile(hostregex, PCRE_CASELESS, &errmsg, &errofs, NULL);
	if (exhostregex && *exhostregex) exhostregexp = pcre_compile(exhostregex, PCRE_CASELESS, &errmsg, &errofs, NULL);
	if (testregex && *testregex) testregexp = pcre_compile(testregex, PCRE_CASELESS, &errmsg, &errofs, NULL);
	if (extestregex && *extestregex) extestregexp = pcre_compile(extestregex, PCRE_CASELESS, &errmsg, &errofs, NULL);
	if (colrregex && *colrregex) colrregexp = pcre_compile(colrregex, PCRE_CASELESS, &errmsg, &errofs, NULL);

	sprintf(eventlogfilename, "%s/allevents", xgetenv("XYMONHISTDIR"));
	eventlog = fopen(eventlogfilename, "r");

	if (eventlog && (stat(eventlogfilename, &st) == 0)) {
		time_t curtime;
		int done = 0;
		int unlimited = (maxcount == -1);

		if (unlimited) maxcount = 1000;
		do {
			/* Find a spot in the eventlog file close to where the firstevent time is */
			fseeko(eventlog, 0, SEEK_END);
			do {
				/* Go back maxcount*80 bytes - one entry is ~80 bytes */
				if (ftello(eventlog) > maxcount*80) {
					unsigned int uicurtime;
					fseeko(eventlog, -maxcount*80, SEEK_CUR); 
					if (fgets(l, sizeof(l), eventlog) &&  /* Skip to start of line */
					    fgets(l, sizeof(l), eventlog)) {
						sscanf(l, "%*s %*s %u %*u %*u %*s %*s %*d", &uicurtime);
						curtime = uicurtime;
						done = (curtime < firstevent);
						if (unlimited && !done) maxcount += 1000;
					}
					else {
						if (output) fprintf(output,"Error reading eventlog file %s: %s\n", eventlogfilename, strerror(errno));
						return;
					}
				}
				else {
					rewind(eventlog);
					curtime = 0;
					done = 1;
				}
			} while (!done);

			if (unlimited) unlimited = ((curtime > firstevent) && (ftello(eventlog) > 0));
		} while (unlimited);
	}
	
	eventhead = NULL;

	while (eventlog && (fgets(l, sizeof(l), eventlog))) {

		time_t eventtime, changetime, duration;
		unsigned int uievt, uicht, uidur;
		char hostname[MAX_LINE_LEN], svcname[MAX_LINE_LEN], newcol[MAX_LINE_LEN], oldcol[MAX_LINE_LEN];
		char *newcolname, *oldcolname;
		int state, itemsfound, colrmatch;
		event_t *newevent;
		void *eventhost;
		struct htnames_t *eventcolumn;
		int ovector[30];
		eventcount_t *countrec;

		itemsfound = sscanf(l, "%s %s %u %u %u %s %s %d",
			hostname, svcname,
			&uievt, &uicht, &uidur, 
			newcol, oldcol, &state);
		eventtime = uievt; changetime = uicht; duration = uidur;
		oldcolname = colorname(eventcolor(oldcol));
		newcolname = colorname(eventcolor(newcol));
		/* For DURATION counts, we must parse all events until now */
		if ((counttype != XYMON_COUNT_DURATION) && (eventtime > lastevent)) break;
		eventhost = hostinfo(hostname);
		eventcolumn = getname(svcname, 1);

		if ( (itemsfound == 8) && 
		     (eventtime >= firstevent) && 
		     (eventhost && !xmh_item(eventhost, XMH_FLAG_NONONGREEN)) && 
		     (wanted_eventcolumn(svcname)) ) {

			if (eventfilter(eventhost, svcname, 
					pageregexp, expageregexp, 
					hostregexp, exhostregexp,
					testregexp, extestregexp,
					ignoredialups, hostcheck) == 0) continue;

			/* For duration counts, record all events. We'll filter out the colors later. */
			if (colrregexp && (counttype != XYMON_COUNT_DURATION)) {
				colrmatch = ( (pcre_exec(colrregexp, NULL, newcolname, strlen(newcolname), 0, 0,
							ovector, (sizeof(ovector)/sizeof(int))) >= 0) ||
					      (pcre_exec(colrregexp, NULL, oldcolname, strlen(oldcolname), 0, 0,
							ovector, (sizeof(ovector)/sizeof(int))) >= 0) );
			}
			else
				colrmatch = 1;
			if (!colrmatch) continue;

			newevent = (event_t *) malloc(sizeof(event_t));
			newevent->host       = eventhost;
			newevent->service    = eventcolumn;
			newevent->eventtime  = eventtime;
			newevent->changetime = changetime;
			newevent->duration   = duration;
			newevent->newcolor   = eventcolor(newcol);
			newevent->oldcolor   = eventcolor(oldcol);
			newevent->next = eventhead;
			eventhead = newevent;

			if (counttype != XYMON_COUNT_DURATION) {
				countrec = (eventcount_t *)xmh_item(eventhost, XMH_DATA);
				while (countrec && (countrec->service != eventcolumn)) countrec = countrec->next;
				if (countrec == NULL) {
					countrec = (eventcount_t *)calloc(1, sizeof(eventcount_t));
					countrec->service = eventcolumn;
					countrec->next = (eventcount_t *)xmh_item(eventhost, XMH_DATA);
					xmh_set_item(eventhost, XMH_DATA, (void *)countrec);
				}
				countrec->count++;
			}
		}
	}

	/* Count the state changes per host */
	svccounthead = hostcounthead = NULL;
	switch (counttype) {
	  case XYMON_COUNT_EVENTS: count_events(&hostcounthead, &svccounthead); break;
	  case XYMON_COUNT_DURATION: count_duration(firstevent, lastevent,
					       pageregexp, expageregexp,
					       hostregexp, exhostregexp,
					       testregexp, extestregexp,
					       ignoredialups, hostcheck,
					       eventhead, &hostcounthead, &svccounthead); break;
	  default: break;
	}

	if (hostcounthead) hostcounthead = msort(hostcounthead, record_compare, record_getnext, record_setnext);
	if (svccounthead)  svccounthead = msort(svccounthead, record_compare, record_getnext, record_setnext);

	if (eventhead && (output != NULL)) {
		char *bgcolors[2] = { "#000000", "#000033" };
		int  bgcolor = 0;
		struct event_t *ewalk, *lasttoshow = eventhead;
		countlist_t *cwalk;
		unsigned long totalcount = 0;

		if (periodstring) fprintf(output, "<p><font size=+1>%s</font></p>\n", htmlquoted(periodstring));

		switch (sumtype) {
		  case XYMON_S_HOST_BREAKDOWN:
			/* Request for a specific service, show breakdown by host */
			for (cwalk = hostcounthead; (cwalk); cwalk = cwalk->next) totalcount += cwalk->total;
			fprintf(output, "<table summary=\"Breakdown by host\" border=0>\n");
			fprintf(output, "<tr><th align=left>Host</th><th colspan=2>%s</th></tr>\n",
				(counttype == XYMON_COUNT_EVENTS) ? "State changes" : "Seconds red/yellow");
			fprintf(output, "<tr><td colspan=3><hr width=\"100%%\"></td></tr>\n");
			for (cwalk = hostcounthead; (cwalk && (cwalk->total > 0)); cwalk = cwalk->next) {
				fprintf(output, "<tr><td align=left>%s</td><td align=right>%lu</td><td align=right>(%6.2f %%)</tr>\n",
					xmh_item(cwalk->src, XMH_HOSTNAME), 
					cwalk->total, ((100.0 * cwalk->total) / totalcount));
			}
			fprintf(output, "</table>\n");
			break;

		  case XYMON_S_SERVICE_BREAKDOWN:
			/* Request for a specific host, show breakdown by service */
			for (cwalk = svccounthead; (cwalk); cwalk = cwalk->next) totalcount += cwalk->total;
			fprintf(output, "<table summary=\"Breakdown by service\" border=0>\n");
			fprintf(output, "<tr><th align=left>Service</th><th colspan=2>%s</th></tr>\n",
				(counttype == XYMON_COUNT_EVENTS) ? "State changes" : "Seconds red/yellow");
			fprintf(output, "<tr><td colspan=3><hr width=\"100%%\"></td></tr>\n");
			for (cwalk = svccounthead; (cwalk && (cwalk->total > 0)); cwalk = cwalk->next) {
				fprintf(output, "<tr><td align=left>%s</td><td align=right>%lu</td><td align=right>(%6.2f %%)</tr>\n",
					((htnames_t *)cwalk->src)->name, 
					cwalk->total, ((100.0 * cwalk->total) / totalcount));
			}
			fprintf(output, "</table>\n");
			break;

		  case XYMON_S_NONE:
			break;
		}

		if (sumtype == XYMON_S_NONE) {
			int  count;
			count=0;
			ewalk=eventhead; 
			do {
				count++;
				lasttoshow = ewalk;
				ewalk = ewalk->next;
			} while (ewalk && (count<maxcount));
			if (ewalk) ewalk->next = NULL;	/* Terminate list if any items left */

			if (maxminutes > 0)  { 
				sprintf(title, "%d events received in the past %u minutes", 
					count, (unsigned int)((getcurrenttime(NULL) - lasttoshow->eventtime) / 60));
			}
			else {
				sprintf(title, "%d events received.", count);
			}
		}
		else {
			strcpy(title, "Events in summary");
		}

		fprintf(output, "<BR><BR>\n");
		fprintf(output, "<TABLE SUMMARY=\"$EVENTSTITLE\" BORDER=0>\n");
		fprintf(output, "<TR BGCOLOR=\"#333333\">\n");
		fprintf(output, "<TD ALIGN=CENTER COLSPAN=6><FONT SIZE=-1 COLOR=\"#33ebf4\">%s</FONT></TD></TR>\n", htmlquoted(title));

		for (ewalk=eventhead; (ewalk); ewalk=ewalk->next) {
			char *hostname = xmh_item(ewalk->host, XMH_HOSTNAME);

			if ( (counttype == XYMON_COUNT_DURATION) &&
			     (ewalk->oldcolor < COL_YELLOW) &&
			     (ewalk->newcolor < COL_YELLOW) ) continue;

			if ( (counttype == XYMON_COUNT_DURATION) &&
			     (ewalk->eventtime >= lastevent) ) continue;

			fprintf(output, "<TR BGCOLOR=%s>\n", bgcolors[bgcolor]);
			bgcolor = ((bgcolor + 1) % 2);

			fprintf(output, "<TD ALIGN=CENTER>%s</TD>\n", ctime(&ewalk->eventtime));

			if (ewalk->newcolor == COL_CLEAR) {
				fprintf(output, "<TD ALIGN=CENTER BGCOLOR=black><FONT COLOR=white>%s</FONT></TD>\n",
					hostname);
			}
			else {
				fprintf(output, "<TD ALIGN=CENTER BGCOLOR=%s><FONT COLOR=black>%s</FONT></TD>\n",
					colorname(ewalk->newcolor), hostname);
			}

			fprintf(output, "<TD ALIGN=LEFT>%s</TD>\n", ewalk->service->name);
			fprintf(output, "<TD><A HREF=\"%s\">\n", 
				histlogurl(hostname, ewalk->service->name, ewalk->changetime, NULL));
			fprintf(output, "<IMG SRC=\"%s/%s\"  HEIGHT=\"%s\" WIDTH=\"%s\" BORDER=0 ALT=\"%s\" TITLE=\"%s\"></A>\n", 
				xgetenv("XYMONSKIN"), dotgiffilename(ewalk->oldcolor, 0, 0), 
				xgetenv("DOTHEIGHT"), xgetenv("DOTWIDTH"), 
				colorname(ewalk->oldcolor), colorname(ewalk->oldcolor));
			fprintf(output, "<IMG SRC=\"%s/arrow.gif\" BORDER=0 ALT=\"From -&gt; To\">\n", 
				xgetenv("XYMONSKIN"));
			fprintf(output, "<TD><A HREF=\"%s\">\n", 
				histlogurl(hostname, ewalk->service->name, ewalk->eventtime, NULL));
			fprintf(output, "<IMG SRC=\"%s/%s\"  HEIGHT=\"%s\" WIDTH=\"%s\" BORDER=0 ALT=\"%s\" TITLE=\"%s\"></A></TD>\n", 
				xgetenv("XYMONSKIN"), dotgiffilename(ewalk->newcolor, 0, 0), 
				xgetenv("DOTHEIGHT"), xgetenv("DOTWIDTH"), 
				colorname(ewalk->newcolor), colorname(ewalk->newcolor));
			fprintf(output, "</TR>\n");
		}

		fprintf(output, "</TABLE>\n");

	}
	else if (output != NULL) {
		/* No events during the past maxminutes */
		if (eventlog)
			sprintf(title, "No events received in the last %d minutes", maxminutes);
		else
			strcpy(title, "No events logged");

		fprintf(output, "<CENTER><BR>\n");
		fprintf(output, "<TABLE SUMMARY=\"%s\" BORDER=0>\n", title);
		fprintf(output, "<TR BGCOLOR=\"#333333\">\n");
		fprintf(output, "<TD ALIGN=CENTER COLSPAN=6><FONT SIZE=-1 COLOR=\"#33ebf4\">%s</FONT></TD>\n", htmlquoted(title));
		fprintf(output, "</TR>\n");
		fprintf(output, "</TABLE>\n");
		fprintf(output, "</CENTER>\n");
	}

	if (eventlog) fclose(eventlog);

	if (pageregexp) pcre_free(pageregexp);
	if (hostregexp) pcre_free(hostregexp);
	if (testregexp) pcre_free(testregexp);
	if (colrregexp) pcre_free(colrregexp);

	/* Return the event- and count-lists, if wanted - or clean them up */
	if (eventlist) {
		*eventlist = eventhead;
	}
	else {
		event_t	*zombie, *ewalk = eventhead;
		while (ewalk) { zombie = ewalk; ewalk = ewalk->next; xfree(zombie); }
	}

	if (hostcounts) {
		*hostcounts = hostcounthead;
	}
	else {
		countlist_t *zombie, *hwalk = hostcounthead;
		while (hwalk) { zombie = hwalk; hwalk = hwalk->next; xfree(zombie); }

	}

	if (servicecounts) {
		*servicecounts = svccounthead;
	}
	else {
		countlist_t *zombie, *swalk = svccounthead;
		while (swalk) { zombie = swalk; swalk = swalk->next; xfree(zombie); }
	}
}
Beispiel #26
0
static void savescores(int score) {
    FILE *handle;
    int i,j,ch;
    score_t scores[NUMSCORES];
    char header[strlen(SCORE_HEADER)+1];
    time_t tmp = 0;
    if ((handle = fopen(scorefile,"r")) == NULL)
    {
        createscores(score);
        return;
    }
    i = fread(header,strlen (SCORE_HEADER),1,handle);
    if ((i != 1) || (strncmp (SCORE_HEADER,header,strlen (SCORE_HEADER)) != 0)) {
        createscores (score);
        return;
    }
    for (i = 0; i < NUMSCORES; i++) {
        j = 0;
        while ((ch = fgetc(handle)) != '\0') {
            if ((ch == EOF) || (j >= NAMELEN - 2)) {
                createscores(score);
                return;
            }
            scores[i].name[j++] = (char) ch;
        }
        scores[i].name[j] = '\0';
        j = fread(&(scores[i].score),sizeof (int),1,handle);
        if (j != 1) {
            createscores (score);
            return;
        }
        j = fread(&(scores[i].timestamp),sizeof (time_t),1,handle);
        if (j != 1) {
            createscores (score);
            return;
        }
    }
    fclose(handle);
    if (score > scores[NUMSCORES - 1].score) {
        getname(scores[NUMSCORES - 1].name);
        scores[NUMSCORES - 1].score = score;
        scores[NUMSCORES - 1].timestamp = tmp = time (NULL);
    }
    qsort(scores,NUMSCORES,sizeof (score_t),cmpscores);
    if ((handle = fopen(scorefile, "w")) == NULL) {
        err2();
    }
    strcpy(header, SCORE_HEADER);
    i = fwrite(header, strlen(SCORE_HEADER), 1, handle);
    if (i != 1) {
        err2();
    }
    for (i = 0; i < NUMSCORES; i++) {
        j = fwrite(scores[i].name,strlen (scores[i].name) + 1,1,handle);
        if (j != 1) {
            err2();
        }
        j = fwrite(&(scores[i].score),sizeof (int),1,handle);
        if (j != 1) {
            err2();
        }
        j = fwrite(&(scores[i].timestamp),sizeof (time_t),1,handle);
        if (j != 1) {
            err2();
        }
    }
    fclose(handle);

    fprintf(stderr,"%s",scoretitle);
    i = 0;
    while ((i < NUMSCORES) && (scores[i].score != -1)) {
        j = scores[i].timestamp == tmp ? '*' : ' ';
        fprintf (stderr,"\t %2d%c %7d        %s\n",i + 1,j,scores[i].score,scores[i].name);
        i++;
    }
    fprintf(stderr,"\n");
}
Beispiel #27
0
static void testC() {
#define getnum(s)	((*s++) - '0')
#define getname(s)	(nome[0] = *s++, nome)

	static int32 locks[10];
	lua_Object reg[10];
	char nome[2];
	char *s = luaL_check_string(1);
	nome[1] = 0;
	while (1) {
		switch (*s++) {
			case '0': case '1': case '2': case '3': case '4':
			case '5': case '6': case '7': case '8': case '9':
				lua_pushnumber(*(s - 1) - '0');
				break;
			case 'c':
				reg[getnum(s)] = lua_createtable();
				break;
			case 'C':
				{
					lua_CFunction f = lua_getcfunction(lua_getglobal(getname(s)));
					lua_pushCclosure(f, getnum(s));
					break;
				}
			case 'P':
				reg[getnum(s)] = lua_pop();
				break;
			case 'g':
				{
					int32 n=getnum(s);
					reg[n] = lua_getglobal(getname(s));
					break;
				}
			case 'G':
				{
					int32 n = getnum(s);
					reg[n] = lua_rawgetglobal(getname(s));
					break;
				}
			case 'l':
				locks[getnum(s)] = lua_ref(1);
				break;
			case 'L':
				locks[getnum(s)] = lua_ref(0);
				break;
			case 'r':
				{
					int32 n = getnum(s);
					reg[n] = lua_getref(locks[getnum(s)]);
					break;
				}
			case 'u':
				lua_unref(locks[getnum(s)]);
				break;
			case 'p':
				{
					int32 n = getnum(s);
					reg[n] = lua_getparam(getnum(s));
					break;
				}
			case '=':
				lua_setglobal(getname(s));
				break;
			case 's':
				lua_pushstring(getname(s));
				break;
			case 'o':
				lua_pushobject(reg[getnum(s)]);
				break;
			case 'f':
				lua_call(getname(s));
				break;
			case 'i':
				reg[getnum(s)] = lua_gettable();
				break;
			case 'I':
				reg[getnum(s)] = lua_rawgettable();
				break;
			case 't':
				lua_settable();
				break;
			case 'T':
				lua_rawsettable();
				break;
			default:
				luaL_verror("unknown command in `testC': %c", *(s - 1));
		}
		if (*s == 0)
			return;
		if (*s++ != ' ')
			lua_error("missing ` ' between commands in `testC'");
	}
}
Beispiel #28
0
}

asmlinkage int microblaze_clone(int flags, unsigned long stack, struct pt_regs *regs)
{
	if (!stack)
		stack = regs->r1;
	return do_fork(flags, stack, regs, 0, NULL, NULL);
}

asmlinkage int microblaze_execve(char __user *filenamei, char __user *__user *argv,
			char __user *__user *envp, struct pt_regs *regs)
{
	int error;
	char *filename;

	filename = getname(filenamei);
	error = PTR_ERR(filename);
	if (IS_ERR(filename))
		goto out;
	error = do_execve(filename, argv, envp, regs);
	putname(filename);
out:
	return error;
}

asmlinkage unsigned long
sys_mmap2(unsigned long addr, size_t len,
	unsigned long prot, unsigned long flags,
	unsigned long fd, unsigned long pgoff)
{
	struct file *file = NULL;
Beispiel #29
0
void
printlong(const DISPLAY *dp)
{
	struct stat *sp;
	FTSENT *p;
	NAMES *np;
	char buf[20];
#ifdef COLORLS
	int color_printed = 0;
#endif

	if ((dp->list == NULL || dp->list->fts_level != FTS_ROOTLEVEL) &&
	    (f_longform || f_size)) {
		xo_emit("{L:total} {:total-blocks/%lu}\n",
			howmany(dp->btotal, blocksize));
	}

	xo_open_list("entry");
	for (p = dp->list; p; p = p->fts_link) {
		char *name, *type;
		if (IS_NOPRINT(p))
			continue;
		xo_open_instance("entry");
		sp = p->fts_statp;
		name = getname(p->fts_name);
		if (name)
		    xo_emit("{ke:name/%hs}", name);
		if (f_inode)
			xo_emit("{t:inode/%*ju} ",
			    dp->s_inode, (uintmax_t)sp->st_ino);
		if (f_size)
			xo_emit("{t:blocks/%*jd} ",
			    dp->s_block, howmany(sp->st_blocks, blocksize));
		strmode(sp->st_mode, buf);
		aclmode(buf, p);
		np = p->fts_pointer;
		xo_attr("value", "%03o", (int) sp->st_mode & ALLPERMS);
		if (f_numericonly) {
			xo_emit("{t:mode/%s}{e:mode_octal/%03o} {t:links/%*u} {td:user/%-*s}{e:user/%ju}  {td:group/%-*s}{e:group/%ju}  ",
				buf, (int) sp->st_mode & ALLPERMS, dp->s_nlink, sp->st_nlink,
				dp->s_user, np->user, sp->st_uid, dp->s_group, np->group, sp->st_gid);
		} else {
			xo_emit("{t:mode/%s}{e:mode_octal/%03o} {t:links/%*u} {t:user/%-*s}  {t:group/%-*s}  ",
				buf, (int) sp->st_mode & ALLPERMS, dp->s_nlink, sp->st_nlink,
				dp->s_user, np->user, dp->s_group, np->group);
		}
		if (S_ISBLK(sp->st_mode))
			asprintf(&type, "block");
		if (S_ISCHR(sp->st_mode))
			asprintf(&type, "character");
		if (S_ISDIR(sp->st_mode))
			asprintf(&type, "directory");
		if (S_ISFIFO(sp->st_mode))
			asprintf(&type, "fifo");
		if (S_ISLNK(sp->st_mode))
			asprintf(&type, "symlink");
		if (S_ISREG(sp->st_mode))
			asprintf(&type, "regular");
		if (S_ISSOCK(sp->st_mode))
			asprintf(&type, "socket");
		if (S_ISWHT(sp->st_mode))
			asprintf(&type, "whiteout");
		xo_emit("{e:type/%s}", type);
		free(type);
		if (f_flags)
			xo_emit("{:flags/%-*s} ", dp->s_flags, np->flags);
		if (f_label)
			xo_emit("{t:label/%-*s} ", dp->s_label, np->label);
		if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode))
			printdev(dp->s_size, sp->st_rdev);
		else
			printsize("size", dp->s_size, sp->st_size);
		if (f_accesstime)
			printtime("access-time", sp->st_atime);
		else if (f_birthtime)
			printtime("birth-time", sp->st_birthtime);
		else if (f_statustime)
			printtime("change-time", sp->st_ctime);
		else
			printtime("modify-time", sp->st_mtime);
#ifdef COLORLS
		if (f_color)
			color_printed = colortype(sp->st_mode);
#endif

		if (name) {
		    xo_emit("{dk:name/%hs}", name);
		    free(name);
		}
		
#ifdef COLORLS
		if (f_color && color_printed)
			endcolor(0);
#endif
		if (f_type)
			(void)printtype(sp->st_mode);
		if (S_ISLNK(sp->st_mode))
			printlink(p);
		xo_close_instance("entry");
		xo_emit("\n");
	}
	xo_close_list("entry");
}
Beispiel #30
0
static void count_duration(time_t fromtime, time_t totime,
			   pcre *pageregexp, pcre *expageregexp,
			   pcre *hostregexp, pcre *exhostregexp,
			   pcre *testregexp, pcre *extestregexp,
			   int ignoredialups, f_hostcheck hostcheck,
			   event_t *eventhead, countlist_t **hostcounthead, countlist_t **svccounthead)
{
	void *hwalk;
	elist_t *lwalk;
	event_t *ewalk;
	ed_t *ed;
	sendreturn_t *bdata;

	/*
	 * Restructure the event-list so we have a tree instead:
	 *
	 *      HostRecord
	 *      |  *Data ---->  EventList
	 *      |               |  *Service
	 *      |               |  *EventHead --> Event --> Event --> Event
	 *      |               |  *EventTail --------------------------^
	 *      |               |
	 *      |               v
	 *      |
	 *      v
	 *
	 */
	for (ewalk = eventhead; (ewalk); ewalk = ewalk->next) {
		lwalk = (elist_t *)xmh_item(ewalk->host, XMH_DATA);
		while (lwalk && (lwalk->svc != ewalk->service)) lwalk = lwalk->next;
		if (lwalk == NULL) {
			lwalk = (elist_t *)calloc(1, sizeof(elist_t));
			lwalk->svc = ewalk->service;
			lwalk->next = (elist_t *)xmh_item(ewalk->host, XMH_DATA);
			xmh_set_item(ewalk->host, XMH_DATA, (void *)lwalk);
		}

		ed = (ed_t *)calloc(1, sizeof(ed_t));
		ed->event = ewalk;
		ed->next = lwalk->head;
		if (lwalk->head == NULL) lwalk->tail = ed;
		lwalk->head = ed;
	}

	if (debug) {
		printf("\n\nEventtree before fixups\n\n");
		dump_eventtree();
	}
	
	/* 
	 * Next, we must add a pseudo record for the current state.
	 * This is for those statuses that haven't changed since the 
	 * start of our data-collection period - they won't have any events
	 * so we cannot tell what color they are. By grabbing the current
	 * color we can add a pseudo-event that lets us determine what the 
	 * color has been since the start of the event-period.
	 */
	bdata = newsendreturnbuf(1, NULL);
	if (sendmessage("xymondboard fields=hostname,testname,color,lastchange", NULL, XYMON_TIMEOUT, bdata) == XYMONSEND_OK) {
		char *bol, *eol;
		char *hname, *tname;
		int color;
		time_t lastchange;
		void *hrec;
		htnames_t *srec;
		char *icname = xgetenv("INFOCOLUMN");
		char *tcname = xgetenv("TRENDSCOLUMN");

		bol = getsendreturnstr(bdata, 0);
		while (bol) {
			eol = strchr(bol, '\n'); if (eol) *eol = '\0';
			hname = strtok(bol, "|");
			tname = (hname ? strtok(NULL, "|") : NULL);
			color = (tname ? parse_color(strtok(NULL, "|")) : -1);
			lastchange = ((color != -1) ? atol(strtok(NULL, "\n")) : totime+1);

			if (hname && tname && (color != -1) && (strcmp(tname, icname) != 0) && (strcmp(tname, tcname) != 0)) {
				hrec = hostinfo(hname);
				srec = getname(tname, 1);

				if (eventfilter(hrec, tname, 
						pageregexp, expageregexp, 
						hostregexp, exhostregexp,
						testregexp, extestregexp,
						ignoredialups, hostcheck) == 0) goto nextrecord;

				lwalk = (elist_t *)xmh_item(hrec, XMH_DATA);
				while (lwalk && (lwalk->svc != srec)) lwalk = lwalk->next;
				if (lwalk == NULL) {
					lwalk = (elist_t *)calloc(1, sizeof(elist_t));
					lwalk->svc = srec;
					lwalk->next = (elist_t *)xmh_item(hrec, XMH_DATA);
					xmh_set_item(hrec, XMH_DATA, (void *)lwalk);
				}

				/* See if we already have an event past the "totime" value */
				if (lwalk->head) {
					ed = lwalk->head;
					while (ed && (ed->event->eventtime < totime)) ed = ed->next;

					if (ed) {
						ed->next = NULL;
						lwalk->tail = ed;
					}
					else {
						ed = (ed_t *)calloc(1, sizeof(ed_t));
						ed->event = (event_t *)calloc(1, sizeof(event_t));
						lwalk->tail->next = ed;

						ed->event->host = hrec;
						ed->event->service = srec;
						ed->event->eventtime = totime;
						ed->event->changetime = lwalk->tail->event->eventtime;
						ed->event->duration = (totime - lwalk->tail->event->eventtime);
						ed->event->newcolor = -1;
						ed->event->oldcolor = lwalk->tail->event->newcolor;
						ed->event->next = NULL;
						ed->next = NULL;

						lwalk->tail = ed;
					}
				}
				else if (lastchange < totime) {
					ed = (ed_t *)calloc(1, sizeof(ed_t));
					ed->event = (event_t *)calloc(1, sizeof(event_t));
					ed->event->host = hrec;
					ed->event->service = srec;
					ed->event->eventtime = totime;
					ed->event->changetime = (lwalk->tail ? lwalk->tail->event->eventtime : fromtime);
					ed->event->duration = (totime - ed->event->changetime);
					ed->event->newcolor = color;
					ed->event->oldcolor = (lwalk->tail ? lwalk->tail->event->newcolor : color);
					ed->event->next = NULL;
					ed->next = NULL;

					lwalk->head = lwalk->tail = ed;
				}
			}

nextrecord:
			bol = (eol ? eol+1 : NULL);
		}

		freesendreturnbuf(bdata);
	}
	else {
		errprintf("Cannot get the current state\n");
		freesendreturnbuf(bdata);
		return;
	}

	if (debug) {
		printf("\n\nEventtree after pseudo-events\n\n");
		dump_eventtree();
	}
	
	/* 
	 * Fixup the beginning-time (and duration) of the first events recorded.
	 * This is to handle events that begin BEFORE our event-logging period.
	 * Fixup the end-time (and duration) of the last events recorded.
	 * This is to handle events that end AFTER our event-logging period.
	 */
	for (hwalk = first_host(); (hwalk); hwalk = next_host(hwalk, 0)) {
		elist_t *lwalk;
		event_t *erec;
		ed_t *ewalk;

		lwalk = (elist_t *)xmh_item(hwalk, XMH_DATA); 
		while (lwalk) {
			if (lwalk->head) {
				erec = lwalk->head->event;
				if (erec->changetime > totime) {
					/* First event is after our start-time. Drop the events */
					lwalk->head = lwalk->tail = NULL;
				}
				else if (erec->changetime < fromtime) {
					/* First event is before our start-time. Adjust to starttime. */
					erec->changetime = fromtime;
					erec->duration = (erec->eventtime - fromtime);
				}

				ewalk = lwalk->head;
				while (ewalk && (ewalk->event->eventtime < totime)) ewalk = ewalk->next;
				if (ewalk) {
					lwalk->tail = ewalk;
					lwalk->tail->next = 0;
				}

				if (lwalk->tail) {
					erec = lwalk->tail->event;
					if (erec->eventtime > totime) {
						/* Last event is after our end-time. Adjust to end-time */
						erec->eventtime = totime;
						erec->duration = (totime - erec->changetime);
					}
				}
			}

			lwalk = lwalk->next;
		}
	}

	if (debug) {
		printf("\n\nEventtree after fixups\n\n");
		dump_eventtree();
	}

	for (hwalk = first_host(); (hwalk); hwalk = next_host(hwalk, 0)) {
		countlist_t *hrec, *srec;

		hrec = (countlist_t *)malloc(sizeof(countlist_t));
		hrec->src = hwalk;
		hrec->total = 0;
		hrec->next = *hostcounthead;
		*hostcounthead = hrec;

		lwalk = (elist_t *)xmh_item(hwalk, XMH_DATA);
		while (lwalk) {
			for (srec = *svccounthead; (srec && (srec->src != (void *)lwalk->svc)); srec = srec->next) ;
			if (!srec) {
				srec = (countlist_t *)malloc(sizeof(countlist_t));
				srec->src = (void *)lwalk->svc;
				srec->total = 0;
				srec->next = *svccounthead;
				*svccounthead = srec;
			}

			if (lwalk->head) {
				ed_t *ewalk = lwalk->head;

				while (ewalk) {
					if (ewalk->event->oldcolor >= COL_YELLOW) {
						hrec->total += ewalk->event->duration;
						srec->total += ewalk->event->duration;
					}
					ewalk = ewalk->next;
				}
			}

			lwalk = lwalk->next;
		}
	}

	if (debug) dump_countlists(*hostcounthead, *svccounthead);
}