int main() { char *installationChoice = (char *) malloc(sizeof(installationChoice)); int choice; printf("### Subuntu Login Menu ###\n"); printf("### 1. Unlock System ###\n"); printf("### 2. Add New User ###\n"); printf("### 3. Delete User ###\n"); printf("### 4. Change Password ###\n"); printf("### 5. Exit ###\n"); printf("Please enter your choice: "); scanf("%d", &choice); if(choice == 1) { login_diffuser(); } else if(choice == 2) { add_user(); } else if(choice == 3) { delete_user(); } else if(choice == 4) { change_password(); } else if(choice == 5) { exit(0); } else { printf("Invalid Option!\n"); printf("Please enter your choice: "); scanf("%d", &choice); } }
void do_quit(const char *source, int ac, char **av) { User *user; NickAlias *na; user = finduser(source); if (!user) { alog("user: QUIT from nonexistent user %s: %s", source, merge_args(ac, av)); return; } if (debug) { alog("debug: %s quits", source); } if ((na = user->na) && (!(na->status & NS_VERBOTEN)) && (!(na->nc->flags & NI_SUSPENDED)) && (na->status & (NS_IDENTIFIED | NS_RECOGNIZED))) { na->last_seen = time(NULL); if (na->last_quit) free(na->last_quit); na->last_quit = *av[0] ? sstrdup(av[0]) : NULL; } if (LimitSessions && !is_ulined(user->server->name)) { del_session(user->host); } delete_user(user); }
void do_kill(char *nick, char *msg) { User *user; NickAlias *na; user = finduser(nick); if (!user) { if (debug) { alog("debug: KILL of nonexistent nick: %s", nick); } return; } if (debug) { alog("debug: %s killed", nick); } if ((na = user->na) && (!(na->status & NS_VERBOTEN)) && (!(na->nc->flags & NI_SUSPENDED)) && (na->status & (NS_IDENTIFIED | NS_RECOGNIZED))) { na->last_seen = time(NULL); if (na->last_quit) free(na->last_quit); na->last_quit = *msg ? sstrdup(msg) : NULL; } if (LimitSessions && !is_ulined(user->server->name)) { del_session(user->host); } delete_user(user); }
static int get_pw_uid(TALLOC_CTX *mem_ctx, struct proxy_id_ctx *ctx, struct sysdb_ctx *sysdb, struct sss_domain_info *dom, uid_t uid) { TALLOC_CTX *tmpctx; struct passwd *pwd; enum nss_status status; char *buffer; size_t buflen; bool del_user = false; int ret; DEBUG(SSSDBG_TRACE_FUNC, ("Searching user by uid (%d)\n", uid)); tmpctx = talloc_new(NULL); if (!tmpctx) { return ENOMEM; } pwd = talloc_zero(tmpctx, struct passwd); if (!pwd) { ret = ENOMEM; goto done; } buflen = DEFAULT_BUFSIZE; buffer = talloc_size(tmpctx, buflen); if (!buffer) { ret = ENOMEM; goto done; } status = ctx->ops.getpwuid_r(uid, pwd, buffer, buflen, &ret); ret = handle_getpw_result(status, pwd, dom, &del_user); if (ret) { DEBUG(SSSDBG_OP_FAILURE, ("getpwuid failed [%d]: %s\n", ret, strerror(ret))); goto done; } if (del_user) { ret = delete_user(sysdb, dom, NULL, uid); goto done; } ret = save_user(sysdb, dom, !dom->case_sensitive, pwd, pwd->pw_name, NULL, dom->user_timeout); done: talloc_zfree(tmpctx); if (ret) { DEBUG(SSSDBG_CRIT_FAILURE, ("proxy -> getpwuid_r failed for '%d' <%d>: %s\n", uid, ret, strerror(ret))); } return ret; }
/*解析消息线程*/ void *pthread_func() { head_user = (struct user_info *)malloc(sizeof(struct user_info)); head_user->next = NULL; struct user_info *tmp; // 循环变量,用于便利在线用户链表将其发送给第一次登录的或者有刷新请求的客户端 struct servmsg *free_tmp; int ret= -1; while(1) { while(H->next != NULL) { // free_tmp = H; H = H->next; //消息头,处理玩就往后移动 // free(free_tmp);//将处理完的消息所占内存释放掉 // free_tmp = NULL; printf("消息链表首地址H :%p\n",H); printf("准备解析消息---\n"); printf("消息来自%s:\tIP:%s(%d)\n",H->recvmsg.self_name,inet_ntoa(H->addr.sin_addr),ntohs(H->addr.sin_port)); if(H->recvmsg.type == REGISTER) { register_user(); continue; } if(H->recvmsg.type == LOG_IN ) { check_user(); // if(find) { add_user(head_user,H);// add } continue; } if(H->recvmsg.type == REFRESH){ printf("%s刷新消息\n",H->recvmsg.self_name); //usleep(50000); send_all_online(H->addr); continue; } if (H->recvmsg.type == OFFLINE){ printf("%s下线\n",H->recvmsg.self_name); delete_user(H->recvmsg.self_name); } if (H->recvmsg.type == CHAT_PRI){ printf("%s私聊消息\n",H->recvmsg.self_name); printf("目标:%s\n",H->recvmsg.dst_name); chat_private(); } if(H->recvmsg.type == CHAT_ALL){ printf("%s群聊消息\n",H->recvmsg.self_name); chat_toall(); } printf("-----------------------------------\n"); }//end while(H) } }
int main (int argc, char *argv[]) { char in[10]; int id = 1; User *s; unsigned num_users; while (1) { printf ("1. add user\n"); printf ("2. find user\n"); printf ("3. delete user\n"); printf ("4. delete all users\n"); printf ("5. sort items by name\n"); printf ("6. sort items by id\n"); printf ("7. print users\n"); printf ("8. count users\n"); gets (in); switch (atoi (in)) { case 1: printf ("name?\n"); add_user (id++, gets (in)); break; case 2: printf ("id?\n"); s = find_user (atoi (gets (in))); printf ("user: %s\n", s ? s->name : "unknown"); break; case 3: printf ("id?\n"); s = find_user (atoi (gets (in))); if (s) delete_user (s); else printf ("id unknown\n"); break; case 4: delete_all (); break; case 5: sort_by_name (); break; case 6: sort_by_id (); break; case 7: print_users (); break; case 8: num_users = HASH_COUNT (users); printf ("there are %u users\n", num_users); break; } } }
static int quit_hook(int argc, char *argv[]) { char *nick = grab_nick(argv[0]); user_t *u = find_user(nick, irc_pick_server()); u->print_relevant_wins(u, "%s %s has quit [%s]\n", timestamp(), u->name, argv[2]); if (u->flags == 0) delete_user(u); else list_init(&(u->chlist)); free(nick); return 0; }
int main(int argc, char* argv[]) { int batch_mode = (argc == 2); char input[INPUT_BUFFER_SIZE]; FILE *input_stream; // Create the heads of the empty data structure User *user_list = NULL; if (batch_mode) { input_stream = fopen(argv[1], "r"); if (input_stream == NULL) { perror("Error opening file"); exit(1); } } else { // interactive mode input_stream = stdin; } printf("Welcome to FriendMe! (Local version)\nPlease type a command:\n> "); while (fgets(input, INPUT_BUFFER_SIZE, input_stream) != NULL) { // only echo the line in batch mode since in interactive mode the user // just typed the line if (batch_mode) { printf("%s", input); } char *cmd_argv[INPUT_ARG_MAX_NUM]; int cmd_argc = tokenize(input, cmd_argv); if (cmd_argc > 0 && process_args(cmd_argc, cmd_argv, &user_list) == -1) { break; // can only reach if quit command was entered } printf("> "); } if (batch_mode) { fclose(input_stream); } // Delete all users. This should free all heap memory that was allocated // during the run of the program. Uncomment after you've implemented // deleting users. printf("Freeing all heap space.\n"); while (user_list != NULL) { delete_user(user_list->name, &user_list); } return 0; }
void userdel(char* argv) { char* firstSpace = strchr(argv, ' '); struct User* user; if (firstSpace == NULL) { printf("Usage: userdel LOGIN\n"); } else if ((user = get_user_by_name(firstSpace + 1)) == NULL) { printf("userdel: user '%s' does not exists.\n", firstSpace + 1) ; } else { delete_group_member(user->gid[0], user->id); delete_user(firstSpace + 1); free_user(user); printf("Successfully deleted user account.\n"); } }
void do_clean_ups (MYSQL *mysql) { MYSQL_RES *res; MYSQL_ROW row; debug (1, "do_clean_ups"); /* auto logout */ /* alt where planet.mode & 0x0F = 2 */ res = do_query (mysql,"SELECT user.planet_id FROM user, planet " \ "WHERE planet.id=user.planet_id " \ "AND now() - INTERVAL 30 MINUTE > user.last "\ "AND (planet.mode = 0xF2 OR planet.mode = 2)"); if (res && mysql_num_rows(res)) { while ((row = mysql_fetch_row (res))) { vx_query(mysql, "UPDATE user SET uptime=" \ "SEC_TO_TIME(UNIX_TIMESTAMP(last) - UNIX_TIMESTAMP(login_date) + TIME_TO_SEC(uptime)) " \ "WHERE planet_id='%s'", row[0]); vx_query (mysql, "UPDATE planet SET mode=((mode & 0xF0) + 1) WHERE id=%s", row[0]); do_log_id (mysql, atoi(row[0]), C_LOGOUT, T_AUTO, ""); } } check_error (mysql); mysql_free_result(res); /* protection */ /* alt where planet.mode & 0xF0 */ res = do_query (mysql,"SELECT user.planet_id FROM user,planet,general " \ "WHERE planet.id=user.planet_id " \ "AND planet.mode>127 " \ "AND general.tick>=user.first_tick+71"); if (res && mysql_num_rows(res)) { while ((row = mysql_fetch_row (res))) { vx_query (mysql, "UPDATE planet SET mode=(mode & 0xF) WHERE id=%s", row[0]); } } check_error (mysql); mysql_free_result(res); /* sleeping */ /* alt where planet.mode & 0x0F = 3 */ res = do_query (mysql,"SELECT user.planet_id FROM user,planet " \ "WHERE planet.id=user.planet_id " \ "AND (planet.mode = 0xF3 OR planet.mode = 3) " \ "AND user.last_sleep < now() - INTERVAL 6 HOUR"); if (res && mysql_num_rows(res)) { while ((row = mysql_fetch_row (res))) { vx_query (mysql, "UPDATE planet SET mode=(mode & 0xF0)+1 WHERE id=%s", row[0]); do_log_id (mysql, atoi(row[0]), C_FLOW, T_SLEEP, ""); } } check_error (mysql); mysql_free_result(res); /* clean politics */ res = do_query (mysql,"SELECT id FROM politics " \ "WHERE now() - INTERVAL 7 DAY > date"); if (res && mysql_num_rows(res)) { while ((row = mysql_fetch_row (res))) { vx_query (mysql, "DELETE FROM politics WHERE id = %s", row[0]); vx_query (mysql, "DELETE FROM poltext WHERE thread_id = %s", row[0]); } } check_error (mysql); mysql_free_result(res); /* delete idle/old/test accounts */ /* only if mytick > 24 hours = 120*24 = 1440 */ if (mytick > 2880) { res = do_query (mysql, "SELECT planet.id FROM planet,user "\ "WHERE planet.id=user.planet_id "\ "AND planet.id>2 "\ "AND (metalroids+crystalroids+eoniumroids+uniniroids) < 4 " \ "AND (user.last < NOW() - INTERVAL 24 HOUR " \ "OR (user.last IS NULL "\ "AND user.signup < NOW() - INTERVAL 24 HOUR))"); if (res && mysql_num_rows(res)) { while ((row = mysql_fetch_row (res))) delete_user(mysql, atoi(row[0])); } } /* delete deleted accounts */ res = do_query (mysql, "SELECT planet_id FROM user "\ "WHERE delete_date !=0 AND delete_date > last " \ "AND delete_date < NOW() - INTERVAL 12 HOUR"); if (res && mysql_num_rows(res)) { while ((row = mysql_fetch_row (res))) delete_user(mysql, atoi(row[0])); } check_error (mysql); mysql_free_result(res); /* delete banned accounts */ res = do_query (mysql, "SELECT planet.id FROM planet,user "\ "WHERE planet.id=user.planet_id AND mode=0 AND " \ "user.last < NOW() - INTERVAL 36 HOUR"); if (res && mysql_num_rows(res)) { while ((row = mysql_fetch_row (res))) delete_user(mysql, atoi(row[0])); } check_error (mysql); mysql_free_result(res); /* check for exiling */ res = do_query (mysql,"SELECT id, x, y, exile_id "\ "FROM galaxy WHERE exile_id>0 AND exile_date<now()"); if (res && mysql_num_rows(res)) { while ((row = mysql_fetch_row (res))) check_exile(mysql, atoi(row[0]), atoi(row[1]),atoi(row[2]),atoi(row[3])); } check_error (mysql); mysql_free_result(res); /* clean news */ do_query (mysql, "DELETE FROM news WHERE date < now() - INTERVAL 48 HOUR"); /* clean journal (1) */ do_query (mysql, "DELETE FROM journal WHERE hidden=1 AND date < NOW() - INTERVAL 10 MINUTE"); /* clean journal (2) */ do_query (mysql, "DELETE FROM journal WHERE hidden=0 AND date < NOW() - INTERVAL 48 HOUR"); /* fleet cleanup */ do_query (mysql, "DELETE FROM units WHERE num=0"); /* clear hostile */ }
int main() { string username; string password; string command; string subcommand; string temp_path; char t; load_user(); init(); save(); while (1) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_GREEN); cout << "welcome to system" << endl; cout << "please login" << endl; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); while (1) { username = ""; password = ""; cout << "username:"******"password:"******"username or password error" << endl; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); } } system("cls"); getline(cin, command); while (1) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE); cout << username; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED); cout << "@filesystem "; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_BLUE); if (path.size() == 1) cout << "/"; else { for (auto p : path) { if (p == 0) continue; cout << "/" << catalog[p].info.name; } } SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); cout << endl << ">"; getline(cin, command); stringstream command_stream(command); command_stream >> subcommand; if (subcommand == "") { } else if (subcommand == "cd") { change_path(command); } else if (subcommand == "ls") { show_folder(command); } else if (subcommand == "create") { create(command); } else if (subcommand == "mkdir") { create_folder(command); } else if (subcommand == "delete") { delete_file(command); } else if (subcommand == "edit") { edit(command); } else if (subcommand == "search") { search_file(command); } else if (subcommand == "open") { open_file(command); } else if (subcommand == "close") { close_file(command); } else if (subcommand == "cp") { copy(command); } else if (subcommand == "mv") { move(command); } else if (subcommand == "bs"){ backstage(); } else if (subcommand == "l"){ l(); } else if (subcommand == "info"){ info(); } else if (subcommand == "format") { char c; cout << "Are you sure you want to format the disk?(y/N)"; c = _getch(); if (c == 'n' || c == 'N' || c == '\r') { cout << c << endl; continue; } else if (c == 'y' || c == 'Y') { remove("disk.txt"); remove("diskdata.txt"); init(); cout << c << "\nformat complete" << endl; } } else if (subcommand == "useradd") { add_user(command); } else if (subcommand == "userdelete") { delete_user(command); } else if (subcommand == "passwd") { change_password(command); } else if (subcommand == "clear") { system("cls"); } else if (subcommand == "exit") { system("cls"); break; } else { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED); cout << "command not found" << endl; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); } cout << endl; save(); command = ""; subcommand = ""; } } }
int cmd_user(sqlite3 *db,char **errmsg,vpChat temp,int sockfd)//用语判别用户信息 { int flag; int sayflag; printf("cmd = %d\n",temp->cmd); switch(temp->cmd ) { case REG: { flag = read_user(db,errmsg,temp->name); if(flag == USERIN) { return REGNO;//注册重名 } else { reg_db(db,errmsg,temp->name,temp->passwd); temp->flag = read_id(db,errmsg,temp->name); return REGOK; } break; } case LOG: { int flagpasswd; flag = read_online_ok(db,errmsg,temp->name); if(flag == ONLINEIN) { return ONLINEIN; } else { flagpasswd = read_pass(db,errmsg,temp->name,temp->passwd); if(flagpasswd == PASSWDOK) { log_db(db,errmsg,temp->name,sockfd); return PASSWDOK; } else { return PASSWDNO; } } break; } case LOGID: { int flagpasswd; read_id_name(db,errmsg,temp);//询问有无此用户 flag = read_online_ok(db,errmsg,temp->name); if(flag == ONLINEIN) { return ONLINEIN; } else { flagpasswd = read_pass(db,errmsg,temp->name,temp->passwd); if(flagpasswd == PASSWDOK) { log_db(db,errmsg,temp->name,sockfd); return PASSWDOK; } else { return PASSWDNO; } } break; } case CHAT: { int tempfd; tempfd = read_online_fd(db,errmsg,temp->toname); if(tempfd == ONLINEOUT) { return ONLINEOUT; } else { sayflag = read_online_flag(db,errmsg,temp->name); if(sayflag == 0) { return MYFLAGNO; } else { temp->flag = flag; temp->sockfd = tempfd; insert_data_db(db,errmsg,temp->time,temp); return CHATOK; } } break; } case ALL: { sayflag = read_online_flag(db,errmsg,temp->name); if(sayflag == 0) { return MYFLAGNO; } else { insert_data_db(db,errmsg,temp->time,temp); return ALLOK; } break; } case SMILE: { sayflag = read_online_flag(db,errmsg,temp->name); if(sayflag == 0) { return MYFLAGNO; } else { insert_data_db(db,errmsg,temp->time,temp); return SMILEOK; } break; } case WELCOME: { sayflag = read_online_flag(db,errmsg,temp->name); if(sayflag == 0) { return MYFLAGNO; } else { insert_data_db(db,errmsg,temp->time,temp); return WELCOMEOK; } break; } case PASSWD: { flag = update_passwd(db,errmsg,temp->name,temp->passwd); return flag; break; } case BOOT: { int tempfd; tempfd = read_online_fd(db,errmsg,temp->toname); if(tempfd == ONLINEOUT) { return ONLINEOUT; } else { temp->sockfd = tempfd; return BOOTOK; } break; } case STEP: { int tempfd; tempfd = read_online_fd(db,errmsg,temp->toname); if(tempfd == ONLINEOUT) { return ONLINEOUT; } else { flag = update_flag(db,errmsg,temp->toname,0); if(flag == 1) { temp->sockfd = tempfd; } return flag; } break; } case BAN: { int tempfd; tempfd = read_online_fd(db,errmsg,temp->toname); if(tempfd == ONLINEOUT) { return ONLINEOUT; } else { sayflag = read_online_flag(db,errmsg,temp->toname); if(sayflag == 1) { return TOFLAGOK; } else { flag = update_flag(db,errmsg,temp->toname,1); if(flag == 1) { temp->sockfd = tempfd; } return flag; } } break; } case SET: { int tempfd; tempfd = read_online_fd(db,errmsg,temp->toname); if(tempfd == ONLINEOUT) { flag = delete_user(db,errmsg,temp->toname); return flag; } else { return ONLINEIN; } break; } case SEE: { return SEEOK; break; } case DATA: { return DATAOK; break; } case SEND: { int tempfd; tempfd = read_online_fd(db,errmsg,temp->toname); if(tempfd == ONLINEOUT) { return ONLINEOUT; } else { temp->sockfd = tempfd; return SENDOK; } break; } case CHANGE: { flag = read_user(db,errmsg,temp->toname); if(flag == USERIN) { return REGNO;//注册重名 } else { flag = update_user(db,errmsg,temp->name,temp->toname);//¿¿¿¿ if(flag == 1) { sayflag = update_db_data(db,errmsg,temp->name,temp->toname);//修改密码 return sayflag; } else { return 0; } } break; } } }
static int get_pw_name(struct proxy_id_ctx *ctx, struct sss_domain_info *dom, const char *name) { TALLOC_CTX *tmpctx; struct passwd *pwd; enum nss_status status; char *buffer; size_t buflen; int ret; uid_t uid; bool del_user; struct ldb_result *cached_pwd = NULL; const char *real_name = NULL; DEBUG(SSSDBG_TRACE_FUNC, "Searching user by name (%s)\n", name); tmpctx = talloc_new(NULL); if (!tmpctx) { return ENOMEM; } pwd = talloc_zero(tmpctx, struct passwd); if (!pwd) { ret = ENOMEM; goto done; } buflen = DEFAULT_BUFSIZE; buffer = talloc_size(tmpctx, buflen); if (!buffer) { ret = ENOMEM; goto done; } /* FIXME: should we move this call outside the transaction to keep the * transaction as short as possible ? */ status = ctx->ops.getpwnam_r(name, pwd, buffer, buflen, &ret); ret = handle_getpw_result(status, pwd, dom, &del_user); if (ret) { DEBUG(SSSDBG_OP_FAILURE, "getpwnam failed [%d]: %s\n", ret, strerror(ret)); goto done; } if (del_user) { ret = delete_user(dom, name, 0); goto done; } uid = pwd->pw_uid; /* Canonicalize the username in case it was actually an alias */ if (ctx->fast_alias == true) { ret = sysdb_getpwuid(tmpctx, dom, uid, &cached_pwd); if (ret != EOK) { /* Non-fatal, attempt to canonicalize online */ DEBUG(SSSDBG_TRACE_FUNC, "Request to cache failed [%d]: %s\n", ret, strerror(ret)); } if (ret == EOK && cached_pwd->count == 1) { real_name = ldb_msg_find_attr_as_string(cached_pwd->msgs[0], SYSDB_NAME, NULL); if (!real_name) { DEBUG(SSSDBG_MINOR_FAILURE, "Cached user has no name?\n"); } } } if (real_name == NULL) { memset(buffer, 0, buflen); status = ctx->ops.getpwuid_r(uid, pwd, buffer, buflen, &ret); ret = handle_getpw_result(status, pwd, dom, &del_user); if (ret) { DEBUG(SSSDBG_OP_FAILURE, "getpwuid failed [%d]: %s\n", ret, strerror(ret)); goto done; } real_name = pwd->pw_name; } if (del_user) { ret = delete_user(dom, name, uid); goto done; } /* Both lookups went fine, we can save the user now */ ret = save_user(dom, !dom->case_sensitive, pwd, real_name, name, dom->user_timeout); done: talloc_zfree(tmpctx); if (ret) { DEBUG(SSSDBG_OP_FAILURE, "proxy -> getpwnam_r failed for '%s' <%d>: %s\n", name, ret, strerror(ret)); } return ret; }
/* * Read and process commands * Return: -1 for quit command * 0 otherwise */ int process_args(int cmd_argc, char **cmd_argv, User **user_list_ptr) { User *user_list = *user_list_ptr; if (cmd_argc <= 0) { return 0; } else if (strcmp(cmd_argv[0], "quit") == 0 && cmd_argc == 1) { return -1; } else if (strcmp(cmd_argv[0], "add_user") == 0 && cmd_argc == 2) { switch (create_user(cmd_argv[1], user_list_ptr)) { case 1: error("user by this name already exists"); break; case 2: error("username is too long"); break; } } else if (strcmp(cmd_argv[0], "list_users") == 0 && cmd_argc == 1) { list_users(user_list); } else if (strcmp(cmd_argv[0], "update_pic") == 0 && cmd_argc == 3) { User *user = find_user(cmd_argv[1], user_list); if (user == NULL) { error("user not found"); } if (update_pic(user, cmd_argv[2]) == 1) { error("file not found"); } } else if (strcmp(cmd_argv[0], "delete_user") == 0 && cmd_argc == 2) { if (delete_user(cmd_argv[1], user_list_ptr) == 1) { error("user by this name does not exist"); } } else if (strcmp(cmd_argv[0], "make_friends") == 0 && cmd_argc == 3) { switch (make_friends(cmd_argv[1], cmd_argv[2], user_list)) { case 1: error("users are already friends"); break; case 2: error("at least one user you entered has the max number of friends"); break; case 3: error("you must enter two different users"); break; case 4: error("at least one user you entered does not exist"); break; } } else if (strcmp(cmd_argv[0], "post") == 0 && cmd_argc >= 4) { // first determine how long a string we need int space_needed = 0; for (int i = 3; i < cmd_argc; i++) { space_needed += strlen(cmd_argv[i]) + 1; } // allocate the space char *contents = malloc(space_needed); // copy in the bits to make a single string strcpy(contents, cmd_argv[3]); for (int i = 4; i < cmd_argc; i++) { strcat(contents, " "); strcat(contents, cmd_argv[i]); } User *author = find_user(cmd_argv[1], user_list); User *target = find_user(cmd_argv[2], user_list); switch (make_post(author, target, contents)) { case 1: error("the users are not friends"); break; case 2: error("at least one user you entered does not exist"); break; } } else if (strcmp(cmd_argv[0], "profile") == 0 && cmd_argc == 2) { User *user = find_user(cmd_argv[1], user_list); if (print_user(user) == 1) { error("user not found"); } } else { error("Incorrect syntax"); } return 0; }
void cb_applybutton(GtkButton *button, gpointer userdata) { GSList *iterator = NULL; GtkTreeModel *model; GtkTreePath *path; GtkTreeIter iter; USER user; model = (GtkTreeModel *) userdata; for (iterator=ins_list; iterator; iterator= iterator->next) { path = gtk_tree_row_reference_get_path(iterator->data); /* gtk_tree_model_get 拷贝新的,需自行释放 */ if (path==NULL)continue; gtk_tree_model_get_iter(model, &iter, path); gtk_tree_model_get(model, &iter, COLUMN_USER_UID , &(user.uid), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_NAME, &(user.name), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_AGE, &(user.age), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_BIRTH, &(user.birth), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_IDCARD, &(user.idcard), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_PLACE, &(user.place), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_ADDRESS, &(user.address), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_PHONE, &(user.phone), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_OTHER, &(user.other), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_AUTHORITY, &(user.authority), -1); inster_user(&user); gtk_tree_path_free(path); gtk_tree_row_reference_free(iterator->data); } if (ins_list != NULL) { g_slist_free(ins_list); ins_list = NULL; } for (iterator=del_list; iterator; iterator= iterator->next) { user.uid = iterator->data; delete_user(&user); } if (del_list != NULL) { g_slist_free(del_list); del_list = NULL; } for (iterator = upt_list; iterator; iterator = iterator->next) { path = gtk_tree_row_reference_get_path(iterator->data); if (path==NULL)continue; /* gtk_tree_model_get 拷贝新的,需自行释放 */ gtk_tree_model_get_iter(model, &iter, path); gtk_tree_model_get(model, &iter, COLUMN_USER_UID , &(user.uid), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_NAME, &(user.name), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_AGE, &(user.age), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_BIRTH, &(user.birth), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_IDCARD, &(user.idcard), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_PLACE, &(user.place), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_ADDRESS, &(user.address), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_PHONE, &(user.phone), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_OTHER, &(user.other), -1); gtk_tree_model_get(model, &iter, COLUMN_USER_AUTHORITY, &(user.authority), -1); update_user(&user); gtk_tree_path_free(path); gtk_tree_row_reference_free(iterator->data); } if (upt_list != NULL) { g_slist_free(upt_list); upt_list = NULL; } }
int main() { //register_user("ezhuang", "john1990", "test"); //register_user("hahaha","dadada","test"); //register_user("ddd","poo","test"); //match_user("ezhuang", "john1990", "test"); //match_user("hahaha","dadada","test"); //match_user("ezhuang", "john1990", "test"); //delete_user("hahaha","dadada","test"); printf("Available commands:\n(1) register_user\n(2) delete_user\n(3) is_user_valid\n(4) match_user\n(5) change_user_password\n(6) quit\n\n\n"); unsigned char command[1024]; int operation_status ; while(1) { printf("enter a command: "); scanf("%s",command) ; // printf("\n") ; operation_status = OKAY ; if(!strcmp(command,"register_user")) { printf("username: "******"%s",username) ; printf("password: "******"%s",password) ; printf("password file name: "); unsigned char pFile[1024] ; scanf("%s",pFile); operation_status = register_user(username,password,pFile) ; } else if(!strcmp(command,"delete_user")) { printf("username: "******"%s",username) ; printf("password: "******"%s",password) ; printf("password file name: "); unsigned char pFile[1024] ; scanf("%s",pFile); operation_status = delete_user(username,password, pFile) ; } else if(!strcmp(command,"is_user_valid")) { printf("username: "******"%s",username) ; printf("password file name: "); unsigned char pFile[1024] ; scanf("%s",pFile); operation_status = is_user_valid(username,pFile) ; } else if(!strcmp(command,"match_user")) { printf("username: "******"%s",username) ; printf("password: "******"%s",password) ; printf("password file name: "); unsigned char pFile[1024] ; scanf("%s",pFile); operation_status = match_user(username,password,pFile) ; } else if(!strcmp(command,"change_user_password")) { printf("username: "******"%s",username) ; printf("current password: "******"%s",password) ; printf("new password: "******"%s",npassword) ; printf("password file name: "); unsigned char pFile[1024] ; scanf("%s",pFile); operation_status = change_user_password(username,password,npassword, pFile) ; } else if(!strcmp(command,"quit")) { printf("INFO: Got the quit command\n"); printf("Program terminating\n"); break; } else { printf("ERROR: Unknown command %s\n",command); printf("INFO: Ignoring command\n") ; } if(operation_status == ERROR) printf("Operation %s failed\n",command) ; } return 0; }
/*解析消息线程*/ void *pthread_func() { int group_fd; //组播套接字 group_fd = udp_link(); head_user = (struct user_info *)malloc(sizeof(struct user_info)); head_user->next = NULL; struct user_info *tmp; // 循环变量,用于便利在线用户链表将其发送给第一次登录的或者有刷新请求的客户端 struct servmsg *free_tmp; int ret= -1; while(1){ while(H->next != NULL){ free_tmp = H; H = H->next; //消息头,处理玩就往后移动 free(free_tmp);//将处理完的消息所占内存释放掉 free_tmp = NULL; printf("消息来自:%s IP:PORT:%s:%d\n",H->recvmsg.self_name,inet_ntoa(H->addr.sin_addr),ntohs(H->addr.sin_port)); switch(H->recvmsg.type) { case LOG_IN: printf("%s登录消息\n",H->recvmsg.self_name); send_message_to_all(H,LOGIN_TOALL); add_user(head_user,H); break; case REFRESH: printf("%s刷新消息\n",H->recvmsg.self_name); //usleep(50000); send_all_online(H->addr); break; case CHAT_PRI: printf("%s私聊消息\n",H->recvmsg.self_name); printf("目标:%s\n",H->recvmsg.dst_name); chat_private(); break; case CHAT_ALL: printf("%s群聊消息\n",H->recvmsg.self_name); send_message_to_all(H,CHAT_ALL); break; case FILE_NAME: printf("%s申请下载\n",H->recvmsg.self_name); send_dir_allfile(H->addr); break; case DOWNLOAD: printf("%s 确认下载\n",H->recvmsg.self_name); pthread_create(&tid2,NULL,download_send,(void *)&H->addr); pthread_detach(tid2); break; case UPLOAD: printf("%s上传文件\n",H->recvmsg.self_name); pthread_create(&tid3,NULL,(void *)&upload_func,NULL); pthread_detach(tid3); break; case OFFLINE: printf("%s下线\n",H->recvmsg.self_name); delete_user(H->recvmsg.self_name); break; case CREATE_GROUP: printf("%s create group\n",H->recvmsg.self_name); create_group(H); break; case JOIN_GROUP: printf("%s join group\n",H->recvmsg.self_name); join_group(H); break; case LIST_GROUP: printf("%s list group\n",H->recvmsg.self_name); list_group(H); break; case GROUP_CHAT: printf("%s group chat\n",H->recvmsg.self_name); group_chat(H); break; case GROUP_DELETE: printf("%s delete group\n",H->recvmsg.self_name); delete_group(H); break; default: printf("msg type error !\n"); break; } printf("-----------------------------------\n"); } } }
int pw_user(int mode, char *name, long id, struct cargs * args) { int rc, edited = 0; char *p = NULL; char *passtmp; struct carg *arg; struct passwd *pwd = NULL; struct group *grp; struct stat st; struct userconf *cnf; char line[_PASSWORD_LEN+1]; char path[MAXPATHLEN]; FILE *fp; char *dmode_c; void *set = NULL; static struct passwd fakeuser = { NULL, "*", -1, -1, 0, "", "User &", "/nonexistent", "/bin/sh", 0 #if defined(__FreeBSD__) ,0 #endif }; cnf = conf.userconf; /* * With M_NEXT, we only need to return the * next uid to stdout */ if (mode == M_NEXT) { uid_t next = pw_uidpolicy(cnf, id); if (getarg(args, 'q')) return next; printf("%u:", next); pw_group(mode, name, -1, args); return EXIT_SUCCESS; } /* * We can do all of the common legwork here */ if ((arg = getarg(args, 'b')) != NULL) { cnf->home = arg->val; } if ((arg = getarg(args, 'M')) != NULL) { dmode_c = arg->val; if ((set = setmode(dmode_c)) == NULL) errx(EX_DATAERR, "invalid directory creation mode '%s'", dmode_c); cnf->homemode = getmode(set, _DEF_DIRMODE); free(set); } /* * If we'll need to use it or we're updating it, * then create the base home directory if necessary */ if (arg != NULL || getarg(args, 'm') != NULL) { int l = strlen(cnf->home); if (l > 1 && cnf->home[l-1] == '/') /* Shave off any trailing path delimiter */ cnf->home[--l] = '\0'; if (l < 2 || *cnf->home != '/') /* Check for absolute path name */ errx(EX_DATAERR, "invalid base directory for home '%s'", cnf->home); if (stat(cnf->home, &st) == -1) { char dbuf[MAXPATHLEN]; /* * This is a kludge especially for Joerg :) * If the home directory would be created in the root partition, then * we really create it under /usr which is likely to have more space. * But we create a symlink from cnf->home -> "/usr" -> cnf->home */ if (strchr(cnf->home+1, '/') == NULL) { snprintf(dbuf, MAXPATHLEN, "/usr%s", cnf->home); if (mkdir(dbuf, _DEF_DIRMODE) != -1 || errno == EEXIST) { chown(dbuf, 0, 0); /* * Skip first "/" and create symlink: * /home -> usr/home */ symlink(dbuf+1, cnf->home); } /* If this falls, fall back to old method */ } strlcpy(dbuf, cnf->home, sizeof(dbuf)); p = dbuf; if (stat(dbuf, &st) == -1) { while ((p = strchr(p + 1, '/')) != NULL) { *p = '\0'; if (stat(dbuf, &st) == -1) { if (mkdir(dbuf, _DEF_DIRMODE) == -1) goto direrr; chown(dbuf, 0, 0); } else if (!S_ISDIR(st.st_mode)) errx(EX_OSFILE, "'%s' (root home parent) is not a directory", dbuf); *p = '/'; } } if (stat(dbuf, &st) == -1) { if (mkdir(dbuf, _DEF_DIRMODE) == -1) { direrr: err(EX_OSFILE, "mkdir '%s'", dbuf); } chown(dbuf, 0, 0); } } else if (!S_ISDIR(st.st_mode)) errx(EX_OSFILE, "root home `%s' is not a directory", cnf->home); } if ((arg = getarg(args, 'e')) != NULL) cnf->expire_days = atoi(arg->val); if ((arg = getarg(args, 'y')) != NULL) cnf->nispasswd = arg->val; if ((arg = getarg(args, 'p')) != NULL && arg->val) cnf->password_days = atoi(arg->val); if ((arg = getarg(args, 'g')) != NULL) { if (!*(p = arg->val)) /* Handle empty group list specially */ cnf->default_group = ""; else { if ((grp = GETGRNAM(p)) == NULL) { if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL) errx(EX_NOUSER, "group `%s' does not exist", p); } cnf->default_group = newstr(grp->gr_name); } } if ((arg = getarg(args, 'L')) != NULL) cnf->default_class = pw_checkname(arg->val, 0); if ((arg = getarg(args, 'G')) != NULL && arg->val) { int i = 0; for (p = strtok(arg->val, ", \t"); p != NULL; p = strtok(NULL, ", \t")) { if ((grp = GETGRNAM(p)) == NULL) { if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL) errx(EX_NOUSER, "group `%s' does not exist", p); } if (extendarray(&cnf->groups, &cnf->numgroups, i + 2) != -1) cnf->groups[i++] = newstr(grp->gr_name); } while (i < cnf->numgroups) cnf->groups[i++] = NULL; } if ((arg = getarg(args, 'k')) != NULL) { if (stat(cnf->dotdir = arg->val, &st) == -1 || !S_ISDIR(st.st_mode)) errx(EX_OSFILE, "skeleton `%s' is not a directory or does not exist", cnf->dotdir); } if ((arg = getarg(args, 's')) != NULL) cnf->shell_default = arg->val; if ((arg = getarg(args, 'w')) != NULL) cnf->default_password = boolean_val(arg->val, cnf->default_password); if (mode == M_ADD && getarg(args, 'D')) { if (name != NULL) errx(EX_DATAERR, "can't combine `-D' with `-n name'"); if ((arg = getarg(args, 'u')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) { if ((cnf->min_uid = (uid_t) atoi(p)) == 0) cnf->min_uid = 1000; if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_uid = (uid_t) atoi(p)) < cnf->min_uid) cnf->max_uid = 32000; } if ((arg = getarg(args, 'i')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) { if ((cnf->min_gid = (gid_t) atoi(p)) == 0) cnf->min_gid = 1000; if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_gid = (gid_t) atoi(p)) < cnf->min_gid) cnf->max_gid = 32000; } if (write_userconfig(conf.config)) return (EXIT_SUCCESS); err(EX_IOERR, "config udpate"); } if (mode == M_PRINT && getarg(args, 'a')) { SETPWENT(); while ((pwd = GETPWENT()) != NULL) print_user(pwd); ENDPWENT(); return EXIT_SUCCESS; } if (name != NULL) pwd = GETPWNAM(pw_checkname(name, 0)); if (id < 0 && name == NULL) errx(EX_DATAERR, "user name or id required"); /* * Update, delete & print require that the user exists */ if (mode == M_UPDATE || mode == M_DELETE || mode == M_PRINT || mode == M_LOCK || mode == M_UNLOCK) { if (name == NULL && pwd == NULL) /* Try harder */ pwd = GETPWUID(id); if (pwd == NULL) { if (mode == M_PRINT && getarg(args, 'F')) { fakeuser.pw_name = name ? name : "nouser"; fakeuser.pw_uid = (uid_t) id; return print_user(&fakeuser); } if (name == NULL) errx(EX_NOUSER, "no such uid `%ld'", id); errx(EX_NOUSER, "no such user `%s'", name); } if (name == NULL) name = pwd->pw_name; /* * The M_LOCK and M_UNLOCK functions simply add or remove * a "*LOCKED*" prefix from in front of the password to * prevent it decoding correctly, and therefore prevents * access. Of course, this only prevents access via * password authentication (not ssh, kerberos or any * other method that does not use the UNIX password) but * that is a known limitation. */ if (mode == M_LOCK) { if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) == 0) errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name); asprintf(&passtmp, "%s%s", locked_str, pwd->pw_passwd); if (passtmp == NULL) /* disaster */ errx(EX_UNAVAILABLE, "out of memory"); pwd->pw_passwd = passtmp; edited = 1; } else if (mode == M_UNLOCK) { if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) != 0) errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name); pwd->pw_passwd += sizeof(locked_str)-1; edited = 1; } else if (mode == M_DELETE) return (delete_user(cnf, pwd, name, getarg(args, 'r') != NULL, mode)); else if (mode == M_PRINT) return print_user(pwd); /* * The rest is edit code */ if (conf.newname != NULL) { if (strcmp(pwd->pw_name, "root") == 0) errx(EX_DATAERR, "can't rename `root' account"); pwd->pw_name = pw_checkname(conf.newname, 0); edited = 1; } if (id > 0 && isdigit((unsigned char)*arg->val)) { pwd->pw_uid = (uid_t)id; edited = 1; if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0) errx(EX_DATAERR, "can't change uid of `root' account"); if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0) warnx("WARNING: account `%s' will have a uid of 0 (superuser access!)", pwd->pw_name); } if ((arg = getarg(args, 'g')) != NULL && pwd->pw_uid != 0) { /* Already checked this */ gid_t newgid = (gid_t) GETGRNAM(cnf->default_group)->gr_gid; if (newgid != pwd->pw_gid) { edited = 1; pwd->pw_gid = newgid; } } if ((arg = getarg(args, 'p')) != NULL) { if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) { if (pwd->pw_change != 0) { pwd->pw_change = 0; edited = 1; } } else { time_t now = time(NULL); time_t expire = parse_date(now, arg->val); if (pwd->pw_change != expire) { pwd->pw_change = expire; edited = 1; } } } if ((arg = getarg(args, 'e')) != NULL) { if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) { if (pwd->pw_expire != 0) { pwd->pw_expire = 0; edited = 1; } } else { time_t now = time(NULL); time_t expire = parse_date(now, arg->val); if (pwd->pw_expire != expire) { pwd->pw_expire = expire; edited = 1; } } } if ((arg = getarg(args, 's')) != NULL) { char *shell = shell_path(cnf->shelldir, cnf->shells, arg->val); if (shell == NULL) shell = ""; if (strcmp(shell, pwd->pw_shell) != 0) { pwd->pw_shell = shell; edited = 1; } } if (getarg(args, 'L')) { if (cnf->default_class == NULL) cnf->default_class = ""; if (strcmp(pwd->pw_class, cnf->default_class) != 0) { pwd->pw_class = cnf->default_class; edited = 1; } } if ((arg = getarg(args, 'd')) != NULL) { if (strcmp(pwd->pw_dir, arg->val)) edited = 1; if (stat(pwd->pw_dir = arg->val, &st) == -1) { if (getarg(args, 'm') == NULL && strcmp(pwd->pw_dir, "/nonexistent") != 0) warnx("WARNING: home `%s' does not exist", pwd->pw_dir); } else if (!S_ISDIR(st.st_mode)) warnx("WARNING: home `%s' is not a directory", pwd->pw_dir); } if ((arg = getarg(args, 'w')) != NULL && getarg(args, 'h') == NULL && getarg(args, 'H') == NULL) { login_cap_t *lc; lc = login_getpwclass(pwd); if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL) warn("setting crypt(3) format"); login_close(lc); pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name); edited = 1; } } else { login_cap_t *lc; /* * Add code */ if (name == NULL) /* Required */ errx(EX_DATAERR, "login name required"); else if ((pwd = GETPWNAM(name)) != NULL) /* Exists */ errx(EX_DATAERR, "login name `%s' already exists", name); /* * Now, set up defaults for a new user */ pwd = &fakeuser; pwd->pw_name = name; pwd->pw_class = cnf->default_class ? cnf->default_class : ""; pwd->pw_uid = pw_uidpolicy(cnf, id); pwd->pw_gid = pw_gidpolicy(args, pwd->pw_name, (gid_t) pwd->pw_uid); pwd->pw_change = pw_pwdpolicy(cnf, args); pwd->pw_expire = pw_exppolicy(cnf, args); pwd->pw_dir = pw_homepolicy(cnf, args, pwd->pw_name); pwd->pw_shell = pw_shellpolicy(cnf, args, NULL); lc = login_getpwclass(pwd); if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL) warn("setting crypt(3) format"); login_close(lc); pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name); edited = 1; if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0) warnx("WARNING: new account `%s' has a uid of 0 (superuser access!)", pwd->pw_name); } /* * Shared add/edit code */ if ((arg = getarg(args, 'c')) != NULL) { char *gecos = pw_checkname(arg->val, 1); if (strcmp(pwd->pw_gecos, gecos) != 0) { pwd->pw_gecos = gecos; edited = 1; } } if ((arg = getarg(args, 'h')) != NULL || (arg = getarg(args, 'H')) != NULL) { if (strcmp(arg->val, "-") == 0) { if (!pwd->pw_passwd || *pwd->pw_passwd != '*') { pwd->pw_passwd = "*"; /* No access */ edited = 1; } } else { int fd = atoi(arg->val); int precrypt = (arg->ch == 'H'); int b; int istty = isatty(fd); struct termios t; login_cap_t *lc; if (istty) { if (tcgetattr(fd, &t) == -1) istty = 0; else { struct termios n = t; /* Disable echo */ n.c_lflag &= ~(ECHO); tcsetattr(fd, TCSANOW, &n); printf("%s%spassword for user %s:", (mode == M_UPDATE) ? "new " : "", precrypt ? "encrypted " : "", pwd->pw_name); fflush(stdout); } } b = read(fd, line, sizeof(line) - 1); if (istty) { /* Restore state */ tcsetattr(fd, TCSANOW, &t); fputc('\n', stdout); fflush(stdout); } if (b < 0) err(EX_IOERR, "-%c file descriptor", precrypt ? 'H' : 'h'); line[b] = '\0'; if ((p = strpbrk(line, "\r\n")) != NULL) *p = '\0'; if (!*line) errx(EX_DATAERR, "empty password read on file descriptor %d", fd); if (precrypt) { if (strchr(line, ':') != NULL) return EX_DATAERR; pwd->pw_passwd = line; } else { lc = login_getpwclass(pwd); if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL) warn("setting crypt(3) format"); login_close(lc); pwd->pw_passwd = pw_pwcrypt(line); } edited = 1; } } /* * Special case: -N only displays & exits */ if (conf.dryrun) return print_user(pwd); if (mode == M_ADD) { edited = 1; /* Always */ rc = addpwent(pwd); if (rc == -1) errx(EX_IOERR, "user '%s' already exists", pwd->pw_name); else if (rc != 0) err(EX_IOERR, "passwd file update"); if (cnf->nispasswd && *cnf->nispasswd=='/') { rc = addnispwent(cnf->nispasswd, pwd); if (rc == -1) warnx("User '%s' already exists in NIS passwd", pwd->pw_name); else warn("NIS passwd update"); /* NOTE: we treat NIS-only update errors as non-fatal */ } } else if (mode == M_UPDATE || mode == M_LOCK || mode == M_UNLOCK) { if (edited) { /* Only updated this if required */ rc = chgpwent(name, pwd); if (rc == -1) errx(EX_IOERR, "user '%s' does not exist (NIS?)", pwd->pw_name); else if (rc != 0) err(EX_IOERR, "passwd file update"); if ( cnf->nispasswd && *cnf->nispasswd=='/') { rc = chgnispwent(cnf->nispasswd, name, pwd); if (rc == -1) warn("User '%s' not found in NIS passwd", pwd->pw_name); else warn("NIS passwd update"); /* NOTE: NIS-only update errors are not fatal */ } } } /* * Ok, user is created or changed - now edit group file */ if (mode == M_ADD || getarg(args, 'G') != NULL) { int i, j; /* First remove the user from all group */ SETGRENT(); while ((grp = GETGRENT()) != NULL) { char group[MAXLOGNAME]; if (grp->gr_mem == NULL) continue; for (i = 0; grp->gr_mem[i] != NULL; i++) { if (strcmp(grp->gr_mem[i] , pwd->pw_name) != 0) continue; for (j = i; grp->gr_mem[j] != NULL ; j++) grp->gr_mem[j] = grp->gr_mem[j+1]; strlcpy(group, grp->gr_name, MAXLOGNAME); chggrent(group, grp); } } ENDGRENT(); /* now add to group where needed */ for (i = 0; cnf->groups[i] != NULL; i++) { grp = GETGRNAM(cnf->groups[i]); grp = gr_add(grp, pwd->pw_name); /* * grp can only be NULL in 2 cases: * - the new member is already a member * - a problem with memory occurs * in both cases we want to skip now. */ if (grp == NULL) continue; chggrent(cnf->groups[i], grp); free(grp); } } /* go get a current version of pwd */ pwd = GETPWNAM(name); if (pwd == NULL) { /* This will fail when we rename, so special case that */ if (mode == M_UPDATE && conf.newname != NULL) { name = conf.newname; /* update new name */ pwd = GETPWNAM(name); /* refetch renamed rec */ } } if (pwd == NULL) /* can't go on without this */ errx(EX_NOUSER, "user '%s' disappeared during update", name); grp = GETGRGID(pwd->pw_gid); pw_log(cnf, mode, W_USER, "%s(%u):%s(%u):%s:%s:%s", pwd->pw_name, pwd->pw_uid, grp ? grp->gr_name : "unknown", (grp ? grp->gr_gid : (uid_t)-1), pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell); /* * If adding, let's touch and chown the user's mail file. This is not * strictly necessary under BSD with a 0755 maildir but it also * doesn't hurt anything to create the empty mailfile */ if (mode == M_ADD) { if (PWALTDIR() != PWF_ALT) { arg = getarg(args, 'R'); snprintf(path, sizeof(path), "%s%s/%s", arg ? arg->val : "", _PATH_MAILDIR, pwd->pw_name); close(open(path, O_RDWR | O_CREAT, 0600)); /* Preserve contents & * mtime */ chown(path, pwd->pw_uid, pwd->pw_gid); } } /* * Let's create and populate the user's home directory. Note * that this also `works' for editing users if -m is used, but * existing files will *not* be overwritten. */ if (PWALTDIR() != PWF_ALT && getarg(args, 'm') != NULL && pwd->pw_dir && *pwd->pw_dir == '/' && pwd->pw_dir[1]) create_and_populate_homedir(mode, pwd); /* * Finally, send mail to the new user as well, if we are asked to */ if (mode == M_ADD && !PWALTDIR() && cnf->newmail && *cnf->newmail && (fp = fopen(cnf->newmail, "r")) != NULL) { FILE *pfp = popen(_PATH_SENDMAIL " -t", "w"); if (pfp == NULL) warn("sendmail"); else { fprintf(pfp, "From: root\n" "To: %s\n" "Subject: Welcome!\n\n", pwd->pw_name); while (fgets(line, sizeof(line), fp) != NULL) { /* Do substitutions? */ fputs(line, pfp); } pclose(pfp); pw_log(cnf, mode, W_USER, "%s(%u) new user mail sent", pwd->pw_name, pwd->pw_uid); } fclose(fp); } return EXIT_SUCCESS; }
static int do_rm_user(char **arg, char reply[REPLY_MAX]) { return delete_user(atoi(arg[0])); /* userid */ }
static int get_pw_uid(struct proxy_id_ctx *ctx, struct sss_domain_info *dom, uid_t uid) { TALLOC_CTX *tmpctx; struct passwd *pwd; enum nss_status status; char *buffer; size_t buflen; bool del_user = false; int ret; char *name; DEBUG(SSSDBG_TRACE_FUNC, "Searching user by uid (%"SPRIuid")\n", uid); tmpctx = talloc_new(NULL); if (!tmpctx) { return ENOMEM; } pwd = talloc_zero(tmpctx, struct passwd); if (!pwd) { ret = ENOMEM; goto done; } buflen = DEFAULT_BUFSIZE; buffer = talloc_size(tmpctx, buflen); if (!buffer) { ret = ENOMEM; goto done; } status = ctx->ops.getpwuid_r(uid, pwd, buffer, buflen, &ret); ret = handle_getpw_result(status, pwd, dom, &del_user); if (ret) { DEBUG(SSSDBG_OP_FAILURE, "getpwuid failed [%d]: %s\n", ret, strerror(ret)); goto done; } if (del_user) { ret = delete_user(dom, NULL, uid); goto done; } name = sss_create_internal_fqname(tmpctx, pwd->pw_name, dom->name); if (name == NULL) { DEBUG(SSSDBG_OP_FAILURE, "failed to qualify name '%s'\n", pwd->pw_name); goto done; } ret = save_user(dom, pwd, name, NULL); done: talloc_zfree(tmpctx); if (ret) { DEBUG(SSSDBG_CRIT_FAILURE, "proxy -> getpwuid_r failed for '%"SPRIuid"' <%d>: %s\n", uid, ret, strerror(ret)); } return ret; }
static int get_initgr(TALLOC_CTX *mem_ctx, struct proxy_id_ctx *ctx, struct sysdb_ctx *sysdb, struct sss_domain_info *dom, const char *name) { TALLOC_CTX *tmpctx; bool in_transaction = false; struct passwd *pwd; enum nss_status status; char *buffer; size_t buflen; int ret; errno_t sret; bool del_user; uid_t uid; struct ldb_result *cached_pwd = NULL; const char *real_name = NULL; tmpctx = talloc_new(mem_ctx); if (!tmpctx) { return ENOMEM; } pwd = talloc_zero(tmpctx, struct passwd); if (!pwd) { ret = ENOMEM; goto fail; } buflen = DEFAULT_BUFSIZE; buffer = talloc_size(tmpctx, buflen); if (!buffer) { ret = ENOMEM; goto fail; } ret = sysdb_transaction_start(sysdb); if (ret) { DEBUG(SSSDBG_CRIT_FAILURE, "Failed to start transaction\n"); goto fail; } in_transaction = true; /* FIXME: should we move this call outside the transaction to keep the * transaction as short as possible ? */ status = ctx->ops.getpwnam_r(name, pwd, buffer, buflen, &ret); ret = handle_getpw_result(status, pwd, dom, &del_user); if (ret) { DEBUG(SSSDBG_OP_FAILURE, "getpwnam failed [%d]: %s\n", ret, strerror(ret)); goto fail; } if (del_user) { ret = delete_user(dom, name, 0); if (ret) { DEBUG(SSSDBG_OP_FAILURE, "Could not delete user\n"); goto fail; } goto done; } uid = pwd->pw_uid; memset(buffer, 0, buflen); /* Canonicalize the username in case it was actually an alias */ if (ctx->fast_alias == true) { ret = sysdb_getpwuid(tmpctx, dom, uid, &cached_pwd); if (ret != EOK) { /* Non-fatal, attempt to canonicalize online */ DEBUG(SSSDBG_TRACE_FUNC, "Request to cache failed [%d]: %s\n", ret, strerror(ret)); } if (ret == EOK && cached_pwd->count == 1) { real_name = ldb_msg_find_attr_as_string(cached_pwd->msgs[0], SYSDB_NAME, NULL); if (!real_name) { DEBUG(SSSDBG_MINOR_FAILURE, "Cached user has no name?\n"); } } } if (real_name == NULL) { memset(buffer, 0, buflen); status = ctx->ops.getpwuid_r(uid, pwd, buffer, buflen, &ret); ret = handle_getpw_result(status, pwd, dom, &del_user); if (ret) { DEBUG(SSSDBG_OP_FAILURE, "getpwuid failed [%d]: %s\n", ret, strerror(ret)); goto done; } real_name = pwd->pw_name; } if (del_user) { ret = delete_user(dom, name, uid); if (ret) { DEBUG(SSSDBG_OP_FAILURE, "Could not delete user\n"); goto fail; } goto done; } ret = save_user(dom, !dom->case_sensitive, pwd, real_name, name, dom->user_timeout); if (ret) { DEBUG(SSSDBG_OP_FAILURE, "Could not save user\n"); goto fail; } ret = get_initgr_groups_process(tmpctx, ctx, sysdb, dom, pwd); if (ret != EOK) { DEBUG(SSSDBG_OP_FAILURE, "Could not process initgroups\n"); goto fail; } done: ret = sysdb_transaction_commit(sysdb); if (ret) { DEBUG(SSSDBG_OP_FAILURE, "Failed to commit transaction\n"); goto fail; } in_transaction = false; fail: talloc_zfree(tmpctx); if (in_transaction) { sret = sysdb_transaction_cancel(sysdb); if (sret != EOK) { DEBUG(SSSDBG_CRIT_FAILURE, "Failed to cancel transaction\n"); } } return ret; }
static int do_rm_user(char **arg, char reply[REPLY_MAX]) { ALOGD("do_rm_user : %s", arg[0]); return delete_user(atoi(arg[0])); /* userid */ }