Exemplo n.º 1
0
int put_run(run_t *run, sqlite3 **sqconn) {

    if(!user_exists(sqconn)) {
        fprintf(stderr, "Create a User before adding runs!\n");
        return RSTAT_FAIL;
    }

    char *statement = sqlite3_mprintf(
            "INSERT INTO runs(uid, location, time, distance, temperature) "
            "VALUES(%d, \"%s\", %lf, %lf, %lf)",
            run->uid,
            run->location,
            run->time,
            run->distance,
            run->temperature);

    DEBUG(printf("Created sql run statement.\n"));
    switch( sqlite3_exec(*sqconn, statement, 0, 0, 0) ) {
        case SQLITE_OK:
            DEBUG(printf("Successfully put run into table."));
            sqlite3_free(statement);
            return RSTAT_SUCCESS;
        default:
            fprintf(stderr, "Error: %s", sqlite3_errmsg(*sqconn));
            sqlite3_free(statement);
            return RSTAT_FAIL;
    }
    sqlite3_free(statement);
    return RSTAT_FAIL;
}
Exemplo n.º 2
0
Room *load_Home(char *username, int flags) {
Room *r;
char filename[MAX_PATHLEN], roomname[MAX_LINE];

	if (username == NULL || !*username || !user_exists(username))
		return NULL;

	Enter(load_Home);

	bufprintf(filename, sizeof(filename), "%s/%c/%s/HomeData", PARAM_USERDIR, *username, username);
	path_strip(filename);

	if ((r = load_RoomData(filename, 2, flags)) == NULL) {
		if ((r = new_Room()) == NULL) {
			Return NULL;
		}
		r->generation = (unsigned long)rtc;
	}
	r->number = HOME_ROOM;
	possession(username, "Home", roomname, MAX_LINE);
	Free(r->name);
	r->name = cstrdup(roomname);

	if (in_StringList(r->room_aides, username) == NULL)
		(void)prepend_StringList(&r->room_aides, new_StringList(username));

	if (in_StringList(r->invited, username) == NULL)
		(void)prepend_StringList(&r->invited, new_StringList(username));

	r->flags = ROOM_CHATROOM | ROOM_NOZAP | ROOM_INVITE_ONLY;
	Return r;
}
Exemplo n.º 3
0
std::string fuh::extract_salt(const std::string& name) {

	// Some double security, this should never be needed
	if(!(user_exists(name))) {
		return "";
	}

	std::string hash;

	try {
		hash = get_hash(name);
	} catch (const error& e) {
		ERR_UH << "Could not retrieve hash for user '" << name << "' :" << e.message << std::endl;
		return "";
	}

	if(utils::md5::is_valid_hash(hash))
		return hash.substr(0,12);

	if(utils::bcrypt::is_valid_prefix(hash)) {
		try {
			return utils::bcrypt::from_hash_string(hash).get_salt();
		} catch(const utils::hash_error& err) {
			ERR_UH << "Error getting salt from hash of user '" << name << "': " << err.what() << std::endl;
			return "";
		}
	}

	return "";
}
Exemplo n.º 4
0
/** \brief Nutzer mit Name, (ggf. Kürzel) und Passwort in die DB einfügen
 *
 * \param pers person*  Personen-Struktur
 * \return void
 * Eine Person in die DB einfügen, falls diese noch nicht existiert.
 * Das Passwort wird mithilfe von crypt() verschlüsselt
 */
void insertUser(person * pers){
	if(pers == NULL){
		printExitFailure("Programm falsch.\n Wörk!");
	}

	if(user_exists(pers->name)){
		printExitFailure("Benutzer Existiert schon!");
	}

	MYSQL *my=mysql_init(NULL);
	if(my == NULL){
		printExitFailure("MYSQL init failure\n Wörk!");
	}

	if(mysql_real_connect(my, "localhost", "root", "WUW", "base4", 0, NULL, 0) == NULL){
		/*fprintf (stderr, "Fehler mysql_real_connect(): %u (%s)\n",
		mysql_errno (my), mysql_error (my));
		exit(EXIT_FAILURE);*/
		printExitFailure("MYSQL-connection error!");
	}else{
		//fprintf(stderr, "Connection extablished!\n");
	}

	//TODO Salt erzeugen und "Salt-reuse verhindern"
	char * salt=NULL;
	salt_generate(&salt);

	while(salt_exists(&salt)){
		salt_generate(&salt);
	}

	pers->passwort=crypt(pers->passwort, salt);


	char * query;
	//Ist es eine Lehrer oder ein Schüler?
	if(!pers->isTeacher){
		query = calloc(strlen("INSERT INTO Benutzer (name, passwort, kurse) VALUES('")+strlen(pers->name)+strlen("', '")+strlen(pers->passwort)+strlen("', 'n/a');")+1, sizeof(char));
		strcat(query, "INSERT INTO Benutzer (name, passwort, kurse) VALUES('");
		strcat(query, pers->name);
		strcat(query, "', '");
		strcat(query, pers->passwort);
		strcat(query, "', 'n/a');");
	}else{
		query = calloc(strlen("INSERT INTO Benutzer (name, passwort, kurse, kuerzel) VALUES('")+strlen(pers->name)+strlen("', '")+strlen(pers->passwort)+strlen("', 'n/a', '")+strlen(pers->acronym)+strlen("');")+1, sizeof(char));
		strcat(query, "INSERT INTO Benutzer (name, passwort, kurse, kuerzel) VALUES('");
		strcat(query, pers->name);
		strcat(query, "', '");
		strcat(query, pers->passwort);
		strcat(query, "', 'n/a', '");
		strcat(query, pers->acronym);
		strcat(query, "');");
	}
	fprintf(stderr, "\nInsert dat:\n%s\n", query);
	if(mysql_query(my, query)){
		fprintf(stderr, "sql_query:\n%s\nfailed\n", query);
		printExitFailure("mysql_query failed (insert)");
	}
	mysql_close(my);
}
Exemplo n.º 5
0
Room *load_Mail(char *username, int flags) {
Room *r;
char filename[MAX_PATHLEN], roomname[MAX_LINE];

	if (username == NULL || !*username || !user_exists(username))
		return NULL;

	Enter(load_Mail);

	bufprintf(filename, sizeof(filename), "%s/%c/%s/MailData", PARAM_USERDIR, *username, username);
	path_strip(filename);

	if ((r = load_RoomData(filename, MAIL_ROOM, flags)) == NULL) {
		if ((r = new_Room()) == NULL) {
			Return NULL;
		}
		r->generation = (unsigned long)rtc;
	}
	r->number = MAIL_ROOM;
	possession(username, "Mail", roomname, MAX_LINE);
	Free(r->name);
	r->name = cstrdup(roomname);

	if (in_StringList(r->invited, username) == NULL)
		(void)prepend_StringList(&r->invited, new_StringList(username));

	r->flags = ROOM_SUBJECTS | ROOM_NOZAP | ROOM_INVITE_ONLY;

	bufprintf(filename, sizeof(filename), "%s/%c/%s/", PARAM_USERDIR, *username, username);
	path_strip(filename);
	room_readroomdir(r, filename, MAX_PATHLEN);
	Return r;
}
std::string fuh::user_info(const std::string& name) {
	if(!user_exists(name)) {
		throw error("No user with the name '" + name + "' exists.");
	}

	time_t reg_date = get_registrationdate(name);
	time_t ll_date = get_lastlogin(name);

	std::string reg_string = ctime(&reg_date);
	std::string ll_string;

	if(ll_date) {
		ll_string = ctime(&ll_date);
	} else {
		ll_string = "Never\n";
	}

	std::stringstream info;
	info << "Name: " << name << "\n"
		 << "Registered: " << reg_string
		 << "Last login: "******"This account is currently inactive.\n";
	}

	return info.str();
}
Exemplo n.º 7
0
varargs string gateway(mixed args){
    string pass_hash, who, password, ip;
    string ret = "";
    int max_tries = 3;
    int no_user = 0;

    if(ENABLE_CREWEB){ 

        ip = previous_object()->GetIp();

        if(!args || !stringp(args)) args = "123456789101112";
        if(sscanf(args,"%s&%s",who, password) != 2){
            ret = "<br>";
        }

        else {
            who = lower_case(who);

            if(!strsrch(who,"username="******"username="******"",1);
            if(!strsrch(password,"password="******"password="******"",1);

            if(!ret && !user_exists(who)){
                no_user = 1;
            }

            else {
                if(!Tries) Tries = ([]);
                if(!Tries[ip]) Tries[ip] = 0;
                if(no_user) pass_hash = alpha_crypt(32);
                else pass_hash = PLAYERS_D->GetPlayerData(who,"Password");
                if(pass_hash != crypt(password, pass_hash)){
                    Tries[ip]++;
                    ret = "Fail! Tries left: "+(max_tries - Tries[ip])+"<br>";
                    if(Tries[ip] >= max_tries){
                        previous_object()->eventBlockIp();
                        Tries[ip] = 0;
                    }
                }
                else {
                    string shibboleth = alpha_crypt(32);
                    string packet=who+"."+shibboleth;
                    WEB_SESSIONS_D->StartSession(ip,who,shibboleth);
                    ret = "Login successful<br>";
                    Tries[ip] = 0;
                    ret += "<meta http-equiv=\"Set-Cookie\" content=\"creweb="+packet+";path=/\">";
                    ret += "<META http-equiv=\"refresh\" content=\"1;URL=creweb.html\">";
                    return ret;
                }
            }
        }

        ret += "Log in to CreWeb using your mud username and mud password.<br><br>";
        ret += "<FORM ACTION=\"login.html\" METHOD=POST>";
        ret += "username: <INPUT TYPE=TEXT NAME=\"username\" MAXLENGTH=32><BR>";
        ret += "password:   <INPUT TYPE=PASSWORD NAME=\"password\" MAXLENGTH=32>";
        ret += "<P><INPUT TYPE=SUBMIT VALUE=\"submit\">";
        ret += "</FORM>";
        ret += "<br>";
    }
    else {
void suh::add_user(const std::string& name, const std::string& mail, const std::string& password) {
	if(user_exists(name)) throw error("This nickname is already registered");

	users_.insert(std::pair<std::string, user>(name, user()));

	set_password(name, password);
	set_mail(name, mail);

	user_logged_in(name);
}
void fuh::set_is_moderator(const std::string& name, const bool& is_moderator) {

	if(!user_exists(name)) return;

	try {
		write_detail(name, "user_is_moderator", is_moderator ? "1" : "0");
	} catch (error& e) {
		ERR_UH << "Could not set is_moderator for user '" << name << "' :" << e.message << std::endl;
	}
}
bool fuh::user_is_moderator(const std::string& name) {

	if(!user_exists(name)) return false;

	try {
		return get_writable_detail_for_user(name, "user_is_moderator") == "1";
	} catch (error& e) {
		ERR_UH << "Could not query user_is_moderator for user '" << name << "' :" << e.message << std::endl;
		// If the database is down mark nobody as a mod
		return false;
	}
}
Exemplo n.º 11
0
bool fuh::user_is_moderator(const std::string& name) {

	if(!user_exists(name)) return false;

	try {
		return get_writable_detail_for_user<int>(name, "user_is_moderator") == 1 || is_user_in_group(name, mp_mod_group_);
	} catch (const sql_error& e) {
		ERR_UH << "Could not query user_is_moderator/MP Moderators group for user '" << name << "' :" << e.message << std::endl;
		// If the database is down mark nobody as a mod
		return false;
	}
}
Exemplo n.º 12
0
fuh::ban_info fuh::user_is_banned(const std::string& name, const std::string& addr)
{
	//
	// NOTE: glob IP and email address bans are NOT supported yet since they
	//       require a different kind of query that isn't supported by our
	//       prepared SQL statement API right now. However, they are basically
	//       never used on forums.wesnoth.org, so this shouldn't be a problem
	//       for the time being.
	//

	// NOTE: A ban end time of 0 is a permanent ban.
	const std::string& is_extant_ban_sql =
		"ban_exclude = 0 AND (ban_end = 0 OR ban_end >=" + std::to_string(std::time(nullptr)) + ")";

	// TODO: retrieve full ban info in a single statement instead of issuing
	//       separate queries to check for a ban's existence and its duration.

	try {
		if(!addr.empty() && prepared_statement<bool>("SELECT 1 FROM `" + db_banlist_table_ + "` WHERE UPPER(ban_ip) = UPPER(?) AND " + is_extant_ban_sql, addr)) {
			LOG_UH << "User '" << name << "' ip " << addr << " banned by IP address\n";
			return retrieve_ban_info(BAN_IP, addr);
		}
	} catch(const sql_error& e) {
		ERR_UH << "Could not check forum bans on address '" << addr << "' :" << e.message << '\n';
		return {};
	}

	if(!user_exists(name)) return {};

	try {
		auto uid = get_detail_for_user<unsigned int>(name, "user_id");

		if(uid == 0) {
			ERR_UH << "Invalid user id for user '" << name << "'\n";
		} else if(prepared_statement<bool>("SELECT 1 FROM `" + db_banlist_table_ + "` WHERE ban_userid = ? AND " + is_extant_ban_sql, uid)) {
			LOG_UH << "User '" << name << "' uid " << uid << " banned by uid\n";
			return retrieve_ban_info(BAN_USER, uid);
		}

		auto email = get_detail_for_user<std::string>(name, "user_email");

		if(!email.empty() && prepared_statement<bool>("SELECT 1 FROM `" + db_banlist_table_ + "` WHERE UPPER(ban_email) = UPPER(?) AND " + is_extant_ban_sql, email)) {
			LOG_UH << "User '" << name << "' email " << email << " banned by email address\n";
			return retrieve_ban_info(BAN_EMAIL, email);
		}

	} catch(const sql_error& e) {
		ERR_UH << "Could not check forum bans on user '" << name << "' :" << e.message << '\n';
	}

	return {};
}
Exemplo n.º 13
0
mixed cmd(string args) {

    if(!archp(previous_object())) {
        write("No.");
        return 1;
    }

    if(!args || !sizeof(args)) args = "me";

    args = lower_case(args);

    if(args == "me" || args == this_player()->GetKeyName()){
        write("To reset your own password, use the command: passwd");
        return 1;
    }

    if( (int)previous_object()->GetForced() )
        return "You cannot be forced to change a password.";
    if( previous_object() != this_player() )
        return "You're being sploited to reset someone's password.";

    if(!user_exists(args)){
        write("That person does not exist on this mud.");
        return 1;
    }

    if(find_player(args)){
        write("That player is currently logged on. Please use "
          "the passwd command to reset their password.");
        return 1;
    }

    savefile = DIR_CRES + "/" + args[0..0] + "/" + args + ".o";
    if(!file_exists(savefile)) {
        write("Couldn't find "+savefile+". Looking for alternate.");
        savefile = DIR_PLAYERS + "/" + args[0..0] + "/"+ args + ".o";
    }

    if(!file_exists(savefile)){
        write("Save file could not be found. Exiting.");
        return 1;
    }

    write("Found "+savefile+".");

    previous_object()->eventPrint("New password: ", MSG_PROMPT);
    input_to( (: NewPass :), I_NOECHO | I_NOESC, previous_object() || args);
    return 1;
}
Exemplo n.º 14
0
int create_user(const char * username){
	if(user_file_exists() != 1) return 0;
	if(user_exists(username) == 1) return 1;

	FILE *fp = fopen(DATA_DIR USERS_INDEX, "a");
	if(!fp){
		fprintf(stderr, "%s\n", FAILED_FILE_OPEN DATA_DIR USERS_INDEX);
		return 0;
	}

	fprintf(fp, "%s\r\n", username);
	fflush(fp);
	fclose(fp);
	return 1;
}
Exemplo n.º 15
0
bool user_handler::send_mail(const std::string& to_user,
		const std::string& /*subject*/, const std::string& /*message*/) {

	//If this user is registered at all
	if(!user_exists(to_user)) {
		throw error("Could not send email. No user with the name '" + to_user + "' exists.");
	}

	// If this user did not provide an email
	if(get_mail(to_user) == "") {
		throw error("Could not send email. The email address of the user '" + to_user + "' is empty.");
	}

	throw user_handler::error("This server is configured not to send email.");
}
std::string suh::user_info(const std::string& name) {
	if(!user_exists(name)) throw error("No user with the name '" + name + "' exists.");

	time_t reg_date = get_registrationdate(name);
	time_t ll_date = get_lastlogin(name);

	std::string reg_string = ctime(&reg_date);
	std::string ll_string = ctime(&ll_date);

	std::stringstream info;
	info << "Name: " << name << "\n"
		 << "Real name: " << get_realname(name) << "\n"
		 << "Registered: " << reg_string
		 << "Last login: " << ll_string;
	return info.str();
}
Exemplo n.º 17
0
int main(int argc, char ** argv){
	cgi thisCGI;

	getCGIdata(&thisCGI);
	char * name=NULL;

	extractPOSTdata(&thisCGI, "name", &name);

	httpHeader(TEXT);
	if(user_exists(name)){
		puts("exists\n");
	}else{
		puts("no\n");
	}

	return 1;

}
Exemplo n.º 18
0
Arquivo: home.c Projeto: Elohim/FGmud
mixed GoHome(string str) {
    object ob, prev;
    string who, room;

    prev = environment(this_player());
    if( !str || str == "" || !creatorp(this_player())){
        who = this_player()->GetKeyName();
    }
    else who = lower_case(str);
    if(!user_exists(who)) return "There's no such user.";
    room = PLAYERS_D->GetHomeRoom(who);
    if(!room || !strsrch(room, "/tmp/")){
        str = user_path(who, 1);
        if(!directory_exists(str)) return "That person has no home dir.";
        str = user_path(who, 1)+"workroom.c";
        arg = str;
        if(!unguarded((: file_exists(arg) :)))
            return capitalize(who)+" has no active workroom.";
    }
Exemplo n.º 19
0
// Changes the inode's owner
unsigned int fs_chown(char * filename, char * username) {
	int new_uid = user_exists(username);
	int current_uid = current_ttyc()->uid;
	int start_inode = current_ttyc()->pwd;
	int namenode = fs_indir(filename, start_inode);

	if (namenode && new_uid != -1) {
		inode_read(namenode, &n);
		if (n.uid == current_uid || current_uid == 0) {
			n.uid = new_uid;
			inode_write(namenode, &n);
		} else {
			return ERR_PERMS;
		}
		return 1;
	} else {
		return ERR_NO_EXIST;
	}
}
std::string fuh::create_pepper(const std::string& name) {

	// Some double security, this should never be needed
	if(!(user_exists(name))) {
		return "";
	}

	std::string hash;

	try {
		hash = get_hash(name);
	} catch (error& e) {
		ERR_UH << "Could not retrieve hash for user '" << name << "' :" << e.message << std::endl;
		return "";
	}

	if(!util::is_valid_hash(hash)) return "";

	return hash.substr(0,12);
}
Exemplo n.º 21
0
// Return 1 on success, 0 on failure
int add_achievement_progress(int achievement_id, int add_progress_count){
	if(achievement_system_disabled){ return ACHIEVEMENT_PUSH_FAILURE; }
	if(ACHIEVEMENT_DEBUG){pline("DEBUG: add_achievement_progress(%i, %i)", achievement_id, add_progress_count);}
	
	if(check_db_connection()){
		disable_achievements();
	}
	
	//Check if user exists
	if(!user_exists()){
		register_user();
	}
	//Calculate user's completion on this achievement
	int pre_achievement_progress = get_achievement_progress(achievement_id);
	int max_achievement_progress = get_achievement_max_progress(achievement_id);
	if(ACHIEVEMENT_DEBUG){pline("DEBUG: get_achievement_max_progress(%i)=%i", achievement_id, max_achievement_progress);}

	if(pre_achievement_progress < max_achievement_progress){ //user still needs achievement
		if(pre_achievement_progress + add_progress_count >= max_achievement_progress){ //Achievement fully achieved!
			if(push_achievement_progress(achievement_id, max_achievement_progress)){ //floor the value to max_progress
				char * achievement_name = get_achievement_name(achievement_id);
				pline("Congratulations! You've earned the achievement: %s", achievement_name);
				free(achievement_name);
				return ACHIEVEMENT_PUSH_SUCCESS;
			}
			else{
				pline("Er, oops. You got an achievement, but it can't be recorded.");
				return ACHIEVEMENT_PUSH_FAILURE;
			}
		}
		else{ //user stills needs achievement, but isn't quite there yet
			if(push_achievement_progress(achievement_id, pre_achievement_progress+add_progress_count)){
				return ACHIEVEMENT_PUSH_SUCCESS;
			}
			else{
				return ACHIEVEMENT_PUSH_FAILURE;
			}
		}
	}
	return ACHIEVEMENT_PUSH_SUCCESS;
}
Exemplo n.º 22
0
varargs mixed is_user_path (string path, string name) {

    string s1,s2 ;

    if (name) {
	if (sscanf(path,"/u/%s/%s",s1,s2)!=2) {
	    if (!STUDENT_D->query_student(name)) return 0 ;
	    if (sscanf(path,"/student/%s",s1)!=1) return 0 ;
	    if (s1!=name) return 0 ;
	    return 1 ;
	}
	if (s1[0] != s2[0])  return 0;
	if (s2!=name) return 0 ;
	return 1 ;
    }
    if (sscanf(path,"/student/%s",s1)==1) {
	if (STUDENT_D->query_student(s1)) return s1 ;
	return 0 ;
    }
    if (sscanf(path,"/u/%s/%s",s1,s2)!=2) return 0 ;
    if (s1[0] != s2[0])  return 0;
    if (!user_exists(s2)) return 0 ;
    return s2 ;
}
Exemplo n.º 23
0
int room_exists(char *name) {
char *p;

	if ((p = cstrchr(name, '\'')) != NULL) {
		if ((PARAM_HAVE_HOMEROOM && (!strcmp(p, "'s Home") || !strcmp(p, "' Home")))
			|| (PARAM_HAVE_MAILROOM && (!strcmp(p, "'s Mail") || !strcmp(p, "' Mail")))) {
			*p = 0;
			if (user_exists(name)) {
				*p = '\'';
				return 1;
			}
			*p = '\'';
			return 0;
		}
	}
	if (*name >= '0' && *name <= '9')
		return roomnumber_exists((unsigned int)atoi(name));
	else {
		Room *r;

		for(r = AllRooms; r != NULL; r = r->next)
			if (!strcmp(r->name, name)) {
				if (r->number == MAIL_ROOM && !PARAM_HAVE_MAILROOM)
					return 0;

				if (r->number == HOME_ROOM && !PARAM_HAVE_HOMEROOM)
					return 0;

				if ((r->flags & ROOM_CHATROOM) && !PARAM_HAVE_CHATROOMS)
					return 0;

				return 1;
			}
	}
	return 0;
}
Exemplo n.º 24
0
int load_RoomData_version0(File *f, Room *r, int flags) {
char buf[MAX_LONGLINE];
StringList *sl;
int i;

/* name */
	if (Fgets(f, buf, MAX_LINE) == NULL)
		goto err_load_room;

	cstrip_line(buf);
	Free(r->name);
	r->name = cstrdup(buf);

	if (flags & LOAD_ROOM_DATA) {
/* generation/creation date */
		if (Fgets(f, buf, MAX_LINE) == NULL)
			goto err_load_room;
		cstrip_line(buf);
		r->generation = cstrtoul(buf, 10);

/* flags */
		if (Fgets(f, buf, MAX_LINE) == NULL)
			goto err_load_room;
		cstrip_line(buf);
		r->flags = (unsigned int)cstrtoul(buf, 16);
		r->flags &= ROOM_ALL;		/* reset non-existant flags */

/* roominfo_changed */
		if (Fgets(f, buf, MAX_LINE) == NULL)
			goto err_load_room;
		cstrip_line(buf);
		r->roominfo_changed = (unsigned int)cstrtoul(buf, 10);
	} else
		LOAD_ROOM_SKIPLINES(3);

/* info */
	destroy_StringIO(r->info);
	r->info = NULL;

	if (PARAM_HAVE_RESIDENT_INFO || (flags & LOAD_ROOM_INFO)) {
		while(Fgets(f, buf, MAX_LINE) != NULL) {
			if (!*buf)
				break;

			if (r->info == NULL && (r->info = new_StringIO()) == NULL)
				continue;

			put_StringIO(r->info, buf);
			write_StringIO(r->info, "\n", 1);
		}
	} else
		LOAD_ROOM_SKIPLIST;

/* room aides */
	listdestroy_StringList(r->room_aides);
	r->room_aides = NULL;

	if (flags & LOAD_ROOM_AIDES) {
		while(Fgets(f, buf, MAX_LINE) != NULL) {
			cstrip_line(buf);
			if (!*buf)
				break;

			if (user_exists(buf) && (sl = new_StringList(buf)) != NULL)
				r->room_aides = add_StringList(&r->room_aides, sl);
		}
		r->room_aides = rewind_StringList(r->room_aides);
	} else
		LOAD_ROOM_SKIPLIST;

/* invited */
	listdestroy_StringList(r->invited);
	r->invited = NULL;

	if (flags & LOAD_ROOM_INVITED) {
		while(Fgets(f, buf, MAX_LINE) != NULL) {
			cstrip_line(buf);
			if (!*buf)
				break;

			if (user_exists(buf) && (sl = new_StringList(buf)) != NULL)
				r->invited = add_StringList(&r->invited, sl);
		}
		r->invited = rewind_StringList(r->invited);
	} else
		LOAD_ROOM_SKIPLIST;

/* kicked */
	listdestroy_StringList(r->kicked);
	r->kicked = NULL;

	if (flags & LOAD_ROOM_KICKED) {
		while(Fgets(f, buf, MAX_LINE) != NULL) {
			cstrip_line(buf);
			if (!*buf)
				break;

			if (user_exists(buf) && (sl = new_StringList(buf)) != NULL)
				r->kicked = add_StringList(&r->kicked, sl);
		}
		r->kicked = rewind_StringList(r->kicked);
	} else
		LOAD_ROOM_SKIPLIST;

/* chat history */
	if ((flags & LOAD_ROOM_CHAT_HISTORY) && (r->flags & ROOM_CHATROOM)) {
		if (r->chat_history == NULL && (r->chat_history = new_StringQueue()) == NULL)
			LOAD_ROOM_SKIPLIST;
		else {
			r->chat_history->tail = (ListType *)Fgetlist(f);
			r->chat_history->head = (ListType *)unwind_StringList((StringList *)r->chat_history->tail);
			r->chat_history->count = count_List(r->chat_history->tail);
		}
	} else
		LOAD_ROOM_SKIPLIST;

	return 0;

err_load_room:
	return -1;
}
Exemplo n.º 25
0
// INT 80h Handler, kernel entry.
void int_80() {
	if(krn)	{
		return;
	}
	
	krn++;
	int systemCall = kernel_buffer[0];
	int fd         = kernel_buffer[1];
	int buffer     = kernel_buffer[2];
	int count      = kernel_buffer[3];

	
	int i, j;
	Process * current;
	Process * p;
	int inode;
	int _fd;
	// Yeah, wanna know why we don't access an array directly? ... Because of big bugs we might have.
	switch(systemCall) {
		case READY:
			kernel_buffer[KERNEL_RETURN] = kernel_ready();
			break;
		case WRITE:
 			current = getp();
			kernel_buffer[KERNEL_RETURN] = fd_write(current->file_descriptors[fd],(char *)buffer,count);
			break;
		case READ:
			current = getp();
			kernel_buffer[KERNEL_RETURN] = fd_read(current->file_descriptors[fd],(char *)buffer,count);
			break;
		case MKFIFO:
			_fd = process_getfreefd();
			fd = fd_open(_FD_FIFO, (void *)kernel_buffer[1],kernel_buffer[2]);
			if(_fd != -1 && fd != -1)	{
				getp()->file_descriptors[_fd] = fd;
				kernel_buffer[KERNEL_RETURN] = _fd;
			}
			else {
				kernel_buffer[KERNEL_RETURN] = -1;
			}
			break;
		case OPEN:
			_fd = process_getfreefd();
			fd = fd_open(_FD_FILE, (void *) kernel_buffer[1], kernel_buffer[2]);
			if(_fd != -1 && fd >= 0)
			{
				getp()->file_descriptors[_fd] = fd;
				kernel_buffer[KERNEL_RETURN] = _fd;
			}
			else {
				kernel_buffer[KERNEL_RETURN] = fd;
			}
			break;
		case CLOSE:
			kernel_buffer[KERNEL_RETURN] = fd_close(getp()->file_descriptors[fd]);
			break;
		case PCREATE:
			kernel_buffer[KERNEL_RETURN] = sched_pcreate(kernel_buffer[1],kernel_buffer[2],kernel_buffer[3]);
			break;
		case PRUN:
			kernel_buffer[KERNEL_RETURN] = sched_prun(kernel_buffer[1]);
			break;
		case PDUP2:
			kernel_buffer[KERNEL_RETURN] = sched_pdup2(kernel_buffer[1],kernel_buffer[2],kernel_buffer[3]);
			break;
		case GETPID:
			kernel_buffer[KERNEL_RETURN] = sched_getpid();
			break;
		case WAITPID:
			kernel_buffer[KERNEL_RETURN] = sched_waitpid(kernel_buffer[1]);
			break;
		case PTICKS:
			kernel_buffer[KERNEL_RETURN] = (int) storage_index();
			break;
		case PNAME:
			p = process_getbypid(kernel_buffer[1]);
			if(p == NULL)
			{
				kernel_buffer[KERNEL_RETURN] = (int) NULL;
			} else {
				kernel_buffer[KERNEL_RETURN] = (int) p->name;
			}
			break;
		case PSTATUS:
			p = process_getbypid(kernel_buffer[1]);
			if(p == NULL)
			{
				kernel_buffer[KERNEL_RETURN] = (int) -1;
			} else {
				kernel_buffer[KERNEL_RETURN] = (int) p->state;
			}
			break;
		case PPRIORITY:
			p = process_getbypid(kernel_buffer[1]);
			if(p == NULL)
			{
				kernel_buffer[KERNEL_RETURN] = (int) -1;
			} else {
				kernel_buffer[KERNEL_RETURN] = (int) p->priority;
			}
			break;
		case PGID:
			p = process_getbypid(kernel_buffer[1]);
			if(p == NULL)
			{
				kernel_buffer[KERNEL_RETURN] = (int) -1;
			} else {
				kernel_buffer[KERNEL_RETURN] = (int) p->gid;
			}
			break;
		case PGETPID_AT:
			p = process_getbypindex(kernel_buffer[1]);
			if (p->state != -1) {
				kernel_buffer[KERNEL_RETURN] = (int) p->pid;
			} else {
				kernel_buffer[KERNEL_RETURN] = -1;
			}
			break;
		case KILL:
			kernel_buffer[KERNEL_RETURN - 1] = kernel_buffer[1];
			kernel_buffer[KERNEL_RETURN - 2] = kernel_buffer[2];
			break;
		case PSETP:
			p = process_getbypid(kernel_buffer[1]);
			if(p == NULL)	{
				kernel_buffer[KERNEL_RETURN] = (int) -1;
			} else {
				if(kernel_buffer[2] <= 4 && kernel_buffer[2] >= 0)	{
					p->priority = kernel_buffer[2];
				}
				kernel_buffer[KERNEL_RETURN] = (int) p->gid;
			}
			break;
		case SETSCHED:
			sched_set_mode(kernel_buffer[1]);
			break;
		case PWD:
			kernel_buffer[KERNEL_RETURN] = (int) fs_pwd();
			break;
		case CD:
			kernel_buffer[KERNEL_RETURN] = (int) fs_cd(kernel_buffer[1]);
			break;
		case FINFO:
			fs_finfo(kernel_buffer[1], kernel_buffer[2]);
			break;
		case MOUNT:
			fs_init();
			break;
		case MKDIR:
			kernel_buffer[KERNEL_RETURN] = (int) fs_mkdir(kernel_buffer[1],current_ttyc()->pwd);
			break;
		case RM:
			inode = fs_indir(kernel_buffer[1],current_ttyc()->pwd);
			if (inode) {
				kernel_buffer[KERNEL_RETURN] = (int) fs_rm(inode,0);
			} else {
				kernel_buffer[KERNEL_RETURN] = ERR_NO_EXIST;
			}
			break;
		case GETUID:
			if(kernel_buffer[1] == 0)
			{
				kernel_buffer[KERNEL_RETURN] = (int) current_ttyc()->uid;
			} else {
				kernel_buffer[KERNEL_RETURN] = (int) user_exists(kernel_buffer[1]);
			}
			break;
		case GETGID:
			if(kernel_buffer[1] == 0)
			{
				kernel_buffer[KERNEL_RETURN] = (int) user_gid(current_ttyc()->uid);
			} else {
				kernel_buffer[KERNEL_RETURN] = (int) user_gid(kernel_buffer[1]);
			}

			break;
		case MAKEUSER:
			kernel_buffer[KERNEL_RETURN] = user_create(kernel_buffer[1],
							kernel_buffer[2], user_gid(current_ttyc()->uid));
			break;
		case SETGID:
			kernel_buffer[KERNEL_RETURN] = user_setgid(kernel_buffer[1], 
													   kernel_buffer[2]);
			break;
		case UDELETE:
			kernel_buffer[KERNEL_RETURN] = user_delete(kernel_buffer[1]);
			break;
		case UEXISTS:
			kernel_buffer[KERNEL_RETURN] = user_exists(kernel_buffer[1]);
			break;
		case ULOGIN:
			kernel_buffer[KERNEL_RETURN] = user_login(kernel_buffer[1], 
													  kernel_buffer[2]);
			break;
		case ULOGOUT:
			kernel_buffer[KERNEL_RETURN] = user_logout();
			break;
		case CHOWN:
			kernel_buffer[KERNEL_RETURN] = fs_chown(kernel_buffer[1],
													kernel_buffer[2]);
			break;
		case CHMOD:
			kernel_buffer[KERNEL_RETURN] = fs_chmod(kernel_buffer[1],
												    kernel_buffer[2]);
			break;
		case GETOWN:
			kernel_buffer[KERNEL_RETURN] = fs_getown(kernel_buffer[1]);
			break;
		case GETMOD:
			kernel_buffer[KERNEL_RETURN] = fs_getmod(kernel_buffer[1]);
			break;
		case CP:
			kernel_buffer[KERNEL_RETURN] = fs_cp(kernel_buffer[1], kernel_buffer[2], current_ttyc()->pwd, current_ttyc()->pwd);
			break;
		case MV:
			kernel_buffer[KERNEL_RETURN] = fs_mv(kernel_buffer[1], kernel_buffer[2], current_ttyc()->pwd);
			break;
		case LINK:
			kernel_buffer[KERNEL_RETURN] = fs_open_link(kernel_buffer[1], kernel_buffer[2], current_ttyc()->pwd);
			break;
		case FSSTAT:
			kernel_buffer[KERNEL_RETURN] = fs_stat(kernel_buffer[1]);
			break;
		case SLEEP:
			kernel_buffer[KERNEL_RETURN] = scheduler_sleep(kernel_buffer[1]);
			break;
		default:
			break;
	}
	
	krn--;
}
Exemplo n.º 26
0
int main(int argc, char** argv) {
    struct mg_server *server;
    char  buf[100];
    char  cert[100];
    const char* pidFile = "/var/run/checkip.pid";
    char  port[140];
    char* user = "******";
    int jail_mode = FALSE;
    int c;
    int fd = -1;

    // init variables
    pid_t process_id = 0;
    pid_t sid = 0;
    daemon_mode = FALSE;
    letsencrypt_req[0] = '\0';
    letsencrypt_resp[0] = '\0';
    strncpy(cert, "checkip-cert.pem", sizeof cert);

    initValidIP();
    jailDir[0] = '\0';

    // Get the start time
    time(&start);

    // Parse command line for "-h -p nnn -c /path/to/file"
    while((c = getopt(argc, argv, "dhj:p:u:r:R:c:")) != -1)
    {
      switch(c)
      {
      case 'c': strncpy(cert, optarg, sizeof cert);
                break;
      case 'd': daemon_mode = TRUE;
                break;
      case 'j': jail_mode = TRUE;
                char* temp_dir = optarg;
                if (!dir_exists(temp_dir)) {
                  printf("Jail root dir '%s' does not exist, or is not a directory\n", jailDir);
                  return -1;
                }
                strncpy(jailDir, realpath(temp_dir, NULL), sizeof jailDir);
                break;
      case 'r': strcpy(letsencrypt_req, optarg);
                break;
      case 'R': strcpy(letsencrypt_resp, optarg);
                break;
      case 'p': strcpy(port, optarg);
                break;
      case 'u': user = optarg;
                if (!user_exists(user)) {
                  printf("User '%s' does not exist\n", user);
                  return -1;
                }
                break;
      case 'h': usage();
		return -1;
		break;
      case '?': printf("Invalid option '%c'\n", optopt);
		usage();
		return -1;
		break;
      default:	printf("Getopt error\n");
		return -100;
      }

    }
    if (jail_mode && !daemon_mode) {
      printf("-j (chroot jail) requires -d (daemon) by specified\n");
      return -1;
    }
    strcpy(ipAddr, getIPaddr());
    strcpy(port, "80,ssl://0.0.0.0:443:");
    strncat(port, cert, (sizeof port)-strlen(port)-1);

    // Open the log
    if (daemon_mode)
      openlog(NULL, LOG_CONS | LOG_PID, LOG_DAEMON);

    // lock the pid file
    fd = createPidFile(argv[0], pidFile, 0);

    // If a daemon, fork a child process and exit the parent
    if (daemon_mode) {
      // 1. create a child process
      process_id = fork();
      if (process_id < 0) {
        log_msg(daemon_mode, "fork() failed! - exiting");
        exit(-1);
      }

      // 2. kill the parent process
      if (process_id > 0)
        exit(0);

      // 3. unmask the file mode
      umask(0);

      // 4. start a new session
      sid = setsid();
      if (sid < 0) {
        log_msg(daemon_mode, "setsid() failed! - exiting");
        exit(-1);
      }

      // 5. redirect stdin, stdout and stderr to null
      redir2null(stdin, O_RDONLY);
      redir2null(stdout, O_WRONLY);
      redir2null(stderr, O_RDWR);	// Note stderr must be r/w

      // 6. Update the PID file with the child PID
      updateChildPid(fd, (long) getpid());
    }

    // Create and configure the server
    log_msg(daemon_mode, "CheckIP version %s starting", VERSION);
    printTZ();
    log_msg(daemon_mode, "Using SSL certificate '%s'", cert);
    server = mg_create_server(NULL, ev_handler);
    mg_set_option(server, "listening_port", port);
    strcpy(buf, mg_get_option(server, "listening_port"));
    if (buf[0] == '\0') {
       log_msg(daemon_mode, "open listening ports failed - exiting");
       goto exit;
    }

    // chroot jail the process
    if (jail_mode && !isChrooted()) {
       // adjust the path
       putenv("PATH=/bin:/sbin");

       // set the new root dir
       int err = chroot(jailDir);
       if (err != 0) {
          log_msg(daemon_mode, "chroot() failed! (err %d) - exiting", errno);
          exit(-1);
       }
       log_msg(daemon_mode, "Established chroot() jail under '%s'", jailDir);

       // Set the curr dir to be within the chroot
       chdir("/");
    }

    // Trap KILL's - cause 'running' flag to be set false, HUP dumps the stats
    running = -1;
    signal(SIGINT, intHandler);
    signal(SIGTERM, intHandler);
    signal(SIGHUP, intHandler);

    // load robots.txt to robots variable
    loadRobots(jailDir);

    // load sitemap.xml to robots variable
    loadSitemap(jailDir);

    // load the GeoIP database
    initGeoIP();

    // Log LetsEncrypt settings
    if (letsencrypt_req[0] != '\0')
        log_msg(daemon_mode, "LE req = '%s'\n", letsencrypt_req);
    if (letsencrypt_resp[0] != '\0')
        log_msg(daemon_mode, "LE resp = '%s'\n", letsencrypt_resp);


    // Serve request. Hit Ctrl-C or SIGTERM to terminate the program
    mg_set_option(server, "run_as_user", user);
    if (user != NULL)
      log_msg(daemon_mode, "Server executing as user '%s'", user);
    log_msg(daemon_mode, "Listening on port %s", buf);

    while (running) {
      mg_poll_server(server, 250);
    }
    if(!daemon_mode) printf("\n");

    // Get the finish time and compute the duration
exit:
    time(&finish);

    // Cleanup, and free server instance
    mg_destroy_server(&server);

    // Close and delete the pid file;
    if (fd != -1) {
    	close(fd);
    	unlink(pidFile);
    }

    // Print stats
    print_stats(daemon_mode, start, finish, "stopping after");

    // Clean up GeoIP2
    closeGeoIP();

    if (!daemon_mode) printf("\nClean shutdown\n");

    return 0;
}
void suh::remove_user(const std::string& name) {
	if(!user_exists(name)) throw error("This nickname is not registered");

	users_.erase(name);
}
bool suh::user_is_moderator(const std::string& name) {
	if(!user_exists(name)) return false;
	return users_[name].is_moderator;
}
void suh::set_is_moderator(const std::string& name, const bool& is_moderator) {
	if(!user_exists(name)) return;
	users_[name].is_moderator = is_moderator;
}