Exemplo n.º 1
0
void
new_record(int cluster, int proc, int start_time, int evict_time, 
		   int good_time, int cpu_usage, char const *host)
{
	static bool initialized = false;
	char hash[40];
	int wall_time = evict_time-start_time;

	// We detect bad records here.  One cause of bad records is the
	// fact that userlogs timestamps do not contain years, so we
	// always assume we are in the same year, which causes time to run
	// backwards at the turn of the year.
	if (wall_time < 0 ||
		good_time < 0 ||
		cpu_usage < 0) {
		if (debug_mode) {
			fprintf(stderr, "internal error: negative time computed for "
					"%d.%d!\n", cluster, proc);
			fprintf(stderr, "  (records around the turn of "
					"the year are not handled correctly)\n");
		}
		return;
	}

	sprintf(hash, "%d.%d", cluster, proc);
	HashKey jobkey(hash);

	JobStatistics *js;
	if (Stats.lookup(jobkey, js) < 0) {
		js = new JobStatistics(cluster, proc);
		Stats.insert(jobkey, js);
		numJobStats++;
	}
	js->allocations++;
	js->kills += (wall_time != good_time);
	js->wall_time += wall_time;
	js->good_time += good_time;
	js->cpu_usage += cpu_usage;

	char ip_addr[128];
	// only use the IP address in the key [TODO:IPV6] Parse IPv6 Addr
	strncpy(ip_addr, host+1, sizeof(ip_addr)-1);
	ip_addr[sizeof(ip_addr)-1] = '\0';
	for (int i=0; i < 128; i++) {
		if (ip_addr[i] == ':') {
			ip_addr[i] = '\0';
			break;
		}
	}
	HostStatistics *hs;
	HashKey hostkey(ip_addr);
	if (HStats.lookup(hostkey, hs) < 0) {
		condor_sockaddr addr;
		const char* hostname = NULL;
		MyString hostname_str;
		addr.from_sinful(host);
		if (!avoid_dns) {
			hostname_str = get_hostname(addr);
			hostname = hostname_str.Value();
		}
		if (hostname == NULL) {
			hostname = ip_addr;
		}
		hs = new HostStatistics(hostname);
		HStats.insert(hostkey, hs);
		numHostStats++;
	}
	hs->allocations++;
	hs->kills += (wall_time != good_time);
	hs->wall_time += wall_time;
	hs->good_time += good_time;
	hs->cpu_usage += cpu_usage;

	if (!totals_only) {
		if (!raw_data && !initialized) {
			printf("\n");
			printf("%-8.8s %-15.15s %-11.11s %-11.11s %9s %9s %9s\n",
				   "Job", "Host", "Start Time", "Evict Time", "Wall Time",
				   "Good Time", "CPU Usage");
			initialized = true;
		}

		printf("%-8.8s %-15.15s ", hash, hs->host);
		printf("%11s ", format_date(start_time));
		printf("%11s ", format_date(evict_time));
		printf("%9s ", format_time_nosecs(wall_time));
		printf("%9s ", format_time_nosecs(good_time));
		printf("%9s\n", format_time_nosecs(cpu_usage));
	}
}
Exemplo n.º 2
0
int     deliver_maildir(LOCAL_STATE state, USER_ATTR usr_attr)
{
    const char *myname = "deliver_maildir";
    char   *newdir;
    char   *tmpdir;
    char   *curdir;
    char   *tmpfile;
    char   *newfile;
    DSN_BUF *why = state.msg_attr.why;
    VSTRING *buf;
    VSTREAM *dst;
    int     mail_copy_status;
    int     deliver_status;
    int     copy_flags;
    struct stat st;
    struct timeval starttime;

    GETTIMEOFDAY(&starttime);

    /*
     * Make verbose logging easier to understand.
     */
    state.level++;
    if (msg_verbose)
	MSG_LOG_STATE(myname, state);

    /*
     * Don't deliver trace-only requests.
     */
    if (DEL_REQ_TRACE_ONLY(state.request->flags)) {
	dsb_simple(why, "2.0.0", "delivers to maildir");
	return (sent(BOUNCE_FLAGS(state.request),
		     SENT_ATTR(state.msg_attr)));
    }

    /*
     * Initialize. Assume the operation will fail. Set the delivered
     * attribute to reflect the final recipient.
     */
    if (vstream_fseek(state.msg_attr.fp, state.msg_attr.offset, SEEK_SET) < 0)
	msg_fatal("seek message file %s: %m", VSTREAM_PATH(state.msg_attr.fp));
    state.msg_attr.delivered = state.msg_attr.rcpt.address;
    mail_copy_status = MAIL_COPY_STAT_WRITE;
    buf = vstring_alloc(100);

    copy_flags = MAIL_COPY_TOFILE | MAIL_COPY_RETURN_PATH
	| MAIL_COPY_DELIVERED | MAIL_COPY_ORIG_RCPT;

    newdir = concatenate(usr_attr.mailbox, "new/", (char *) 0);
    tmpdir = concatenate(usr_attr.mailbox, "tmp/", (char *) 0);
    curdir = concatenate(usr_attr.mailbox, "cur/", (char *) 0);

    /*
     * Create and write the file as the recipient, so that file quota work.
     * Create any missing directories on the fly. The file name is chosen
     * according to ftp://koobera.math.uic.edu/www/proto/maildir.html:
     * 
     * "A unique name has three pieces, separated by dots. On the left is the
     * result of time(). On the right is the result of gethostname(). In the
     * middle is something that doesn't repeat within one second on a single
     * host. I fork a new process for each delivery, so I just use the
     * process ID. If you're delivering several messages from one process,
     * use starttime.pid_count.host, where starttime is the time that your
     * process started, and count is the number of messages you've
     * delivered."
     * 
     * Well, that stopped working on fast machines, and on operating systems
     * that randomize process ID values. When creating a file in tmp/ we use
     * the process ID because it still is an exclusive resource. When moving
     * the file to new/ we use the device number and inode number. I do not
     * care if this breaks on a remote AFS file system, because people should
     * know better.
     * 
     * On January 26, 2003, http://cr.yp.to/proto/maildir.html said:
     * 
     * A unique name has three pieces, separated by dots. On the left is the
     * result of time() or the second counter from gettimeofday(). On the
     * right is the result of gethostname(). (To deal with invalid host
     * names, replace / with \057 and : with \072.) In the middle is a
     * delivery identifier, discussed below.
     * 
     * [...]
     * 
     * Modern delivery identifiers are created by concatenating enough of the
     * following strings to guarantee uniqueness:
     * 
     * [...]
     * 
     * In, where n is (in hexadecimal) the UNIX inode number of this file.
     * Unfortunately, inode numbers aren't always available through NFS.
     * 
     * Vn, where n is (in hexadecimal) the UNIX device number of this file.
     * Unfortunately, device numbers aren't always available through NFS.
     * (Device numbers are also not helpful with the standard UNIX
     * filesystem: a maildir has to be within a single UNIX device for link()
     * and rename() to work.)
     * 
     * Mn, where n is (in decimal) the microsecond counter from the same
     * gettimeofday() used for the left part of the unique name.
     * 
     * Pn, where n is (in decimal) the process ID.
     * 
     * [...]
     */
    set_eugid(usr_attr.uid, usr_attr.gid);
    vstring_sprintf(buf, "%lu.P%d.%s",
		 (unsigned long) starttime.tv_sec, var_pid, get_hostname());
    tmpfile = concatenate(tmpdir, STR(buf), (char *) 0);
    newfile = 0;
    if ((dst = vstream_fopen(tmpfile, O_WRONLY | O_CREAT | O_EXCL, 0600)) == 0
	&& (errno != ENOENT
	    || make_dirs(tmpdir, 0700) < 0
	    || (dst = vstream_fopen(tmpfile, O_WRONLY | O_CREAT | O_EXCL, 0600)) == 0)) {
	dsb_simple(why, mbox_dsn(errno, "4.2.0"),
		   "create maildir file %s: %m", tmpfile);
    } else if (fstat(vstream_fileno(dst), &st) < 0) {

	/*
	 * Coverity 200604: file descriptor leak in code that never executes.
	 * Code replaced by msg_fatal(), as it is not worthwhile to continue
	 * after an impossible error condition.
	 */
	msg_fatal("fstat %s: %m", tmpfile);
    } else {
	vstring_sprintf(buf, "%lu.V%lxI%lxM%lu.%s",
			(unsigned long) starttime.tv_sec,
			(unsigned long) st.st_dev,
			(unsigned long) st.st_ino,
			(unsigned long) starttime.tv_usec,
			get_hostname());
	newfile = concatenate(newdir, STR(buf), (char *) 0);
	if ((mail_copy_status = mail_copy(COPY_ATTR(state.msg_attr),
					  dst, copy_flags, "\n",
					  why)) == 0) {
	    if (sane_link(tmpfile, newfile) < 0
		&& (errno != ENOENT
		    || (make_dirs(curdir, 0700), make_dirs(newdir, 0700)) < 0
		    || sane_link(tmpfile, newfile) < 0)) {
		dsb_simple(why, mbox_dsn(errno, "4.2.0"),
			   "create maildir file %s: %m", newfile);
		mail_copy_status = MAIL_COPY_STAT_WRITE;
	    }
	}
	if (unlink(tmpfile) < 0)
	    msg_warn("remove %s: %m", tmpfile);
    }
    set_eugid(var_owner_uid, var_owner_gid);

    /*
     * The maildir location is controlled by the mail administrator. If
     * delivery fails, try again later. We would just bounce when the maildir
     * location possibly under user control.
     */
    if (mail_copy_status & MAIL_COPY_STAT_CORRUPT) {
	deliver_status = DEL_STAT_DEFER;
    } else if (mail_copy_status != 0) {
	if (errno == EACCES) {
	    msg_warn("maildir access problem for UID/GID=%lu/%lu: %s",
		     (long) usr_attr.uid, (long) usr_attr.gid,
		     STR(why->reason));
	    msg_warn("perhaps you need to create the maildirs in advance");
	}
	vstring_sprintf_prepend(why->reason, "maildir delivery failed: ");
	deliver_status =
	    (STR(why->status)[0] == '4' ?
	     defer_append : bounce_append)
	    (BOUNCE_FLAGS(state.request),
	     BOUNCE_ATTR(state.msg_attr));
    } else {
	dsb_simple(why, "2.0.0", "delivered to maildir");
	deliver_status = sent(BOUNCE_FLAGS(state.request),
			      SENT_ATTR(state.msg_attr));
    }
    vstring_free(buf);
    myfree(newdir);
    myfree(tmpdir);
    myfree(curdir);
    myfree(tmpfile);
    if (newfile)
	myfree(newfile);
    return (deliver_status);
}
Exemplo n.º 3
0
int main(int argc, char ** argv)
{
    interactive_signals();

    if (loadConfig(argc, argv, true) < 0) {
        // Fatal error loading config file
        return EXIT_CONFIG_ERROR;
    }

    if (daemon_flag) {
        int pid = daemonise();
        if (pid == -1) {
            return EXIT_FORK_ERROR;
        } else if (pid > 0) {
            return EXIT_SUCCESS;
        }
    }

    // If we are a daemon logging to syslog, we need to set it up.
    initLogger();

    // Initialise the persistance subsystem. If we have been built with
    // database support, this will open the various databases used to
    // store server data.
    if (database_flag) {
        Persistence * p = Persistence::instance();
        int dbstatus = p->init();
        if (dbstatus < 0) {
            database_flag = false;
            log(ERROR, "Error opening database. Database disabled.");
            if (dbstatus == DATABASE_TABERR) {
                log(INFO, "Database connection established, "
                          "but unable to create required tables.");
                log(INFO, "Please ensure that any obsolete database "
                          "tables have been removed.");
            } else {
                log(INFO, "Unable to connect to the RDBMS.");
                log(INFO, "Please ensure that the RDBMS is running, "
                          "the cyphesis database exists and is accessible "
                          "to the user running cyphesis.");
            }
            log(INFO, String::compose("To disable this message please run:\n\n"
                                      "    cyconfig --%1:usedatabase=false\n\n"
                                      "to permanently disable database usage.",
                                      instance));
        }
    }

    // If the restricted flag is set in the config file, then we
    // don't allow connecting users to create accounts. Accounts must
    // be created manually by the server administrator.
    if (readConfigItem("cyphesis","restricted", restricted_flag) == 0) {
        if (restricted_flag) {
            log(INFO, "Setting restricted mode.");
        }
    }

    readConfigItem("cyphesis","inittime", timeoffset);

    std::string mserver("metaserver.worldforge.org");
    readConfigItem("cyphesis", "metaserver", mserver);

    std::string serverName;
    if (readConfigItem("cyphesis","servername", serverName) != 0) {
        serverName = get_hostname();
    }

    std::string serverHostname("localhost");
    readConfigItem("slave","server", serverHostname);
    
    // Start up the python subsystem.
    init_python_api();

    { // scope for CommServer

    // Create commserver instance that will handle connections from clients.
    // The commserver will create the other server related objects, and the
    // world object pair (World + WorldRouter), and initialise the admin
    // account. The primary ruleset name is passed in so it
    // can be stored and queried by clients.
    WorldRouter world;

    // This ID is currently generated every time, but should perhaps be
    // persistent in future.
    std::string server_id, lobby_id;
    long int_id, lobby_int_id;

    if (((int_id = newId(server_id)) < 0) ||
        ((lobby_int_id = newId(lobby_id)) < 0)) {
        log(CRITICAL, "Unable to get server IDs from Database");
        return EXIT_DATABASE_ERROR;
    }

    ServerRouting server(world, ruleset, serverName,
                         server_id, int_id,
                         lobby_id, lobby_int_id);

    CommServer commServer(server);

    // This is where we should restore the database, before
    // the listen sockets are open. Unlike earlier code, we are
    // attempting to construct the internal state from the database,
    // not creating a new world using the contents of the database as a
    // template

    CommUnixListener * listener = new CommUnixListener(commServer,
          *new CommClientFactory<SlaveClientConnection>());
    if (listener->setup(slave_socket_name) != 0) {
        log(ERROR, "Could not create listen socket. Init failed.");
        return EXIT_SOCKET_ERROR;
    }
    commServer.addSocket(listener);

    std::string master_id;
    if (newId(master_id) < 0) {
        log(CRITICAL, "Unable to get master ID from Database");
        return EXIT_DATABASE_ERROR;
    }

    CommMaster * master = new CommMaster(commServer);
    if (master->connect(serverHostname) != 0) {
        log(ERROR, "Could not connect to master. Init failed.");
        return EXIT_SOCKET_ERROR;
    }
    master->setup(new Master(*master, commServer.m_server, master_id));
    commServer.addSocket(master);

    log(INFO, "Running");

    // Inform things that want to know that we are running.
    running();

    // Loop until the exit flag is set. The exit flag can be set anywhere in
    // the code easily.
    while (!exit_flag) {
        try {
            commServer.poll();
        }
        catch (...) {
            // It is hoped that commonly thrown exception, particularly
            // exceptions that can be caused  by external influences
            // should be caught close to where they are thrown. If
            // an exception makes it here then it should be debugged.
            log(ERROR, "Exception caught in main()");
        }
    }
    // exit flag has been set so we close down the databases, and indicate
    // to the metaserver (if we are using one) that this server is going down.
    // It is assumed that any preparation for the shutdown that is required
    // by the game has been done before exit flag was set.
    log(NOTICE, "Performing clean shutdown...");

    } // close scope of CommServer, which cause the destruction of the
      // server and world objects, and the entire world contents

    Persistence::instance()->shutdown();

    EntityBuilder::instance()->flushFactories();
    EntityBuilder::del();
    MindFactory::del();

    Inheritance::clear();

    // Shutdown the python interpretter. This frees lots of memory, and if
    // the malloc heap is in any way corrupt, a segfault is likely to
    // occur at this point. Previous occassions where pointers have been
    // deleted twice elsewhere in the code, have resulted in a segfault
    // at this point. AlRiddoch 10th November 2001
    shutdown_python_api();

    delete global_conf;

    log(INFO, "Clean shutdown complete.");
    return 0;
}
Exemplo n.º 4
0
static int dissect_bat_batman_v5(tvbuff_t *tvb, int offset, packet_info *pinfo, proto_tree *tree)
{
	proto_item *tf, *tgw;
	proto_tree *bat_batman_tree = NULL, *flag_tree;
	struct batman_packet_v5 *batman_packeth;
	const guint8  *old_orig_addr, *orig_addr;
	guint32 old_orig, orig;
	gint i;

	tvbuff_t *next_tvb;

	batman_packeth = wmem_new(wmem_packet_scope(), struct batman_packet_v5);

	batman_packeth->version = tvb_get_guint8(tvb, offset+0);
	batman_packeth->flags = tvb_get_guint8(tvb, offset+1);
	batman_packeth->ttl = tvb_get_guint8(tvb, offset+2);
	batman_packeth->gwflags = tvb_get_guint8(tvb, offset+3);
	batman_packeth->seqno = tvb_get_ntohs(tvb, offset+4);
	batman_packeth->gwport = tvb_get_ntohs(tvb, offset+6);
	orig_addr = tvb_get_ptr(tvb, offset+8, 4);
	orig = tvb_get_ipv4(tvb, offset+8);
	SET_ADDRESS(&batman_packeth->orig, AT_IPv4, 4, orig_addr);
	old_orig_addr = tvb_get_ptr(tvb, offset+12, 4);
	old_orig = tvb_get_ipv4(tvb, offset+12);
	SET_ADDRESS(&batman_packeth->old_orig, AT_IPv4, 4, old_orig_addr);
	batman_packeth->tq = tvb_get_guint8(tvb, offset+16);
	batman_packeth->hna_len = tvb_get_guint8(tvb, offset+17);

	/* Set info column */
	col_add_fstr(pinfo->cinfo, COL_INFO, "Seq=%u", batman_packeth->seqno);

	/* Set tree info */
	if (tree) {
		proto_item *ti;

		if (PTREE_DATA(tree)->visible) {
			ti = proto_tree_add_protocol_format(tree, proto_bat_plugin, tvb, offset, BATMAN_PACKET_V5_SIZE,
							    "B.A.T.M.A.N., Orig: %s (%s)",
							    get_hostname(orig), ip_to_str((const guint8 *)batman_packeth->orig.data));
		} else {
			ti = proto_tree_add_item(tree, proto_bat_plugin, tvb, offset, BATMAN_PACKET_V5_SIZE, ENC_NA);
		}
		bat_batman_tree = proto_item_add_subtree(ti, ett_bat_batman);
	}

	/* items */
	proto_tree_add_item(bat_batman_tree, hf_bat_batman_version, tvb, offset, 1, ENC_BIG_ENDIAN);
	offset += 1;

	tf = proto_tree_add_item(bat_batman_tree, hf_bat_batman_flags, tvb, offset, 1, ENC_BIG_ENDIAN);
	/* <flags> */
	flag_tree =  proto_item_add_subtree(tf, ett_bat_batman_flags);
	proto_tree_add_boolean(flag_tree, hf_bat_batman_flags_unidirectional, tvb, offset, 1, batman_packeth->flags);
	proto_tree_add_boolean(flag_tree, hf_bat_batman_flags_directlink, tvb, offset, 1, batman_packeth->flags);
	/* </flags> */
	offset += 1;

	proto_tree_add_item(bat_batman_tree, hf_bat_batman_ttl, tvb, offset, 1, ENC_BIG_ENDIAN);
	offset += 1;

	tgw = proto_tree_add_item(bat_batman_tree, hf_bat_batman_gwflags, tvb, offset, 1, ENC_BIG_ENDIAN);
	dissect_bat_gwflags(tvb, batman_packeth->gwflags, offset, tgw);
	offset += 1;

	proto_tree_add_item(bat_batman_tree, hf_bat_batman_seqno, tvb, offset, 2, ENC_BIG_ENDIAN);
	offset += 2;

	proto_tree_add_item(bat_batman_tree, hf_bat_batman_gwport, tvb, offset, 2, ENC_BIG_ENDIAN);
	offset += 2;

	proto_tree_add_ipv4(bat_batman_tree, hf_bat_batman_orig, tvb, offset, 4, orig);
	offset += 4;

	proto_tree_add_ipv4(bat_batman_tree, hf_bat_batman_old_orig, tvb, offset, 4,  old_orig);
	offset += 4;

	proto_tree_add_item(bat_batman_tree, hf_bat_batman_tq, tvb, offset, 1, ENC_BIG_ENDIAN);
	offset += 1;

	proto_tree_add_item(bat_batman_tree, hf_bat_batman_hna_len, tvb, offset, 1, ENC_BIG_ENDIAN);
	offset += 1;

	tap_queue_packet(bat_tap, pinfo, batman_packeth);

	for (i = 0; i < batman_packeth->hna_len; i++) {
		next_tvb = tvb_new_subset(tvb, offset, 5, 5);

		if (have_tap_listener(bat_follow_tap)) {
			tap_queue_packet(bat_follow_tap, pinfo, next_tvb);
		}

		dissect_bat_hna(next_tvb, pinfo, bat_batman_tree);
		offset += 5;
	}

	return offset;
}
Exemplo n.º 5
0
int Condor_Auth_Kerberos :: init_server_info()
{
    // First, where to find cache
    //if (defaultStash_) {
    //  ccname_  = new char[MAXPATHLEN];
    //  sprintf(ccname_, STR_KRB_FORMAT, defaultStash_, my_username());
    //}
    //else {
    // Exception!
    //  dprintf(D_ALWAYS,"KERBEROS: Unable to stash ticket -- STASH directory is not defined!\n");
    //}

    char * serverPrincipal = param(STR_KERBEROS_SERVER_PRINCIPAL);
    krb5_principal * server;

	if (mySock_->isClient()) {
		server = &server_;
	} else {
		server = &krb_principal_;
	}

    if (serverPrincipal) {
    	if (krb5_parse_name(krb_context_,serverPrincipal,server)) {
        	dprintf(D_SECURITY, "Failed to build server principal\n");
			free (serverPrincipal);
        	return 0;
		}
		free (serverPrincipal);
    } else {
		int  size;
		char *name = 0;
		const char *instance = 0;
		MyString hostname;

		serverPrincipal = param(STR_KERBEROS_SERVER_SERVICE);
		if(!serverPrincipal) {
			serverPrincipal = strdup(STR_DEFAULT_CONDOR_SERVICE);
		}

		size = strlen(serverPrincipal);

		if ((instance = strchr( serverPrincipal, '/')) != NULL) {
			size = instance - serverPrincipal;
			instance += 1;
		}

		name = (char *) malloc(size + 1);
		ASSERT( name );
		memset(name, 0, size + 1);
		strncpy(name, serverPrincipal, size);

		if (mySock_->isClient()) {
			if (instance == 0) {
				hostname = get_hostname(mySock_->peer_addr());
				instance = hostname.Value();
			}
		}

		//------------------------------------------
		// First, find out the principal mapping
		//------------------------------------------
		if (krb5_sname_to_principal(krb_context_,instance,name,KRB5_NT_SRV_HST,server)) {
			dprintf(D_SECURITY, "Failed to build server principal\n");
			free(name);
			free(serverPrincipal);
			return 0;
		}
		free(name);
		free(serverPrincipal);
	}

	if ( mySock_->isClient() && !map_kerberos_name( server ) ) {
		dprintf(D_SECURITY, "Failed to map principal to user\n");
		return 0;
	}

	char * tmp = 0;
    krb5_unparse_name(krb_context_, *server, &tmp);
	dprintf(D_SECURITY, "KERBEROS: Server principal is %s\n", tmp);
	free(tmp);

    return 1;
}
Exemplo n.º 6
0
int platform_make_x11_server(Plug *plug, const char *progname, int mindisp,
                             const char *screen_number_suffix,
                             ptrlen authproto, ptrlen authdata,
                             Socket **sockets, Conf *conf)
{
    char *tmpdir;
    char *authfilename = NULL;
    strbuf *authfiledata = NULL;
    char *unix_path = NULL;

    SockAddr *a_tcp = NULL, *a_unix = NULL;

    int authfd;
    FILE *authfp;

    int displayno;

    authfiledata = strbuf_new_nm();

    int nsockets = 0;

    /*
     * Look for a free TCP port to run our server on.
     */
    for (displayno = mindisp;; displayno++) {
        const char *err;
        int tcp_port = displayno + 6000;
        int addrtype = ADDRTYPE_IPV4;

        sockets[nsockets] = new_listener(
            NULL, tcp_port, plug, false, conf, addrtype);

        err = sk_socket_error(sockets[nsockets]);
        if (!err) {
            char *hostname = get_hostname();
            if (hostname) {
                char *canonicalname = NULL;
                a_tcp = name_lookup(hostname, tcp_port, &canonicalname,
                                    conf, addrtype, NULL, "");
                sfree(canonicalname);
            }
            sfree(hostname);
            nsockets++;
            break;                     /* success! */
        } else {
            sk_close(sockets[nsockets]);
        }

        if (!strcmp(err, strerror(EADDRINUSE))) /* yuck! */
            goto out;
    }

    if (a_tcp) {
        x11_format_auth_for_authfile(
            BinarySink_UPCAST(authfiledata),
            a_tcp, displayno, authproto, authdata);
    }

    /*
     * Try to establish the Unix-domain analogue. That may or may not
     * work - file permissions in /tmp may prevent it, for example -
     * but it's worth a try, and we don't consider it a fatal error if
     * it doesn't work.
     */
    unix_path = dupprintf("/tmp/.X11-unix/X%d", displayno);
    a_unix = unix_sock_addr(unix_path);

    sockets[nsockets] = new_unix_listener(a_unix, plug);
    if (!sk_socket_error(sockets[nsockets])) {
        x11_format_auth_for_authfile(
            BinarySink_UPCAST(authfiledata),
            a_unix, displayno, authproto, authdata);
        nsockets++;
    } else {
        sk_close(sockets[nsockets]);
        sfree(unix_path);
        unix_path = NULL;
    }

    /*
     * Decide where the authority data will be written.
     */

    tmpdir = getenv("TMPDIR");
    if (!tmpdir || !*tmpdir)
        tmpdir = "/tmp";

    authfilename = dupcat(tmpdir, "/", progname, "-Xauthority-XXXXXX", NULL);

    {
        int oldumask = umask(077);
        authfd = mkstemp(authfilename);
        umask(oldumask);
    }
    if (authfd < 0) {
        while (nsockets-- > 0)
            sk_close(sockets[nsockets]);
        goto out;
    }

    /*
     * Spawn a subprocess which will try to reliably delete our
     * auth file when we terminate, in case we die unexpectedly.
     */
    {
        int cleanup_pipe[2];
        pid_t pid;

        /* Don't worry if pipe or fork fails; it's not _that_ critical. */
        if (!pipe(cleanup_pipe)) {
            if ((pid = fork()) == 0) {
                int buf[1024];
                /*
                 * Our parent process holds the writing end of
                 * this pipe, and writes nothing to it. Hence,
                 * we expect read() to return EOF as soon as
                 * that process terminates.
                 */

                close(0);
                close(1);
                close(2);

                setpgid(0, 0);
                close(cleanup_pipe[1]);
                close(authfd);
                while (read(cleanup_pipe[0], buf, sizeof(buf)) > 0);
                unlink(authfilename);
                if (unix_path)
                    unlink(unix_path);
                _exit(0);
            } else if (pid < 0) {
                close(cleanup_pipe[0]);
                close(cleanup_pipe[1]);
            } else {
                close(cleanup_pipe[0]);
                cloexec(cleanup_pipe[1]);
            }
        }
    }

    authfp = fdopen(authfd, "wb");
    fwrite(authfiledata->u, 1, authfiledata->len, authfp);
    fclose(authfp);

    {
        char *display = dupprintf(":%d%s", displayno, screen_number_suffix);
        conf_set_str_str(conf, CONF_environmt, "DISPLAY", display);
        sfree(display);
    }
    conf_set_str_str(conf, CONF_environmt, "XAUTHORITY", authfilename);

    /*
     * FIXME: return at least the DISPLAY and XAUTHORITY env settings,
     * and perhaps also the display number
     */

  out:
    if (a_tcp)
        sk_addr_free(a_tcp);
    /* a_unix doesn't need freeing, because new_unix_listener took it over */
    sfree(authfilename);
    strbuf_free(authfiledata);
    sfree(unix_path);
    return nsockets;
}
Exemplo n.º 7
0
int main(int argc, char *argv[])
{
    int sockfd;
    struct addrinfo hints, *servinfo, *p;
    int rv;
    int numbytes;
    struct sockaddr_storage their_addr;
    char buf[MAXBUFLEN];
    socklen_t addr_len;
    char s[INET6_ADDRSTRLEN];

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_flags = AI_PASSIVE; // use my IP

    if ((rv = getaddrinfo(NULL, MYPORT, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
    }

    // loop through all the results and bind to the first we can
    for(p = servinfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype,
                p->ai_protocol)) == -1) {
            perror("listener: socket");
            continue;
        }

        if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            perror("listener: bind");
            continue;
        }

        break;
    }

    if (p == NULL) {
        fprintf(stderr, "listener: failed to bind socket\n");
        return 2;
    }

    freeaddrinfo(servinfo);

    printf("listener: waiting to recvfrom...\n");

    int run = 1;

    while(run){
        addr_len = sizeof their_addr;
        if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0,
            (struct sockaddr *)&their_addr, &addr_len)) == -1) {
            perror("recvfrom");
            exit(1);
        }

        printf("listener: got packet from %s\n",
            inet_ntop(their_addr.ss_family,
                get_in_addr((struct sockaddr *)&their_addr),
                s, sizeof s));
        printf("listener: packet is %d bytes long\n", numbytes);
        buf[numbytes] = '\0';
        printf("listener: packet contains \"%s\"\n", buf);

        if(!strcmp(buf, "terminator")){
            printf("> Shutting down client interface...\n");
            run = 0;
        } else if(strcmp(buf, "name") == 0){
            printf("> requesting hostname\n");
            char name[256] = {'\0'};
            get_hostname(name);

            printf("listener: hostname = %s\n", name);
        } else if(!strcmp(buf, "uptime")){
            char name[128] = {'\0'};

            get_uptime(name);
            printf("listener: uptime = %s\n", name);
        } else if(!strcmp(buf, "users")){
            char buf[128] = {'\0'};

            get_logged_in(buf);
        } else if(!strcmp(buf, "rxb")){
            char buf[128] = {'\0'};
            uint64_t bytes = rx_bytes("eth0");
            printf("listener: rx bytes = %uld\n", bytes);
        } else{
            printf("listener: unknown command: %s", buf);
        }
    }

    close(sockfd);

    printf("Good bye.\n");

    return 0;
}
Exemplo n.º 8
0
// And this is the routine that sets up the array.
static void setup_init_properties ()
{
   int ix = 0;
   BSTR scriptname = get_scriptname();
   BSTR hostname   = get_hostname();

   // Init array so that all entrys are unused and init propset_info.
   memset(gbl_init_props, not_in_use,
          MAX_INIT_PROPERTIES * sizeof(init_property));


   // DBPROPSET_DBINIT, main OLE DB init and auth properties.
   init_propset_info[oleinit_props].start = ix;
   init_propset_info[oleinit_props].no_of_props = 0;

   add_init_property("IntegratedSecurity", oleinit_props, DBPROP_AUTH_INTEGRATED,
                     TRUE, VT_BSTR, FALSE, L"SSPI", NULL, ix);
   add_init_property("Password", oleinit_props, DBPROP_AUTH_PASSWORD,
                     TRUE, VT_BSTR, TRUE, NULL, NULL, ix);
   add_init_property("Username", oleinit_props, DBPROP_AUTH_USERID,
                     TRUE, VT_BSTR, TRUE, NULL, NULL, ix);
   add_init_property("Database", oleinit_props, DBPROP_INIT_CATALOG,
                     TRUE, VT_BSTR, FALSE, L"tempdb", NULL, ix);
   add_init_property("Server", oleinit_props, DBPROP_INIT_DATASOURCE,
                     TRUE, VT_BSTR, FALSE, L"(local)", NULL, ix);
   add_init_property("GeneralTimeout", oleinit_props, DBPROP_INIT_GENERALTIMEOUT,
                     TRUE, VT_I4, FALSE, NULL, 0, ix);
   add_init_property("LCID", oleinit_props, DBPROP_INIT_LCID,
                     TRUE, VT_I4, FALSE, NULL, GetUserDefaultLCID(), ix);
   add_init_property("Pooling", oleinit_props, DBPROP_INIT_OLEDBSERVICES,
                     TRUE, VT_I4, FALSE, NULL, DBPROPVAL_OS_RESOURCEPOOLING, ix);
   add_init_property("Prompt", oleinit_props, DBPROP_INIT_PROMPT,
                     TRUE, VT_I2, FALSE, NULL, DBPROMPT_NOPROMPT, ix);
   add_init_property("ConnectionString", oleinit_props, DBPROP_INIT_PROVIDERSTRING,
                     TRUE, VT_BSTR, TRUE, NULL, NULL, ix);
   add_init_property("ConnectTimeout", oleinit_props, DBPROP_INIT_TIMEOUT,
                     TRUE, VT_I4, FALSE, NULL, 15, ix);

   // DBPROPSET_SQLSERVERDBINIT, SQLOLEDB specific proprties.
   init_propset_info[ssinit_props].start = ix;
   init_propset_info[ssinit_props].no_of_props = 0;

   add_init_property("Appname", ssinit_props, SSPROP_INIT_APPNAME,
                     TRUE, VT_BSTR, FALSE, scriptname, NULL, ix);
   add_init_property("Autotranslate", ssinit_props, SSPROP_INIT_AUTOTRANSLATE,
                     TRUE, VT_BOOL, TRUE, NULL, NULL, ix);
   add_init_property("Language", ssinit_props, SSPROP_INIT_CURRENTLANGUAGE,
                     TRUE, VT_BSTR, TRUE, NULL, NULL, ix);
   add_init_property("AttachFilename", ssinit_props, SSPROP_INIT_FILENAME,
                     TRUE, VT_BSTR, TRUE, NULL, NULL, ix);
   add_init_property("NetworkAddress", ssinit_props, SSPROP_INIT_NETWORKADDRESS,
                     TRUE, VT_BSTR, TRUE, NULL, NULL, ix);
   add_init_property("Netlib", ssinit_props, SSPROP_INIT_NETWORKLIBRARY,
                     TRUE, VT_BSTR, TRUE, NULL, NULL, ix);
   add_init_property("PacketSize", ssinit_props, SSPROP_INIT_PACKETSIZE,
                     TRUE, VT_I4, TRUE, NULL, NULL, ix);
   add_init_property("UseProcForPrep", ssinit_props, SSPROP_INIT_USEPROCFORPREP,
                     TRUE, VT_I4, FALSE, NULL, SSPROPVAL_USEPROCFORPREP_OFF, ix);
   add_init_property("Hostname", ssinit_props, SSPROP_INIT_WSID,
                     TRUE, VT_BSTR, FALSE, hostname, NULL, ix);
   // Available first in 2.6.
   add_init_property("Encrypt", ssinit_props, SSPROP_INIT_ENCRYPT,
                     TRUE, VT_BOOL, TRUE, NULL, NULL, ix);
   // The above properties are those that are in SQLOLEDB.
   no_of_ssprops_sqloledb = init_propset_info[ssinit_props].no_of_props;

   // These properties were added in SQL 2005.
   add_init_property("FailoverPartner", ssinit_props, SSPROP_INIT_FAILOVERPARTNER,
                     FALSE, VT_BSTR, TRUE, NULL, NULL, ix);
   add_init_property("TrustServerCert", ssinit_props, SSPROP_INIT_TRUST_SERVER_CERTIFICATE,
                     FALSE, VT_BOOL, TRUE, NULL, NULL, ix);
   add_init_property("OldPassword", ssinit_props, SSPROP_AUTH_OLD_PASSWORD,
                     FALSE, VT_BSTR, TRUE, NULL, NULL, ix);
   no_of_ssprops_sqlncli = init_propset_info[ssinit_props].no_of_props;

   // These two were added with SQL 2008.
   add_init_property("ServerSPN", ssinit_props, SSPROP_INIT_SERVERSPN,
                     FALSE, VT_BSTR, TRUE, NULL, NULL, ix);
   add_init_property("FailoverPartnerSPN", ssinit_props, SSPROP_INIT_FAILOVERPARTNERSPN,
                     FALSE, VT_BSTR, TRUE, NULL, NULL, ix);
   no_of_ssprops_sqlncli10 = init_propset_info[ssinit_props].no_of_props;

   // And here is a single one that made into SQL 2012.
   add_init_property("ApplicationIntent", ssinit_props, SSPROP_INIT_APPLICATIONINTENT,
                     FALSE, VT_BSTR, FALSE, L"ReadWrite", NULL, ix);
   no_of_ssprops_sqlncli11 = init_propset_info[ssinit_props].no_of_props;
   
   // DBPROPSET_DATASOURCE, data-source properties.
   init_propset_info[datasrc_props].start = ix;
   init_propset_info[datasrc_props].no_of_props = 0;

   add_init_property("MultiConnections", datasrc_props, DBPROP_MULTIPLECONNECTIONS,
                     TRUE, VT_BOOL, FALSE, NULL, FALSE, ix);

   SysFreeString(scriptname);
   SysFreeString(hostname);
}
Exemplo n.º 9
0
Arquivo: Test.c Projeto: utayo/typing
	/**
	 * タイピングの結果を表示する.
	 */
	void Test_result()
	{
	  char buf[MAXSTRLEN];
	  int writeResult = TRUE;
	  Examination * examination2;
	  Test * test2 = Test_get_test();
	  
	  //合格情報を記録する for typingtestex拡張
	  Examination_writePassInfoAndShowResult(&(test.examination), &(test.user));
	 
	  term_clear();
	  
	  Test_disp_info(RESULT_X+2, RESULT_Y);
	  
	  term_gotoxy(RESULT_X, RESULT_Y+1);
	  term_rev_disp(ref("result_message"));
	  
	  //合否を表示
	  term_gotoxy(RESULT_X + 5, RESULT_Y + 3);
	  term_disp(ref("exam_result"));
	  if(exam_result(typing_second)==TRUE){    
	    term_disp(ref("pass_message"));
	  }else{
	    term_disp(ref("fail_message"));
	  }    
	  
	  //試験日を表示
	  term_gotoxy(RESULT_X + 5, RESULT_Y + 4);
	  term_disp(ref("exam_date"));
	  get_date(buf);
	  term_disp(buf);
	  
	  //タイピング時間を表示
	  term_gotoxy(RESULT_X + 5, RESULT_Y + 5);
	  term_disp(ref("typing_time"));
	  sprintf(buf, "%d ", typing_second);
	  term_disp(buf);
	  term_disp(ref("second_message"));
	  
	  //端末名を表示
	  term_gotoxy(RESULT_X + 5, RESULT_Y + 6);
	  term_disp(ref("machine_name"));
	  get_hostname(buf);
	  term_disp(buf);
	  
	  //正打鍵数を表示    
	  term_gotoxy(RESULT_X + 5, RESULT_Y + 7);
	  term_disp(ref("correct_type"));
	  sprintf(buf, "%d ", err_correct_type());
	  term_disp(buf);
	  term_disp(ref("word_message"));
	  
	  //ミスタッチ数を表示    
	  term_gotoxy(RESULT_X + 5, RESULT_Y + 8);
	  term_disp(ref("miss_count"));
	  sprintf(buf, "%d ", err_error_type());
	  term_disp(buf);
	  term_disp(ref("word_message"));
	  
	  //1分あたりの正しいタッチ数を表示    
	  term_gotoxy(RESULT_X + 5, RESULT_Y + 9);
	  term_disp(ref("correct_type_per_min"));
	  sprintf(buf, "%d ", correct_type_per_min(typing_second));
	  term_disp(buf);
	  term_disp(ref("per_min_message"));
	  
	  
	  //テキスト情報のタイトル表示
	  term_gotoxy(RESULT_X, RESULT_Y + 11);
	  term_rev_disp(ref("exam_info_message"));
	  
	  //問題名を表示
	  term_gotoxy(RESULT_X + 5, RESULT_Y + 13);
	  term_disp(ref("exam_title"));
	  term_disp(ref("title"));
	  
	  //最大誤字数
	  term_gotoxy(RESULT_X + 5, RESULT_Y + 14);
	  term_disp(ref("max_error_type_msg"));
	  term_disp(ref("max_error_type"));
	  term_disp(ref("word_message"));
	  
	  //制限時間
	  term_gotoxy(RESULT_X + 5, RESULT_Y + 15);
	  term_disp(ref("time_limit_msg"));
	  term_disp(ref("time_limit"));
	  term_disp(ref("second_message"));
	  
	  //テキスト総文字数
	  term_gotoxy(RESULT_X + 5, RESULT_Y + 16);
	  term_disp(ref("text_length_msg"));
	  term_disp(ref("total_text_length"));
	  term_disp(ref("word_message"));
	  
	  Intprt_disp_guide(&test.intprt);
	  
	  //次の画面遷移のメッセージを表示する
	  examination2 = &(test2->examination);
	  if(examination2->mode  == EXAM_MODE){//本番モードの場合
	    if(HIDE_ERR_MODE_EX){  
	      Intprt_pause_core(&test.intprt, ref("result_end_message"), FALSE);
	    }else{
      	  Intprt_pause_core(&test.intprt, ref("go_error_check_message"), FALSE);
	    }
	  }else{//練習モードの場合
	    if(HIDE_ERR_MODE_PRA){
	      Intprt_pause_core(&test.intprt, ref("result_end_message"), FALSE);
	    }else{
     	  Intprt_pause_core(&test.intprt, ref("go_error_check_message"), FALSE);
	    }
	  }
	}
Exemplo n.º 10
0
//=====================================================================================
//
//	* Function : RightSpoof()
//	* Description 
//		이 함수는 위의 ChildRightProc콜백함수의 WM_SPOOF메시지에 대응하는 메시지 처리 함수
//		이다. wParam로 SM_INIT, SM_CHANGE, SM_ADD등 종류의 메시지를 보내어 탐지모듈들과
//		데이터를 주도받을 수 있다.
//
//=====================================================================================
LRESULT RightSpoof(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
	static PSPOOF_L HEAD=NULL;
	PSPOOF_L __ARP_LIST=(PSPOOF_L)lParam;
	INT LIST_index;
	ARPDATA* arpnode;
	char hostStr[17];
	
	switch(wParam)
		{
		//List View를 초기화할 때 쓰는 메시지이다.
		case SM_INIT:
			HEAD=__ARP_LIST;
			ListView_DeleteAllItems(hWnd);
			while(__ARP_LIST!=NULL){
				AddList(hWnd,__ARP_LIST);
				__ARP_LIST=__ARP_LIST->next;
			}
			ChangeState();
			SendMessage(hC2,WM_PAINT,0,0);
			break;
		//List View의 해당 인덱스를 변경할 때 쓰는 메시지이다.
		case SM_CHANGE:
			LIST_index=ChatchChange(hWnd,__ARP_LIST,HEAD);
			ChangeList(LIST_index);
			/* 의심이나 공격상황에 트레이 발생*/
			if(__ARP_LIST->flag==SUSPICIOUS || __ARP_LIST->flag==ATTACK){
				nid.cbSize = sizeof(NOTIFYICONDATA);
				nid.hWnd = hWndMain;
				nid.uID = 0;
				nid.uFlags = NIF_ICON|NIF_TIP|NIF_MESSAGE|NIF_INFO;
				nid.dwInfoFlags = 0x0006;
				nid.uTimeout = 500;
				nid.hIcon = LoadIcon(g_hInst, MAKEINTRESOURCE(IDI_ICON1));
				lstrcpy(nid.szInfoTitle, TEXT("주의상황"));
				wsprintf(nid.szTip, TEXT("의심스러운 %d.%d.%d.%d"),
					__ARP_LIST->ipAddr[0],__ARP_LIST->ipAddr[1],__ARP_LIST->ipAddr[2],__ARP_LIST->ipAddr[3]);
				wsprintf(nid.szInfo, TEXT("의심스러운 %d.%d.%d.%d가 프로그램에 포착되었습니다."),
					__ARP_LIST->ipAddr[0],__ARP_LIST->ipAddr[1],__ARP_LIST->ipAddr[2],__ARP_LIST->ipAddr[3]);
				Shell_NotifyIcon(NIM_MODIFY, &nid);
			}
			break;
		//List View를 더할 때 쓰는 메시지이다.
		case SM_ADD:
			get_hostname(__ARP_LIST->ipAddr, hostStr);
			add_hostname(ARP_LIST,__ARP_LIST->ipAddr,hostStr);
			AddList(hWnd,__ARP_LIST);
			break;
		case SM_NODEVICE:
			MessageBox(hWnd,TEXT("인터페이스를 찾을수 없습니다.\nWinpcap이 설치 되었는지 확인해 주시기 바랍니다."),TEXT("알림"),MB_OK);
			break;
		case SM_STOP_THREAD:
			SuspendThread(hThread);
			break;
		case SM_RESUME_THREAD:
			ResumeThread(hThread);
			break;
		case SM_UPDATE_HOSTNAME:
			LIST_index=ChatchChange(hWnd,__ARP_LIST,HEAD);
			ChangeList(LIST_index);
			break;
		case SM_UPDATE_LIST_NOMAL:
			arpnode = (ARPDATA*)lParam;
			updateState(ARP_LIST,NOMAL,arpnode->ipAddr,arpnode->macAddr, arpnode->vendor,arpnode->timestr," ");
			break;
		case SM_UPDATE_LIST_SUSP:
			arpnode = (ARPDATA*)lParam;
			updateState(ARP_LIST,SUSPICIOUS,arpnode->ipAddr,arpnode->macAddr, arpnode->vendor,arpnode->timestr," ");
			break;
		case SM_UPDATE_LIST_ATTACK:
			arpnode = (ARPDATA*)lParam;
			updateState(ARP_LIST,ATTACK,arpnode->ipAddr,arpnode->macAddr, arpnode->vendor,arpnode->timestr," ");
			break;
		case SM_UPDATE_LIST_STATIC:
			arpnode = (ARPDATA*)lParam;
			updateState(ARP_LIST,STATIC,arpnode->ipAddr,arpnode->macAddr, arpnode->vendor,arpnode->timestr," ");
	}
		return 0;
}
Exemplo n.º 11
0
static void
dissect_ntp_std(tvbuff_t *tvb, proto_tree *ntp_tree, guint8 flags)
{
	proto_tree      *flags_tree;
	proto_item	*tf;
	guint8		 stratum;
	guint8		 ppoll;
	gint8		 precision;
	double		 rootdelay;
	double		 rootdispersion;
	guint32		 refid_addr;
	const gchar	*buffc;
	gchar           *buff;
	int		 i;
	int		 macofs;
	gint		 maclen;

	tf = proto_tree_add_uint(ntp_tree, hf_ntp_flags, tvb, 0, 1, flags);

	/* Adding flag subtree and items */
	flags_tree = proto_item_add_subtree(tf, ett_ntp_flags);
	proto_tree_add_uint(flags_tree, hf_ntp_flags_li, tvb, 0, 1, flags);
	proto_tree_add_uint(flags_tree, hf_ntp_flags_vn, tvb, 0, 1, flags);
	proto_tree_add_uint(flags_tree, hf_ntp_flags_mode, tvb, 0, 1, flags);

	/* Stratum, 1byte field represents distance from primary source
	 */
	stratum = tvb_get_guint8(tvb, 1);
	if (stratum == 0) {
		buffc="Peer Clock Stratum: unspecified or invalid (%u)";
	} else if (stratum == 1) {
		buffc="Peer Clock Stratum: primary reference (%u)";
	} else if ((stratum >= 2) && (stratum <= 15)) {
		buffc="Peer Clock Stratum: secondary reference (%u)";
	} else if (stratum == 16) {
		buffc="Peer Clock Stratum: unsynchronized (%u)";
	} else {
		buffc="Peer Clock Stratum: reserved: %u";
	}
	proto_tree_add_uint_format(ntp_tree, hf_ntp_stratum, tvb, 1, 1,
				   stratum, buffc, stratum);
	/* Poll interval, 1byte field indicating the maximum interval
	 * between successive messages, in seconds to the nearest
	 * power of two.
	 */
	ppoll = tvb_get_guint8(tvb, 2);
	if ((ppoll >= 4) && (ppoll <= 17)) {
		proto_tree_add_uint_format(ntp_tree, hf_ntp_ppoll, tvb, 2, 1,
				   ppoll,
				   "Peer Polling Interval: %u (%u sec)",
				   ppoll,
				   1 << ppoll);
	} else {
		proto_tree_add_uint_format(ntp_tree, hf_ntp_ppoll, tvb, 2, 1,
				   ppoll,
				   "Peer Polling Interval: invalid (%u)",
				   ppoll);
	}

	/* Precision, 1byte field indicating the precision of the
	 * local clock, in seconds to the nearest power of two.
	 */
	precision = tvb_get_guint8(tvb, 3);
	proto_tree_add_int_format(ntp_tree, hf_ntp_precision, tvb, 3, 1,
				   precision,
				   "Peer Clock Precision: %8.6f sec",
				   pow(2, precision));

	/* Root Delay is a 32-bit signed fixed-point number indicating
	 * the total roundtrip delay to the primary reference source,
	 * in seconds with fraction point between bits 15 and 16.
	 */
	rootdelay = ((gint16)tvb_get_ntohs(tvb, 4)) +
			(tvb_get_ntohs(tvb, 6) / 65536.0);
	proto_tree_add_double_format(ntp_tree, hf_ntp_rootdelay, tvb, 4, 4,
				   rootdelay,
				   "Root Delay: %9.4f sec",
				   rootdelay);

	/* Root Dispersion, 32-bit unsigned fixed-point number indicating
	 * the nominal error relative to the primary reference source, in
	 * seconds with fraction point between bits 15 and 16.
	 */
	rootdispersion = ((gint16)tvb_get_ntohs(tvb, 8)) +
				(tvb_get_ntohs(tvb, 10) / 65536.0);
	proto_tree_add_double_format(ntp_tree, hf_ntp_rootdispersion, tvb, 8, 4,
				   rootdispersion,
				   "Root Dispersion: %9.4f sec",
				   rootdispersion);

	/* Now, there is a problem with secondary servers.  Standards
	 * asks from stratum-2 - stratum-15 servers to set this to the
	 * low order 32 bits of the latest transmit timestamp of the
	 * reference source.
	 * But, all V3 and V4 servers set this to IP address of their
	 * higher level server. My decision was to resolve this address.
	 */
	buff = ep_alloc(NTP_TS_SIZE);
	if (stratum <= 1) {
		g_snprintf (buff, NTP_TS_SIZE, "Unidentified reference source '%.4s'",
			tvb_get_ephemeral_string(tvb, 12, 4));
		for (i = 0; primary_sources[i].id; i++) {
			if (tvb_memeql(tvb, 12, primary_sources[i].id, 4) == 0) {
				g_snprintf(buff, NTP_TS_SIZE, "%s",
					primary_sources[i].data);
				break;
			}
		}
	} else {
		int buffpos;
		refid_addr = tvb_get_ipv4(tvb, 12);
		buffpos = g_snprintf(buff, NTP_TS_SIZE, "%s", get_hostname (refid_addr));
		if (buffpos >= NTP_TS_SIZE) {
			buff[NTP_TS_SIZE-4]='.';
			buff[NTP_TS_SIZE-3]='.';
			buff[NTP_TS_SIZE-2]='.';
			buff[NTP_TS_SIZE-1]=0;
		}
	}
	proto_tree_add_bytes_format(ntp_tree, hf_ntp_refid, tvb, 12, 4,
				    NULL, "Reference ID: %s", buff);

	/* Reference Timestamp: This is the time at which the local clock was
	 * last set or corrected.
	 */
	proto_tree_add_item(ntp_tree, hf_ntp_reftime, tvb, 16, 8, ENC_TIME_NTP|ENC_BIG_ENDIAN);

	/* Originate Timestamp: This is the time at which the request departed
	 * the client for the server.
	 */
	proto_tree_add_item(ntp_tree, hf_ntp_org, tvb, 24, 8, ENC_TIME_NTP|ENC_BIG_ENDIAN);

	/* Receive Timestamp: This is the time at which the request arrived at
	 * the server.
	 */
	proto_tree_add_item(ntp_tree, hf_ntp_rec, tvb, 32, 8, ENC_TIME_NTP|ENC_BIG_ENDIAN);

	/* Transmit Timestamp: This is the time at which the reply departed the
	 * server for the client.
	 */
	proto_tree_add_item(ntp_tree, hf_ntp_xmt, tvb, 40, 8, ENC_TIME_NTP|ENC_BIG_ENDIAN);

	/* MAX_MAC_LEN is the largest message authentication code
	 * (MAC) length.  If we have more data left in the packet
	 * after the header than that, the extra data is NTP4
	 * extensions; parse them as such.
	 */
	macofs = 48;
	while (tvb_reported_length_remaining(tvb, macofs) > (gint)MAX_MAC_LEN)
		macofs = dissect_ntp_ext(tvb, ntp_tree, macofs);

	/* When the NTP authentication scheme is implemented, the
	 * Key Identifier and Message Digest fields contain the
	 * message authentication code (MAC) information defined in
	 * Appendix C of RFC-1305. Will print this as hex code for now.
	 */
	if (tvb_reported_length_remaining(tvb, macofs) >= 4)
		proto_tree_add_item(ntp_tree, hf_ntp_keyid, tvb, macofs, 4,
				    ENC_NA);
	macofs += 4;
	maclen = tvb_reported_length_remaining(tvb, macofs);
	if (maclen > 0)
		proto_tree_add_item(ntp_tree, hf_ntp_mac, tvb, macofs,
				    maclen, ENC_NA);
}
Exemplo n.º 12
0
int     main(int argc, char **argv)
{
    SESSION *session;
    char   *host;
    char   *port;
    char   *path;
    int     path_len;
    int     sessions = 1;
    int     ch;
    ssize_t len;
    int     n;
    int     i;
    char   *buf;
    const char *parse_err;
    struct addrinfo *res;
    int     aierr;
    const char *protocols = INET_PROTO_NAME_ALL;
    INET_PROTO_INFO *proto_info;

    /*
     * Fingerprint executables and core dumps.
     */
    MAIL_VERSION_STAMP_ALLOCATE;

    signal(SIGPIPE, SIG_IGN);
    msg_vstream_init(argv[0], VSTREAM_ERR);

    /*
     * Parse JCL.
     */
    while ((ch = GETOPT(argc, argv, "46cC:f:l:m:M:r:R:s:t:vw:")) > 0) {
	switch (ch) {
	case '4':
	    protocols = INET_PROTO_NAME_IPV4;
	    break;
	case '6':
	    protocols = INET_PROTO_NAME_IPV6;
	    break;
	case 'c':
	    count++;
	    break;
	case 'C':
	    if ((connect_count = atoi(optarg)) <= 0)
		usage(argv[0]);
	    break;
	case 'f':
	    sender = optarg;
	    break;
	case 'l':
	    if ((message_length = atoi(optarg)) <= 0)
		usage(argv[0]);
	    break;
	case 'm':
	    if ((message_count = atoi(optarg)) <= 0)
		usage(argv[0]);
	    break;
	case 'M':
	    if (*optarg == '[') {
		if (!valid_mailhost_literal(optarg, DO_GRIPE))
		    msg_fatal("bad address literal: %s", optarg);
	    } else {
		if (!valid_hostname(optarg, DO_GRIPE))
		    msg_fatal("bad hostname: %s", optarg);
	    }
	    var_myhostname = optarg;
	    break;
	case 'r':
	    if ((recipients = atoi(optarg)) <= 0)
		usage(argv[0]);
	    break;
	case 'R':
	    if (fixed_delay > 0 || (random_delay = atoi(optarg)) <= 0)
		usage(argv[0]);
	    break;
	case 's':
	    if ((sessions = atoi(optarg)) <= 0)
		usage(argv[0]);
	    break;
	case 't':
	    recipient = optarg;
	    break;
	case 'v':
	    msg_verbose++;
	    break;
	case 'w':
	    if (random_delay > 0 || (fixed_delay = atoi(optarg)) <= 0)
		usage(argv[0]);
	    break;
	default:
	    usage(argv[0]);
	}
    }
    if (argc - optind != 1)
	usage(argv[0]);

    if (random_delay > 0)
	srand(getpid());

    /*
     * Translate endpoint address to internal form.
     */
    proto_info = inet_proto_init("protocols", protocols);
    if (strncmp(argv[optind], "unix:", 5) == 0) {
	path = argv[optind] + 5;
	path_len = strlen(path);
	if (path_len >= (int) sizeof(sun.sun_path))
	    msg_fatal("unix-domain name too long: %s", path);
	memset((char *) &sun, 0, sizeof(sun));
	sun.sun_family = AF_UNIX;
#ifdef HAS_SUN_LEN
	sun.sun_len = path_len + 1;
#endif
	memcpy(sun.sun_path, path, path_len);
	sa = (struct sockaddr *) & sun;
	sa_length = sizeof(sun);
    } else {
	if (strncmp(argv[optind], "inet:", 5) == 0)
	    argv[optind] += 5;
	buf = mystrdup(argv[optind]);
	if ((parse_err = host_port(buf, &host, (char *) 0, &port, "628")) != 0)
	    msg_fatal("%s: %s", argv[optind], parse_err);
	if ((aierr = hostname_to_sockaddr(host, port, SOCK_STREAM, &res)) != 0)
	    msg_fatal("%s: %s", argv[optind], MAI_STRERROR(aierr));
	myfree(buf);
	sa = (struct sockaddr *) & ss;
	if (res->ai_addrlen > sizeof(ss))
	    msg_fatal("address length %d > buffer length %d",
		      (int) res->ai_addrlen, (int) sizeof(ss));
	memcpy((char *) sa, res->ai_addr, res->ai_addrlen);
	sa_length = res->ai_addrlen;
#ifdef HAS_SA_LEN
	sa->sa_len = sa_length;
#endif
	freeaddrinfo(res);
    }

    /*
     * Allocate space for temporary buffer.
     */
    buffer = vstring_alloc(100);

    /*
     * Make sure we have sender and recipient addresses.
     */
    if (var_myhostname == 0)
	var_myhostname = get_hostname();
    if (sender == 0 || recipient == 0) {
	vstring_sprintf(buffer, "foo@%s", var_myhostname);
	defaddr = mystrdup(vstring_str(buffer));
	if (sender == 0)
	    sender = defaddr;
	if (recipient == 0)
	    recipient = defaddr;
    }

    /*
     * Prepare some results that may be used multiple times: the message
     * content netstring, the sender netstring, and the recipient netstrings.
     */
    mydate = mail_date(time((time_t *) 0));
    mypid = getpid();

    message_buffer = vstring_alloc(message_length + 200);
    vstring_sprintf(buffer,
		  "From: <%s>\nTo: <%s>\nDate: %s\nMessage-Id: <%d@%s>\n\n",
		    sender, recipient, mydate, mypid, var_myhostname);
    for (n = 1; LEN(buffer) < message_length; n++) {
	for (i = 0; i < n && i < 79; i++)
	    VSTRING_ADDCH(buffer, 'X');
	VSTRING_ADDCH(buffer, '\n');
    }
    STR(buffer)[message_length - 1] = '\n';
    netstring_memcpy(message_buffer, STR(buffer), message_length);

    len = strlen(sender);
    sender_buffer = vstring_alloc(len);
    netstring_memcpy(sender_buffer, sender, len);

    if (recipients == 1) {
	len = strlen(recipient);
	recipient_buffer = vstring_alloc(len);
	netstring_memcpy(recipient_buffer, recipient, len);
    } else {
	recipient_buffer = vstring_alloc(100);
	for (n = 0; n < recipients; n++) {
	    vstring_sprintf(buffer, "%d%s", n, recipient);
	    netstring_memcat(recipient_buffer, STR(buffer), LEN(buffer));
	}
    }

    /*
     * Start sessions.
     */
    while (sessions-- > 0) {
	session = (SESSION *) mymalloc(sizeof(*session));
	session->stream = 0;
	session->xfer_count = 0;
	session->connect_count = connect_count;
	session->next = 0;
	session_count++;
	startup(session);
    }
    for (;;) {
	event_loop(-1);
	if (session_count <= 0 && message_count <= 0) {
	    if (count) {
		VSTREAM_PUTC('\n', VSTREAM_OUT);
		vstream_fflush(VSTREAM_OUT);
	    }
	    exit(0);
	}
    }
}
Exemplo n.º 13
0
Arquivo: net.c Projeto: agargiulo/DOSS
uint8_t is_known_host(mac_addr_t *hw_addr)
{
	return (get_hostname(hw_addr) != NULL ? 1 : 0);
}
Exemplo n.º 14
0
static int getSSHremotehost(char *source, char *options, char *host, int len, unsigned char *islocal)
{
    char *separator1, *separator2;
    int nreturn=0;

    /* remote host is in mountsource */

    /* sshfs uses the [email protected]:/path format when in ipv4
	user is optional, which defaults to the user making the connection
        path is also optional, it defaults to the home directory of the user on the remote host
    */

    if (! source || ! options) {

	nreturn=-EINVAL;
	goto out;

    }


    /* look for user part */

    separator1=strchr(source, '@');

    if ( separator1 ) {

	/* there is a user part */

	separator1++;

    } else {

	separator1=source;

    }

    /* look for host part (there must be a : )*/

    separator2=strchr(separator1, ':');

    if ( separator2 ) {

	if ( separator2-separator1<=len ) {
	    int len0=separator2-separator1;
	    char address[len0];

	    memset(address, '\0', len0);
	    memcpy(address, separator1, len0);

	    /* what to do when the port is different from the default(=22) */

	    nreturn=get_hostname(address, "22", host, len, islocal);

	} else {

	    nreturn=-E2BIG;

	}

    } else {

	/* error: no ":" separator */

	nreturn=-EINVAL;

    }

    out:

    return nreturn;

}
Exemplo n.º 15
0
/*******************************************************************************
* The entry point to client. Builds a request packet, and then sends it. The
* way the packet is built depends on whether the URI and method have been
* specified in the command line arguments.
*******************************************************************************/
int main(int argc, char **argv)
{
    int num_bytes;
    coffee_socket sockfd;
    int port = 0;
    char hostname[MAXHOSTNAMESIZE + 1] = { 0 };
    char method[MAXMETHODSIZE + 1] = { 0 };
    int pot_number = 0;
    char additions[400] = { 0 };
    char message[80];
    char packet[MAXPACKETSIZE + 1] = { 0 };
    int i;

    /*check the arguments*/
    printf("\n");
    for (i = 1; i < argc; ++i) {
        if (strcmp(argv[i], "-f") == 0) {
            ++i;
            continue;
        } else if (strcmp(argv[i], "-u") == 0) {
            process_uri(argv[++i], &pot_number, additions, hostname, &port);
            continue;
        } else if (strcmp(argv[i], "-m") == 0) {
            strcpy(method, argv[++i]);
            continue;
        } else {
            printf("usage: %s [-f \"file\"] | [[-m \"method\"] [- u \"URI\"]]",
                argv[0]);
            exit(1);
        }
    }

    if (method[0] == '\0') {
        get_method(method);
    }

    /*allows the user to choose the message for a BREW/POST request*/
    if (strcmp(method, "BREW") == 0 || strcmp(method, "POST") == 0) {
        get_message(message);
    } else {
        strcpy(message, "Content-length:0\r\n\r\n");
    }

    if (strstr(message, "start") && additions[0] == '\0') {
        get_additions(additions);
    }

    if (pot_number == 0) {
        pot_number = get_pot_number();
    }

    if (hostname[0] == '\0') {
        get_hostname(hostname);
    }

    if (port == 0) {
        get_port(&port);
    }

    /*build the packet from the indivdual elements built up to now*/
    sprintf(packet, "%s pot-%d HTCPCP/1.0\r\n%s%s", method, pot_number,
        additions, message);

    sockfd = connect_to_server(hostname, port);

    /*send the packet*/
    num_bytes = send_message(sockfd, packet);
    if (num_bytes == 0) {
        printf("Failed to send message %s", packet);
    }

    /*wait for response*/
    do {
        num_bytes = receive_message(sockfd, packet, MAXPACKETSIZE);
        if (num_bytes != 0) {
            packet[num_bytes] = '\0';
            printf("received: %s\n", packet);
        }
    } while (packet[0] == '\0');

    disconnect_from_server(sockfd);
    return 0;
}
Exemplo n.º 16
0
static void
dissect_slarp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
  proto_item *ti;
  proto_tree *slarp_tree = NULL;
  guint32     code;
  guint32     addr;
  guint32     mysequence;
  guint32     yoursequence;

  col_set_str(pinfo->cinfo, COL_PROTOCOL, "SLARP");
  col_clear(pinfo->cinfo, COL_INFO);

  code = tvb_get_ntohl(tvb, 0);

  if (tree) {
    ti = proto_tree_add_item(tree, proto_slarp, tvb, 0, 14, ENC_NA);
    slarp_tree = proto_item_add_subtree(ti, ett_slarp);
  }

  switch (code) {

  case SLARP_REQUEST:
  case SLARP_REPLY:
    addr = tvb_get_ipv4(tvb, 4);
    col_add_fstr(pinfo->cinfo, COL_INFO, "%s, from %s, mask %s",
                     val_to_str(code, slarp_ptype_vals, "Unknown (%d)"),
                     get_hostname(addr), tvb_ip_to_str(tvb, 8));
    if (tree) {
      proto_tree_add_uint(slarp_tree, hf_slarp_ptype, tvb, 0, 4, code);
      proto_tree_add_item(slarp_tree, hf_slarp_address, tvb, 4, 4, ENC_BIG_ENDIAN);
      proto_tree_add_text(slarp_tree, tvb, 8, 4,
                          "Netmask: %s", tvb_ip_to_str(tvb, 8));
    }
    break;

  case SLARP_LINECHECK:
    mysequence = tvb_get_ntohl(tvb, 4);
    yoursequence = tvb_get_ntohl(tvb, 8);
        col_add_fstr(pinfo->cinfo, COL_INFO,
                     "%s, outgoing sequence %u, returned sequence %u",
                     val_to_str(code, slarp_ptype_vals, "Unknown (%d)"),
                     mysequence, yoursequence);
    if (tree) {
      proto_tree_add_uint(slarp_tree, hf_slarp_ptype, tvb, 0, 4, code);
      proto_tree_add_uint(slarp_tree, hf_slarp_mysequence, tvb, 4, 4,
                          mysequence);
      proto_tree_add_uint(slarp_tree, hf_slarp_mysequence, tvb, 8, 4,
                          yoursequence);
    }
    break;

  default:
    col_add_fstr(pinfo->cinfo, COL_INFO, "Unknown packet type 0x%08X", code);
    if (tree) {
      proto_tree_add_uint(slarp_tree, hf_slarp_ptype, tvb, 0, 4, code);
      call_dissector(data_handle, tvb_new_subset_remaining(tvb, 4), pinfo,
                     slarp_tree);
    }
    break;
  }
}
bool FollowStreamDialog::follow(QString previous_filter, bool use_tcp_index)
{
    int                 tmp_fd;
    QString             follow_filter;
    const char          *hostname0 = NULL, *hostname1 = NULL;
    char                *port0 = NULL, *port1 = NULL;
    QString             server_to_client_string;
    QString             client_to_server_string;
    QString             both_directions_string;
    follow_stats_t      stats;
    tcp_stream_chunk    sc;
    size_t              nchars;
    GString *           msg;
    gboolean is_tcp = FALSE, is_udp = FALSE;

    resetStream();

    if (cap_file_ == NULL)
    {
        QMessageBox::warning(this, tr("No capture file."), tr("Please make sure you have a capture file opened."));
        return false;
    }

    if (cap_file_->edt == NULL)
    {
        QMessageBox::warning(this, tr("Error following stream."), tr("Capture file invalid."));
        return false;
    }

    proto_get_frame_protocols(cap_file_->edt->pi.layers, NULL, &is_tcp, &is_udp, NULL, NULL);

    switch (follow_type_)
    {
    case FOLLOW_TCP:
        if (!is_tcp) {
            QMessageBox::warning(this, tr("Error following stream."), tr("Please make sure you have a TCP packet selected."));
            return false;
        }
        break;
    case FOLLOW_UDP:
        removeStreamControls();
        if (!is_udp) {
            QMessageBox::warning(this, tr("Error following stream."), tr("Please make sure you have a UDP packet selected."));
            return false;
        }
        break;
    case FOLLOW_SSL:
        /* we got ssl so we can follow */
        removeStreamControls();
        if (!epan_dissect_packet_contains_field(cap_file_->edt, "ssl")) {
            QMessageBox::critical(this, tr("Error following stream."),
                               tr("Please make sure you have an SSL packet selected."));
            return false;
        }
        break;
    }

    if (follow_type_ == FOLLOW_TCP || follow_type_ == FOLLOW_SSL)
    {
        /* Create a new filter that matches all packets in the TCP stream,
           and set the display filter entry accordingly */
        reset_tcp_reassembly();
    }

    if (use_tcp_index) {
        follow_filter = gchar_free_to_qstring(build_follow_index_filter());
    } else {
        follow_filter = gchar_free_to_qstring(build_follow_conv_filter(&cap_file_->edt->pi));
    }
    if (follow_filter.isEmpty()) {
        QMessageBox::warning(this,
                             tr("Error creating filter for this stream."),
                             tr("A transport or network layer header is needed."));
        return false;
    }

    if (follow_type_ == FOLLOW_TCP || follow_type_ == FOLLOW_SSL)
    {
        /* Create a temporary file into which to dump the reassembled data
           from the TCP stream, and set "data_out_file" to refer to it, so
           that the TCP code will write to it.

           XXX - it might be nicer to just have the TCP code directly
           append stuff to the text widget for the TCP stream window,
           if we can arrange that said window not pop up until we're
           done. */
        gchar *data_out_filename;
        tmp_fd = create_tempfile(&data_out_filename, "follow");
        data_out_filename_ = data_out_filename;

        if (tmp_fd == -1) {
            QMessageBox::warning(this, "Error",
                                 "Could not create temporary file %1: %2",
                                 data_out_filename_, g_strerror(errno));
            data_out_filename_.clear();
            return false;
        }

        data_out_file = fdopen(tmp_fd, "w+b");
        if (data_out_file == NULL) {
            QMessageBox::warning(this, "Error",
                                 "Could not create temporary file %1: %2",
                                 data_out_filename_, g_strerror(errno));
            //ws_close(tmp_fd);
            ws_unlink(data_out_filename_.toUtf8().constData());
            data_out_filename_.clear();
            return false;
        }
    }

    /* append the negation */
    if(!previous_filter.isEmpty()) {
        filter_out_filter_ = QString("%1 and !(%2)")
                .arg(previous_filter).arg(follow_filter);
    }
    else
    {
        filter_out_filter_ = QString("!(%1)").arg(follow_filter);
    }

    switch (follow_type_)
    {
    case FOLLOW_TCP:
    {
        int stream_count = get_tcp_stream_count() - 1;
        ui->streamNumberSpinBox->blockSignals(true);
        ui->streamNumberSpinBox->setMaximum(stream_count);
        ui->streamNumberSpinBox->setValue(get_follow_tcp_index());
        ui->streamNumberSpinBox->blockSignals(false);
        ui->streamNumberSpinBox->setToolTip(tr("%Ln total stream(s).", "", stream_count));
        ui->streamNumberLabel->setToolTip(ui->streamNumberSpinBox->toolTip());

        break;
    }
    case FOLLOW_UDP:
        /* data will be passed via tap callback*/
        msg = register_tap_listener("udp_follow", &follow_info_,
                                    follow_filter.toUtf8().constData(),
                                    0, NULL, udp_queue_packet_data, NULL);
        if (msg) {
            QMessageBox::critical(this, "Error",
                               "Can't register udp_follow tap: %1",
                               msg->str);
            return false;
        }
        break;
    case FOLLOW_SSL:
        /* we got ssl so we can follow */
        msg = register_tap_listener("ssl", &follow_info_,
                                    follow_filter.toUtf8().constData(), 0,
                                    NULL, ssl_queue_packet_data, NULL);
        if (msg)
        {
            QMessageBox::critical(this, "Error",
                          "Can't register ssl tap: %1", msg->str);
            return false;
        }
        break;
    }

    /* Run the display filter so it goes in effect - even if it's the
       same as the previous display filter. */
    emit updateFilter(follow_filter, TRUE);

    switch (follow_type_)
    {
    case FOLLOW_TCP:

        break;
    case FOLLOW_UDP:
        remove_tap_listener(&follow_info_);
        break;
    case FOLLOW_SSL:
        remove_tap_listener(&follow_info_);
        break;
    }

    if (follow_type_ == FOLLOW_TCP)
    {
        /* Check whether we got any data written to the file. */
        if (empty_tcp_stream) {
            QMessageBox::warning(this, "Error",
                                 "The packets in the capture file for that stream have no data.");
            //ws_close(tmp_fd);
            ws_unlink(data_out_filename_.toUtf8().constData());
            data_out_filename_.clear();
            return false;
        }

        /* Go back to the top of the file and read the first tcp_stream_chunk
         * to ensure that the IP addresses and port numbers in the drop-down
         * list are tied to the correct lines displayed by follow_read_stream()
         * later on (which also reads from this file).  Close the file when
         * we're done.
         *
         * We read the data now, before we pop up a window, in case the
         * read fails.  We use the data later.
         */

        rewind(data_out_file);
        nchars=fread(&sc, 1, sizeof(sc), data_out_file);
        if (nchars != sizeof(sc)) {
            if (ferror(data_out_file)) {
                QMessageBox::warning(this, "Error",
                                     QString(tr("Could not read from temporary file %1: %2"))
                                     .arg(data_out_filename_)
                                     .arg(g_strerror(errno)));
            } else {
                QMessageBox::warning(this, "Error",
                                     QString(tr("Short read from temporary file %1: expected %2, got %3"))
                                     .arg(data_out_filename_)
                                     .arg((unsigned long)sizeof(sc))
                                     .arg((unsigned long)nchars));

            }
            //ws_close(tmp_fd);
            ws_unlink(data_out_filename_.toUtf8().constData());
            data_out_filename_.clear();
            return false;
        }
        fclose(data_out_file);
        data_out_file = NULL;
    }

    /* Stream to show */
    follow_stats(&stats);

    if (stats.is_ipv6) {
        struct e_in6_addr ipaddr;
        memcpy(&ipaddr, stats.ip_address[0], 16);
        hostname0 = get_hostname6(&ipaddr);
        memcpy(&ipaddr, (follow_type_ == FOLLOW_TCP) ? stats.ip_address[1] : stats.ip_address[0], 16);
        hostname1 = get_hostname6(&ipaddr);
    } else {
        guint32 ipaddr;
        memcpy(&ipaddr, stats.ip_address[0], 4);
        hostname0 = get_hostname(ipaddr);
        memcpy(&ipaddr, stats.ip_address[1], 4);
        hostname1 = get_hostname(ipaddr);
    }

    switch (follow_type_)
    {
    case FOLLOW_TCP:
        port0 = ep_tcp_port_to_display(stats.port[0]);
        port1 = ep_tcp_port_to_display(stats.port[1]);
        break;
    case FOLLOW_UDP:
        port0 = ep_udp_port_to_display(stats.port[0]);
        port1 = ep_udp_port_to_display(stats.port[1]);
        break;
    case FOLLOW_SSL:
        port0 = ep_tcp_port_to_display(stats.port[0]);
        port1 = ep_tcp_port_to_display(stats.port[1]);
        break;
    }

    follow_info_.is_ipv6 = stats.is_ipv6;

    if (follow_type_ == FOLLOW_TCP)
    {
        /* Host 0 --> Host 1 */
        if(sc.src_port == stats.port[0]) {
            server_to_client_string =
                    QString("%1:%2 %3 %4:%5 (%6)")
                    .arg(hostname0).arg(port0)
                    .arg(UTF8_RIGHTWARDS_ARROW)
                    .arg(hostname1).arg(port1)
                    .arg(gchar_free_to_qstring(format_size(
                                                   stats.bytes_written[0],
                                               format_size_unit_bytes|format_size_prefix_si)));
        } else {
            server_to_client_string =
                    QString("%1:%2 %3 %4:%5 (%6)")
                    .arg(hostname1).arg(port1)
                    .arg(UTF8_RIGHTWARDS_ARROW)
                    .arg(hostname0).arg(port0)
                    .arg(gchar_free_to_qstring(format_size(
                                                   stats.bytes_written[0],
                                               format_size_unit_bytes|format_size_prefix_si)));
        }

        /* Host 1 --> Host 0 */
        if(sc.src_port == stats.port[1]) {
            client_to_server_string =
                    QString("%1:%2 %3 %4:%5 (%6)")
                    .arg(hostname0).arg(port0)
                    .arg(UTF8_RIGHTWARDS_ARROW)
                    .arg(hostname1).arg(port1)
                    .arg(gchar_free_to_qstring(format_size(
                                                   stats.bytes_written[1],
                                               format_size_unit_bytes|format_size_prefix_si)));
        } else {
            client_to_server_string =
                    QString("%1:%2 %3 %4:%5 (%6)")
                    .arg(hostname1).arg(port1)
                    .arg(UTF8_RIGHTWARDS_ARROW)
                    .arg(hostname0).arg(port0)
                    .arg(gchar_free_to_qstring(format_size(
                                                   stats.bytes_written[1],
                                               format_size_unit_bytes|format_size_prefix_si)));
        }

    }
    else
    {
        if(follow_info_.client_port == stats.port[0]) {
            server_to_client_string =
                    QString("%1:%2 %3 %4:%5 (%6)")
                    .arg(hostname0).arg(port0)
                    .arg(UTF8_RIGHTWARDS_ARROW)
                    .arg(hostname1).arg(port1)
                    .arg(gchar_free_to_qstring(format_size(
                                                   follow_info_.bytes_written[0],
                                               format_size_unit_bytes|format_size_prefix_si)));

            client_to_server_string =
                    QString("%1:%2 %3 %4:%5 (%6)")
                    .arg(hostname0).arg(port0)
                    .arg(UTF8_RIGHTWARDS_ARROW)
                    .arg(hostname1).arg(port1)
                    .arg(gchar_free_to_qstring(format_size(
                                                   follow_info_.bytes_written[1],
                                               format_size_unit_bytes|format_size_prefix_si)));
        } else {
            server_to_client_string =
                    QString("%1:%2 %3 %4:%5 (%6)")
                    .arg(hostname1).arg(port1)
                    .arg(UTF8_RIGHTWARDS_ARROW)
                    .arg(hostname0).arg(port0)
                    .arg(gchar_free_to_qstring(format_size(
                                                   follow_info_.bytes_written[0],
                                               format_size_unit_bytes|format_size_prefix_si)));

            client_to_server_string =
                    QString("%1:%2 %3 %4:%5 (%6)")
                    .arg(hostname1).arg(port1)
                    .arg(UTF8_RIGHTWARDS_ARROW)
                    .arg(hostname0).arg(port0)
                    .arg(gchar_free_to_qstring(format_size(
                                                   follow_info_.bytes_written[1],
                                               format_size_unit_bytes|format_size_prefix_si)));
        }
    }

    /* Both Stream Directions */
    switch (follow_type_)
    {
    case FOLLOW_TCP:
        both_directions_string = QString("Entire conversation (%1)")
                .arg(gchar_free_to_qstring(format_size(
                                               stats.bytes_written[0] + stats.bytes_written[1],
                     format_size_unit_bytes|format_size_prefix_si)));
        this->setWindowTitle(QString("Follow TCP Stream (%1)").arg(follow_filter));
        break;
    case FOLLOW_UDP:
        both_directions_string = QString("Entire conversation (%1)")
                .arg(gchar_free_to_qstring(format_size(
                                               follow_info_.bytes_written[0] + follow_info_.bytes_written[1],
                     format_size_unit_bytes|format_size_prefix_si)));
        this->setWindowTitle(QString("Follow UDP Stream (%1)").arg(follow_filter));
        break;
    case FOLLOW_SSL:
        both_directions_string = QString("Entire conversation (%1)")
                .arg(gchar_free_to_qstring(format_size(
                                               follow_info_.bytes_written[0] + follow_info_.bytes_written[1],
                     format_size_unit_bytes|format_size_prefix_si)));
        this->setWindowTitle(QString("Follow SSL Stream (%1)").arg(follow_filter));
        break;
    }

    ui->cbDirections->clear();
    this->ui->cbDirections->addItem(both_directions_string);
    this->ui->cbDirections->addItem(client_to_server_string);
    this->ui->cbDirections->addItem(server_to_client_string);

    follow_stream();
    fillHintLabel(-1);

    data_out_file = NULL;

    return true;
}
Exemplo n.º 18
0
void contact(char* host) {
    // Determine remote address
    struct addrinfo* hostaddr;
    struct addrinfo hints;
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_DGRAM;
    char port[6];
    snprintf(port, 6, "%d", PORT);
    if (getaddrinfo(host, port, &hints, &hostaddr) != 0) {
        perror("getaddrinfo failed");
        return;
    }

    // Create socket
    int sock = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
    if (sock == -1) {
        perror("socket creation failed");
        return;
    }

    // Compose message
    char sendbuf[1+MAXSIZE];
    int msglen = snprintf(sendbuf, sizeof sendbuf, "M%s", get_hostname()) + 1;

    // Configure socket timeouts
    struct timeval timeout;
    memset(&timeout, 0, sizeof timeout);
    timeout.tv_sec = 1;
    if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof timeout) == -1) {
        perror("setsockopt(SO_RCVTIMEO) failed");
        close(sock);
        return;
    }
    if (setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof timeout) == -1) {
        perror("setsockopt(SO_SNDTIMEO) failed");
        close(sock);
        return;
    }

    // Send message
    if (sendto(sock, sendbuf, msglen, 0, hostaddr->ai_addr, hostaddr->ai_addrlen) == -1) {
        perror("sendto failed");
        close(sock);
        return;
    }

    char recvbuf[4*MAXSIZE];
    struct sockaddr peer;
    socklen_t peer_len = sizeof peer;
    size_t msgsize = recvfrom(sock, &recvbuf, sizeof recvbuf, 0, &peer, &peer_len);
    if (msgsize == -1) {
        if (errno == EWOULDBLOCK) {
            fprintf(stderr, "No response from %s!\n", host);
            close(sock);
            return;
        }

        perror("recvfrom failed");
        close(sock);
        return;
    }

    recvbuf[msgsize-1] = '\0';
    // Max length of IPv6 address is 8 * 4 + 7 and 1 for the \0
    char peeraddr[40];
    inet_ntop(AF_INET6, hostaddr, peeraddr, 40);
    if (recvbuf[0] != 'R') {
        fprintf(stderr, "Reply from %s(%s) does not follow protocol!\n"
                "Expected message type 'R', but got %c\n",
                peeraddr, host, recvbuf[0]);
        close(sock);
        return;
    }

    printf("\"%s\" from %s (%s)\n", recvbuf+1, peeraddr, host);

    close(sock);
}
Exemplo n.º 19
0
void Application::createQmlApp()
{
    loadSettings();

    engine.addImportPath("qrc:/qml/");

    connect(HardwareUtils::Instance(), SIGNAL(networkStatusChanged()),
            this, SLOT(networkStatusChanged()));
    connect(HardwareUtils::Instance(), SIGNAL(calaosServerDetected()),
            this, SLOT(calaosServerDetected()));

    connect(HardwareUtils::Instance(), &HardwareUtils::applicationWillResignActive, [=]()
    {
        qDebug() << "Application is in background, logout";
        startedWithOptHandled = false;
        logout();
    });

    connect(HardwareUtils::Instance(), &HardwareUtils::applicationBecomeActive, [=]()
    {
        qDebug() << "Application is in foreground, login again";
        QTimer::singleShot(0, [=]()
        {
            login(get_username(), get_password(), get_hostname());
        });
    });

    Common::registerQml();

#ifdef Q_OS_ANDROID
    QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;");
    QAndroidJniObject resource = activity.callObjectMethod("getResources","()Landroid/content/res/Resources;");
    QAndroidJniObject metrics = resource.callObjectMethod("getDisplayMetrics","()Landroid/util/DisplayMetrics;");
    update_density(metrics.getField<float>("density"));

    update_needBackButton(false);
    // Need to fix a bug on Android where text is scratched at runtime on some devices
    qputenv("QML_USE_GLYPHCACHE_WORKAROUND", QByteArray("1"));

    update_isAndroid(true);
    update_isIOS(false);
    update_isDesktop(false);
#else
    if (arguments().contains("--force-hdpi"))
        update_density(2.0);
    else
        update_density(1.0);

    update_needBackButton(true);

#ifdef Q_OS_IOS
    update_isAndroid(false);
    update_isIOS(true);
    update_isDesktop(false);
#else
    update_isAndroid(false);
    update_isIOS(false);
    update_isDesktop(true);
#endif
#endif

    update_applicationStatus(Common::NotConnected);

    calaosConnect = new CalaosConnection(this);
    connect(calaosConnect, SIGNAL(homeLoaded(QVariantMap)),
            this, SLOT(homeLoaded(QVariantMap)));
    connect(calaosConnect, SIGNAL(loginFailed()),
            this, SLOT(loginFailed()));
    connect(calaosConnect, &CalaosConnection::disconnected, [=]()
    {
        update_applicationStatus(Common::NotConnected);

#ifdef CALAOS_DESKTOP
        HardwareUtils::Instance()->showAlertMessage(tr("Network error"),
                                                    tr("The connection to calaos_server was lost."
                                                       "It will reconnect automatically when calaos_server"
                                                       "is available again."),
                                                    tr("Close"));

        //restart autologin, only on desktop to continually try to connect
        QTimer::singleShot(1000, [=]()
        {
            //reload settings in case it was changed
            loadSettings();
            login(get_username(), get_password(), get_hostname());
        });
#endif
    });

    scenarioModel = new ScenarioModel(&engine, calaosConnect, this);
    scenarioSortModel = new ScenarioSortModel(&engine, this);
    scenarioSortModel->setSourceModel(scenarioModel);
    engine.rootContext()->setContextProperty("scenarioModel", scenarioSortModel);
    lightOnModel = new LightOnModel(&engine, calaosConnect, this);
    engine.rootContext()->setContextProperty("lightOnModel", lightOnModel);
    homeModel = new HomeModel(&engine, calaosConnect, scenarioModel, lightOnModel, this);
    engine.rootContext()->setContextProperty("homeModel", homeModel);
    audioModel = new AudioModel(&engine, calaosConnect, this);
    engine.rootContext()->setContextProperty("audioModel", audioModel);
    favModel = new FavoritesModel(&engine, calaosConnect, this);
    engine.rootContext()->setContextProperty("favoritesModel", favModel);
    favHomeModel = new HomeFavModel(&engine, calaosConnect, this);
    engine.rootContext()->setContextProperty("favoritesHomeModel", favHomeModel);
    cameraModel = new CameraModel(&engine, calaosConnect);
    engine.rootContext()->setContextProperty("cameraModel", cameraModel);

#ifdef CALAOS_DESKTOP
    CalaosWidgetModel::Instance()->loadFromDisk();
    engine.rootContext()->setContextProperty("widgetsModel", CalaosWidgetModel::Instance());
#endif

    engine.rootContext()->setContextProperty("calaosApp", this);

    //Register Units singleton
    //qmlRegisterSingletonType(QUrl("qrc:/qml/Units.qml"), "Units", 1, 0, "Units");

    qmlRegisterType<RoomFilterModel>("Calaos", 1, 0, "RoomFilterModel");

#if defined(CALAOS_MOBILE)
    engine.load(QUrl(QStringLiteral("qrc:///qml/mobile/main.qml")));
#elif defined(CALAOS_DESKTOP)
    engine.load(QUrl(QStringLiteral("qrc:///qml/desktop/main.qml")));
#else
#error "Unknown UI type!"
#endif

#ifndef CALAOS_DESKTOP
    //Start autologin, only on mobile. On desktop we wait for calaos_server detection
    QTimer::singleShot(100, [=]()
    {
        login(get_username(), get_password(), get_hostname());
    });
#endif
}
Exemplo n.º 20
0
int main(int argc, char **argv)
{
	FILE *fh;
	int i, j;
	char c;
	bool eof = false;
	int mag = START_MAG, ten = START_TEN, page = START_PAGE;
	char *buffer = malloc(42);

	if(argc != 2) {
		printf("%s <filename>\n\n", argv[0]);
		return 5;
	}
	
	fh = fopen(argv[1], "r");
	
	while(1) {
		for(j = 0; j < 24; j++) {
			if(j > 0) {
				for(i = 0; i < 40; i++) {
					c = fgetc(fh);
					if((c == EOF) || (c == (char)255)) eof = true;
					if((eof != true) && (c != '\n')) {
						buffer[i+2] = c;
					} else {
						while(i < 40) {
							buffer[i+2] = ' ';
							i++;
						}
						break;
					}
				}
			} else {
				get_hostname(buffer + 10); //8
				sprintf(buffer + 18, "\x06%d%d%d", mag, ten, page);
				get_time(buffer + 22); /* injects date/time */
			}

			pkt_header(buffer, j, mag, ten, page);
			
			for(i = 0; i < 42; i++) {
				putchar(buffer[i]);
			}
		}
		
		page++;
		if(page == 10) {
			page = 0;
			ten++;
			
			if(ten == 10) {
				ten = 0;
				mag++;
			}
		}
		
		if(eof == true) {
			fclose(fh);
			eof = false;
			mag = START_MAG;
			ten = START_TEN;
			page = START_PAGE;
			fh = fopen(argv[1], "r");
		}
	}
	
	free(buffer);
	return 0;
}
Exemplo n.º 21
0
/*
 * This function acquires a lockfile for the given path. Returns true if the
 * lock was acquired, otherwise false. If the lock has been considered stale
 * for the number of microseconds specified by staleness_limit, the function
 * will (if possible) break the lock and then try to acquire it again. The
 * staleness limit should be reasonably larger than the longest time the lock
 * can be expected to be held, and the updates of the locked path should
 * probably be made with an atomic rename(2) to avoid corruption in the rare
 * case that the lock is broken by another process.
 */
bool
lockfile_acquire(const char *path, unsigned staleness_limit)
{
	char *lockfile = format("%s.lock", path);
	char *my_content = NULL, *content = NULL, *initial_content = NULL;
	const char *hostname = get_hostname();
	bool acquired = false;
#ifdef _WIN32
	const size_t bufsize = 1024;
	int fd, len;
#else
	int ret;
#endif
	unsigned to_sleep = 1000, slept = 0; /* Microseconds. */

	while (1) {
		free(my_content);
		my_content = format("%s:%d:%d", hostname, (int)getpid(), (int)time(NULL));

#ifdef _WIN32
		fd = open(lockfile, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0666);
		if (fd == -1) {
			cc_log("lockfile_acquire: open WRONLY %s: %s", lockfile, strerror(errno));
			if (errno == ENOENT) {
				/* Directory doesn't exist? */
				if (create_parent_dirs(lockfile) == 0) {
					/* OK. Retry. */
					continue;
				}
			}
			if (errno != EEXIST) {
				/* Directory doesn't exist or isn't writable? */
				goto out;
			}
			/* Someone else has the lock. */
			fd = open(lockfile, O_RDONLY|O_BINARY);
			if (fd == -1) {
				if (errno == ENOENT) {
					/*
					 * The file was removed after the open() call above, so retry
					 * acquiring it.
					 */
					continue;
				} else {
					cc_log("lockfile_acquire: open RDONLY %s: %s",
					       lockfile, strerror(errno));
					goto out;
				}
			}
			free(content);
			content = x_malloc(bufsize);
			if ((len = read(fd, content, bufsize - 1)) == -1) {
				cc_log("lockfile_acquire: read %s: %s", lockfile, strerror(errno));
				close(fd);
				goto out;
			}
			close(fd);
			content[len] = '\0';
		} else {
			/* We got the lock. */
			if (write(fd, my_content, strlen(my_content)) == -1) {
				cc_log("lockfile_acquire: write %s: %s", lockfile, strerror(errno));
				close(fd);
				x_unlink(lockfile);
				goto out;
			}
			close(fd);
			acquired = true;
			goto out;
		}
#else
		ret = symlink(my_content, lockfile);
		if (ret == 0) {
			/* We got the lock. */
			acquired = true;
			goto out;
		}
		cc_log("lockfile_acquire: symlink %s: %s", lockfile, strerror(errno));
		if (errno == ENOENT) {
			/* Directory doesn't exist? */
			if (create_parent_dirs(lockfile) == 0) {
				/* OK. Retry. */
				continue;
			}
		}
		if (errno != EEXIST) {
			/* Directory doesn't exist or isn't writable? */
			goto out;
		}
		free(content);
		content = x_readlink(lockfile);
		if (!content) {
			if (errno == ENOENT) {
				/*
				 * The symlink was removed after the symlink() call above, so retry
				 * acquiring it.
				 */
				continue;
			} else {
				cc_log("lockfile_acquire: readlink %s: %s", lockfile, strerror(errno));
				goto out;
			}
		}
#endif

		if (str_eq(content, my_content)) {
			/* Lost NFS reply? */
			cc_log("lockfile_acquire: symlink %s failed but we got the lock anyway",
			       lockfile);
			acquired = true;
			goto out;
		}
		/*
		 * A possible improvement here would be to check if the process holding the
		 * lock is still alive and break the lock early if it isn't.
		 */
		cc_log("lockfile_acquire: lock info for %s: %s", lockfile, content);
		if (!initial_content) {
			initial_content = x_strdup(content);
		}
		if (slept > staleness_limit) {
			if (str_eq(content, initial_content)) {
				/* The lock seems to be stale -- break it. */
				cc_log("lockfile_acquire: breaking %s", lockfile);
				if (lockfile_acquire(lockfile, staleness_limit)) {
					lockfile_release(path);
					lockfile_release(lockfile);
					to_sleep = 1000;
					slept = 0;
					continue;
				}
			}
			cc_log("lockfile_acquire: gave up acquiring %s", lockfile);
			goto out;
		}
		cc_log("lockfile_acquire: failed to acquire %s; sleeping %u microseconds",
		       lockfile, to_sleep);
		usleep(to_sleep);
		slept += to_sleep;
		to_sleep *= 2;
	}

out:
	if (acquired) {
		cc_log("Acquired lock %s", lockfile);
	} else {
		cc_log("Failed to acquire lock %s", lockfile);
	}
	free(lockfile);
	free(my_content);
	free(initial_content);
	free(content);
	return acquired;
}