int command_process(netcon_client_t *netcon_client, const char *command) { char *tokens[MAX_TOKENS]; char str[1024]; int num_tokens; syslog(LOG_DEBUG, "Command: %s", command); // Make a copy of the command since we modify it strncpy(str, command, sizeof(str)); num_tokens = str_split(str, tokens, MAX_TOKENS, ' '); if (num_tokens == 0) { return 0; } if (strcmp(tokens[0], "get") == 0) { command_get(netcon_client, tokens, num_tokens); } else if (strcmp(tokens[0], "toggle") == 0) { command_toggle(netcon_client, tokens, num_tokens); } else if (strcmp(tokens[0], "exit") == 0) { command_exit(netcon_client, tokens, num_tokens); } else { syslog(LOG_WARNING, "Invalid command: %s", command); } return 0; }
void command_rget(int sfd_client, struct packet* chp) { char temp[LENBUFFER]; clear_packet(chp); chp->type = REQU; chp->comid = RGET; send_packet(sfd_client, chp); recv_packet(sfd_client, chp); //printpacket(chp, HP); while(chp->type == REQU) { if(chp->comid == LMKDIR) { strcpy(temp, chp->buffer); command_lmkdir(temp); } else if(chp->comid == LCD) { strcpy(temp, chp->buffer); command_lcd(temp); } else if(chp->comid == GET) { strcpy(temp, chp->buffer); command_get(sfd_client, chp, temp); } recv_packet(sfd_client, chp); //printpacket(chp, HP); } if(chp->type == EOT) printf("\tTransmission successfully ended.\n"); else fprintf(stderr, "There was a problem completing the request.\n"); }
/** * \brief Wait command implementation */ int command_wait(MountPrx mount, bool dowait) { if (dowait) { mountstate s = mount->state(); while (s == MountGOTO) { sleep(1); s = mount->state(); } } return command_get(mount); }
void command_mget(int sfd_client, struct packet* chp, int n, char** filenames) { int i; char* filename; for(i = 0; i < n; i++) { filename = *(filenames + i); printf("\tProcessing file %d of %d:\t%s\n", i + 1, n, filename); command_get(sfd_client, chp, filename); } if(i != n) fprintf(stderr, "Not all files could be downloaded.\n"); }
struct process *find_process(char *key, int key_sz) { int cmd; for(cmd=0; cmd<256; cmd++) { int flags; struct process *process; command_get(cmd, &flags, (void*)&process); if(NULL == process) continue; if(process->key_sz == key_sz && !memcmp(process->key, key, key_sz)) return(process); } return(NULL); }
/* -------------------------------------------------------------------------- * * control_exec - execute the cmd in av[0] * * * * cptr - pointer to control connection struct * * ac - argument count * * av - argument vector * * -------------------------------------------------------------------------- */ static int control_exec(control_t *cptr, int ac, char **av) { struct cmd_table *cmdptr; if(ac < 1) return -1; cmdptr = command_get(cmds, av[0]); if(cmdptr != NULL) return cmdptr->func(cptr, ac, av); return -1; }
int interactive_mode (PedDevice** dev, PedDisk** disk, Command* cmd_list[]) { StrList* list; StrList* command_names = command_get_names (cmd_list); commands = cmd_list; /* FIXME yucky, nasty, evil hack */ fputs (prog_name, stdout); print_using_dev (*dev); list = str_list_create (_(banner_msg), NULL); str_list_print_wrap (list, screen_width (), 0, 0, stdout); str_list_destroy (list); while (1) { char* word; Command* cmd; while (!command_line_get_word_count ()) { if (got_ctrl_c) { putchar ('\n'); return 1; } command_line_prompt_words ("(parted)", NULL, command_names, 1); } word = command_line_pop_word (); if (word) { cmd = command_get (commands, word); free (word); if (cmd) { if (!command_run (cmd, dev, disk)) { command_line_flush (); if (*disk) { ped_disk_destroy (*disk); *disk = 0; } } } else print_commands_help (); } } return 1; }
bool bot_get_next_cmd(struct bot *bot, struct command_ctx *ctx) { char buff[BUF_SZ]; int len; if (socket_recv_line(bot->socket, buff, &len, BUF_SZ) == false) return false; buff[len] = '\0'; DEBUG(LOG_VERBOSE, "recived msg = %s\n", buff); command_get(buff, len, ctx); return true; }
static void exec_next_command(struct service_processor *sp) { unsigned long flags; char tsbuf[32]; dbg("%s:%d at %s\n", __FUNCTION__, __LINE__, get_timestamp(tsbuf)); spin_lock_irqsave(&sp->lock, flags); sp->current_command = dequeue_command(sp); if (sp->current_command) { command_get(sp->current_command); spin_unlock_irqrestore(&sp->lock, flags); do_exec_command(sp); } else { spin_unlock_irqrestore(&sp->lock, flags); } }
/** * exec_command * send a command to a service processor * Commands are executed sequentially. One command (sp->current_command) * is sent to the service processor. Once the interrupt handler gets a * message of type command_response, the message is copied into * the current commands buffer, */ void ibmasm_exec_command(struct service_processor *sp, struct command *cmd) { unsigned long flags; char tsbuf[32]; dbg("%s:%d at %s\n", __FUNCTION__, __LINE__, get_timestamp(tsbuf)); spin_lock_irqsave(&sp->lock, flags); if (!sp->current_command) { sp->current_command = cmd; command_get(sp->current_command); spin_unlock_irqrestore(&sp->lock, flags); do_exec_command(sp); } else { enqueue_command(sp, cmd); spin_unlock_irqrestore(&sp->lock, flags); } }
static retro_input_t input_driver_keys_pressed(void) { unsigned key; retro_input_t ret = {0}; for (key = 0; key < RARCH_BIND_LIST_END; key++) { bool state = false; if ((!input_driver_is_libretro_input_blocked() && ((key < RARCH_FIRST_META_KEY))) || !input_driver_is_hotkey_blocked()) state = input_driver_key_pressed(&key); if (key >= RARCH_FIRST_META_KEY) state |= current_input->meta_key_pressed(current_input_data, key); #ifdef HAVE_OVERLAY state |= input_overlay_key_pressed(key); #endif #ifdef HAVE_COMMAND if (input_driver_command) { command_handle_t handle; handle.handle = input_driver_command; handle.id = key; state |= command_get(&handle); } #endif #ifdef HAVE_NETWORKGAMEPAD if (input_driver_remote) state |= input_remote_key_pressed(key,0); #endif if (state) ret.state |= (UINT64_C(1) << key); } return ret; }
int non_interactive_mode (PedDevice** dev, PedDisk **disk, Command* cmd_list[], int argc, char* argv[]) { int i; Command* cmd; commands = cmd_list; /* FIXME yucky, nasty, evil hack */ for (i = 0; i < argc; i++) command_line_push_line (argv [i], 1); while (command_line_get_word_count ()) { char* word; word = command_line_pop_word (); if (!word) break; cmd = command_get (commands, word); free (word); if (!cmd) { help_msg (); goto error; } if (!(cmd->non_interactive)) { fputs(_("This command does not make sense in " "non-interactive mode.\n"), stdout); exit(EXIT_FAILURE); goto error; } if (!command_run (cmd, dev, disk)) goto error; } return 1; error: return 0; }
/** * Dispatch a command to its handling function based on the single-letter * command. */ void handle_command(char *command) { switch(command[0]) { case 'S': command_set(command); break; case 's': command_set_from_gps(); break; case 'G': command_get(); break; case 'O': command_offset(command); break; case 'E': command_eeprom_dump(); break; case 'D': led_sequencer_dump_sequence(); break; case 'm': led_sequencer_halt(); enqueue_minutely_show(); led_sequencer_run(); break; case 'h': led_sequencer_halt(); enqueue_hourly_show(); led_sequencer_run(); break; case 'g': command_get_gps(); break; default: break; } }
static int do_run(t_env *env, char **splitted) { if (!ft_strcmp(splitted[0], "ls")) command_ls(env, splitted); else if (!ft_strcmp(splitted[0], "cd")) command_cd(env, splitted); else if (!ft_strcmp(splitted[0], "get")) command_get(env, splitted); else if (!ft_strcmp(splitted[0], "put")) command_put(env, splitted); else if (!ft_strcmp(splitted[0], "pwd")) command_pwd(env, splitted); else if (!ft_strcmp(splitted[0], "quit") || !ft_strcmp(splitted[0], "exit")) command_quit(env, splitted); else if (!ft_strcmp(splitted[0], "touch")) command_touch(env, splitted); else if (!ft_strcmp(splitted[0], "unlink")) command_unlink(env, splitted); else return (0); return (1); }
/** * @function _process_connection * Handle and process an incoming connection. * @param thread Pointer to the thread's structure. */ static void _process_connection(comm_thread_t *thread) { uint8_t cmd; // loop on incoming requests for (; ; ) { // read command byte if (read(thread->client_sock, &cmd, sizeof(cmd)) <= 0) { close(thread->client_sock); break; } // interpret command switch (cmd) { case PROTO_PUT: command_put(thread); break; case PROTO_DELETE: command_delete(thread); break; case PROTO_GET: command_get(thread); break; } } }
/*------------------------------------------------------------------------ * MAIN PROGRAM *------------------------------------------------------------------------*/ int main(int argc, const char *argv[]) { command_t command; /* the current command being processed */ //char command_text[MAX_COMMAND_LENGTH]; /* the raw text of the command */ char *command_text; ttp_session_t *session = NULL; ttp_parameter_t parameter; int argc_curr = 1; /* command line argument currently to be processed */ char *ptr_command_text = &command_text[0]; /* reset the client */ memset(¶meter, 0, sizeof(parameter)); reset_client(¶meter); /* show version / build information */ #ifdef VSIB_REALTIME fprintf(stderr, "Tsunami Realtime Client for protocol rev %X\nRevision: %s\nCompiled: %s %s\n" " /dev/vsib VSIB accesses mode is %d, gigabit=%d, 1pps embed=%d, sample skip=%d\n", PROTOCOL_REVISION, TSUNAMI_CVS_BUILDNR, __DATE__ , __TIME__, vsib_mode, vsib_mode_gigabit, vsib_mode_embed_1pps_markers, vsib_mode_skip_samples); #else fprintf(stderr, "Tsunami Client for protocol rev %X\nRevision: %s\nCompiled: %s %s\n", PROTOCOL_REVISION, TSUNAMI_CVS_BUILDNR, __DATE__ , __TIME__); #endif /* while the command loop is still running */ while (1) { /* retrieve the user's commands */ if (argc<=1 || argc_curr>=argc) { /* present the prompt */ fprintf(stdout, "tsunami> "); fflush(stdout); /* read next command */ if (fgets(command_text, MAX_COMMAND_LENGTH, stdin) == NULL) { error("Could not read command input"); } } else { // severe TODO: check that command_text appends do not over flow MAX_COMMAND_LENGTH... /* assemble next command from command line arguments */ for ( ; argc_curr<argc; argc_curr++) { // zero argument commands if (!strcasecmp(argv[argc_curr], "close") || !strcasecmp(argv[argc_curr], "quit") || !strcasecmp(argv[argc_curr], "exit") || !strcasecmp(argv[argc_curr], "bye") || !strcasecmp(argv[argc_curr], "help") || !strcasecmp(argv[argc_curr], "dir")) { strcpy(command_text, argv[argc_curr]); argc_curr += 1; break; } // single argument commands if (!strcasecmp(argv[argc_curr], "connect")) { if (argc_curr+1 < argc) { strcpy(ptr_command_text, argv[argc_curr]); strcat(command_text, " "); strcat(command_text, argv[argc_curr+1]); } else { fprintf(stderr, "Connect: no host specified\n"); exit(1); } argc_curr += 2; break; } /*__FINAL_PROJECT_START__ if (!strcasecmp(argv[argc_curr], "connect6")) { if (argc_curr+1 < argc) { strcpy(ptr_command_text, argv[argc_curr]); strcat(command_text, " "); strcat(command_text, argv[argc_curr+1]); } else { fprintf(stderr, "Connect: no host specified\n"); exit(1); } argc_curr += 2; break; } __FINAL_PROJECT_END __*/ if (!strcasecmp(argv[argc_curr], "get")) { if (argc_curr+1 < argc) { strcpy(ptr_command_text, argv[argc_curr]); strcat(command_text, " "); strcat(command_text, argv[argc_curr+1]); } else { fprintf(stderr, "Get: no file specified\n"); exit(1); } argc_curr += 2; break; } // double argument commands if (!strcasecmp(argv[argc_curr], "set")) { if (argc_curr+2 < argc) { strcpy(ptr_command_text, argv[argc_curr]); strcat(command_text, " "); strcat(command_text, argv[argc_curr+1]); strcat(command_text, " "); strcat(command_text, argv[argc_curr+2]); } else { fprintf(stderr, "Connect: no host specified\n"); exit(1); } argc_curr += 3; break; } // unknown commands, skip fprintf(stderr, "Unsupported command console command: %s\n", argv[argc_curr]); } } /* parse the command */ parse_command(&command, command_text); /* make sure we have at least one word */ if (command.count == 0) continue; /* dispatch on the command type */ if (!strcasecmp(command.text[0], "close")) command_close (&command, session); else if (!strcasecmp(command.text[0], "connect")) session = command_connect(&command, ¶meter); //else if (!strcasecmp(command.text[0], "connect6")) session = command_connect6(&command, ¶meter); else if (!strcasecmp(command.text[0], "get")) command_get (&command, session); else if (!strcasecmp(command.text[0], "dir")) command_dir (&command, session); else if (!strcasecmp(command.text[0], "help")) command_help (&command, session); else if (!strcasecmp(command.text[0], "quit")) command_quit (&command, session); else if (!strcasecmp(command.text[0], "exit")) command_quit (&command, session); else if (!strcasecmp(command.text[0], "bye")) command_quit (&command, session); else if (!strcasecmp(command.text[0], "set")) command_set (&command, ¶meter); else fprintf(stderr, "Unrecognized command: '%s'. Use 'HELP' for help.\n\n", command.text[0]); } /* if we're here, we shouldn't be */ return 1; }
int main(int argc, char *argv[]) { char buf[1024]; int i; #ifdef TIOCGWINSZ struct winsize ws; if (ioctl(fileno(stdout), TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0) TERMWIDTH = ws.ws_col; #endif /* Start handling the arguments. * monetdb [monetdb_options] command [options] [database [...]] * this means we first scout for monetdb_options which stops as soon * as we find a non-option argument, which then must be command */ /* first handle the simple no argument case */ if (argc <= 1) { command_help(0, NULL); return(1); } /* handle monetdb_options */ for (i = 1; argc > i && argv[i][0] == '-'; i++) { switch (argv[i][1]) { case 'v': command_version(); return(0); case 'q': monetdb_quiet = 1; break; case 'h': if (strlen(&argv[i][2]) > 0) { mero_host = &argv[i][2]; } else { if (i + 1 < argc) { mero_host = argv[++i]; } else { fprintf(stderr, "monetdb: -h needs an argument\n"); return(1); } } break; case 'p': if (strlen(&argv[i][2]) > 0) { mero_port = atoi(&argv[i][2]); } else { if (i + 1 < argc) { mero_port = atoi(argv[++i]); } else { fprintf(stderr, "monetdb: -p needs an argument\n"); return(1); } } break; case 'P': /* take care we remove the password from argv so it * doesn't show up in e.g. ps -ef output */ if (strlen(&argv[i][2]) > 0) { mero_pass = strdup(&argv[i][2]); memset(&argv[i][2], 0, strlen(mero_pass)); } else { if (i + 1 < argc) { mero_pass = strdup(argv[++i]); memset(argv[i], 0, strlen(mero_pass)); } else { fprintf(stderr, "monetdb: -P needs an argument\n"); return(1); } } break; case '-': /* skip -- */ if (argv[i][2] == '\0') break; if (strcmp(&argv[i][2], "version") == 0) { command_version(); return(0); } else if (strcmp(&argv[i][2], "help") == 0) { command_help(0, NULL); return(0); } default: fprintf(stderr, "monetdb: unknown option: %s\n", argv[i]); command_help(0, NULL); return(1); break; } } /* check consistency of -h -p and -P args */ if (mero_pass != NULL && (mero_host == NULL || *mero_host == '/')) { fprintf(stderr, "monetdb: -P requires -h to be used with a TCP hostname\n"); exit(1); } else if (mero_host != NULL && *mero_host != '/' && mero_pass == NULL) { fprintf(stderr, "monetdb: -h requires -P to be used\n"); exit(1); } /* see if we still have arguments at this stage */ if (i >= argc) { command_help(0, NULL); return(1); } /* commands that do not need merovingian to be running */ if (strcmp(argv[i], "help") == 0) { command_help(argc - i, &argv[i]); return(0); } else if (strcmp(argv[i], "version") == 0) { command_version(); return(0); } /* use UNIX socket if no hostname given */ if (mero_host == NULL || *mero_host == '/') { /* a socket looks like /tmp/.s.merovingian.<tcpport>, try * finding such port. If mero_host is set, it is the location * where we should search, which defaults to '/tmp' */ if (mero_host == NULL) mero_host = "/tmp"; /* first try the port given (or else its default) */ snprintf(buf, sizeof(buf), "%s/.s.merovingian.%d", mero_host, mero_port == -1 ? 50000 : mero_port); if (control_ping(buf, -1, NULL) == 0) { mero_host = buf; } else { /* if port wasn't given, we can try and search * for available sockets */ if (mero_port == -1) { DIR *d; struct dirent *e; struct stat s; d = opendir(mero_host); if (d == NULL) { fprintf(stderr, "monetdb: cannot find a control socket, use -h and/or -p\n"); exit(1); } while ((e = readdir(d)) != NULL) { if (strncmp(e->d_name, ".s.merovingian.", 15) != 0) continue; snprintf(buf, sizeof(buf), "%s/%s", mero_host, e->d_name); if (stat(buf, &s) == -1) continue; if (S_ISSOCK(s.st_mode)) { if (control_ping(buf, -1, NULL) == 0) { mero_host = buf; break; } } } closedir(d); } } if (mero_host != buf) { fprintf(stderr, "monetdb: cannot find a control socket, use -h and/or -p\n"); exit(1); } /* don't confuse control_send lateron */ mero_port = -1; } /* for TCP connections */ if (mero_host != NULL && *mero_host != '/' && mero_port == -1) mero_port = 50000; /* handle regular commands */ if (strcmp(argv[i], "create") == 0) { command_create(argc - i, &argv[i]); } else if (strcmp(argv[i], "destroy") == 0) { command_destroy(argc - i, &argv[i]); } else if (strcmp(argv[i], "lock") == 0) { command_lock(argc - i, &argv[i]); } else if (strcmp(argv[i], "release") == 0) { command_release(argc - i, &argv[i]); } else if (strcmp(argv[i], "status") == 0) { command_status(argc - i, &argv[i]); } else if (strcmp(argv[i], "start") == 0) { command_startstop(argc - i, &argv[i], START); } else if (strcmp(argv[i], "stop") == 0) { command_startstop(argc - i, &argv[i], STOP); } else if (strcmp(argv[i], "kill") == 0) { command_startstop(argc - i, &argv[i], KILL); } else if (strcmp(argv[i], "set") == 0) { command_set(argc - i, &argv[i], SET); } else if (strcmp(argv[i], "get") == 0) { command_get(argc - i, &argv[i]); } else if (strcmp(argv[i], "inherit") == 0) { command_set(argc - i, &argv[i], INHERIT); } else if (strcmp(argv[i], "discover") == 0) { command_discover(argc - i, &argv[i]); } else { fprintf(stderr, "monetdb: unknown command: %s\n", argv[i]); command_help(0, NULL); } if (mero_pass != NULL) free(mero_pass); return(0); }
/** * \brief main function */ int main(int argc, char *argv[]) { debug_set_ident("snowmount"); CommunicatorSingleton communicator(argc, argv); int c; int longindex; astro::ServerName servername; putenv("POSIXLY_CORRECT=1"); while (EOF != (c = getopt_long(argc, argv, "dhc:fw", longopts, &longindex))) switch (c) { case 'd': debuglevel = LOG_DEBUG; break; case 'f': decimal = true; break; case 'h': usage(argv[0]); return EXIT_SUCCESS; case 'w': await_completion = true; break; default: throw std::runtime_error("unknown option"); } // next comes the command if (argc <= optind) { throw std::runtime_error("command missing"); } std::string command(argv[optind++]); // handle the help command if (command == "help") { return command_help(argv[0]); } servername = astro::ServerName(command); // next argument must be the command if (argc <= optind) { throw std::runtime_error("command missing"); } command = std::string(argv[optind++]); if (command == "help") { return command_help(argv[0]); } // we need a remote device proxy for all other commands Ice::CommunicatorPtr ic = CommunicatorSingleton::get(); Ice::ObjectPrx base = ic->stringToProxy(servername.connect("Devices")); DevicesPrx devices = DevicesPrx::checkedCast(base); // handle the list command if (command == "list") { return command_list(devices); } // for the other commands we need the mount name if (argc <= optind) { throw std::runtime_error("no mount name"); } std::string mountname(argv[optind++]); // get a proxy for the mount MountPrx mount = devices->getMount(mountname); // get command if (command == "get") { return command_get(mount); } if (command == "cancel") { return command_cancel(mount); } if (command == "wait") { return command_wait(mount, true); } // two more arguments are angles if (command == "set") { if (argc < (optind + 2)) { throw std::runtime_error("missing angle arguments"); } RaDec radec; astro::Angle ra = astro::Angle::hms_to_angle(argv[optind++]); radec.ra = ra.hours(); astro::Angle dec = astro::Angle::dms_to_angle(argv[optind++]); radec.dec = dec.degrees(); return command_set(mount, radec); } // if we get here, then an unknown command was given throw std::runtime_error("unknown command"); }
void* serve_client(void* info) { int sfd_client, connection_id, x; struct packet* data = (struct packet*) malloc(size_packet); struct packet* shp; char lpwd[LENBUFFER]; struct client_info* ci = (struct client_info*) info; sfd_client = ci->sfd; connection_id = ci->cid; while(1) { if((x = recv(sfd_client, data, size_packet, 0)) == 0) { fprintf(stderr, "client closed/terminated. closing connection.\n"); break; } shp = ntohp(data); if(shp->type == TERM) break; if(shp->conid == -1) shp->conid = connection_id; if(shp->type == REQU) { switch(shp->comid) { case PWD: if(!getcwd(lpwd, sizeof lpwd)) er("getcwd()", 0); command_pwd(shp, data, sfd_client, lpwd); break; case CD: if((x = chdir(shp->buffer)) == -1) fprintf(stderr, "Wrong path.\n"); command_cd(shp, data, sfd_client, x == -1 ? "fail" : "success"); break; case MKDIR: command_mkdir(shp, data, sfd_client); break; case LS: if(!getcwd(lpwd, sizeof lpwd)) er("getcwd()", 0); command_ls(shp, data, sfd_client, lpwd); break; case GET: command_get(shp, data, sfd_client); break; case PUT: command_put(shp, data, sfd_client); break; case RGET: if(!getcwd(lpwd, sizeof lpwd)) er("getcwd()", 0); command_rget(shp, data, sfd_client); send_EOT(shp, data, sfd_client); if((x = chdir(lpwd)) == -1) fprintf(stderr, "Wrong path.\n"); default: // print error break; } /* //send info and then proceed to complete the request shp->type = INFO; strcpy(path, shp->buffer); sprintf(shp->buffer, "File found. Processing..."); data = htonp(shp); if((x = send(sfd_client, data, size_packet, 0)) != size_packet) er("send()", x); send_file(path, sfd_client, shp); send_TERM(sfd_client, shp); */ } else { //show error, send TERM and break fprintf(stderr, "packet incomprihensible. closing connection.\n"); send_TERM(shp, data, sfd_client); break; } } close(sfd_client); fflush(stdout); }
int main(int argc, char* argv[]) { //BEGIN: initialization struct sockaddr_in sin_server; int sfd_client, x; size_t size_sockaddr = sizeof(struct sockaddr), size_packet = sizeof(struct packet); short int connection_id; struct packet* chp = (struct packet*) malloc(size_packet); // client host packet set0(chp); struct packet* data; // network packet if((x = sfd_client = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) er("socket()", x); memset((char*) &sin_server, 0, sizeof(struct sockaddr_in)); sin_server.sin_family = AF_INET; sin_server.sin_addr.s_addr = inet_addr(IPSERVER); sin_server.sin_port = htons(PORTSERVER); if((x = connect(sfd_client, (struct sockaddr*) &sin_server, size_sockaddr)) < 0) er("connect()", x); printf(ID "FTP Client started up. Attempting communication with server @ %s:%d...\n\n", IPSERVER, PORTSERVER); //END: initialization struct command* cmd; char lpwd[LENBUFFER], pwd[LENBUFFER]; //用作本地和FTP server端的当前工作区间名的缓冲区 char userinput[LENUSERINPUT]; while(1) { printf("\t> "); fgets(userinput, LENUSERINPUT, stdin); /* in order to give a filename with spaces, put ':' instead of ' '. If a command needs x paths, and y (y > x) paths are provided, y - x paths will be ignored. */ cmd = userinputtocommand(userinput); if(!cmd) continue; //printcommand(cmd); switch(cmd->id) { case GET: if(cmd->npaths) command_get(chp, data, sfd_client, *cmd->paths); else fprintf(stderr, "No path to file given.\n"); break; case PUT: if(cmd->npaths) command_put(chp, data, sfd_client, *cmd->paths); else fprintf(stderr, "No path to file given.\n"); break; case MGET: if(cmd->npaths) command_mget(chp, data, sfd_client, cmd->npaths, cmd->paths); else fprintf(stderr, "No path to file given.\n"); break; case MPUT: if(cmd->npaths) command_mput(chp, data, sfd_client, cmd->npaths, cmd->paths); else fprintf(stderr, "No path to file given.\n"); break; case MGETWILD: command_mgetwild(chp, data, sfd_client); break; case MPUTWILD: if(!getcwd(lpwd, sizeof lpwd)) er("getcwd()", 0); command_mputwild(chp, data, sfd_client, lpwd); break; case CD: if(cmd->npaths) command_cd(chp, data, sfd_client, *cmd->paths); else fprintf(stderr, "No path given.\n"); break; case LCD: // 改变local 工作区间 if(cmd->npaths) command_lcd(*cmd->paths); else fprintf(stderr, "No path given.\n"); break; case PWD: command_pwd(chp, data, sfd_client); break; case LPWD: // local pwd if(!getcwd(lpwd, sizeof lpwd)) er("getcwd()", 0); printf("\t%s\n", lpwd); break; case DIR_: case LS: command_ls(chp, data, sfd_client); break; case LDIR: case LLS: if(!getcwd(lpwd, sizeof lpwd)) er("getcwd()", 0); command_lls(lpwd); break; case MKDIR: if(cmd->npaths) command_mkdir(chp, data, sfd_client, *cmd->paths); else fprintf(stderr, "No path to directory given.\n"); break; case LMKDIR: if(cmd->npaths) command_lmkdir(*cmd->paths); else fprintf(stderr, "No path to directory given.\n"); break; case RGET: if(!getcwd(lpwd, sizeof lpwd)) er("getcwd()", 0); command_rget(chp, data, sfd_client); if((x = chdir(lpwd)) == -1) fprintf(stderr, "Wrong path.\n"); break; case RPUT: if(!getcwd(lpwd, sizeof lpwd)) er("getcwd()", 0); command_rput(chp, data, sfd_client); if((x = chdir(lpwd)) == -1) fprintf(stderr, "Wrong path.\n"); break; case EXIT: goto outside_client_command_loop; default: // display error break; } } outside_client_command_loop: /* chp->type = REQU; chp->conid = -1; strcpy(path, argv[1]); strcpy(chp->buffer, argv[1]); //printpacket(chp, HP); data = htonp(chp); if((x = send(sfd_client, data, size_packet, 0)) != size_packet) er("send()", x); set0(data); do { if((x = recv(sfd_client, data, size_packet, 0)) <= 0) er("recv()", x); chp = htonp(data); if(chp->type == INFO) printf(ID "Server says: %s\n", chp->buffer); else if(chp->type == DATA) { //printpacket(chp, HP); receive_file(extract_filename(path), sfd_client, chp); } } while(chp->type != TERM); fprintf(stderr, "TERM received; exiting...\n"); */ close(sfd_client); printf(ID "Done.\n"); fflush(stdout); return 0; }
/* Main function. */ int main(int argc, char *argv[]) { cli_t cli; char *hostname = DEFAULT_HOST; char history_file[4096]; ybool_t interactive_mode = YTRUE; bzero(&cli, sizeof(cli_t)); cli.autocheck = YTRUE; if (argc == 2 && argv[1][0] != '-') hostname = argv[1]; if (argc == 3 && !strcmp(argv[2], "-")) interactive_mode = YFALSE; // init database connection if ((cli.finedb = finedb_create(hostname, 11138)) == NULL) { printf_color("red", "Memory error."); printf("\n"); exit(1); } if (finedb_connect(cli.finedb) != FINEDB_OK) { printf_color("red", "Unable to connect to server '%s' on port '%d'.", argv[1], 11138); printf("\n"); exit(2); } // interactive mode init if (interactive_mode) { char *home = NULL; if ((home = getenv("HOME")) != NULL) { FILE *hist; snprintf(history_file, sizeof(history_file), "%s/%s", home, HISTORY_FILE); if ((hist = fopen(history_file, "w+")) != NULL) { fclose(hist); linenoiseHistoryLoad(HISTORY_FILE); } linenoiseSetCompletionCallback(cli_completion); } } // main loop for (; ; ) { char buff[4096], *line = NULL, *pt, *cmd; if (!interactive_mode) { ssize_t bufsz, linesz = 0; while ((bufsz = read(0, buff, sizeof(buff))) > 0) { pt = (char*)malloc(linesz + bufsz + 1); memcpy(pt, line, linesz); memcpy((void*)((size_t)pt + linesz), buff, bufsz); linesz += bufsz; pt[linesz] = '\0'; if (line) free(line); line = pt; } } else { snprintf(buff, sizeof(buff), "%s > ", (cli.dbname ? cli.dbname : "default")); if ((line = linenoise(buff)) == NULL) break; } pt = line; LTRIM(pt); cmd = pt; // add command line to history linenoiseHistoryAdd(cmd); linenoiseHistorySave(history_file); // extract the command while (*pt && !IS_SPACE(*pt)) ++pt; *pt++ = '\0'; LTRIM(pt); /* command management */ if (cmd[0] == '\0') goto reloop; //continue; // local commands, no need for a running connection if (!strcasecmp(cmd, "exit") || !strcasecmp(cmd, "quit")) exit(0); if (!strcasecmp(cmd, "help") || cmd[0] == '?') { command_help(); goto reloop; //continue; } else if (!strcasecmp(cmd, "sync")) { command_sync(&cli); goto reloop; //continue; } else if (!strcasecmp(cmd, "async")) { command_async(&cli); goto reloop; //continue; } // commands that need a running connection if (!strcasecmp(cmd, "use")) command_use(&cli, pt); else if (!strcasecmp(cmd, "get")) command_get(&cli, pt); else if (!strcasecmp(cmd, "del")) command_del(&cli, pt); else if (!strcasecmp(cmd, "put")) command_send_data(&cli, pt, YFALSE, YFALSE); else if (!strcasecmp(cmd, "add")) command_send_data(&cli, pt, YTRUE, YFALSE); else if (!strcasecmp(cmd, "update")) command_send_data(&cli, pt, YFALSE, YTRUE); else if (!strcasecmp(cmd, "inc")) command_inc(&cli, pt); else if (!strcasecmp(cmd, "dec")) command_dec(&cli, pt); else if (!strcasecmp(cmd, "start")) command_start(&cli); else if (!strcasecmp(cmd, "stop")) command_stop(&cli); #if 0 else if (!strcasecmp(cmd, "list")) command_list(&cli, pt); #endif else if (!strcasecmp(cmd, "ping")) command_ping(&cli); else if (!strcasecmp(cmd, "autocheck")) command_autocheck(&cli, pt); else { printf_color("red", "Bad command."); printf("\n"); } reloop: free(line); } return (0); }
// Get command stuct for current buffer // Returns 0 for invalid command struct command_info *serial_proto_cmd_info(void) { return command_get((uint8_t)serial_buffer.data[0]); }
int main(int argc, char *argv[]) { err e; int argp; char dbfarm[1024]; char *pidfilename = NULL; char *p; FILE *pidfile = NULL; char control_usock[1024]; char mapi_usock[1024]; dpair d = NULL; struct _dpair dpcons; struct _dpair dpmero; struct _dpair dpdisc; struct _dpair dpcont; int pfd[2]; pthread_t tid = 0; struct sigaction sa; int ret; int lockfd = -1; int sock = -1; int usock = -1; int unsock = -1; int socku = -1; unsigned short port = 0; char discovery = 0; struct stat sb; FILE *oerr = NULL; pthread_mutexattr_t mta; int thret; char merodontfork = 0; confkeyval ckv[] = { {"logfile", strdup("merovingian.log"), 0, STR}, {"pidfile", strdup("merovingian.pid"), 0, STR}, {"sockdir", strdup("/tmp"), 0, STR}, {"port", strdup(MERO_PORT), atoi(MERO_PORT), INT}, {"exittimeout", strdup("60"), 60, INT}, {"forward", strdup("proxy"), 0, OTHER}, {"discovery", strdup("true"), 1, BOOLEAN}, {"discoveryttl", strdup("600"), 600, INT}, {"control", strdup("false"), 0, BOOLEAN}, {"passphrase", NULL, 0, STR}, { NULL, NULL, 0, INVALID} }; confkeyval *kv; int retfd = -1; /* seed the randomiser for when we create a database, send responses * to HELO, etc */ srand(time(NULL)); /* figure out our hostname */ gethostname(_mero_hostname, 128); /* where is the mserver5 binary we fork on demand? * first try to locate it based on our binary location, fall-back to * hardcoded bin-dir */ _mero_mserver = get_bin_path(); if (_mero_mserver != NULL) { /* replace the trailing monetdbd by mserver5, fits nicely since * they happen to be of same length */ char *s = strrchr(_mero_mserver, '/'); if (s != NULL && strcmp(s + 1, "monetdbd") == 0) { s++; *s++ = 'm'; *s++ = 's'; *s++ = 'e'; *s++ = 'r'; *s++ = 'v'; *s++ = 'e'; *s++ = 'r'; *s++ = '5'; if (stat(_mero_mserver, &sb) == -1) _mero_mserver = NULL; } } /* setup default database properties, constants: unlike historical * versions, we do not want changing defaults any more */ _mero_db_props = getDefaultProps(); kv = findConfKey(_mero_db_props, "shared"); kv->val = strdup("yes"); kv = findConfKey(_mero_db_props, "readonly"); kv->val = strdup("no"); kv = findConfKey(_mero_db_props, "nclients"); kv->val = strdup("64"); kv = findConfKey(_mero_db_props, "type"); kv->val = strdup("database"); kv = findConfKey(_mero_db_props, "optpipe"); kv->val = strdup("default_pipe"); { /* nrthreads */ int ncpus = -1; char cnt[8]; #if defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN) /* this works on Linux, Solaris and AIX */ ncpus = sysconf(_SC_NPROCESSORS_ONLN); #elif defined(HAVE_SYS_SYSCTL_H) && defined(HW_NCPU) /* BSD */ size_t len = sizeof(int); int mib[3]; /* Everyone should have permission to make this call, * if we get a failure something is really wrong. */ mib[0] = CTL_HW; mib[1] = HW_NCPU; mib[2] = -1; sysctl(mib, 3, &ncpus, &len, NULL, 0); #elif defined(WIN32) SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); ncpus = sysinfo.dwNumberOfProcessors; #endif if (ncpus > 0) { snprintf(cnt, sizeof(cnt), "%d", ncpus); kv = findConfKey(_mero_db_props, "nthreads"); kv->val = strdup(cnt); } } *dbfarm = '\0'; if (argc > 1) { if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "help") == 0) { exit(command_help(argc - 1, &argv[1])); } else if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "version") == 0) { exit(command_version()); } else if (strcmp(argv[1], "create") == 0) { exit(command_create(argc - 1, &argv[1])); } else if (strcmp(argv[1], "get") == 0) { exit(command_get(ckv, argc - 1, &argv[1])); } else if (strcmp(argv[1], "set") == 0) { exit(command_set(ckv, argc - 1, &argv[1])); } else if (strcmp(argv[1], "start") == 0) { if (argc > 3 && strcmp(argv[2], "-n") == 0) merodontfork = 1; if (argc == 3 + merodontfork) { int len; len = snprintf(dbfarm, sizeof(dbfarm), "%s", argv[2 + merodontfork]); if (len > 0 && (size_t)len >= sizeof(dbfarm)) { Mfprintf(stderr, "fatal: dbfarm exceeds allocated " \ "path length, please file a bug at " \ "http://bugs.monetdb.org/\n"); exit(1); } } else { command_help(argc, argv); exit(1); } } else if (strcmp(argv[1], "stop") == 0) { exit(command_stop(ckv, argc - 1, &argv[1])); } else { fprintf(stderr, "monetdbd: unknown command: %s\n", argv[1]); command_help(0, NULL); exit(1); } } else { command_help(0, NULL); exit(1); } assert(*dbfarm != '\0'); /* fork into background before doing anything more */ if (!merodontfork) { char buf[4]; /* Fork into the background immediately. By doing this our child * can simply do everything it needs to do itself. Via a pipe it * will tell us if it is happy or not. */ if (pipe(pfd) == -1) { Mfprintf(stderr, "unable to create pipe: %s\n", strerror(errno)); return(1); } switch (fork()) { case -1: /* oops, forking went wrong! */ Mfprintf(stderr, "unable to fork into background: %s\n", strerror(errno)); return(1); case 0: /* detach client from controlling tty, we only write to the * pipe to daddy */ if (setsid() < 0) Mfprintf(stderr, "hmmm, can't detach from controlling tty, " "continuing anyway\n"); retfd = open("/dev/null", O_RDONLY); dup2(retfd, 0); close(retfd); close(pfd[0]); /* close unused read end */ retfd = pfd[1]; /* store the write end */ break; default: /* the parent, we want it to die, after we know the child * has a good time */ close(pfd[1]); /* close unused write end */ if (read(pfd[0], &buf, 1) != 1) { Mfprintf(stderr, "unable to retrieve startup status\n"); return(1); } close(pfd[0]); return(buf[0]); /* whatever the child returned, we return */ } } /* use after the logger thread has started */ #define MERO_EXIT(status) if (!merodontfork) { \ char s = status; \ if (write(retfd, &s, 1) != 1 || close(retfd) != 0) { \ Mfprintf(stderr, "could not write to parent\n"); \ } \ if (status != 0) { \ Mfprintf(stderr, "fatal startup condition encountered, " \ "aborting startup\n"); \ goto shutdown; \ } \ } else { \ if (status != 0) { \ Mfprintf(stderr, "fatal startup condition encountered, " \ "aborting startup\n"); \ goto shutdown; \ } \ } /* use before logger thread has started */ #define MERO_EXIT_CLEAN(status) if (!merodontfork) { \ char s = status; \ if (write(retfd, &s, 1) != 1 || close(retfd) != 0) { \ Mfprintf(stderr, "could not write to parent\n"); \ } \ exit(s); \ } else { \ exit(status); \ } /* check if dbfarm actually exists */ if (stat(dbfarm, &sb) == -1) { Mfprintf(stderr, "dbfarm directory '%s' does not exist, " "use monetdbd create first\n", dbfarm); MERO_EXIT_CLEAN(1); } /* chdir to dbfarm so we are at least in a known to exist location */ if (chdir(dbfarm) < 0) { Mfprintf(stderr, "could not move to dbfarm '%s': %s\n", dbfarm, strerror(errno)); MERO_EXIT_CLEAN(1); } /* absolutise dbfarm if it isn't yet (we're in it now) */ if (dbfarm[0] != '/') { if (getcwd(dbfarm, sizeof(dbfarm)) == NULL) { if (errno == ERANGE) { Mfprintf(stderr, "current path exceeds allocated path length" \ "please file a bug at http://bugs.monetdb.org\n"); } else { Mfprintf(stderr, "could not get dbfarm working directory: %s\n", strerror(errno)); } MERO_EXIT_CLEAN(1); } } if (_mero_mserver == NULL) { _mero_mserver = BINDIR "/mserver5"; if (stat(_mero_mserver, &sb) == -1) { /* exit early if this is not going to work well */ Mfprintf(stderr, "cannot stat %s executable: %s\n", _mero_mserver, strerror(errno)); MERO_EXIT_CLEAN(1); } } /* read the merovingian properties from the dbfarm */ if (readProps(ckv, ".") != 0) { Mfprintf(stderr, "cannot find or read properties file, was " "this dbfarm created by `monetdbd create`?\n"); MERO_EXIT_CLEAN(1); } _mero_props = ckv; pidfilename = getConfVal(_mero_props, "pidfile"); p = getConfVal(_mero_props, "forward"); if (strcmp(p, "redirect") != 0 && strcmp(p, "proxy") != 0) { Mfprintf(stderr, "invalid forwarding mode: %s, defaulting to proxy\n", p); kv = findConfKey(_mero_props, "forward"); setConfVal(kv, "proxy"); writeProps(_mero_props, "."); } kv = findConfKey(_mero_props, "port"); if (kv->ival <= 0 || kv->ival > 65535) { Mfprintf(stderr, "invalid port number: %s, defaulting to %s\n", kv->val, MERO_PORT); setConfVal(kv, MERO_PORT); writeProps(_mero_props, "."); } port = (unsigned short)kv->ival; discovery = getConfNum(_mero_props, "discovery"); /* check and trim the hash-algo from the passphrase for easy use * lateron */ kv = findConfKey(_mero_props, "passphrase"); if (kv->val != NULL) { char *h = kv->val + 1; if ((p = strchr(h, '}')) == NULL) { Mfprintf(stderr, "warning: incompatible passphrase (not hashed as " MONETDB5_PASSWDHASH "), disabling passphrase\n"); } else { *p = '\0'; if (strcmp(h, MONETDB5_PASSWDHASH) != 0) { Mfprintf(stderr, "warning: passphrase hash '%s' incompatible, " "expected '%s', disabling passphrase\n", h, MONETDB5_PASSWDHASH); } else { setConfVal(kv, p + 1); } } } /* set up UNIX socket paths for control and mapi */ p = getConfVal(_mero_props, "sockdir"); snprintf(control_usock, sizeof(control_usock), "%s/" CONTROL_SOCK "%d", p, port); snprintf(mapi_usock, sizeof(control_usock), "%s/" MERO_SOCK "%d", p, port); /* lock such that we are alone on this world */ if ((lockfd = MT_lockf(".merovingian_lock", F_TLOCK, 4, 1)) == -1) { /* locking failed */ Mfprintf(stderr, "another monetdbd is already running\n"); MERO_EXIT_CLEAN(1); } else if (lockfd == -2) { /* directory or something doesn't exist */ Mfprintf(stderr, "unable to create %s/.merovingian_lock file: %s\n", dbfarm, strerror(errno)); MERO_EXIT_CLEAN(1); } _mero_topdp = &dpcons; _mero_topdp->pid = 0; _mero_topdp->type = MERO; _mero_topdp->dbname = NULL; /* where should our msg output go to? */ p = getConfVal(_mero_props, "logfile"); /* write to the given file */ _mero_topdp->out = open(p, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR); if (_mero_topdp->out == -1) { Mfprintf(stderr, "unable to open '%s': %s\n", p, strerror(errno)); MT_lockf(".merovingian_lock", F_ULOCK, 4, 1); close(lockfd); MERO_EXIT_CLEAN(1); } _mero_topdp->err = _mero_topdp->out; _mero_logfile = fdopen(_mero_topdp->out, "a"); d = _mero_topdp->next = &dpmero; /* redirect stdout */ if (pipe(pfd) == -1) { Mfprintf(stderr, "unable to create pipe: %s\n", strerror(errno)); MERO_EXIT(1); } d->out = pfd[0]; dup2(pfd[1], 1); close(pfd[1]); /* redirect stderr */ if (pipe(pfd) == -1) { Mfprintf(stderr, "unable to create pipe: %s\n", strerror(errno)); MERO_EXIT(1); } /* before it is too late, save original stderr */ oerr = fdopen(dup(2), "w"); d->err = pfd[0]; dup2(pfd[1], 2); close(pfd[1]); d->pid = getpid(); d->type = MERO; d->dbname = "merovingian"; /* separate entry for the neighbour discovery service */ d = d->next = &dpdisc; if (pipe(pfd) == -1) { Mfprintf(stderr, "unable to create pipe: %s\n", strerror(errno)); MERO_EXIT(1); } d->out = pfd[0]; _mero_discout = fdopen(pfd[1], "a"); if (pipe(pfd) == -1) { Mfprintf(stderr, "unable to create pipe: %s\n", strerror(errno)); MERO_EXIT(1); } d->err = pfd[0]; _mero_discerr = fdopen(pfd[1], "a"); d->pid = getpid(); d->type = MERO; d->dbname = "discovery"; d->next = NULL; /* separate entry for the control runner */ d = d->next = &dpcont; if (pipe(pfd) == -1) { Mfprintf(stderr, "unable to create pipe: %s\n", strerror(errno)); MERO_EXIT(1); } d->out = pfd[0]; _mero_ctlout = fdopen(pfd[1], "a"); if (pipe(pfd) == -1) { Mfprintf(stderr, "unable to create pipe: %s\n", strerror(errno)); MERO_EXIT(1); } d->err = pfd[0]; _mero_ctlerr = fdopen(pfd[1], "a"); d->pid = getpid(); d->type = MERO; d->dbname = "control"; d->next = NULL; /* allow a thread to relock this mutex */ pthread_mutexattr_init(&mta); pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&_mero_topdp_lock, &mta); if ((thret = pthread_create(&tid, NULL, (void *(*)(void *))logListener, (void *)NULL)) != 0) { Mfprintf(oerr, "%s: FATAL: unable to create logthread: %s\n", argv[0], strerror(thret)); MERO_EXIT(1); } sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = handler; if ( sigaction(SIGINT, &sa, NULL) == -1 || sigaction(SIGQUIT, &sa, NULL) == -1 || sigaction(SIGTERM, &sa, NULL) == -1) { Mfprintf(oerr, "%s: FATAL: unable to create signal handlers: %s\n", argv[0], strerror(errno)); MERO_EXIT(1); } sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = huphandler; if (sigaction(SIGHUP, &sa, NULL) == -1) { Mfprintf(oerr, "%s: FATAL: unable to create signal handlers: %s\n", argv[0], strerror(errno)); MERO_EXIT(1); } sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = segvhandler; if (sigaction(SIGSEGV, &sa, NULL) == -1) { Mfprintf(oerr, "%s: FATAL: unable to create signal handlers: %s\n", argv[0], strerror(errno)); MERO_EXIT(1); } sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = SIG_IGN; if (sigaction(SIGPIPE, &sa, NULL) == -1) { Mfprintf(oerr, "%s: FATAL: unable to create signal handlers: %s\n", argv[0], strerror(errno)); MERO_EXIT(1); } sa.sa_flags = SA_SIGINFO; sigemptyset(&sa.sa_mask); sa.sa_sigaction = childhandler; if (sigaction(SIGCHLD, &sa, NULL) == -1) { Mfprintf(oerr, "%s: FATAL: unable to create signal handlers: %s\n", argv[0], strerror(errno)); MERO_EXIT(1); } /* make sure we will be able to write our pid */ if ((pidfile = fopen(pidfilename, "w")) == NULL) { Mfprintf(stderr, "unable to open '%s%s%s' for writing: %s\n", pidfilename[0] != '/' ? dbfarm : "", pidfilename[0] != '/' ? "/" : "", pidfilename, strerror(errno)); MERO_EXIT(1); } msab_dbfarminit(dbfarm); /* write out the pid */ Mfprintf(pidfile, "%d\n", (int)d->pid); fclose(pidfile); Mfprintf(stdout, "Merovingian %s (%s) starting\n", MERO_VERSION, MONETDB_RELEASE); Mfprintf(stdout, "monitoring dbfarm %s\n", dbfarm); /* open up connections */ if ( (e = openConnectionTCP(&sock, port, stdout)) == NO_ERR && /* coverity[operator_confusion] */ (unlink(control_usock) | unlink(mapi_usock) | 1) && (e = openConnectionUNIX(&socku, mapi_usock, 0, stdout)) == NO_ERR && (discovery == 0 || (e = openConnectionUDP(&usock, port)) == NO_ERR) && (e = openConnectionUNIX(&unsock, control_usock, S_IRWXO, _mero_ctlout)) == NO_ERR ) { pthread_t ctid = 0; pthread_t dtid = 0; if (discovery == 1) { _mero_broadcastsock = socket(AF_INET, SOCK_DGRAM, 0); ret = 1; if ((setsockopt(_mero_broadcastsock, SOL_SOCKET, SO_BROADCAST, &ret, sizeof(ret))) == -1) { Mfprintf(stderr, "cannot create broadcast package, " "discovery services disabled\n"); close(usock); usock = -1; } _mero_broadcastaddr.sin_family = AF_INET; _mero_broadcastaddr.sin_addr.s_addr = htonl(INADDR_BROADCAST); /* the target port is our configured port, not elegant, but how * else can we do it? can't broadcast to all ports or something */ _mero_broadcastaddr.sin_port = htons(port); } /* From this point merovingian considers itself to be in position to * start running, so flag the parent we will have fun. */ MERO_EXIT(0); /* Paranoia umask, but good, because why would people have to sniff * our private parts? */ umask(S_IRWXG | S_IRWXO); /* handle control commands */ if ((thret = pthread_create(&ctid, NULL, (void *(*)(void *))controlRunner, (void *)&unsock)) != 0) { Mfprintf(stderr, "unable to create control command thread: %s\n", strerror(thret)); ctid = 0; } /* start neighbour discovery and notification thread */ if (usock >= 0 && (thret = pthread_create(&dtid, NULL, (void *(*)(void *))discoveryRunner, (void *)&usock)) != 0) { Mfprintf(stderr, "unable to start neighbour discovery thread: %s\n", strerror(thret)); dtid = 0; } /* handle external connections main loop */ e = acceptConnections(sock, socku); /* wait for the control runner and discovery thread to have * finished announcing they're going down */ close(unsock); if (ctid != 0) pthread_join(ctid, NULL); if (usock >= 0) { close(usock); if (dtid != 0) pthread_join(dtid, NULL); } } /* control channel is already closed at this point */ if (unsock != -1 && unlink(control_usock) == -1) Mfprintf(stderr, "unable to unlink control socket '%s': %s\n", control_usock, strerror(errno)); if (socku != -1 && unlink(mapi_usock) == -1) Mfprintf(stderr, "unable to unlink mapi socket '%s': %s\n", mapi_usock, strerror(errno)); if (e != NO_ERR) { /* console */ Mfprintf(oerr, "%s: %s\n", argv[0], e); /* logfile */ Mfprintf(stderr, "%s\n", e); MERO_EXIT(1); } shutdown: /* stop started mservers */ kv = findConfKey(ckv, "exittimeout"); if (d->next != NULL && atoi(kv->val) > 0) { dpair t; threadlist tl = NULL, tlw = tl; pthread_mutex_lock(&_mero_topdp_lock); t = d->next; while (t != NULL) { if (tl == NULL) { tl = tlw = malloc(sizeof(struct _threadlist)); } else { tlw = tlw->next = malloc(sizeof(struct _threadlist)); } tlw->next = NULL; if ((thret = pthread_create(&(tlw->tid), NULL, (void *(*)(void *))terminateProcess, (void *)t)) != 0) { Mfprintf(stderr, "%s: unable to create thread to terminate " "database '%s': %s\n", argv[0], t->dbname, strerror(thret)); tlw->tid = 0; } t = t->next; } pthread_mutex_unlock(&_mero_topdp_lock); /* wait for all processes to be terminated */ tlw = tl; while (tlw != NULL) { if (tlw->tid != 0 && (argp = pthread_join(tlw->tid, NULL)) != 0) { Mfprintf(stderr, "failed to wait for termination thread: " "%s\n", strerror(argp)); } tl = tlw->next; free(tlw); tlw = tl; } } /* need to do this here, since the logging thread is shut down as * next thing */ Mfprintf(stdout, "Merovingian %s stopped\n", MERO_VERSION); _mero_keep_logging = 0; if (tid != 0 && (argp = pthread_join(tid, NULL)) != 0) { Mfprintf(oerr, "failed to wait for logging thread: %s\n", strerror(argp)); } if (_mero_topdp != NULL) { close(_mero_topdp->out); if (_mero_topdp->out != _mero_topdp->err) close(_mero_topdp->err); } /* remove files that suggest our existence */ unlink(".merovingian_lock"); if (pidfilename != NULL) { unlink(pidfilename); free(pidfilename); } /* mostly for valgrind... */ freeConfFile(ckv); if (_mero_db_props != NULL) { freeConfFile(_mero_db_props); free(_mero_db_props); } if (lockfd >= 0) { MT_lockf(".merovingian_lock", F_ULOCK, 4, 1); close(lockfd); } /* the child's return code at this point doesn't matter, as noone * will see it */ return(0); }
void* serve_client(void* info) { int sfd_client, connection_id, x; struct packet shp; char lpwd[LENBUFFER]; struct client_info* ci = (struct client_info*) info; sfd_client = ci->sfd; connection_id = ci->cid; while(1) { if(recv_packet_ret(sfd_client, &shp) < 0) { fprintf(stderr, "client ID(%d) closed/terminated. closing connection.\n", connection_id); break; } if(shp.type == TERM) break; if(shp.conid == -1) shp.conid = connection_id; if(shp.type == REQU) { switch(shp.comid) { case PWD: if(!getcwd(lpwd, sizeof lpwd)) er("getcwd()", 0); command_pwd(sfd_client, &shp, lpwd); break; case CD: if((x = chdir(shp.buffer)) == -1) fprintf(stderr, "Wrong path.\n"); command_cd(sfd_client, &shp, x == -1 ? "fail" : "success"); break; case MKDIR: command_mkdir(sfd_client, &shp); break; case LS: if(!getcwd(lpwd, sizeof lpwd)) er("getcwd()", 0); command_ls(sfd_client, &shp, lpwd); break; case GET: command_get(sfd_client, &shp); break; case PUT: command_put(sfd_client, &shp); break; case RGET: if(!getcwd(lpwd, sizeof lpwd)) er("getcwd()", 0); command_rget(sfd_client, &shp); send_EOT(sfd_client, &shp); if((x = chdir(lpwd)) == -1) fprintf(stderr, "Wrong path.\n"); break; default: // print error break; } } else { //show error, send TERM and break fprintf(stderr, "packet incomprihensible. closing connection.\n"); send_TERM(sfd_client, &shp); break; } } close(sfd_client); fflush(stdout); return NULL; }