diff --git a/lw12ctl.c b/lw12ctl.c index 8ffc698..e8d28c7 100644 --- a/lw12ctl.c +++ b/lw12ctl.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -18,6 +19,11 @@ #define DebugPrintPos fprintf(stderr, "%s:%d\n", __FILE__, __LINE__) +struct config { + char *host; + int port; +}; + int exit_interactive_session = 0; int sockfd = 0; struct sockaddr_in server_addr; @@ -215,15 +221,77 @@ void cmd_loop() { } while (!exit_interactive_session); } +int read_conf(const char *filename, struct config *conf){ + FILE *fd; + const size_t line_size = 300; + char *line = (char *)malloc(line_size); + char *start_pos, *pos; + char *value = NULL; + + // set default + conf->host = NULL; + conf->port = 5000; + + // read config + fd = fopen(filename, "r"); + if (fd) { + while (fgets(line, line_size, fd) != NULL) { + pos = line; + while (*pos == ' ') + pos++; + if (*pos == '#' || *pos == '\n') + continue; + + start_pos = pos; + while (*pos != '\0') { + if (*pos == '\n') { + *pos = '\0'; + break; + } + pos++; + } + + value = strrchr(start_pos, '='); + start_pos[value - start_pos - 1] = '\0'; + while (*value == ' ' || *value == '=') + value++; + + if (strncasecmp(start_pos, "host", 4) == 0) { + size_t param_len = strlen(value); + conf->host = (char *)malloc(param_len); + strncpy(conf->host, value, param_len); + } else if (strncasecmp(start_pos, "port", 4) == 0) { + conf->port = atoi(value); + } + } + } + + free(line); + return 0; +} + int main() { - char serverip[] = "192.168.178.24"; - uint16_t serverport = 5000; + struct passwd *pw = getpwuid(getuid()); + const char *homedir = pw->pw_dir; + char confpath[510] = {}; + struct config conf; + + strcat(confpath, homedir); + strcat(confpath, "/.lw12rc"); + read_conf(confpath, &conf); + if (conf.host == NULL) { + fprintf(stderr, "Option 'host' is missing or not set in config.\n"); + return 1; + } rl_bind_key('\t', rl_abort); - lw12_connect(&sockfd, &server_addr, serverport, serverip); + lw12_connect(&sockfd, &server_addr, conf.port, conf.host); cmd_loop(); close(sockfd); + // Clean config environment + free(conf.host); + return 0; }