diff options
author | Nicolas Lécureuil <neoclust@mageia.org> | 2012-11-09 20:44:52 +0000 |
---|---|---|
committer | Nicolas Lécureuil <neoclust@mageia.org> | 2012-11-09 20:44:52 +0000 |
commit | 820fd62a86a88b3c53d5ebe1939e4dc51cc8bcdc (patch) | |
tree | c68a3c36dfae599c50c1f1dcda92113dab70effc /mdk-stage1 | |
parent | 0db2372d5a031bad0f5df98b83f7fb7d648215ed (diff) | |
download | drakx-backup-do-not-use-820fd62a86a88b3c53d5ebe1939e4dc51cc8bcdc.tar drakx-backup-do-not-use-820fd62a86a88b3c53d5ebe1939e4dc51cc8bcdc.tar.gz drakx-backup-do-not-use-820fd62a86a88b3c53d5ebe1939e4dc51cc8bcdc.tar.bz2 drakx-backup-do-not-use-820fd62a86a88b3c53d5ebe1939e4dc51cc8bcdc.tar.xz drakx-backup-do-not-use-820fd62a86a88b3c53d5ebe1939e4dc51cc8bcdc.zip |
Do not mix tabs and spaces
Diffstat (limited to 'mdk-stage1')
33 files changed, 7455 insertions, 7372 deletions
diff --git a/mdk-stage1/adsl.c b/mdk-stage1/adsl.c index ace741c18..afddb455b 100644 --- a/mdk-stage1/adsl.c +++ b/mdk-stage1/adsl.c @@ -40,144 +40,148 @@ static enum return_type adsl_connect(struct interface_info * intf, char * username, char * password, char * acname) { - char pppoe_call[500]; - char * pppd_launch[] = { "/sbin/pppd", "pty", pppoe_call, "noipdefault", "noauth", "default-asyncmap", "defaultroute", - "hide-password", "nodetach", "usepeerdns", "local", "mtu", "1492", "mru", "1492", "noaccomp", - "noccp", "nobsdcomp", "nodeflate", "nopcomp", "novj", "novjccomp", "user", username, - "password", password, "lcp-echo-interval", "20", "lcp-echo-failure", "3", "lock", "persist", NULL }; - int fd; - int retries = 10; - char * tty_adsl = "/dev/tty6"; - enum return_type status = RETURN_ERROR; - pid_t ppp_pid; - - snprintf(pppoe_call, sizeof(pppoe_call), "/sbin/pppoe -p /var/run/pppoe.conf-adsl.pid.pppoe -I %s -T 80 -U -m 1412", intf->device); - - if (!streq(acname, "")) { - strcat(pppoe_call, "-C "); - strcat(pppoe_call, acname); + char pppoe_call[500]; + char * pppd_launch[] = { "/sbin/pppd", "pty", pppoe_call, "noipdefault", "noauth", "default-asyncmap", "defaultroute", + "hide-password", "nodetach", "usepeerdns", "local", "mtu", "1492", "mru", "1492", "noaccomp", + "noccp", "nobsdcomp", "nodeflate", "nopcomp", "novj", "novjccomp", "user", username, + "password", password, "lcp-echo-interval", "20", "lcp-echo-failure", "3", "lock", "persist", NULL }; + int fd; + int retries = 10; + char * tty_adsl = "/dev/tty6"; + enum return_type status = RETURN_ERROR; + pid_t ppp_pid; + + snprintf(pppoe_call, sizeof(pppoe_call), "/sbin/pppoe -p /var/run/pppoe.conf-adsl.pid.pppoe -I %s -T 80 -U -m 1412", intf->device); + + if (!streq(acname, "")) { + strcat(pppoe_call, "-C "); + strcat(pppoe_call, acname); + } + + fd = open(tty_adsl, O_RDWR); + if (fd == -1) { + log_message("cannot open tty -- no pppd"); + return RETURN_ERROR; + } + else if (access(pppd_launch[0], X_OK)) { + log_message("cannot open pppd - %s doesn't exist", pppd_launch[0]); + return RETURN_ERROR; + } + + if (!(ppp_pid = fork())) { + dup2(fd, 0); + dup2(fd, 1); + dup2(fd, 2); + + close(fd); + setsid(); + if (ioctl(0, TIOCSCTTY, NULL)) { + log_perror("could not set new controlling tty"); } - fd = open(tty_adsl, O_RDWR); - if (fd == -1) { - log_message("cannot open tty -- no pppd"); - return RETURN_ERROR; - } - else if (access(pppd_launch[0], X_OK)) { - log_message("cannot open pppd - %s doesn't exist", pppd_launch[0]); - return RETURN_ERROR; - } - - if (!(ppp_pid = fork())) { - dup2(fd, 0); - dup2(fd, 1); - dup2(fd, 2); - - close(fd); - setsid(); - if (ioctl(0, TIOCSCTTY, NULL)) - log_perror("could not set new controlling tty"); - - printf("\t(exec of pppd)\n"); - execv(pppd_launch[0], pppd_launch); - log_message("execve of %s failed: %s", pppd_launch[0], strerror(errno)); - exit(-1); - } - close(fd); - while (retries > 0 && kill(ppp_pid, 0) == 0) { - FILE * f; - if ((f = fopen("/var/run/pppd.tdb", "rb"))) { - while (1) { - char buf[500]; - char *p; - if (!fgets(buf, sizeof(buf), f)) - break; - p = strstr(buf, "IPLOCAL="); - if (p) { - struct sockaddr_in addr; - if (inet_aton(p + 8, &addr.sin_addr)) - intf->ip = addr.sin_addr; - status = RETURN_OK; - } - } - fclose(f); - if (status == RETURN_OK) { - log_message("PPP: connected!"); - break; - } - } - retries--; - log_message("PPP: <sleep>"); - sleep(2); - } - - if (status != RETURN_OK) { - log_message("PPP: could not connect"); - kill(ppp_pid, SIGTERM); - sleep(1); - kill(ppp_pid, SIGKILL); - sleep(1); - } - return status; + printf("\t(exec of pppd)\n"); + execv(pppd_launch[0], pppd_launch); + log_message("execve of %s failed: %s", pppd_launch[0], strerror(errno)); + exit(-1); + } + close(fd); + while (retries > 0 && kill(ppp_pid, 0) == 0) { + FILE * f; + if ((f = fopen("/var/run/pppd.tdb", "rb"))) { + while (1) { + char buf[500]; + char *p; + if (!fgets(buf, sizeof(buf), f)) { + break; + } + p = strstr(buf, "IPLOCAL="); + if (p) { + struct sockaddr_in addr; + if (inet_aton(p + 8, &addr.sin_addr)) { + intf->ip = addr.sin_addr; + } + status = RETURN_OK; + } + } + fclose(f); + if (status == RETURN_OK) { + log_message("PPP: connected!"); + break; + } + } + retries--; + log_message("PPP: <sleep>"); + sleep(2); + } + + if (status != RETURN_OK) { + log_message("PPP: could not connect"); + kill(ppp_pid, SIGTERM); + sleep(1); + kill(ppp_pid, SIGKILL); + sleep(1); + } + return status; } enum return_type perform_adsl(struct interface_info * intf) { - struct in_addr addr; - char * questions[] = { "Username", "Password", "AC Name", NULL }; - char * questions_auto[] = { "adsluser", "adslpass", "adslacname", NULL }; - static char ** answers = NULL; - enum return_type results; + struct in_addr addr; + char * questions[] = { "Username", "Password", "AC Name", NULL }; + char * questions_auto[] = { "adsluser", "adslpass", "adslacname", NULL }; + static char ** answers = NULL; + enum return_type results; - inet_aton("10.0.0.10", &addr); - memcpy(&intf->ip, &addr, sizeof(addr)); + inet_aton("10.0.0.10", &addr); + memcpy(&intf->ip, &addr, sizeof(addr)); - inet_aton("255.255.255.0", &addr); - memcpy(&intf->netmask, &addr, sizeof(addr)); + inet_aton("255.255.255.0", &addr); + memcpy(&intf->netmask, &addr, sizeof(addr)); - *((uint32_t *) &intf->broadcast) = (*((uint32_t *) &intf->ip) & - *((uint32_t *) &intf->netmask)) | ~(*((uint32_t *) &intf->netmask)); + *((uint32_t *) &intf->broadcast) = (*((uint32_t *) &intf->ip) & + *((uint32_t *) &intf->netmask)) | ~(*((uint32_t *) &intf->netmask)); - intf->is_ptp = 0; + intf->is_ptp = 0; - if (configure_net_device(intf)) { - stg1_error_message("Could not configure.."); - return RETURN_ERROR; - } + if (configure_net_device(intf)) { + stg1_error_message("Could not configure.."); + return RETURN_ERROR; + } - results = ask_from_entries_auto("Please enter the username and password for your ADSL account.\n" + results = ask_from_entries_auto("Please enter the username and password for your ADSL account.\n" "Leave blank the AC Name field if you don't know what it means.\n" - "(Warning! only PPPoE protocol is supported)", - questions, &answers, 40, questions_auto, NULL); - if (results != RETURN_OK) - return results; - - intf->boot_proto = BOOTPROTO_ADSL_PPPOE; - - wait_message("Waiting for ADSL connection to show up..."); - my_insmod("ppp_generic", ANY_DRIVER_TYPE, NULL, 1); - my_insmod("ppp_async", ANY_DRIVER_TYPE, NULL, 1); - results = adsl_connect(intf, answers[0], answers[1], answers[2]); - remove_wait_message(); - - if (results != RETURN_OK) { - wait_message("Retrying the ADSL connection..."); - results = adsl_connect(intf, answers[0], answers[1], answers[2]); - remove_wait_message(); - } else { - intf->user = strdup(answers[0]); - intf->pass = strdup(answers[1]); - intf->acname = strdup(answers[2]); - } - - if (results != RETURN_OK) { - stg1_error_message("I could not connect to the ADSL network."); - return perform_adsl(intf); - } - - sleep(1); - res_init(); /* reinit the resolver, pppd modified /etc/resolv.conf */ - - return RETURN_OK; + "(Warning! only PPPoE protocol is supported)", + questions, &answers, 40, questions_auto, NULL); + if (results != RETURN_OK) { + return results; + } + + intf->boot_proto = BOOTPROTO_ADSL_PPPOE; + + wait_message("Waiting for ADSL connection to show up..."); + my_insmod("ppp_generic", ANY_DRIVER_TYPE, NULL, 1); + my_insmod("ppp_async", ANY_DRIVER_TYPE, NULL, 1); + results = adsl_connect(intf, answers[0], answers[1], answers[2]); + remove_wait_message(); + + if (results != RETURN_OK) { + wait_message("Retrying the ADSL connection..."); + results = adsl_connect(intf, answers[0], answers[1], answers[2]); + remove_wait_message(); + } else { + intf->user = strdup(answers[0]); + intf->pass = strdup(answers[1]); + intf->acname = strdup(answers[2]); + } + + if (results != RETURN_OK) { + stg1_error_message("I could not connect to the ADSL network."); + return perform_adsl(intf); + } + + sleep(1); + res_init(); /* reinit the resolver, pppd modified /etc/resolv.conf */ + + return RETURN_OK; } diff --git a/mdk-stage1/automatic.c b/mdk-stage1/automatic.c index fd9eb3679..a3821da23 100644 --- a/mdk-stage1/automatic.c +++ b/mdk-stage1/automatic.c @@ -36,131 +36,138 @@ static char * value_not_bound = ""; void grab_automatic_params(char * line) { - int i, p; - struct param_elem tmp_params[50]; - - i = 0; p = 0; - while (line[i] != '\0') { - char *name, *value; - int k; - int j = i; - while (line[i] != ':' && line[i] != '\0') - i++; - name = _memdup(&line[j], i-j + 1); - name[i-j] = 0; - - k = i+1; - i++; - while (line[i] != ',' && line[i] != '\0') - i++; - value = _memdup(&line[k], i-k + 1); - value[i-k] = 0; - - tmp_params[p].name = name; - tmp_params[p].value = value; - p++; - if (line[i] == '\0') - break; - i++; - } - - tmp_params[p++].name = NULL; - automatic_params = _memdup(tmp_params, sizeof(struct param_elem) * p); - - log_message("AUTOMATIC MODE: got %d params", p-1); + int i, p; + struct param_elem tmp_params[50]; + + i = 0; p = 0; + while (line[i] != '\0') { + char *name, *value; + int k; + int j = i; + + while (line[i] != ':' && line[i] != '\0') { + i++; + } + + name = _memdup(&line[j], i-j + 1); + name[i-j] = 0; + + k = i+1; + i++; + + while (line[i] != ',' && line[i] != '\0') { + i++; + } + + value = _memdup(&line[k], i-k + 1); + value[i-k] = 0; + + tmp_params[p].name = name; + tmp_params[p].value = value; + p++; + if (line[i] == '\0') { + break; + } + i++; + } + + tmp_params[p++].name = NULL; + automatic_params = _memdup(tmp_params, sizeof(struct param_elem) * p); + + log_message("AUTOMATIC MODE: got %d params", p-1); } char * get_auto_value(char * auto_param) { - struct param_elem * ptr = automatic_params; - - struct param_elem short_aliases[] = - { { "method", "met" }, { "network", "netw" }, { "interface", "int" }, { "gateway", "gat" }, - { "netmask", "netm" }, { "adsluser", "adslu" }, { "adslpass", "adslp" }, { "hostname", "hos" }, - { "domain", "dom" }, { "server", "ser" }, { "directory", "dir" }, { "user", "use" }, - { "pass", "pas" }, { "disk", "dis" }, { "partition", "par" }, { "proxy_host", "proxh" }, - { "proxy_port", "proxp" }, { NULL, NULL } }; - struct param_elem * ptr_alias = short_aliases; - while (ptr_alias->name) { - if (streq(auto_param, ptr_alias->name)) - break; - ptr_alias++; - } - - while (ptr->name) { - if (streq(ptr->name, auto_param) - || (ptr_alias->name && streq(ptr_alias->value, ptr->name))) - return ptr->value; - ptr++; - } - - return value_not_bound; + struct param_elem * ptr = automatic_params; + + struct param_elem short_aliases[] = + { { "method", "met" }, { "network", "netw" }, { "interface", "int" }, { "gateway", "gat" }, + { "netmask", "netm" }, { "adsluser", "adslu" }, { "adslpass", "adslp" }, { "hostname", "hos" }, + { "domain", "dom" }, { "server", "ser" }, { "directory", "dir" }, { "user", "use" }, + { "pass", "pas" }, { "disk", "dis" }, { "partition", "par" }, { "proxy_host", "proxh" }, + { "proxy_port", "proxp" }, { NULL, NULL } }; + struct param_elem * ptr_alias = short_aliases; + while (ptr_alias->name) { + if (streq(auto_param, ptr_alias->name)) + break; + ptr_alias++; + } + + while (ptr->name) { + if (streq(ptr->name, auto_param) + || (ptr_alias->name && streq(ptr_alias->value, ptr->name))) + return ptr->value; + ptr++; + } + + return value_not_bound; } enum return_type ask_from_list_auto(char *msg, char ** elems, char ** choice, char * auto_param, char ** elems_auto) { - if (!IS_AUTOMATIC) { - exit_bootsplash(); - return ask_from_list(msg, elems, choice); - } else { - char ** sav_elems = elems; - char * tmp = get_auto_value(auto_param); - while (elems && *elems) { - if (!strcmp(tmp, *elems_auto)) { - *choice = *elems; - log_message("AUTOMATIC: parameter %s for %s means returning %s", tmp, auto_param, *elems); - return RETURN_OK; - } - elems++; - elems_auto++; - } - unset_automatic(); /* we are in a fallback mode */ - return ask_from_list(msg, sav_elems, choice); - } + if (!IS_AUTOMATIC) { + exit_bootsplash(); + return ask_from_list(msg, elems, choice); + } else { + char ** sav_elems = elems; + char * tmp = get_auto_value(auto_param); + while (elems && *elems) { + if (!strcmp(tmp, *elems_auto)) { + *choice = *elems; + log_message("AUTOMATIC: parameter %s for %s means returning %s", tmp, auto_param, *elems); + return RETURN_OK; + } + elems++; + elems_auto++; + } + unset_automatic(); /* we are in a fallback mode */ + return ask_from_list(msg, sav_elems, choice); + } } enum return_type ask_from_list_comments_auto(char *msg, char ** elems, char ** elems_comments, char ** choice, char * auto_param, char ** elems_auto) { - if (!IS_AUTOMATIC) { - exit_bootsplash(); - return ask_from_list_comments(msg, elems, elems_comments, choice); - } else { - char ** sav_elems = elems; - char * tmp = get_auto_value(auto_param); - while (elems && *elems) { - if (!strcmp(tmp, *elems_auto)) { - *choice = *elems; - log_message("AUTOMATIC: parameter %s for %s means returning %s", tmp, auto_param, *elems); - return RETURN_OK; - } - elems++; - elems_auto++; - } - unset_automatic(); /* we are in a fallback mode */ - return ask_from_list_comments(msg, sav_elems, elems_comments, choice); - } + if (!IS_AUTOMATIC) { + exit_bootsplash(); + return ask_from_list_comments(msg, elems, elems_comments, choice); + } else { + char ** sav_elems = elems; + char * tmp = get_auto_value(auto_param); + while (elems && *elems) { + if (!strcmp(tmp, *elems_auto)) { + *choice = *elems; + log_message("AUTOMATIC: parameter %s for %s means returning %s", tmp, auto_param, *elems); + return RETURN_OK; + } + elems++; + elems_auto++; + } + unset_automatic(); /* we are in a fallback mode */ + return ask_from_list_comments(msg, sav_elems, elems_comments, choice); + } } enum return_type ask_from_entries_auto(char *msg, char ** questions, char *** answers, int entry_size, char ** questions_auto, void (*callback_func)(char ** strings)) { - if (!IS_AUTOMATIC) { - exit_bootsplash(); - return ask_from_entries(msg, questions, answers, entry_size, callback_func); - } else { - char * tmp_answers[50]; - int i = 0; - while (questions && *questions) { - tmp_answers[i] = get_auto_value(*questions_auto); - log_message("AUTOMATIC: question %s answers %s because of param %s", *questions, tmp_answers[i], *questions_auto); - i++; - questions++; - questions_auto++; - - } - *answers = _memdup(tmp_answers, sizeof(char *) * i); - return RETURN_OK; - } + if (!IS_AUTOMATIC) { + exit_bootsplash(); + return ask_from_entries(msg, questions, answers, entry_size, callback_func); + } else { + char * tmp_answers[50]; + int i = 0; + while (questions && *questions) { + tmp_answers[i] = get_auto_value(*questions_auto); + log_message("AUTOMATIC: question %s answers %s because of param %s", *questions, tmp_answers[i], *questions_auto); + i++; + questions++; + questions_auto++; + + } + *answers = _memdup(tmp_answers, sizeof(char *) * i); + return RETURN_OK; + } } diff --git a/mdk-stage1/bootsplash.c b/mdk-stage1/bootsplash.c index 9d0d53327..839b4562e 100644 --- a/mdk-stage1/bootsplash.c +++ b/mdk-stage1/bootsplash.c @@ -23,48 +23,53 @@ static FILE* splash = NULL; static void update_progression_only(int current_size) { - if (splash && total_size) { - float ratio = (float) (current_size + 1) / total_size; - if (ratio > previous + 0.01) { - fprintf(splash, "show %d\n", (int) (ratio * 65534)); - fflush(splash); - previous = ratio; - } - } + if (splash && total_size) { + float ratio = (float) (current_size + 1) / total_size; + if (ratio > previous + 0.01) { + fprintf(splash, "show %d\n", (int) (ratio * 65534)); + fflush(splash); + previous = ratio; + } + } } static void open_bootsplash(void) { - if (!splash) splash = fopen("/proc/splash", "w"); - if (!splash) log_message("opening /proc/splash failed"); + if (!splash) { + splash = fopen("/proc/splash", "w"); + } + + if (!splash) { + log_message("opening /proc/splash failed"); + } } void exit_bootsplash(void) { - log_message("exiting bootsplash"); - open_bootsplash(); - if (splash) { - fprintf(splash, "verbose\n"); - fflush(splash); - } + log_message("exiting bootsplash"); + open_bootsplash(); + if (splash) { + fprintf(splash, "verbose\n"); + fflush(splash); + } } void init_progression(char *msg, int size) { - previous = 0; total_size = size; - open_bootsplash(); - update_progression_only(0); - init_progression_raw(msg, size); + previous = 0; total_size = size; + open_bootsplash(); + update_progression_only(0); + init_progression_raw(msg, size); } void update_progression(int current_size) { - update_progression_only(current_size); - update_progression_raw(current_size); + update_progression_only(current_size); + update_progression_raw(current_size); } void end_progression(void) { - end_progression_raw(); + end_progression_raw(); } diff --git a/mdk-stage1/cdrom.c b/mdk-stage1/cdrom.c index e75e0fde4..b0060880b 100644 --- a/mdk-stage1/cdrom.c +++ b/mdk-stage1/cdrom.c @@ -38,16 +38,16 @@ static int mount_that_cd_device(char * dev_name) { - char device_fullname[50]; - int mount_result; + char device_fullname[50]; + int mount_result; - snprintf(device_fullname, sizeof(device_fullname), "/dev/%s", dev_name); + snprintf(device_fullname, sizeof(device_fullname), "/dev/%s", dev_name); - mount_result = my_mount(device_fullname, MEDIA_LOCATION, "iso9660", 0); + mount_result = my_mount(device_fullname, MEDIA_LOCATION, "iso9660", 0); - create_IMAGE_LOCATION(MEDIA_LOCATION); + create_IMAGE_LOCATION(MEDIA_LOCATION); - return mount_result; + return mount_result; } @@ -55,172 +55,177 @@ static enum return_type try_with_device(char * dev_name, char * dev_model); static enum return_type do_with_device(char * dev_name, char * dev_model) { - if (!image_has_stage2()) { - enum return_type results; - umount(MEDIA_LOCATION); - results = ask_yes_no("That CDROM disc does not seem to be a " DISTRIB_NAME " Installation CDROM.\nRetry with another disc?"); - if (results == RETURN_OK) - return try_with_device(dev_name, dev_model); - return results; - } + if (!image_has_stage2()) { + enum return_type results; + umount(MEDIA_LOCATION); + results = ask_yes_no("That CDROM disc does not seem to be a " DISTRIB_NAME " Installation CDROM.\nRetry with another disc?"); + if (results == RETURN_OK) { + return try_with_device(dev_name, dev_model); + } + return results; + } - log_message("found a " DISTRIB_NAME " CDROM, good news!"); + log_message("found a " DISTRIB_NAME " CDROM, good news!"); - may_load_compressed_image(); + may_load_compressed_image(); - if (!KEEP_MOUNTED) - /* in rescue mode, we don't need the media anymore */ - umount(MEDIA_LOCATION); + if (!KEEP_MOUNTED) { + /* in rescue mode, we don't need the media anymore */ + umount(MEDIA_LOCATION); + } + + add_to_env("METHOD", "cdrom"); - add_to_env("METHOD", "cdrom"); - return RETURN_OK; -} + return RETURN_OK; +} static enum return_type try_with_device(char * dev_name, char * dev_model) { - wait_message("Trying to access a CDROM disc (drive %s)", dev_model); - - if (mount_that_cd_device(dev_name) == -1) { - enum return_type results; - char msg[500]; - unset_automatic(); /* we are in a fallback mode */ - remove_wait_message(); - - snprintf(msg, sizeof(msg), "I can't access a " DISTRIB_NAME " Installation disc in your CDROM drive (%s).\nRetry?", dev_model); - results = ask_yes_no(msg); - if (results == RETURN_OK) - return try_with_device(dev_name, dev_model); - return results; - } - remove_wait_message(); - - return do_with_device(dev_name, dev_model); + wait_message("Trying to access a CDROM disc (drive %s)", dev_model); + + if (mount_that_cd_device(dev_name) == -1) { + enum return_type results; + char msg[500]; + unset_automatic(); /* we are in a fallback mode */ + remove_wait_message(); + + snprintf(msg, sizeof(msg), "I can't access a " DISTRIB_NAME " Installation disc in your CDROM drive (%s).\nRetry?", dev_model); + results = ask_yes_no(msg); + if (results == RETURN_OK) { + return try_with_device(dev_name, dev_model); + } + return results; + } + remove_wait_message(); + + return do_with_device(dev_name, dev_model); } int try_automatic(char ** medias, char ** medias_models) { - static char * already_tried[50] = { NULL }; - char ** model = medias_models; - char ** ptr = medias; - int i = 0; - while (ptr && *ptr) { - char ** p; - for (p = already_tried; p && *p; p++) - if (streq(*p, *ptr)) - goto try_automatic_already_tried; - *p = strdup(*ptr); - *(p+1) = NULL; - - wait_message("Trying to access " DISTRIB_NAME " CDROM disc (drive %s)", *model); - if (mount_that_cd_device(*ptr) != -1) { - if (image_has_stage2()) { - remove_wait_message(); - return i; - } - else - umount(MEDIA_LOCATION); - } - remove_wait_message(); - - try_automatic_already_tried: - ptr++; - model++; - i++; - } - return -1; + static char * already_tried[50] = { NULL }; + char ** model = medias_models; + char ** ptr = medias; + int i = 0; + while (ptr && *ptr) { + char ** p; + for (p = already_tried; p && *p; p++) + if (streq(*p, *ptr)) + goto try_automatic_already_tried; + *p = strdup(*ptr); + *(p+1) = NULL; + + wait_message("Trying to access " DISTRIB_NAME " CDROM disc (drive %s)", *model); + if (mount_that_cd_device(*ptr) != -1) { + if (image_has_stage2()) { + remove_wait_message(); + return i; + } + else + umount(MEDIA_LOCATION); + } + remove_wait_message(); + + try_automatic_already_tried: + ptr++; + model++; + i++; + } + return -1; } enum return_type cdrom_prepare(void) { - char ** medias, ** ptr, ** medias_models; - char * choice; - int i, count = 0; - enum return_type results; - static int already_probed_ide_generic = 0; - - my_insmod("ide_cd_mod", ANY_DRIVER_TYPE, NULL, 0); - - if (IS_AUTOMATIC) { - get_medias(CDROM, &medias, &medias_models, BUS_IDE); - if ((i = try_automatic(medias, medias_models)) != -1) - return do_with_device(medias[i], medias_models[i]); - - get_medias(CDROM, &medias, &medias_models, BUS_PCMCIA); - if ((i = try_automatic(medias, medias_models)) != -1) - return do_with_device(medias[i], medias_models[i]); - - my_insmod("sr_mod", ANY_DRIVER_TYPE, NULL, 0); - get_medias(CDROM, &medias, &medias_models, BUS_SCSI); - if ((i = try_automatic(medias, medias_models)) != -1) - return do_with_device(medias[i], medias_models[i]); - - get_medias(CDROM, &medias, &medias_models, BUS_USB); - if ((i = try_automatic(medias, medias_models)) != -1) - return do_with_device(medias[i], medias_models[i]); - - /* detect hybrid isos (isos dumped to an USB stick) */ - my_insmod("sd_mod", ANY_DRIVER_TYPE, NULL, 0); - get_medias(DISK, &medias, &medias_models, BUS_USB); - if ((i = try_automatic(medias, medias_models)) != -1) { - return do_with_device(medias[i], medias_models[i]); - } - - unset_automatic(); - } else - my_insmod("sr_mod", ANY_DRIVER_TYPE, NULL, 0); - - - get_medias(CDROM, &medias, &medias_models, BUS_ANY); - ptr = medias; - while (ptr && *ptr) { - count++; - ptr++; + char ** medias, ** ptr, ** medias_models; + char * choice; + int i, count = 0; + enum return_type results; + static int already_probed_ide_generic = 0; + + my_insmod("ide_cd_mod", ANY_DRIVER_TYPE, NULL, 0); + + if (IS_AUTOMATIC) { + get_medias(CDROM, &medias, &medias_models, BUS_IDE); + if ((i = try_automatic(medias, medias_models)) != -1) + return do_with_device(medias[i], medias_models[i]); + + get_medias(CDROM, &medias, &medias_models, BUS_PCMCIA); + if ((i = try_automatic(medias, medias_models)) != -1) + return do_with_device(medias[i], medias_models[i]); + + my_insmod("sr_mod", ANY_DRIVER_TYPE, NULL, 0); + get_medias(CDROM, &medias, &medias_models, BUS_SCSI); + if ((i = try_automatic(medias, medias_models)) != -1) + return do_with_device(medias[i], medias_models[i]); + + get_medias(CDROM, &medias, &medias_models, BUS_USB); + if ((i = try_automatic(medias, medias_models)) != -1) + return do_with_device(medias[i], medias_models[i]); + + /* detect hybrid isos (isos dumped to an USB stick) */ + my_insmod("sd_mod", ANY_DRIVER_TYPE, NULL, 0); + get_medias(DISK, &medias, &medias_models, BUS_USB); + if ((i = try_automatic(medias, medias_models)) != -1) { + return do_with_device(medias[i], medias_models[i]); } - if (count == 0) { - if (!already_probed_ide_generic) { - already_probed_ide_generic = 1; - my_insmod("ide_generic", ANY_DRIVER_TYPE, NULL, 0); - return cdrom_prepare(); - } - stg1_error_message("No CDROM device found."); - i = ask_insmod(MEDIA_ADAPTERS); - if (i == RETURN_BACK) - return RETURN_BACK; - return cdrom_prepare(); - } - - if (count == 1) { - results = try_with_device(*medias, *medias_models); - if (results == RETURN_OK) - return RETURN_OK; - i = ask_insmod(MEDIA_ADAPTERS); - if (i == RETURN_BACK) - return RETURN_BACK; - return cdrom_prepare(); - } - - results = ask_from_list_comments("Please choose the CDROM drive to use for the installation.", medias, medias_models, &choice); - if (results == RETURN_OK) { - char ** model = medias_models; - ptr = medias; - while (ptr && *ptr && model && *model) { - if (!strcmp(*ptr, choice)) - break; - ptr++; - model++; - } - results = try_with_device(choice, *model); - } else - return results; - - if (results == RETURN_OK) - return RETURN_OK; - if (results == RETURN_BACK) - return cdrom_prepare(); - - i = ask_insmod(MEDIA_ADAPTERS); - if (i == RETURN_BACK) - return RETURN_BACK; - return cdrom_prepare(); + unset_automatic(); + } else + my_insmod("sr_mod", ANY_DRIVER_TYPE, NULL, 0); + + + get_medias(CDROM, &medias, &medias_models, BUS_ANY); + ptr = medias; + while (ptr && *ptr) { + count++; + ptr++; + } + + if (count == 0) { + if (!already_probed_ide_generic) { + already_probed_ide_generic = 1; + my_insmod("ide_generic", ANY_DRIVER_TYPE, NULL, 0); + return cdrom_prepare(); + } + stg1_error_message("No CDROM device found."); + i = ask_insmod(MEDIA_ADAPTERS); + if (i == RETURN_BACK) + return RETURN_BACK; + return cdrom_prepare(); + } + + if (count == 1) { + results = try_with_device(*medias, *medias_models); + + if (results == RETURN_OK) + return RETURN_OK; + i = ask_insmod(MEDIA_ADAPTERS); + if (i == RETURN_BACK) + return RETURN_BACK; + return cdrom_prepare(); + } + + results = ask_from_list_comments("Please choose the CDROM drive to use for the installation.", medias, medias_models, &choice); + if (results == RETURN_OK) { + char ** model = medias_models; + ptr = medias; + while (ptr && *ptr && model && *model) { + if (!strcmp(*ptr, choice)) + break; + ptr++; + model++; + } + results = try_with_device(choice, *model); + } else + return results; + + if (results == RETURN_OK) + return RETURN_OK; + if (results == RETURN_BACK) + return cdrom_prepare(); + + i = ask_insmod(MEDIA_ADAPTERS); + if (i == RETURN_BACK) + return RETURN_BACK; + return cdrom_prepare(); } diff --git a/mdk-stage1/dhcp.c b/mdk-stage1/dhcp.c index a4cc07446..bec9e24cf 100644 --- a/mdk-stage1/dhcp.c +++ b/mdk-stage1/dhcp.c @@ -57,50 +57,50 @@ typedef int bp_int32; typedef short bp_int16; -#define BOOTP_OPTION_NETMASK 1 -#define BOOTP_OPTION_GATEWAY 3 -#define BOOTP_OPTION_DNS 6 -#define BOOTP_OPTION_HOSTNAME 12 -#define BOOTP_OPTION_DOMAIN 15 -#define BOOTP_OPTION_BROADCAST 28 +#define BOOTP_OPTION_NETMASK 1 +#define BOOTP_OPTION_GATEWAY 3 +#define BOOTP_OPTION_DNS 6 +#define BOOTP_OPTION_HOSTNAME 12 +#define BOOTP_OPTION_DOMAIN 15 +#define BOOTP_OPTION_BROADCAST 28 -#define DHCP_OPTION_REQADDR 50 -#define DHCP_OPTION_LEASE 51 -#define DHCP_OPTION_TYPE 53 -#define DHCP_OPTION_SERVER 54 -#define DHCP_OPTION_OPTIONREQ 55 -#define DHCP_OPTION_MAXSIZE 57 +#define DHCP_OPTION_REQADDR 50 +#define DHCP_OPTION_LEASE 51 +#define DHCP_OPTION_TYPE 53 +#define DHCP_OPTION_SERVER 54 +#define DHCP_OPTION_OPTIONREQ 55 +#define DHCP_OPTION_MAXSIZE 57 -#define DHCP_OPTION_CLIENT_IDENTIFIER 61 +#define DHCP_OPTION_CLIENT_IDENTIFIER 61 -#define BOOTP_CLIENT_PORT 68 -#define BOOTP_SERVER_PORT 67 +#define BOOTP_CLIENT_PORT 68 +#define BOOTP_SERVER_PORT 67 -#define BOOTP_OPCODE_REQUEST 1 -#define BOOTP_OPCODE_REPLY 2 +#define BOOTP_OPCODE_REQUEST 1 +#define BOOTP_OPCODE_REPLY 2 -#define DHCP_TYPE_DISCOVER 1 -#define DHCP_TYPE_OFFER 2 -#define DHCP_TYPE_REQUEST 3 -#define DHCP_TYPE_ACK 5 -#define DHCP_TYPE_RELEASE 7 +#define DHCP_TYPE_DISCOVER 1 +#define DHCP_TYPE_OFFER 2 +#define DHCP_TYPE_REQUEST 3 +#define DHCP_TYPE_ACK 5 +#define DHCP_TYPE_RELEASE 7 -#define BOOTP_VENDOR_LENGTH 64 -#define DHCP_VENDOR_LENGTH 340 +#define BOOTP_VENDOR_LENGTH 64 +#define DHCP_VENDOR_LENGTH 340 struct bootp_request { - char opcode; - char hw; - char hwlength; - char hopcount; - bp_int32 id; - bp_int16 secs; - bp_int16 flags; - bp_int32 ciaddr, yiaddr, server_ip, bootp_gw_ip; - char hwaddr[16]; - char servername[64]; - char bootfile[128]; - char vendor[DHCP_VENDOR_LENGTH]; + char opcode; + char hw; + char hwlength; + char hopcount; + bp_int32 id; + bp_int16 secs; + bp_int16 flags; + bp_int32 ciaddr, yiaddr, server_ip, bootp_gw_ip; + char hwaddr[16]; + char servername[64]; + char bootfile[128]; + char vendor[DHCP_VENDOR_LENGTH]; } ; static const char vendor_cookie[] = { 99, 130, 83, 99, 255 }; @@ -108,396 +108,396 @@ static const char vendor_cookie[] = { 99, 130, 83, 99, 255 }; static unsigned int verify_checksum(void * buf2, int length2) { - unsigned int csum = 0; - unsigned short * sp; + unsigned int csum = 0; + unsigned short * sp; - for (sp = (unsigned short *) buf2; length2 > 0; (length2 -= 2), sp++) - csum += *sp; - - while (csum >> 16) - csum = (csum & 0xffff) + (csum >> 16); + for (sp = (unsigned short *) buf2; length2 > 0; (length2 -= 2), sp++) + csum += *sp; + + while (csum >> 16) + csum = (csum & 0xffff) + (csum >> 16); - return (csum == 0xffff); + return (csum == 0xffff); } static int initial_setup_interface(char * device, int s) { - struct sockaddr_in * addrp; - struct ifreq req; - struct rtentry route; - int true = 1; - - addrp = (struct sockaddr_in *) &req.ifr_addr; - - strcpy(req.ifr_name, device); - addrp->sin_family = AF_INET; - addrp->sin_port = 0; - memset(&addrp->sin_addr, 0, sizeof(addrp->sin_addr)); - - req.ifr_flags = 0; /* take it down */ - if (ioctl(s, SIOCSIFFLAGS, &req)) { - log_perror("SIOCSIFFLAGS (downing)"); - return -1; - } + struct sockaddr_in * addrp; + struct ifreq req; + struct rtentry route; + int true = 1; + + addrp = (struct sockaddr_in *) &req.ifr_addr; + + strcpy(req.ifr_name, device); + addrp->sin_family = AF_INET; + addrp->sin_port = 0; + memset(&addrp->sin_addr, 0, sizeof(addrp->sin_addr)); + + req.ifr_flags = 0; /* take it down */ + if (ioctl(s, SIOCSIFFLAGS, &req)) { + log_perror("SIOCSIFFLAGS (downing)"); + return -1; + } + + addrp->sin_family = AF_INET; + addrp->sin_addr.s_addr = htonl(0); + if (ioctl(s, SIOCSIFADDR, &req)) { + log_perror("SIOCSIFADDR"); + return -1; + } + + req.ifr_flags = IFF_UP | IFF_BROADCAST | IFF_RUNNING; + if (ioctl(s, SIOCSIFFLAGS, &req)) { + log_perror("SIOCSIFFLAGS (upping)"); + return -1; + } + + memset(&route, 0, sizeof(route)); + memcpy(&route.rt_gateway, addrp, sizeof(*addrp)); - addrp->sin_family = AF_INET; - addrp->sin_addr.s_addr = htonl(0); - if (ioctl(s, SIOCSIFADDR, &req)) { - log_perror("SIOCSIFADDR"); - return -1; - } - - req.ifr_flags = IFF_UP | IFF_BROADCAST | IFF_RUNNING; - if (ioctl(s, SIOCSIFFLAGS, &req)) { - log_perror("SIOCSIFFLAGS (upping)"); - return -1; - } - - memset(&route, 0, sizeof(route)); - memcpy(&route.rt_gateway, addrp, sizeof(*addrp)); - - addrp->sin_family = AF_INET; - addrp->sin_port = 0; - addrp->sin_addr.s_addr = INADDR_ANY; - memcpy(&route.rt_dst, addrp, sizeof(*addrp)); - memcpy(&route.rt_genmask, addrp, sizeof(*addrp)); - - route.rt_dev = device; - route.rt_flags = RTF_UP; - route.rt_metric = 0; - - if (ioctl(s, SIOCADDRT, &route)) { - if (errno != EEXIST) { - close(s); - log_perror("SIOCADDRT"); - return -1; - } - } - - if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &true, sizeof(true))) { - close(s); - log_perror("setsockopt"); - return -1; - } - - /* I need to sleep a bit in order for kernel to finish init of the + addrp->sin_family = AF_INET; + addrp->sin_port = 0; + addrp->sin_addr.s_addr = INADDR_ANY; + memcpy(&route.rt_dst, addrp, sizeof(*addrp)); + memcpy(&route.rt_genmask, addrp, sizeof(*addrp)); + + route.rt_dev = device; + route.rt_flags = RTF_UP; + route.rt_metric = 0; + + if (ioctl(s, SIOCADDRT, &route)) { + if (errno != EEXIST) { + close(s); + log_perror("SIOCADDRT"); + return -1; + } + } + + if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &true, sizeof(true))) { + close(s); + log_perror("setsockopt"); + return -1; + } + + /* I need to sleep a bit in order for kernel to finish init of the network device; this would allow to not send further multiple dhcp requests when only one is needed. */ - wait_message("Bringing up networking..."); - sleep(2); - remove_wait_message(); + wait_message("Bringing up networking..."); + sleep(2); + remove_wait_message(); - return 0; + return 0; } void set_missing_ip_info(struct interface_info * intf) { - bp_int32 ipNum = *((bp_int32 *) &intf->ip); - bp_int32 nmNum; + bp_int32 ipNum = *((bp_int32 *) &intf->ip); + bp_int32 nmNum; - if (intf->netmask.s_addr == 0) - inet_aton(guess_netmask(inet_ntoa(intf->ip)), &intf->netmask); + if (intf->netmask.s_addr == 0) + inet_aton(guess_netmask(inet_ntoa(intf->ip)), &intf->netmask); - nmNum = *((bp_int32 *) &intf->netmask); + nmNum = *((bp_int32 *) &intf->netmask); - if (intf->broadcast.s_addr == 0) - *((bp_int32 *) &intf->broadcast) = (ipNum & nmNum) | ~(nmNum); + if (intf->broadcast.s_addr == 0) + *((bp_int32 *) &intf->broadcast) = (ipNum & nmNum) | ~(nmNum); - if (intf->network.s_addr == 0) - *((bp_int32 *) &intf->network) = ipNum & nmNum; + if (intf->network.s_addr == 0) + *((bp_int32 *) &intf->network) = ipNum & nmNum; } static void parse_reply(struct bootp_request * breq, struct interface_info * intf) { - unsigned char * chptr; - unsigned char option, length; + unsigned char * chptr; + unsigned char option, length; - if (breq->bootfile && strlen(breq->bootfile) > 0) { + if (breq->bootfile && strlen(breq->bootfile) > 0) { if (IS_NETAUTO) add_to_env("KICKSTART", breq->bootfile); else log_message("warning: ignoring `bootfile' DHCP server parameter, since `netauto' boot parameter was not given; reboot with `linux netauto' (and anymore useful boot parameters) if you want `bootfile' to be used as a `auto_inst.cfg.pl' stage2 configuration file"); } - - memcpy(&intf->ip, &breq->yiaddr, 4); - - chptr = (unsigned char *) breq->vendor; - chptr += 4; - while (*chptr != 0xFF && (void *) chptr < (void *) breq->vendor + DHCP_VENDOR_LENGTH) { - char tmp_str[500]; - option = *chptr++; - if (!option) - continue; - length = *chptr++; - - switch (option) { - case BOOTP_OPTION_DNS: - memcpy(&dns_server, chptr, sizeof(dns_server)); - log_message("got dns %s", inet_ntoa(dns_server)); - if (length >= sizeof(dns_server)*2) { - memcpy(&dns_server2, chptr+sizeof(dns_server), sizeof(dns_server2)); - log_message("got dns2 %s", inet_ntoa(dns_server2)); - } - break; - - case BOOTP_OPTION_NETMASK: - memcpy(&intf->netmask, chptr, sizeof(intf->netmask)); - log_message("got netmask %s", inet_ntoa(intf->netmask)); - break; - - case BOOTP_OPTION_DOMAIN: - memcpy(tmp_str, chptr, length); - tmp_str[length] = '\0'; - domain = strdup(tmp_str); - log_message("got domain %s", domain); - break; - - case BOOTP_OPTION_BROADCAST: - memcpy(&intf->broadcast, chptr, sizeof(intf->broadcast)); - log_message("got broadcast %s", inet_ntoa(intf->broadcast)); - break; - - case BOOTP_OPTION_GATEWAY: - memcpy(&gateway, chptr, sizeof(gateway)); - log_message("got gateway %s", inet_ntoa(gateway)); - break; - - } - - chptr += length; - } - - set_missing_ip_info(intf); + + memcpy(&intf->ip, &breq->yiaddr, 4); + + chptr = (unsigned char *) breq->vendor; + chptr += 4; + while (*chptr != 0xFF && (void *) chptr < (void *) breq->vendor + DHCP_VENDOR_LENGTH) { + char tmp_str[500]; + option = *chptr++; + if (!option) + continue; + length = *chptr++; + + switch (option) { + case BOOTP_OPTION_DNS: + memcpy(&dns_server, chptr, sizeof(dns_server)); + log_message("got dns %s", inet_ntoa(dns_server)); + if (length >= sizeof(dns_server)*2) { + memcpy(&dns_server2, chptr+sizeof(dns_server), sizeof(dns_server2)); + log_message("got dns2 %s", inet_ntoa(dns_server2)); + } + break; + + case BOOTP_OPTION_NETMASK: + memcpy(&intf->netmask, chptr, sizeof(intf->netmask)); + log_message("got netmask %s", inet_ntoa(intf->netmask)); + break; + + case BOOTP_OPTION_DOMAIN: + memcpy(tmp_str, chptr, length); + tmp_str[length] = '\0'; + domain = strdup(tmp_str); + log_message("got domain %s", domain); + break; + + case BOOTP_OPTION_BROADCAST: + memcpy(&intf->broadcast, chptr, sizeof(intf->broadcast)); + log_message("got broadcast %s", inet_ntoa(intf->broadcast)); + break; + + case BOOTP_OPTION_GATEWAY: + memcpy(&gateway, chptr, sizeof(gateway)); + log_message("got gateway %s", inet_ntoa(gateway)); + break; + + } + + chptr += length; + } + + set_missing_ip_info(intf); } static void init_vendor_codes(struct bootp_request * breq) { - memcpy(breq->vendor, vendor_cookie, sizeof(vendor_cookie)); + memcpy(breq->vendor, vendor_cookie, sizeof(vendor_cookie)); } static char gen_hwaddr[16]; static int prepare_request(struct bootp_request * breq, int sock, char * device) { - struct ifreq req; - - memset(breq, 0, sizeof(*breq)); - - breq->opcode = BOOTP_OPCODE_REQUEST; - - strcpy(req.ifr_name, device); - if (ioctl(sock, SIOCGIFHWADDR, &req)) { - log_perror("SIOCSIFHWADDR"); - return -1; - } - - breq->hw = req.ifr_hwaddr.sa_family; - breq->hwlength = IFHWADDRLEN; - memcpy(breq->hwaddr, req.ifr_hwaddr.sa_data, IFHWADDRLEN); - memcpy(gen_hwaddr, req.ifr_hwaddr.sa_data, IFHWADDRLEN); - - breq->hopcount = 0; - - init_vendor_codes(breq); - - return 0; + struct ifreq req; + + memset(breq, 0, sizeof(*breq)); + + breq->opcode = BOOTP_OPCODE_REQUEST; + + strcpy(req.ifr_name, device); + if (ioctl(sock, SIOCGIFHWADDR, &req)) { + log_perror("SIOCSIFHWADDR"); + return -1; + } + + breq->hw = req.ifr_hwaddr.sa_family; + breq->hwlength = IFHWADDRLEN; + memcpy(breq->hwaddr, req.ifr_hwaddr.sa_data, IFHWADDRLEN); + memcpy(gen_hwaddr, req.ifr_hwaddr.sa_data, IFHWADDRLEN); + + breq->hopcount = 0; + + init_vendor_codes(breq); + + return 0; } static int get_vendor_code(struct bootp_request * bresp, unsigned char option, void * data) { - unsigned char * chptr; - unsigned int length, theOption; - - chptr = (unsigned char*) bresp->vendor + 4; - while (*chptr != 0xFF && *chptr != option) { - theOption = *chptr++; - if (!theOption) - continue; - length = *chptr++; - chptr += length; - } - - if (*chptr++ == 0xff) - return 1; - - length = *chptr++; - memcpy(data, chptr, length); - - return 0; + unsigned char * chptr; + unsigned int length, theOption; + + chptr = (unsigned char*) bresp->vendor + 4; + while (*chptr != 0xFF && *chptr != option) { + theOption = *chptr++; + if (!theOption) + continue; + length = *chptr++; + chptr += length; + } + + if (*chptr++ == 0xff) + return 1; + + length = *chptr++; + memcpy(data, chptr, length); + + return 0; } static unsigned long currticks(void) { - struct timeval tv; - unsigned long csecs; - unsigned long ticks_per_csec, ticks_per_usec; - - /* Note: 18.2 ticks/sec. */ - - gettimeofday (&tv, 0); - csecs = tv.tv_sec / 10; - ticks_per_csec = csecs * 182; - ticks_per_usec = (((tv.tv_sec - csecs * 10) * 1000000 + tv.tv_usec) * 182 / 10000000); - return ticks_per_csec + ticks_per_usec; + struct timeval tv; + unsigned long csecs; + unsigned long ticks_per_csec, ticks_per_usec; + + /* Note: 18.2 ticks/sec. */ + + gettimeofday (&tv, 0); + csecs = tv.tv_sec / 10; + ticks_per_csec = csecs * 182; + ticks_per_usec = (((tv.tv_sec - csecs * 10) * 1000000 + tv.tv_usec) * 182 / 10000000); + return ticks_per_csec + ticks_per_usec; } #define BACKOFF_LIMIT 7 -#define TICKS_PER_SEC 18 -#define MAX_ARP_RETRIES 7 +#define TICKS_PER_SEC 18 +#define MAX_ARP_RETRIES 7 static void rfc951_sleep(int exp) { - static long seed = 0; - long q; - unsigned long tmo; - - if (exp > BACKOFF_LIMIT) - exp = BACKOFF_LIMIT; - - if (!seed) - /* Initialize linear congruential generator. */ - seed = (currticks () + *(long *) &gen_hwaddr + ((short *) gen_hwaddr)[2]); + static long seed = 0; + long q; + unsigned long tmo; + + if (exp > BACKOFF_LIMIT) + exp = BACKOFF_LIMIT; + + if (!seed) + /* Initialize linear congruential generator. */ + seed = (currticks () + *(long *) &gen_hwaddr + ((short *) gen_hwaddr)[2]); - /* Simplified version of the LCG given in Bruce Scheier's - "Applied Cryptography". */ - q = seed / 53668; - if ((seed = 40014 * (seed - 53668 * q) - 12211 * q) < 0) - seed += 2147483563l; - - /* Compute mask. */ - for (tmo = 63; tmo <= 60 * TICKS_PER_SEC && --exp > 0; tmo = 2 * tmo + 1) - ; + /* Simplified version of the LCG given in Bruce Scheier's + "Applied Cryptography". */ + q = seed / 53668; + if ((seed = 40014 * (seed - 53668 * q) - 12211 * q) < 0) + seed += 2147483563l; + + /* Compute mask. */ + for (tmo = 63; tmo <= 60 * TICKS_PER_SEC && --exp > 0; tmo = 2 * tmo + 1) + ; - /* Sleep. */ - log_message("<sleep>"); - - for (tmo = (tmo & seed) + currticks (); currticks () < tmo;); + /* Sleep. */ + log_message("<sleep>"); + + for (tmo = (tmo & seed) + currticks (); currticks () < tmo;); } static int handle_transaction(int s, struct bootp_request * breq, struct bootp_request * bresp, - struct sockaddr_in * server_addr, int dhcp_type) + struct sockaddr_in * server_addr, int dhcp_type) { - struct pollfd polls; - int i, j; - int retry = 1; - int sin; - char eth_packet[ETH_FRAME_LEN]; - struct iphdr * ip_hdr; - struct udphdr * udp_hdr; - unsigned char type; - unsigned long starttime; - int timeout = 1; - - breq->id = starttime = currticks(); - breq->secs = 0; - - sin = socket(AF_PACKET, SOCK_DGRAM, ntohs(ETH_P_IP)); - if (sin < 0) { - log_perror("af_packet socket"); - return -1; - } - - while (retry <= MAX_ARP_RETRIES) { - i = sizeof(*breq); - - if (sendto(s, breq, i, 0, (struct sockaddr *) server_addr, sizeof(*server_addr)) != i) { - close(s); - log_perror("sendto"); - return -1; - } - - polls.fd = sin; - polls.events = POLLIN; - - while (poll(&polls, 1, timeout*1000) == 1) { - - if ((j = recv(sin, eth_packet, sizeof(eth_packet), 0)) == -1) { - log_perror("recv"); - continue; - } - - /* We need to do some basic sanity checking of the header */ - if (j < (signed)(sizeof(*ip_hdr) + sizeof(*udp_hdr))) - continue; - - ip_hdr = (void *) eth_packet; - if (!verify_checksum(ip_hdr, sizeof(*ip_hdr))) - continue; - - if (ntohs(ip_hdr->tot_len) > j) - continue; - - j = ntohs(ip_hdr->tot_len); - - if (ip_hdr->protocol != IPPROTO_UDP) - continue; - - udp_hdr = (void *) (eth_packet + sizeof(*ip_hdr)); - - if (ntohs(udp_hdr->source) != BOOTP_SERVER_PORT) - continue; - - if (ntohs(udp_hdr->dest) != BOOTP_CLIENT_PORT) - continue; - /* Go on with this packet; it looks sane */ - - /* Originally copied sizeof (*bresp) - this is a security - problem due to a potential underflow of the source - buffer. Also, it trusted that the packet was properly - 0xFF terminated, which is not true in the case of the - DHCP server on Cisco 800 series ISDN router. */ - - memset (bresp, 0xFF, sizeof (*bresp)); - memcpy (bresp, (char *) udp_hdr + sizeof (*udp_hdr), j - sizeof (*ip_hdr) - sizeof (*udp_hdr)); - - /* sanity checks */ - if (bresp->id != breq->id) - continue; - if (bresp->opcode != BOOTP_OPCODE_REPLY) - continue; - if (bresp->hwlength != breq->hwlength) - continue; - if (memcmp(bresp->hwaddr, breq->hwaddr, bresp->hwlength)) - continue; - if (get_vendor_code(bresp, DHCP_OPTION_TYPE, &type) || type != dhcp_type) - continue; - if (memcmp(bresp->vendor, vendor_cookie, 4)) - continue; - return 0; - } - rfc951_sleep(retry); - breq->secs = htons ((currticks () - starttime) / 20); - retry++; - timeout *= 2; - if (timeout > 5) - timeout = 5; - } - - return -1; + struct pollfd polls; + int i, j; + int retry = 1; + int sin; + char eth_packet[ETH_FRAME_LEN]; + struct iphdr * ip_hdr; + struct udphdr * udp_hdr; + unsigned char type; + unsigned long starttime; + int timeout = 1; + + breq->id = starttime = currticks(); + breq->secs = 0; + + sin = socket(AF_PACKET, SOCK_DGRAM, ntohs(ETH_P_IP)); + if (sin < 0) { + log_perror("af_packet socket"); + return -1; + } + + while (retry <= MAX_ARP_RETRIES) { + i = sizeof(*breq); + + if (sendto(s, breq, i, 0, (struct sockaddr *) server_addr, sizeof(*server_addr)) != i) { + close(s); + log_perror("sendto"); + return -1; + } + + polls.fd = sin; + polls.events = POLLIN; + + while (poll(&polls, 1, timeout*1000) == 1) { + + if ((j = recv(sin, eth_packet, sizeof(eth_packet), 0)) == -1) { + log_perror("recv"); + continue; + } + + /* We need to do some basic sanity checking of the header */ + if (j < (signed)(sizeof(*ip_hdr) + sizeof(*udp_hdr))) + continue; + + ip_hdr = (void *) eth_packet; + if (!verify_checksum(ip_hdr, sizeof(*ip_hdr))) + continue; + + if (ntohs(ip_hdr->tot_len) > j) + continue; + + j = ntohs(ip_hdr->tot_len); + + if (ip_hdr->protocol != IPPROTO_UDP) + continue; + + udp_hdr = (void *) (eth_packet + sizeof(*ip_hdr)); + + if (ntohs(udp_hdr->source) != BOOTP_SERVER_PORT) + continue; + + if (ntohs(udp_hdr->dest) != BOOTP_CLIENT_PORT) + continue; + /* Go on with this packet; it looks sane */ + + /* Originally copied sizeof (*bresp) - this is a security + problem due to a potential underflow of the source + buffer. Also, it trusted that the packet was properly + 0xFF terminated, which is not true in the case of the + DHCP server on Cisco 800 series ISDN router. */ + + memset (bresp, 0xFF, sizeof (*bresp)); + memcpy (bresp, (char *) udp_hdr + sizeof (*udp_hdr), j - sizeof (*ip_hdr) - sizeof (*udp_hdr)); + + /* sanity checks */ + if (bresp->id != breq->id) + continue; + if (bresp->opcode != BOOTP_OPCODE_REPLY) + continue; + if (bresp->hwlength != breq->hwlength) + continue; + if (memcmp(bresp->hwaddr, breq->hwaddr, bresp->hwlength)) + continue; + if (get_vendor_code(bresp, DHCP_OPTION_TYPE, &type) || type != dhcp_type) + continue; + if (memcmp(bresp->vendor, vendor_cookie, 4)) + continue; + return 0; + } + rfc951_sleep(retry); + breq->secs = htons ((currticks () - starttime) / 20); + retry++; + timeout *= 2; + if (timeout > 5) + timeout = 5; + } + + return -1; } static void add_vendor_code(struct bootp_request * breq, unsigned char option, unsigned char length, void * data) { - unsigned char * chptr; - int theOption, theLength; - - chptr = (unsigned char*) breq->vendor; - chptr += 4; - while (*chptr != 0xFF && *chptr != option) { - theOption = *chptr++; - if (!theOption) continue; - theLength = *chptr++; - chptr += theLength; - } - - *chptr++ = option; - *chptr++ = length; - memcpy(chptr, data, length); - chptr[length] = 0xff; + unsigned char * chptr; + int theOption, theLength; + + chptr = (unsigned char*) breq->vendor; + chptr += 4; + while (*chptr != 0xFF && *chptr != option) { + theOption = *chptr++; + if (!theOption) continue; + theLength = *chptr++; + chptr += theLength; + } + + *chptr++ = option; + *chptr++ = length; + memcpy(chptr, data, length); + chptr[length] = 0xff; } @@ -506,173 +506,173 @@ char * dhcp_domain = NULL; enum return_type perform_dhcp(struct interface_info * intf) { - int s, i; - struct sockaddr_in server_addr; - struct sockaddr_in client_addr; - struct sockaddr_in broadcast_addr; - struct bootp_request breq, bresp; - unsigned char messageType; - unsigned int lease; - short aShort; - int num_options; - char requested_options[50]; - char * client_id_str, * client_id_hwaddr; - - s = socket(AF_INET, SOCK_DGRAM, 0); - if (s < 0) { - log_perror("socket"); - return RETURN_ERROR; - } - - { - enum return_type results; - char * questions[] = { "Host name", "Domain name", NULL }; - char * questions_auto[] = { "hostname", "domain" }; - static char ** answers = NULL; - char * boulet; - - client_id_str = client_id_hwaddr = NULL; - - results = ask_from_entries_auto("If the DHCP server needs to know you by name; please fill in this information. " - "Valid answers are for example: `mybox' for hostname and `mynetwork.com' for " - "domain name, for a machine called `mybox.mynetwork.com' on the Internet.", - questions, &answers, 32, questions_auto, NULL); - if (results == RETURN_OK) - { - dhcp_hostname = answers[0]; - if ((boulet = strchr(dhcp_hostname, '.')) != NULL) - boulet[0] = '\0'; - dhcp_domain = answers[1]; - - if (*dhcp_hostname && *dhcp_domain) { - /* if we have both, then create client id from them */ - client_id_str = malloc(1 + strlen(dhcp_hostname) + 1 + strlen(dhcp_domain) + 1); - client_id_str[0] = '\0'; - sprintf(client_id_str+1, "%s.%s", dhcp_hostname, dhcp_domain); - } - } - } - - if (initial_setup_interface(intf->device, s) != 0) { - close(s); - return RETURN_ERROR; - } - - if (prepare_request(&breq, s, intf->device) != 0) { - close(s); - return RETURN_ERROR; - } - - messageType = DHCP_TYPE_DISCOVER; - add_vendor_code(&breq, DHCP_OPTION_TYPE, 1, &messageType); - - /* add pieces needed to have DDNS/DHCP IP selection based on requested name */ - if (dhcp_hostname && *dhcp_hostname) { /* pick client id form based on absence or presence of domain name */ - if (*dhcp_domain) /* alternate style <hostname>.<domainname> */ - add_vendor_code(&breq, DHCP_OPTION_CLIENT_IDENTIFIER, strlen(client_id_str+1)+1, client_id_str); - else { /* usual style (aka windows / dhcpcd) */ - /* but put MAC in form required for client identifier first */ - client_id_hwaddr = malloc(IFHWADDRLEN+2); - /* (from pump-0.8.22/dhcp.c) - * Microsoft uses a client identifier field of the 802.3 address with a - * pre-byte of a "1". In order to re-use the DHCP address that they set - * for this interface, we have to mimic their identifier. - */ - client_id_hwaddr[0] = 1; /* set flag for ethernet */ - memcpy(client_id_hwaddr+1, gen_hwaddr, IFHWADDRLEN); - add_vendor_code(&breq, DHCP_OPTION_CLIENT_IDENTIFIER, IFHWADDRLEN+1, client_id_hwaddr); - } - /* this is the one that the dhcp server really wants for DDNS updates */ - add_vendor_code(&breq, BOOTP_OPTION_HOSTNAME, strlen(dhcp_hostname), dhcp_hostname); - log_message("DHCP: telling server to use name = %s", dhcp_hostname); - } - - memset(&client_addr.sin_addr, 0, sizeof(&client_addr.sin_addr)); - client_addr.sin_family = AF_INET; - client_addr.sin_port = htons(BOOTP_CLIENT_PORT); /* bootp client */ - - if (bind(s, (struct sockaddr *) &client_addr, sizeof(client_addr))) { - log_perror("bind"); - return RETURN_ERROR; - } - - broadcast_addr.sin_family = AF_INET; - broadcast_addr.sin_port = htons(BOOTP_SERVER_PORT); /* bootp server */ - memset(&broadcast_addr.sin_addr, 0xff, sizeof(broadcast_addr.sin_addr)); /* broadcast */ - - log_message("DHCP: sending DISCOVER"); - - wait_message("Sending DHCP request..."); - i = handle_transaction(s, &breq, &bresp, &broadcast_addr, DHCP_TYPE_OFFER); - remove_wait_message(); - - if (i != 0) { - stg1_error_message("No DHCP reply received."); - close(s); - return RETURN_ERROR; - } - - server_addr.sin_family = AF_INET; - server_addr.sin_port = htons(BOOTP_SERVER_PORT); /* bootp server */ - if (get_vendor_code(&bresp, DHCP_OPTION_SERVER, &server_addr.sin_addr)) { - close(s); - log_message("DHCPOFFER didn't include server address"); - return RETURN_ERROR; - } - - init_vendor_codes(&breq); - messageType = DHCP_TYPE_REQUEST; - add_vendor_code(&breq, DHCP_OPTION_TYPE, 1, &messageType); - add_vendor_code(&breq, DHCP_OPTION_SERVER, 4, &server_addr.sin_addr); - add_vendor_code(&breq, DHCP_OPTION_REQADDR, 4, &bresp.yiaddr); - - /* if used the first time, then have to use it again */ - if (dhcp_hostname && *dhcp_hostname) { /* add pieces needed to have DDNS/DHCP IP selection based on requested name */ - if (dhcp_domain && *dhcp_domain) /* alternate style */ - add_vendor_code(&breq, DHCP_OPTION_CLIENT_IDENTIFIER, strlen(client_id_str+1)+1, client_id_str); - else /* usual style (aka windows / dhcpcd) */ - add_vendor_code(&breq, DHCP_OPTION_CLIENT_IDENTIFIER, IFHWADDRLEN+1, client_id_hwaddr); - /* this is the one that the dhcp server really wants for DDNS updates */ - add_vendor_code(&breq, BOOTP_OPTION_HOSTNAME, strlen(dhcp_hostname), dhcp_hostname); - } - - aShort = ntohs(sizeof(struct bootp_request)); - add_vendor_code(&breq, DHCP_OPTION_MAXSIZE, 2, &aShort); - - num_options = 0; - requested_options[num_options++] = BOOTP_OPTION_NETMASK; - requested_options[num_options++] = BOOTP_OPTION_GATEWAY; - requested_options[num_options++] = BOOTP_OPTION_DNS; - requested_options[num_options++] = BOOTP_OPTION_DOMAIN; - requested_options[num_options++] = BOOTP_OPTION_BROADCAST; - add_vendor_code(&breq, DHCP_OPTION_OPTIONREQ, num_options, requested_options); - - /* request a lease of 1 hour */ - i = htonl(60 * 60); - add_vendor_code(&breq, DHCP_OPTION_LEASE, 4, &i); - - log_message("DHCP: sending REQUEST"); - - i = handle_transaction(s, &breq, &bresp, &broadcast_addr, DHCP_TYPE_ACK); - - if (i != 0) { - close(s); - return RETURN_ERROR; - } - - if (get_vendor_code(&bresp, DHCP_OPTION_LEASE, &lease)) { - log_message("failed to get lease time\n"); - return RETURN_ERROR; - } - lease = ntohl(lease); - - close(s); - - intf->netmask.s_addr = 0; - intf->broadcast.s_addr = 0; - intf->network.s_addr = 0; - - parse_reply(&bresp, intf); - - return RETURN_OK; + int s, i; + struct sockaddr_in server_addr; + struct sockaddr_in client_addr; + struct sockaddr_in broadcast_addr; + struct bootp_request breq, bresp; + unsigned char messageType; + unsigned int lease; + short aShort; + int num_options; + char requested_options[50]; + char * client_id_str, * client_id_hwaddr; + + s = socket(AF_INET, SOCK_DGRAM, 0); + if (s < 0) { + log_perror("socket"); + return RETURN_ERROR; + } + + { + enum return_type results; + char * questions[] = { "Host name", "Domain name", NULL }; + char * questions_auto[] = { "hostname", "domain" }; + static char ** answers = NULL; + char * boulet; + + client_id_str = client_id_hwaddr = NULL; + + results = ask_from_entries_auto("If the DHCP server needs to know you by name; please fill in this information. " + "Valid answers are for example: `mybox' for hostname and `mynetwork.com' for " + "domain name, for a machine called `mybox.mynetwork.com' on the Internet.", + questions, &answers, 32, questions_auto, NULL); + if (results == RETURN_OK) + { + dhcp_hostname = answers[0]; + if ((boulet = strchr(dhcp_hostname, '.')) != NULL) + boulet[0] = '\0'; + dhcp_domain = answers[1]; + + if (*dhcp_hostname && *dhcp_domain) { + /* if we have both, then create client id from them */ + client_id_str = malloc(1 + strlen(dhcp_hostname) + 1 + strlen(dhcp_domain) + 1); + client_id_str[0] = '\0'; + sprintf(client_id_str+1, "%s.%s", dhcp_hostname, dhcp_domain); + } + } + } + + if (initial_setup_interface(intf->device, s) != 0) { + close(s); + return RETURN_ERROR; + } + + if (prepare_request(&breq, s, intf->device) != 0) { + close(s); + return RETURN_ERROR; + } + + messageType = DHCP_TYPE_DISCOVER; + add_vendor_code(&breq, DHCP_OPTION_TYPE, 1, &messageType); + + /* add pieces needed to have DDNS/DHCP IP selection based on requested name */ + if (dhcp_hostname && *dhcp_hostname) { /* pick client id form based on absence or presence of domain name */ + if (*dhcp_domain) /* alternate style <hostname>.<domainname> */ + add_vendor_code(&breq, DHCP_OPTION_CLIENT_IDENTIFIER, strlen(client_id_str+1)+1, client_id_str); + else { /* usual style (aka windows / dhcpcd) */ + /* but put MAC in form required for client identifier first */ + client_id_hwaddr = malloc(IFHWADDRLEN+2); + /* (from pump-0.8.22/dhcp.c) + * Microsoft uses a client identifier field of the 802.3 address with a + * pre-byte of a "1". In order to re-use the DHCP address that they set + * for this interface, we have to mimic their identifier. + */ + client_id_hwaddr[0] = 1; /* set flag for ethernet */ + memcpy(client_id_hwaddr+1, gen_hwaddr, IFHWADDRLEN); + add_vendor_code(&breq, DHCP_OPTION_CLIENT_IDENTIFIER, IFHWADDRLEN+1, client_id_hwaddr); + } + /* this is the one that the dhcp server really wants for DDNS updates */ + add_vendor_code(&breq, BOOTP_OPTION_HOSTNAME, strlen(dhcp_hostname), dhcp_hostname); + log_message("DHCP: telling server to use name = %s", dhcp_hostname); + } + + memset(&client_addr.sin_addr, 0, sizeof(&client_addr.sin_addr)); + client_addr.sin_family = AF_INET; + client_addr.sin_port = htons(BOOTP_CLIENT_PORT); /* bootp client */ + + if (bind(s, (struct sockaddr *) &client_addr, sizeof(client_addr))) { + log_perror("bind"); + return RETURN_ERROR; + } + + broadcast_addr.sin_family = AF_INET; + broadcast_addr.sin_port = htons(BOOTP_SERVER_PORT); /* bootp server */ + memset(&broadcast_addr.sin_addr, 0xff, sizeof(broadcast_addr.sin_addr)); /* broadcast */ + + log_message("DHCP: sending DISCOVER"); + + wait_message("Sending DHCP request..."); + i = handle_transaction(s, &breq, &bresp, &broadcast_addr, DHCP_TYPE_OFFER); + remove_wait_message(); + + if (i != 0) { + stg1_error_message("No DHCP reply received."); + close(s); + return RETURN_ERROR; + } + + server_addr.sin_family = AF_INET; + server_addr.sin_port = htons(BOOTP_SERVER_PORT); /* bootp server */ + if (get_vendor_code(&bresp, DHCP_OPTION_SERVER, &server_addr.sin_addr)) { + close(s); + log_message("DHCPOFFER didn't include server address"); + return RETURN_ERROR; + } + + init_vendor_codes(&breq); + messageType = DHCP_TYPE_REQUEST; + add_vendor_code(&breq, DHCP_OPTION_TYPE, 1, &messageType); + add_vendor_code(&breq, DHCP_OPTION_SERVER, 4, &server_addr.sin_addr); + add_vendor_code(&breq, DHCP_OPTION_REQADDR, 4, &bresp.yiaddr); + + /* if used the first time, then have to use it again */ + if (dhcp_hostname && *dhcp_hostname) { /* add pieces needed to have DDNS/DHCP IP selection based on requested name */ + if (dhcp_domain && *dhcp_domain) /* alternate style */ + add_vendor_code(&breq, DHCP_OPTION_CLIENT_IDENTIFIER, strlen(client_id_str+1)+1, client_id_str); + else /* usual style (aka windows / dhcpcd) */ + add_vendor_code(&breq, DHCP_OPTION_CLIENT_IDENTIFIER, IFHWADDRLEN+1, client_id_hwaddr); + /* this is the one that the dhcp server really wants for DDNS updates */ + add_vendor_code(&breq, BOOTP_OPTION_HOSTNAME, strlen(dhcp_hostname), dhcp_hostname); + } + + aShort = ntohs(sizeof(struct bootp_request)); + add_vendor_code(&breq, DHCP_OPTION_MAXSIZE, 2, &aShort); + + num_options = 0; + requested_options[num_options++] = BOOTP_OPTION_NETMASK; + requested_options[num_options++] = BOOTP_OPTION_GATEWAY; + requested_options[num_options++] = BOOTP_OPTION_DNS; + requested_options[num_options++] = BOOTP_OPTION_DOMAIN; + requested_options[num_options++] = BOOTP_OPTION_BROADCAST; + add_vendor_code(&breq, DHCP_OPTION_OPTIONREQ, num_options, requested_options); + + /* request a lease of 1 hour */ + i = htonl(60 * 60); + add_vendor_code(&breq, DHCP_OPTION_LEASE, 4, &i); + + log_message("DHCP: sending REQUEST"); + + i = handle_transaction(s, &breq, &bresp, &broadcast_addr, DHCP_TYPE_ACK); + + if (i != 0) { + close(s); + return RETURN_ERROR; + } + + if (get_vendor_code(&bresp, DHCP_OPTION_LEASE, &lease)) { + log_message("failed to get lease time\n"); + return RETURN_ERROR; + } + lease = ntohl(lease); + + close(s); + + intf->netmask.s_addr = 0; + intf->broadcast.s_addr = 0; + intf->network.s_addr = 0; + + parse_reply(&bresp, intf); + + return RETURN_OK; } diff --git a/mdk-stage1/directory.c b/mdk-stage1/directory.c index 0538b55b6..e33838035 100644 --- a/mdk-stage1/directory.c +++ b/mdk-stage1/directory.c @@ -34,136 +34,136 @@ char * extract_list_directory(char * direct) { - char ** full = list_directory(direct); - char tmp[20000] = ""; - int i; - for (i=0; i<50 ; i++) { - if (!full || !*full) - break; - strcat(tmp, *full); - strcat(tmp, "\n"); - full++; - } - return strdup(tmp); + char ** full = list_directory(direct); + char tmp[20000] = ""; + int i; + for (i=0; i<50 ; i++) { + if (!full || !*full) + break; + strcat(tmp, *full); + strcat(tmp, "\n"); + full++; + } + return strdup(tmp); } static void choose_iso_in_directory(char *directory, char *location_full) { - char **file; - char *stage2_isos[100] = { "Use directory as a mirror tree", "-----" }; - int stage2_iso_number = 2; - - log_message("\"%s\" exists and is a directory, looking for iso files", directory); - - for (file = list_directory(directory); *file; file++) { - char isofile[500]; - char * loopdev = NULL; - - if (strstr(*file, ".iso") != *file + strlen(*file) - 4) - /* file doesn't end in .iso, skipping */ - continue; - - strcpy(isofile, directory); - strcat(isofile, "/"); - strcat(isofile, *file); - - if (lomount(isofile, LOOP_LOCATION, &loopdev, 0)) { - log_message("unable to mount iso file \"%s\", skipping", isofile); - continue; - } - symlink(LOOP_LOCATION_REL "/" ARCH, IMAGE_LOCATION); - - if (image_has_stage2()) { - log_message("stage2 installer found in ISO image \"%s\"", isofile); - stage2_isos[stage2_iso_number++] = strdup(*file); - } else { - log_message("ISO image \"%s\" doesn't contain stage2 installer", isofile); - } - - unlink(IMAGE_LOCATION); - umount(LOOP_LOCATION); - del_loop(loopdev); - } - - stage2_isos[stage2_iso_number] = NULL; - - if (stage2_iso_number > 2) { - enum return_type results; - do { - results = ask_from_list("Please choose the ISO image to be used to install the " - DISTRIB_NAME " Distribution.", - stage2_isos, file); - if (results == RETURN_BACK) { - return; - } else if (results == RETURN_OK) { - if (!strcmp(*file, stage2_isos[0])) { - /* use directory as a mirror tree */ - continue; - } else if (!strcmp(*file, stage2_isos[1])) { - /* the separator has been selected */ - results = RETURN_ERROR; - continue; - } else { - /* use selected ISO image */ - strcat(location_full, "/"); - strcat(location_full, *file); - log_message("installer will use ISO image \"%s\"", location_full); - } - } - } while (results == RETURN_ERROR); - } else { - log_message("no ISO image found in \"%s\" directory", location_full); - } + char **file; + char *stage2_isos[100] = { "Use directory as a mirror tree", "-----" }; + int stage2_iso_number = 2; + + log_message("\"%s\" exists and is a directory, looking for iso files", directory); + + for (file = list_directory(directory); *file; file++) { + char isofile[500]; + char * loopdev = NULL; + + if (strstr(*file, ".iso") != *file + strlen(*file) - 4) + /* file doesn't end in .iso, skipping */ + continue; + + strcpy(isofile, directory); + strcat(isofile, "/"); + strcat(isofile, *file); + + if (lomount(isofile, LOOP_LOCATION, &loopdev, 0)) { + log_message("unable to mount iso file \"%s\", skipping", isofile); + continue; + } + symlink(LOOP_LOCATION_REL "/" ARCH, IMAGE_LOCATION); + + if (image_has_stage2()) { + log_message("stage2 installer found in ISO image \"%s\"", isofile); + stage2_isos[stage2_iso_number++] = strdup(*file); + } else { + log_message("ISO image \"%s\" doesn't contain stage2 installer", isofile); + } + + unlink(IMAGE_LOCATION); + umount(LOOP_LOCATION); + del_loop(loopdev); + } + + stage2_isos[stage2_iso_number] = NULL; + + if (stage2_iso_number > 2) { + enum return_type results; + do { + results = ask_from_list("Please choose the ISO image to be used to install the " + DISTRIB_NAME " Distribution.", + stage2_isos, file); + if (results == RETURN_BACK) { + return; + } else if (results == RETURN_OK) { + if (!strcmp(*file, stage2_isos[0])) { + /* use directory as a mirror tree */ + continue; + } else if (!strcmp(*file, stage2_isos[1])) { + /* the separator has been selected */ + results = RETURN_ERROR; + continue; + } else { + /* use selected ISO image */ + strcat(location_full, "/"); + strcat(location_full, *file); + log_message("installer will use ISO image \"%s\"", location_full); + } + } + } while (results == RETURN_ERROR); + } else { + log_message("no ISO image found in \"%s\" directory", location_full); + } } enum return_type try_with_directory(char *directory, char *method_live, char *method_iso) { - char location_full[500]; + char location_full[500]; char * loopdev = NULL; - struct stat statbuf; - enum return_type ret = RETURN_OK; - - unlink(IMAGE_LOCATION); - strcpy(location_full, directory); - - if (!stat(directory, &statbuf) && S_ISDIR(statbuf.st_mode)) { - choose_iso_in_directory(directory, location_full); - } - - loopdev = NULL; - if (!stat(location_full, &statbuf) && !S_ISDIR(statbuf.st_mode)) { - log_message("%s exists and is not a directory, assuming this is an ISO image", location_full); - if (lomount(location_full, LOOP_LOCATION, &loopdev, 0)) { - stg1_error_message("Could not mount file %s as an ISO image of the " DISTRIB_NAME " Distribution.", location_full); - return RETURN_ERROR; - } - symlink(LOOP_LOCATION_REL "/" ARCH, IMAGE_LOCATION); - add_to_env("ISOPATH", location_full); - add_to_env("METHOD", method_iso); - } else { - create_IMAGE_LOCATION(location_full); - add_to_env("METHOD", method_live); - } - - if (access(IMAGE_LOCATION "/" COMPRESSED_LOCATION_REL, R_OK)) { - stg1_error_message("I can't find the " DISTRIB_NAME " Distribution in the specified directory. " - "(I need the subdirectory " COMPRESSED_LOCATION_REL ")\n" - "Here's a short extract of the files in the directory:\n" - "%s", extract_list_directory(IMAGE_LOCATION)); - ret = RETURN_BACK; - } else if (may_load_compressed_image() != RETURN_OK) { - stg1_error_message("Could not load program into memory."); - ret = RETURN_ERROR; - } - - if (ret == RETURN_OK) - log_message("found the " DISTRIB_NAME " Installation, good news!"); - - if (!KEEP_MOUNTED || ret != RETURN_OK) { - /* in rescue mode, we don't need the media anymore */ - umount(LOOP_LOCATION); - del_loop(loopdev); - } - - return ret; + struct stat statbuf; + enum return_type ret = RETURN_OK; + + unlink(IMAGE_LOCATION); + strcpy(location_full, directory); + + if (!stat(directory, &statbuf) && S_ISDIR(statbuf.st_mode)) { + choose_iso_in_directory(directory, location_full); + } + + loopdev = NULL; + if (!stat(location_full, &statbuf) && !S_ISDIR(statbuf.st_mode)) { + log_message("%s exists and is not a directory, assuming this is an ISO image", location_full); + if (lomount(location_full, LOOP_LOCATION, &loopdev, 0)) { + stg1_error_message("Could not mount file %s as an ISO image of the " DISTRIB_NAME " Distribution.", location_full); + return RETURN_ERROR; + } + symlink(LOOP_LOCATION_REL "/" ARCH, IMAGE_LOCATION); + add_to_env("ISOPATH", location_full); + add_to_env("METHOD", method_iso); + } else { + create_IMAGE_LOCATION(location_full); + add_to_env("METHOD", method_live); + } + + if (access(IMAGE_LOCATION "/" COMPRESSED_LOCATION_REL, R_OK)) { + stg1_error_message("I can't find the " DISTRIB_NAME " Distribution in the specified directory. " + "(I need the subdirectory " COMPRESSED_LOCATION_REL ")\n" + "Here's a short extract of the files in the directory:\n" + "%s", extract_list_directory(IMAGE_LOCATION)); + ret = RETURN_BACK; + } else if (may_load_compressed_image() != RETURN_OK) { + stg1_error_message("Could not load program into memory."); + ret = RETURN_ERROR; + } + + if (ret == RETURN_OK) + log_message("found the " DISTRIB_NAME " Installation, good news!"); + + if (!KEEP_MOUNTED || ret != RETURN_OK) { + /* in rescue mode, we don't need the media anymore */ + umount(LOOP_LOCATION); + del_loop(loopdev); + } + + return ret; } diff --git a/mdk-stage1/disk.c b/mdk-stage1/disk.c index 804c8ea2b..c324a01f2 100644 --- a/mdk-stage1/disk.c +++ b/mdk-stage1/disk.c @@ -43,79 +43,79 @@ #include "disk.h" static enum return_type try_automatic_with_partition(char *dev) { - enum return_type results; - int mounted; - wait_message("Trying to access " DISTRIB_NAME " disk (partition %s)", dev); - mounted = !try_mount(dev, MEDIA_LOCATION); - remove_wait_message(); - if (mounted) { - create_IMAGE_LOCATION(MEDIA_LOCATION); - if (image_has_stage2()) { - results = try_with_directory(MEDIA_LOCATION, "disk", "disk-iso"); - if (results == RETURN_OK) { - if (!KEEP_MOUNTED) - umount(MEDIA_LOCATION); - return RETURN_OK; - } - } - } - if (mounted) - umount(MEDIA_LOCATION); - return RETURN_ERROR; + enum return_type results; + int mounted; + wait_message("Trying to access " DISTRIB_NAME " disk (partition %s)", dev); + mounted = !try_mount(dev, MEDIA_LOCATION); + remove_wait_message(); + if (mounted) { + create_IMAGE_LOCATION(MEDIA_LOCATION); + if (image_has_stage2()) { + results = try_with_directory(MEDIA_LOCATION, "disk", "disk-iso"); + if (results == RETURN_OK) { + if (!KEEP_MOUNTED) + umount(MEDIA_LOCATION); + return RETURN_OK; + } + } + } + if (mounted) + umount(MEDIA_LOCATION); + return RETURN_ERROR; } static enum return_type try_automatic_with_disk(char *disk, char *model) { - char * parts[50]; - char * parts_comments[50]; - enum return_type results; - char **dev; - wait_message("Trying to access " DISTRIB_NAME " disk (drive %s)", model); - if (list_partitions(disk, parts, parts_comments)) { - stg1_error_message("Could not read partitions information."); - return RETURN_ERROR; - } - remove_wait_message(); - dev = parts; - while (dev && *dev) { - results = try_automatic_with_partition(*dev); - if (results == RETURN_OK) { - return RETURN_OK; - } - dev++; - } - return RETURN_ERROR; + char * parts[50]; + char * parts_comments[50]; + enum return_type results; + char **dev; + wait_message("Trying to access " DISTRIB_NAME " disk (drive %s)", model); + if (list_partitions(disk, parts, parts_comments)) { + stg1_error_message("Could not read partitions information."); + return RETURN_ERROR; + } + remove_wait_message(); + dev = parts; + while (dev && *dev) { + results = try_automatic_with_partition(*dev); + if (results == RETURN_OK) { + return RETURN_OK; + } + dev++; + } + return RETURN_ERROR; } static enum return_type try_automatic(char ** medias, char ** medias_models) { - char ** model = medias_models; - char ** ptr = medias; - while (ptr && *ptr) { - enum return_type results; - results = try_automatic_with_disk(*ptr, *model); - if (results == RETURN_OK) - return RETURN_OK; - ptr++; - model++; - } - return RETURN_ERROR; + char ** model = medias_models; + char ** ptr = medias; + while (ptr && *ptr) { + enum return_type results; + results = try_automatic_with_disk(*ptr, *model); + if (results == RETURN_OK) + return RETURN_OK; + ptr++; + model++; + } + return RETURN_ERROR; } static enum return_type try_with_device(char *dev_name) { - char * questions_location[] = { "Directory or ISO images directory or ISO image", NULL }; - char * questions_location_auto[] = { "directory", NULL }; - static char ** answers_location = NULL; - char location_full[500]; - - char * parts[50]; - char * parts_comments[50]; - enum return_type results; - char * choice; + char * questions_location[] = { "Directory or ISO images directory or ISO image", NULL }; + char * questions_location_auto[] = { "directory", NULL }; + static char ** answers_location = NULL; + char location_full[500]; + + char * parts[50]; + char * parts_comments[50]; + enum return_type results; + char * choice; if (list_partitions(dev_name, parts, parts_comments)) { - stg1_error_message("Could not read partitions information."); - return RETURN_ERROR; + stg1_error_message("Could not read partitions information."); + return RETURN_ERROR; } /* uglyness to allow auto starting with devfs */ @@ -126,103 +126,103 @@ static enum return_type try_with_device(char *dev_name) } results = ask_from_list_comments_auto("Please select the partition containing the copy of the " - DISTRIB_NAME " Distribution install source.", + DISTRIB_NAME " Distribution install source.", parts, parts_comments, &choice, "partition", parts); if (results != RETURN_OK) return results; } - /* in testing mode, assume the partition is already mounted on MEDIA_LOCATION */ + /* in testing mode, assume the partition is already mounted on MEDIA_LOCATION */ if (!IS_TESTING && try_mount(choice, MEDIA_LOCATION)) { - stg1_error_message("I can't find a valid filesystem (tried: ext2, vfat, ntfs, reiserfs). " + stg1_error_message("I can't find a valid filesystem (tried: ext2, vfat, ntfs, reiserfs). " "Make sure the partition has been cleanly unmounted."); - return try_with_device(dev_name); - } + return try_with_device(dev_name); + } ask_dir: - if (ask_from_entries_auto("Please enter the directory (or ISO image file) containing the " - DISTRIB_NAME " Distribution install source.", - questions_location, &answers_location, 24, questions_location_auto, NULL) != RETURN_OK) { - umount(MEDIA_LOCATION); - return try_with_device(dev_name); - } - - strcpy(location_full, MEDIA_LOCATION); - strcat(location_full, "/"); - strcat(location_full, answers_location[0]); - - if (access(location_full, R_OK)) { - char * path = strdup(answers_location[0]); - stg1_error_message("Directory or ISO image file could not be found on partition.\n" - "Here's a short extract of the files in the directory %s:\n" - "%s", my_dirname(path), extract_list_directory(my_dirname(location_full))); - free(path); - goto ask_dir; - } - - results = try_with_directory(location_full, "disk", "disk-iso"); - if (results != RETURN_OK) { - goto ask_dir; - } - - if (!KEEP_MOUNTED) - umount(MEDIA_LOCATION); - - return RETURN_OK; + if (ask_from_entries_auto("Please enter the directory (or ISO image file) containing the " + DISTRIB_NAME " Distribution install source.", + questions_location, &answers_location, 24, questions_location_auto, NULL) != RETURN_OK) { + umount(MEDIA_LOCATION); + return try_with_device(dev_name); + } + + strcpy(location_full, MEDIA_LOCATION); + strcat(location_full, "/"); + strcat(location_full, answers_location[0]); + + if (access(location_full, R_OK)) { + char * path = strdup(answers_location[0]); + stg1_error_message("Directory or ISO image file could not be found on partition.\n" + "Here's a short extract of the files in the directory %s:\n" + "%s", my_dirname(path), extract_list_directory(my_dirname(location_full))); + free(path); + goto ask_dir; + } + + results = try_with_directory(location_full, "disk", "disk-iso"); + if (results != RETURN_OK) { + goto ask_dir; + } + + if (!KEEP_MOUNTED) + umount(MEDIA_LOCATION); + + return RETURN_OK; } enum return_type disk_prepare(void) { - char ** medias, ** medias_models; - char * choice; - int i; - enum return_type results; - static int already_probed_ide_generic = 0; + char ** medias, ** medias_models; + char * choice; + int i; + enum return_type results; + static int already_probed_ide_generic = 0; int count = get_disks(&medias, &medias_models); - if (IS_AUTOMATIC) { - results = try_automatic(medias, medias_models); - if (results != RETURN_ERROR) - return results; - unset_automatic(); + if (IS_AUTOMATIC) { + results = try_automatic(medias, medias_models); + if (results != RETURN_ERROR) + return results; + unset_automatic(); } - if (count == 0) { - if (!already_probed_ide_generic) { - already_probed_ide_generic = 1; - my_insmod("ide_generic", ANY_DRIVER_TYPE, NULL, 0); - return disk_prepare(); - } - stg1_error_message("No DISK drive found."); - i = ask_insmod(MEDIA_ADAPTERS); - if (i == RETURN_BACK) - return RETURN_BACK; - return disk_prepare(); - } - - if (count == 1) { - results = try_with_device(*medias); - if (results != RETURN_ERROR) - return results; - i = ask_insmod(MEDIA_ADAPTERS); - if (i == RETURN_BACK) - return RETURN_BACK; - return disk_prepare(); - } - - results = ask_from_list_comments_auto("Please select the disk containing the copy of the " - DISTRIB_NAME " Distribution install source.", - medias, medias_models, &choice, "disk", medias); - - if (results != RETURN_OK) - return results; - - results = try_with_device(choice); - if (results != RETURN_ERROR) - return results; - i = ask_insmod(MEDIA_ADAPTERS); - if (i == RETURN_BACK) - return RETURN_BACK; - return disk_prepare(); + if (count == 0) { + if (!already_probed_ide_generic) { + already_probed_ide_generic = 1; + my_insmod("ide_generic", ANY_DRIVER_TYPE, NULL, 0); + return disk_prepare(); + } + stg1_error_message("No DISK drive found."); + i = ask_insmod(MEDIA_ADAPTERS); + if (i == RETURN_BACK) + return RETURN_BACK; + return disk_prepare(); + } + + if (count == 1) { + results = try_with_device(*medias); + if (results != RETURN_ERROR) + return results; + i = ask_insmod(MEDIA_ADAPTERS); + if (i == RETURN_BACK) + return RETURN_BACK; + return disk_prepare(); + } + + results = ask_from_list_comments_auto("Please select the disk containing the copy of the " + DISTRIB_NAME " Distribution install source.", + medias, medias_models, &choice, "disk", medias); + + if (results != RETURN_OK) + return results; + + results = try_with_device(choice); + if (results != RETURN_ERROR) + return results; + i = ask_insmod(MEDIA_ADAPTERS); + if (i == RETURN_BACK) + return RETURN_BACK; + return disk_prepare(); } diff --git a/mdk-stage1/dns.c b/mdk-stage1/dns.c index 488b4844e..36fb0f187 100644 --- a/mdk-stage1/dns.c +++ b/mdk-stage1/dns.c @@ -39,58 +39,46 @@ int mygethostbyname(char * name, struct in_addr * addr) { - struct addrinfo hints, *res, *p; - int status; - char ipstr[INET6_ADDRSTRLEN]; + struct hostent * h; - memset(&hints, 0, sizeof hints); - hints.ai_family = AF_INET; //AF_UNSPEC for both IPv4 & IPv6 - hints.ai_socktype = SOCK_STREAM; + /* prevent from timeouts */ + if (_res.nscount == 0) + return -1; - /* prevent from timeouts */ - if (_res.nscount == 0) - return -1; + h = gethostbyname(name); - if ((status = getaddrinfo(name, NULL, &hints, &res)) != 0) { - log_message("getaddrinfo: %s\n", gai_strerror(status)); - return -1; - } + if (!h && domain) { + // gethostbyname from dietlibc doesn't support domain handling + char fully_qualified[500]; + sprintf(fully_qualified, "%s.%s", name, domain); + h = gethostbyname(fully_qualified); + } - for (p = res;p != NULL; p = p->ai_next) { - void *tmp_addr; + if (h && h->h_addr_list && (h->h_addr_list)[0]) { + memcpy(addr, (h->h_addr_list)[0], sizeof(*addr)); + log_message("is-at: %s", inet_ntoa(*addr)); + return 0; + } - struct sockaddr_in *ipv = (struct sockaddr_in *)p->ai_addr; - tmp_addr = &(ipv->sin_addr); - - /* convert the IP to a string: */ - inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr); - - memcpy(addr, tmp_addr, sizeof(*addr)); - log_message("is-at: %s\n", inet_ntoa(*addr)); - } - - freeaddrinfo(res); // free the linked list - return 0; + log_message("unknown host %s", name); + return -1; } char * mygethostbyaddr(char * ipnum) { - struct sockaddr_in sa; - char hbuf[NI_MAXHOST]; + struct in_addr in; + struct hostent * host; /* prevent from timeouts */ if (_res.nscount == 0) return NULL; - - memset(&sa, 0, sizeof sa); - sa.sin_family = AF_INET; - - if (inet_pton(AF_INET, ipnum, &sa.sin_addr) != 1) - return NULL; - if (getnameinfo((struct sockaddr*)&sa, sizeof(sa), hbuf, sizeof(hbuf), NULL, 0, 0 |NI_NAMEREQD) == 0) //NI_NUMERICHOST NI_NAMEREQD - return strdup(hbuf); - else return NULL; + if (!inet_aton(ipnum, &in)) + return NULL; + host = gethostbyaddr(&(in.s_addr), sizeof(in.s_addr) /* INADDRSZ */, AF_INET); + if (host && host->h_name) + return host->h_name; + return NULL; } #elif defined(__GLIBC__) @@ -117,116 +105,116 @@ union dns_response { static int do_query(char * query, int queryType, char ** domainName, struct in_addr * ipNum) { - int len, ancount, type; - u_char * data, * end; - char name[MAXDNAME]; - union dns_response response; - + int len, ancount, type; + u_char * data, * end; + char name[MAXDNAME]; + union dns_response response; + #ifdef __sparc__ - /* from jj: */ - /* We have to wait till ethernet negotiation is done */ - _res.retry = 3; + /* from jj: */ + /* We have to wait till ethernet negotiation is done */ + _res.retry = 3; #else - _res.retry = 2; + _res.retry = 2; #endif - len = res_search(query, C_IN, queryType, (void *) &response, sizeof(response)); - if (len <= 0) - return -1; - - if (ntohs(response.hdr.rcode) != NOERROR) - return -1; - - ancount = ntohs(response.hdr.ancount); - if (ancount < 1) - return -1; - - data = response.buf + sizeof(HEADER); - end = response.buf + len; - - /* skip the question */ - data += dn_skipname(data, end) + QFIXEDSZ; - - /* parse the answer(s) */ - while (--ancount >= 0 && data < end) { - - /* skip the domain name portion of the RR record */ - data += dn_skipname(data, end); - - /* get RR information */ - GETSHORT(type, data); - data += INT16SZ; /* skipp class */ - data += INT32SZ; /* skipp TTL */ - GETSHORT(len, data); - - if (type == T_PTR) { - /* we got a pointer */ - len = dn_expand(response.buf, end, data, name, sizeof(name)); - if (len <= 0) return -1; - if (queryType == T_PTR && domainName) { - /* we wanted a pointer */ - *domainName = malloc(strlen(name) + 1); - strcpy(*domainName, name); - return 0; - } - } else if (type == T_A) { - /* we got an address */ - if (queryType == T_A && ipNum) { - /* we wanted an address */ - memcpy(ipNum, data, sizeof(*ipNum)); - return 0; - } - } - - /* move ahead to next RR */ - data += len; - } - - return -1; + len = res_search(query, C_IN, queryType, (void *) &response, sizeof(response)); + if (len <= 0) + return -1; + + if (ntohs(response.hdr.rcode) != NOERROR) + return -1; + + ancount = ntohs(response.hdr.ancount); + if (ancount < 1) + return -1; + + data = response.buf + sizeof(HEADER); + end = response.buf + len; + + /* skip the question */ + data += dn_skipname(data, end) + QFIXEDSZ; + + /* parse the answer(s) */ + while (--ancount >= 0 && data < end) { + + /* skip the domain name portion of the RR record */ + data += dn_skipname(data, end); + + /* get RR information */ + GETSHORT(type, data); + data += INT16SZ; /* skipp class */ + data += INT32SZ; /* skipp TTL */ + GETSHORT(len, data); + + if (type == T_PTR) { + /* we got a pointer */ + len = dn_expand(response.buf, end, data, name, sizeof(name)); + if (len <= 0) return -1; + if (queryType == T_PTR && domainName) { + /* we wanted a pointer */ + *domainName = malloc(strlen(name) + 1); + strcpy(*domainName, name); + return 0; + } + } else if (type == T_A) { + /* we got an address */ + if (queryType == T_A && ipNum) { + /* we wanted an address */ + memcpy(ipNum, data, sizeof(*ipNum)); + return 0; + } + } + + /* move ahead to next RR */ + data += len; + } + + return -1; } char * mygethostbyaddr(char * ipnum) { - int rc; - char * result; - char * strbuf; - char * chptr; - char * splits[4]; - int i; - - _res.retry = 1; - - strbuf = alloca(strlen(ipnum) + 1); - strcpy(strbuf, ipnum); - - ipnum = alloca(strlen(strbuf) + 20); - - for (i = 0; i < 4; i++) { - chptr = strbuf; - while (*chptr && *chptr != '.') - chptr++; - *chptr = '\0'; - - if (chptr - strbuf > 3) return NULL; - splits[i] = strbuf; - strbuf = chptr + 1; - } - - sprintf(ipnum, "%s.%s.%s.%s.in-addr.arpa", splits[3], splits[2], splits[1], splits[0]); - - rc = do_query(ipnum, T_PTR, &result, NULL); - - if (rc) - return NULL; - else - return result; + int rc; + char * result; + char * strbuf; + char * chptr; + char * splits[4]; + int i; + + _res.retry = 1; + + strbuf = alloca(strlen(ipnum) + 1); + strcpy(strbuf, ipnum); + + ipnum = alloca(strlen(strbuf) + 20); + + for (i = 0; i < 4; i++) { + chptr = strbuf; + while (*chptr && *chptr != '.') + chptr++; + *chptr = '\0'; + + if (chptr - strbuf > 3) return NULL; + splits[i] = strbuf; + strbuf = chptr + 1; + } + + sprintf(ipnum, "%s.%s.%s.%s.in-addr.arpa", splits[3], splits[2], splits[1], splits[0]); + + rc = do_query(ipnum, T_PTR, &result, NULL); + + if (rc) + return NULL; + else + return result; } int mygethostbyname(char * name, struct in_addr * addr) { - int rc = do_query(name, T_A, NULL, addr); - if (!rc) - log_message("is-at %s", inet_ntoa(*addr)); - return rc; + int rc = do_query(name, T_A, NULL, addr); + if (!rc) + log_message("is-at %s", inet_ntoa(*addr)); + return rc; } #else diff --git a/mdk-stage1/frontend-common.c b/mdk-stage1/frontend-common.c index cdc972740..32a0127aa 100644 --- a/mdk-stage1/frontend-common.c +++ b/mdk-stage1/frontend-common.c @@ -23,42 +23,42 @@ void info_message(char *msg, ...) { - va_list args; - va_start(args, msg); - vinfo_message(msg, args); - va_end(args); + va_list args; + va_start(args, msg); + vinfo_message(msg, args); + va_end(args); } void wait_message(char *msg, ...) { - va_list args; - va_start(args, msg); - vwait_message(msg, args); - va_end(args); + va_list args; + va_start(args, msg); + vwait_message(msg, args); + va_end(args); } void error_message(char *msg, ...) { - va_list args; - va_start(args, msg); - verror_message(msg, args); - va_end(args); + va_list args; + va_start(args, msg); + verror_message(msg, args); + va_end(args); } enum return_type ask_from_list_comments(char *msg, char ** elems, char ** elems_comments, char ** choice) { - int answer = 0; - enum return_type results; + int answer = 0; + enum return_type results; - results = ask_from_list_index(msg, elems, elems_comments, &answer); + results = ask_from_list_index(msg, elems, elems_comments, &answer); - if (results == RETURN_OK) - *choice = strdup(elems[answer]); + if (results == RETURN_OK) + *choice = strdup(elems[answer]); - return results; + return results; } enum return_type ask_from_list(char *msg, char ** elems, char ** choice) { - return ask_from_list_comments(msg, elems, NULL, choice); + return ask_from_list_comments(msg, elems, NULL, choice); } diff --git a/mdk-stage1/init.c b/mdk-stage1/init.c index af6aefd2a..937549120 100644 --- a/mdk-stage1/init.c +++ b/mdk-stage1/init.c @@ -40,19 +40,19 @@ #include <sys/syscall.h> #define syslog(...) syscall(__NR_syslog, __VA_ARGS__) -#define LINUX_REBOOT_MAGIC1 0xfee1dead -#define LINUX_REBOOT_MAGIC2 672274793 -#define BMAGIC_HARD 0x89ABCDEF -#define BMAGIC_SOFT 0 -#define BMAGIC_REBOOT 0x01234567 -#define BMAGIC_HALT 0xCDEF0123 -#define BMAGIC_POWEROFF 0x4321FEDC +#define LINUX_REBOOT_MAGIC1 0xfee1dead +#define LINUX_REBOOT_MAGIC2 672274793 +#define BMAGIC_HARD 0x89ABCDEF +#define BMAGIC_SOFT 0 +#define BMAGIC_REBOOT 0x01234567 +#define BMAGIC_HALT 0xCDEF0123 +#define BMAGIC_POWEROFF 0x4321FEDC static unsigned int reboot_magic = BMAGIC_REBOOT; static inline long reboot(unsigned int command) { - return (long) syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, command, 0); + return (long) syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, command, 0); } #include "config-stage1.h" @@ -68,27 +68,26 @@ static inline long reboot(unsigned int command) char * env[] = { - "PATH=/usr/bin:/bin:/sbin:/usr/sbin:/mnt/sbin:/mnt/usr/sbin:/mnt/bin:/mnt/usr/bin", - "LD_LIBRARY_PATH=/lib:/usr/lib:/mnt/lib:/mnt/usr/lib:/usr/X11R6/lib:/mnt/usr/X11R6/lib" + "PATH=/usr/bin:/bin:/sbin:/usr/sbin:/mnt/sbin:/mnt/usr/sbin:/mnt/bin:/mnt/usr/bin", + "LD_LIBRARY_PATH=/lib:/usr/lib:/mnt/lib:/mnt/usr/lib:/usr/X11R6/lib:/mnt/usr/X11R6/lib" #if defined(__x86_64__) || defined(__ppc64__) - ":/lib64:/usr/lib64:/usr/X11R6/lib64:/mnt/lib64:/mnt/usr/lib64:/mnt/usr/X11R6/lib64" + ":/lib64:/usr/lib64:/usr/X11R6/lib64:/mnt/lib64:/mnt/usr/lib64:/mnt/usr/X11R6/lib64" #endif - , - "HOME=/", - "TERM=linux", - "TERMINFO=/etc/terminfo", - "LC_CTYPE=UTF-8", - NULL + , + "HOME=/", + "TERM=screen", + "TERMINFO=/etc/terminfo", + NULL }; /* * this needs to handle the following cases: * - * 1) run from a CD root filesystem - * 2) run from a read only nfs rooted filesystem + * 1) run from a CD root filesystem + * 2) run from a read only nfs rooted filesystem * 3) run from a floppy - * 4) run from a floppy that's been loaded into a ramdisk + * 4) run from a floppy that's been loaded into a ramdisk * */ @@ -98,45 +97,45 @@ int klog_pid; void fatal_error(char *msg) { - printf("FATAL ERROR IN INIT: %s\n\nI can't recover from this, please reboot manually and send bugreport.\n", msg); + printf("FATAL ERROR IN INIT: %s\n\nI can't recover from this, please reboot manually and send bugreport.\n", msg); select(0, NULL, NULL, NULL, NULL); } void print_error(char *msg) { - printf("E: %s\n", msg); + printf("E: %s\n", msg); } void print_warning(char *msg) { - printf("W: %s\n", msg); + printf("W: %s\n", msg); } void print_int_init(int fd, int i) { - char buf[10]; - char * chptr = buf + 9; - int j = 0; - - if (i < 0) - { - write(1, "-", 1); - i = -1 * i; - } - - while (i) - { - *chptr-- = '0' + (i % 10); - j++; - i = i / 10; - } - - write(fd, chptr + 1, j); + char buf[10]; + char * chptr = buf + 9; + int j = 0; + + if (i < 0) + { + write(1, "-", 1); + i = -1 * i; + } + + while (i) + { + *chptr-- = '0' + (i % 10); + j++; + i = i / 10; + } + + write(fd, chptr + 1, j); } void print_str_init(int fd, char * string) { - write(fd, string, strlen(string)); + write(fd, string, strlen(string)); } /* fork to: @@ -145,114 +144,115 @@ void print_str_init(int fd, char * string) */ void doklog() { - fd_set readset, unixs; - int in, out, i; - int log; - socklen_t s; - int sock = -1; - struct sockaddr_un sockaddr; - char buf[1024]; - int readfd; - - /* open kernel message logger */ - in = open("/proc/kmsg", O_RDONLY,0); - if (in < 0) { - print_error("could not open /proc/kmsg"); - return; - } - - if ((log = open("/tmp/syslog", O_WRONLY | O_CREAT | O_APPEND, 0644)) < 0) { - print_error("error opening /tmp/syslog"); - sleep(5); - return; - } - - if ((klog_pid = fork())) { - close(in); - close(log); - return; - } else { - close(0); - close(1); - close(2); - } - - out = open("/dev/tty4", O_WRONLY, 0); - if (out < 0) - print_warning("couldn't open tty for syslog -- still using /tmp/syslog\n"); - - /* now open the syslog socket */ + fd_set readset, unixs; + int in, out, i; + int log; + socklen_t s; + int sock = -1; + struct sockaddr_un sockaddr; + char buf[1024]; + int readfd; + + /* open kernel message logger */ + in = open("/proc/kmsg", O_RDONLY,0); + if (in < 0) { + print_error("could not open /proc/kmsg"); + return; + } + + mkdir("/tmp", 0755); + if ((log = open("/tmp/syslog", O_WRONLY | O_CREAT | O_APPEND, 0644)) < 0) { + print_error("error opening /tmp/syslog"); + sleep(5); + return; + } + + if ((klog_pid = fork())) { + close(in); + close(log); + return; + } else { + close(0); + close(1); + close(2); + } + + out = open("/dev/tty4", O_WRONLY, 0); + if (out < 0) + print_warning("couldn't open tty for syslog -- still using /tmp/syslog\n"); + + /* now open the syslog socket */ // ############# LINUX 2.4 /dev/log IS BUGGED! --> apparently the syslogs can't reach me, and it's full up after a while -// sockaddr.sun_family = AF_UNIX; -// strncpy(sockaddr.sun_path, "/dev/log", UNIX_PATH_MAX); -// sock = socket(AF_UNIX, SOCK_STREAM, 0); -// if (sock < 0) { -// printf("error creating socket: %d\n", errno); -// sleep(5); -// } +// sockaddr.sun_family = AF_UNIX; +// strncpy(sockaddr.sun_path, "/dev/log", UNIX_PATH_MAX); +// sock = socket(AF_UNIX, SOCK_STREAM, 0); +// if (sock < 0) { +// printf("error creating socket: %d\n", errno); +// sleep(5); +// } // -// print_str_init(log, "] got socket\n"); -// if (bind(sock, (struct sockaddr *) &sockaddr, sizeof(sockaddr.sun_family) + strlen(sockaddr.sun_path))) { -// print_str_init(log, "] bind error: "); -// print_int_init(log, errno); -// print_str_init(log, "\n"); -// sleep(// } +// print_str_init(log, "] got socket\n"); +// if (bind(sock, (struct sockaddr *) &sockaddr, sizeof(sockaddr.sun_family) + strlen(sockaddr.sun_path))) { +// print_str_init(log, "] bind error: "); +// print_int_init(log, errno); +// print_str_init(log, "\n"); +// sleep(// } // -// print_str_init(log, "] bound socket\n"); -// chmod("/dev/log", 0666); -// if (listen(sock, 5)) { -// print_str_init(log, "] listen error: "); -// print_int_init(log, errno); -// print_str_init(log, "\n"); -// sleep(5); -// } - - /* disable on-console syslog output */ - syslog(8, NULL, 1); - - print_str_init(log, "] kernel/system logger ok\n"); - FD_ZERO(&unixs); - while (1) { - memcpy(&readset, &unixs, sizeof(unixs)); - - if (sock >= 0) - FD_SET(sock, &readset); - FD_SET(in, &readset); - - i = select(20, &readset, NULL, NULL, NULL); - if (i <= 0) - continue; - - /* has /proc/kmsg things to tell us? */ - if (FD_ISSET(in, &readset)) { - i = read(in, buf, sizeof(buf)); - if (i > 0) { - if (out >= 0) - write(out, buf, i); - write(log, buf, i); - } - } - - /* the socket has moved, new stuff to do */ - if (sock >= 0 && FD_ISSET(sock, &readset)) { - s = sizeof(sockaddr); - readfd = accept(sock, (struct sockaddr *) &sockaddr, &s); - if (readfd < 0) { - char * msg_error = "] error in accept\n"; - if (out >= 0) - write(out, msg_error, strlen(msg_error)); - write(log, msg_error, strlen(msg_error)); - close(sock); - sock = -1; - } - else - FD_SET(readfd, &unixs); - } - } +// print_str_init(log, "] bound socket\n"); +// chmod("/dev/log", 0666); +// if (listen(sock, 5)) { +// print_str_init(log, "] listen error: "); +// print_int_init(log, errno); +// print_str_init(log, "\n"); +// sleep(5); +// } + + /* disable on-console syslog output */ + syslog(8, NULL, 1); + + print_str_init(log, "] kernel/system logger ok\n"); + FD_ZERO(&unixs); + while (1) { + memcpy(&readset, &unixs, sizeof(unixs)); + + if (sock >= 0) + FD_SET(sock, &readset); + FD_SET(in, &readset); + + i = select(20, &readset, NULL, NULL, NULL); + if (i <= 0) + continue; + + /* has /proc/kmsg things to tell us? */ + if (FD_ISSET(in, &readset)) { + i = read(in, buf, sizeof(buf)); + if (i > 0) { + if (out >= 0) + write(out, buf, i); + write(log, buf, i); + } + } + + /* the socket has moved, new stuff to do */ + if (sock >= 0 && FD_ISSET(sock, &readset)) { + s = sizeof(sockaddr); + readfd = accept(sock, (struct sockaddr *) &sockaddr, &s); + if (readfd < 0) { + char * msg_error = "] error in accept\n"; + if (out >= 0) + write(out, msg_error, strlen(msg_error)); + write(log, msg_error, strlen(msg_error)); + close(sock); + sock = -1; + } + else + FD_SET(readfd, &unixs); + } + } } -#define LOOP_CLR_FD 0x4C01 +#define LOOP_CLR_FD 0x4C01 void del_loops(void) { @@ -280,10 +280,10 @@ void del_loops(void) struct filesystem { - char * dev; - char * name; - char * fs; - int mounted; + char * dev; + char * name; + char * fs; + int mounted; }; char* strcat(register char* s,register const char* t) @@ -299,76 +299,76 @@ char* strcat(register char* s,register const char* t) /* attempt to unmount all filesystems in /proc/mounts */ void unmount_filesystems(void) { - int fd, size; - char buf[65535]; /* this should be big enough */ - char *p; - struct filesystem fs[500]; - int numfs = 0; - int i, nb; - - printf("unmounting filesystems...\n"); - - fd = open("/proc/mounts", O_RDONLY, 0); - if (fd < 1) { - print_error("failed to open /proc/mounts"); - sleep(2); - return; - } - - size = read(fd, buf, sizeof(buf) - 1); - buf[size] = '\0'; - - close(fd); - - p = buf; - while (*p) { - fs[numfs].mounted = 1; - fs[numfs].dev = p; - while (*p != ' ') p++; - *p++ = '\0'; - fs[numfs].name = p; - while (*p != ' ') p++; - *p++ = '\0'; - fs[numfs].fs = p; - while (*p != ' ') p++; - *p++ = '\0'; - while (*p != '\n') p++; - p++; - if (strcmp(fs[numfs].name, "/") + int fd, size; + char buf[65535]; /* this should be big enough */ + char *p; + struct filesystem fs[500]; + int numfs = 0; + int i, nb; + + printf("unmounting filesystems...\n"); + + fd = open("/proc/mounts", O_RDONLY, 0); + if (fd < 1) { + print_error("failed to open /proc/mounts"); + sleep(2); + return; + } + + size = read(fd, buf, sizeof(buf) - 1); + buf[size] = '\0'; + + close(fd); + + p = buf; + while (*p) { + fs[numfs].mounted = 1; + fs[numfs].dev = p; + while (*p != ' ') p++; + *p++ = '\0'; + fs[numfs].name = p; + while (*p != ' ') p++; + *p++ = '\0'; + fs[numfs].fs = p; + while (*p != ' ') p++; + *p++ = '\0'; + while (*p != '\n') p++; + p++; + if (strcmp(fs[numfs].name, "/") && !strstr(fs[numfs].dev, "ram") && strcmp(fs[numfs].name, "/dev") && strcmp(fs[numfs].name, "/sys") && strncmp(fs[numfs].name, "/proc", 5)) numfs++; - } - - /* Pixel's ultra-optimized sorting algorithm: - multiple passes trying to umount everything until nothing moves - anymore (a.k.a holy shotgun method) */ - do { - nb = 0; - for (i = 0; i < numfs; i++) { - /*printf("trying with %s\n", fs[i].name);*/ + } + + /* Pixel's ultra-optimized sorting algorithm: + multiple passes trying to umount everything until nothing moves + anymore (a.k.a holy shotgun method) */ + do { + nb = 0; + for (i = 0; i < numfs; i++) { + /*printf("trying with %s\n", fs[i].name);*/ del_loops(); - if (fs[i].mounted && umount(fs[i].name) == 0) { - printf("\t%s\n", fs[i].name); - fs[i].mounted = 0; - nb++; - } - } - } while (nb); - - for (i = nb = 0; i < numfs; i++) - if (fs[i].mounted) { - printf("\tumount failed: %s\n", fs[i].name); - if (strcmp(fs[i].fs, "ext3") == 0) nb++; /* don't count not-ext3 umount failed */ - } - - - if (nb) { - printf("failed to umount some filesystems\n"); + if (fs[i].mounted && umount(fs[i].name) == 0) { + printf("\t%s\n", fs[i].name); + fs[i].mounted = 0; + nb++; + } + } + } while (nb); + + for (i = nb = 0; i < numfs; i++) + if (fs[i].mounted) { + printf("\tumount failed: %s\n", fs[i].name); + if (strcmp(fs[i].fs, "ext3") == 0) nb++; /* don't count not-ext3 umount failed */ + } + + + if (nb) { + printf("failed to umount some filesystems\n"); select(0, NULL, NULL, NULL, NULL); - } + } } int in_reboot(void) @@ -390,11 +390,11 @@ int exit_value_restart = 0x35; int main(int argc, char **argv) { - pid_t installpid, childpid; - int wait_status; - int fd; - int counter = 0; - int abnormal_termination = 0; + pid_t installpid, childpid; + int wait_status; + int fd; + int counter = 0; + int abnormal_termination = 0; if (argc > 1 && argv[1][0] >= '0' && argv[1][0] <= '9') { printf("This is no normal init, sorry.\n" @@ -402,76 +402,68 @@ int main(int argc, char **argv) return 0; } - if (!testing) { - /* turn off screen blanking */ - printf("\033[9;0]"); - printf("\033[8]"); - } - else - printf("*** TESTING MODE *** (pid is %d)\n", getpid()); - - - if (!testing) { - if (mount("/proc", "/proc", "proc", 0, NULL)) - fatal_error("Unable to mount proc filesystem"); - if (mount("none", "/sys", "sysfs", 0, NULL)) - fatal_error("Unable to mount sysfs filesystem"); - if (mount("none", "/sys/kernel/debug", "debugfs", MS_NOSUID, "mode=0755")) - fatal_error("Unable to mount debugfs filesystem"); - if (mount("none", "/dev", "devtmpfs", 0, NULL)) - fatal_error("Unable to mount dev filesystem"); - mkdir("/dev/pts", 0755); - if (mount("/dev/pts", "/dev/pts", "devpts", MS_NOSUID|MS_NOEXEC, "gid=5,mode=0620")) - fatal_error("Unable to mount /dev/pts devpts filesystem"); - mkdir("/dev/shm", 0755); - if (mount("/dev/shm", "/dev/shm", "tmpfs", MS_NOSUID|MS_NODEV, "mode=1777")) - fatal_error("Unable to mount /dev/shm tmpfs filesystem"); - } - - - /* ignore Control-C and keyboard stop signals */ - signal(SIGINT, SIG_IGN); - signal(SIGTSTP, SIG_IGN); - - if (!testing) { - fd = open("/dev/console", O_RDWR, 0); - if (fd < 0) - fatal_error("failed to open /dev/console"); - - dup2(fd, 0); - dup2(fd, 1); - dup2(fd, 2); - close(fd); - } - - - /* I set me up as session leader (probably not necessary?) */ - setsid(); -// if (ioctl(0, TIOCSCTTY, NULL)) -// print_error("could not set new controlling tty"); - - if (!testing) { - char my_hostname[] = "localhost"; - sethostname(my_hostname, sizeof(my_hostname)); - /* the default domainname (as of 2.0.35) is "(none)", which confuses - glibc */ - setdomainname("", 0); - } - - if (!testing) - doklog(); - - /* Go into normal init mode - keep going, and then do a orderly shutdown - when: - - 1) install exits - 2) we receive a SIGHUP - */ + if (!testing) { + /* turn off screen blanking */ + printf("\033[9;0]"); + printf("\033[8]"); + } + else + printf("*** TESTING MODE *** (pid is %d)\n", getpid()); + + + if (!testing) { + mkdir("/proc", 0755); + if (mount("/proc", "/proc", "proc", 0, NULL)) + fatal_error("Unable to mount proc filesystem"); + mkdir("/sys", 0755); + if (mount("none", "/sys", "sysfs", 0, NULL)) + fatal_error("Unable to mount sysfs filesystem"); + } + + + /* ignore Control-C and keyboard stop signals */ + signal(SIGINT, SIG_IGN); + signal(SIGTSTP, SIG_IGN); + + if (!testing) { + fd = open("/dev/console", O_RDWR, 0); + if (fd < 0) + fatal_error("failed to open /dev/console"); + + dup2(fd, 0); + dup2(fd, 1); + dup2(fd, 2); + close(fd); + } + + + /* I set me up as session leader (probably not necessary?) */ + setsid(); +// if (ioctl(0, TIOCSCTTY, NULL)) +// print_error("could not set new controlling tty"); + + if (!testing) { + char my_hostname[] = "localhost"; + sethostname(my_hostname, sizeof(my_hostname)); + /* the default domainname (as of 2.0.35) is "(none)", which confuses + glibc */ + setdomainname("", 0); + } + + if (!testing) + doklog(); + + /* Go into normal init mode - keep going, and then do a orderly shutdown + when: + + 1) install exits + 2) we receive a SIGHUP + */ do { - if (counter == 1) { - printf("proceeding, please wait...\n"); - } + if (counter == 1) { + printf("proceeding, please wait...\n"); + } if (!(installpid = fork())) { /* child */ @@ -488,7 +480,7 @@ int main(int argc, char **argv) childpid = wait4(-1, &wait_status, 0, NULL); } while (childpid != installpid); - counter++; + counter++; } while (WIFEXITED(wait_status) && WEXITSTATUS(wait_status) == exit_value_restart); /* allow Ctrl Alt Del to reboot */ @@ -496,21 +488,21 @@ int main(int argc, char **argv) if (in_reboot()) { // any exitcode is valid if we're in_reboot - } else if (WIFEXITED(wait_status) && WEXITSTATUS(wait_status) == exit_value_proceed) { - kill(klog_pid, 9); - printf("proceeding, please wait...\n"); - - { - char * child_argv[2] = { "/sbin/init", NULL }; - execve(child_argv[0], child_argv, env); - } - fatal_error("failed to exec /sbin/init"); + } else if (WIFEXITED(wait_status) && WEXITSTATUS(wait_status) == exit_value_proceed) { + kill(klog_pid, 9); + printf("proceeding, please wait...\n"); + + { + char * child_argv[2] = { "/sbin/init", NULL }; + execve(child_argv[0], child_argv, env); + } + fatal_error("failed to exec /sbin/init"); } else if (!WIFEXITED(wait_status) || WEXITSTATUS(wait_status) != 0) { - printf("exited abnormally :-( "); - if (WIFSIGNALED(wait_status)) - printf("-- received signal %d", WTERMSIG(wait_status)); - printf("\n"); - abnormal_termination = 1; + printf("exited abnormally :-( "); + if (WIFSIGNALED(wait_status)) + printf("-- received signal %d", WTERMSIG(wait_status)); + printf("\n"); + abnormal_termination = 1; } if (!abnormal_termination) { @@ -519,40 +511,40 @@ int main(int argc, char **argv) printf("\n"); /* cleanup startkde messages */ } - if (testing) - return 0; + if (testing) + return 0; - sync(); sync(); - sleep(2); + sync(); sync(); + sleep(2); - printf("sending termination signals..."); - kill(-1, 15); - sleep(2); - printf("done\n"); + printf("sending termination signals..."); + kill(-1, 15); + sleep(2); + printf("done\n"); - printf("sending kill signals..."); - kill(-1, 9); - sleep(2); - printf("done\n"); + printf("sending kill signals..."); + kill(-1, 9); + sleep(2); + printf("done\n"); - unmount_filesystems(); + unmount_filesystems(); - sync(); sync(); + sync(); sync(); - if (!abnormal_termination) { - if (reboot_magic == BMAGIC_REBOOT) { + if (!abnormal_termination) { + if (reboot_magic == BMAGIC_REBOOT) { #ifdef DEBUG - printf("automatic reboot in 10 seconds\n"); - sleep(10); + printf("automatic reboot in 10 seconds\n"); + sleep(10); #endif - reboot(reboot_magic); - } else { - printf("you may safely poweroff your computer now\n"); - } - } else { - printf("you may safely reboot or halt your system\n"); - } + reboot(reboot_magic); + } else { + printf("you may safely poweroff your computer now\n"); + } + } else { + printf("you may safely reboot or halt your system\n"); + } select(0, NULL, NULL, NULL, NULL); - return 0; + return 0; } diff --git a/mdk-stage1/ka.c b/mdk-stage1/ka.c index 670abe5af..1f0b1dedd 100644 --- a/mdk-stage1/ka.c +++ b/mdk-stage1/ka.c @@ -36,163 +36,163 @@ static void save_stuff_for_rescue(void) #endif static void my_pause(void) { - unsigned char t; - fflush(stdout); - read(0, &t, 1); + unsigned char t; + fflush(stdout); + read(0, &t, 1); } static enum return_type ka_wait_for_stage2(int count) { - char * ramdisk = "/dev/ram3"; /* warning, verify that this file exists in the initrd*/ - char * ka_launch[] = { "/ka/ka-d-client", "-w","-s","getstage2","-e","(cd /tmp/stage2; tar -x -f - )", NULL }; /* The command line for ka_launch */ - char * mkfs_launch[] = { "/sbin/mke2fs", "-m", "0", ramdisk, NULL}; /* The mkfs command for formating the ramdisk */ + char * ramdisk = "/dev/ram3"; /* warning, verify that this file exists in the initrd*/ + char * ka_launch[] = { "/ka/ka-d-client", "-w","-s","getstage2","-e","(cd /tmp/stage2; tar -x -f - )", NULL }; /* The command line for ka_launch */ + char * mkfs_launch[] = { "/sbin/mke2fs", "-m", "0", ramdisk, NULL}; /* The mkfs command for formating the ramdisk */ - log_message("KA: Preparing to receive stage 2...."); + log_message("KA: Preparing to receive stage 2...."); wait_message("Preparing to receive stage 2"); - int pida, wait_status; + int pida, wait_status; - if (!(pida = fork())) { /* Forking current process for running mkfs */ - //close(1); - close(2); - execv(mkfs_launch[0], mkfs_launch); /* Formating the ramdisk */ - printf("KA: Can't execute %s\n<press Enter>\n", mkfs_launch[0]); - my_pause(); - return KAERR_CANTFORK; - } - while (wait4(-1, &wait_status, 0, NULL) != pida) {}; /* Waiting the end of mkfs */ - remove_wait_message(); + if (!(pida = fork())) { /* Forking current process for running mkfs */ + //close(1); + close(2); + execv(mkfs_launch[0], mkfs_launch); /* Formating the ramdisk */ + printf("KA: Can't execute %s\n<press Enter>\n", mkfs_launch[0]); + my_pause(); + return KAERR_CANTFORK; + } + while (wait4(-1, &wait_status, 0, NULL) != pida) {}; /* Waiting the end of mkfs */ + remove_wait_message(); wait_message("Mounting /dev/ram3 at %s", STAGE2_LOCATION); - if (my_mount(ramdisk, STAGE2_LOCATION, "ext2", 1)) {/* Trying to mount the ramdisk */ - return RETURN_ERROR; - } - remove_wait_message(); - - log_message("KA: Waiting for stage 2...."); - wait_message("Waiting for rescue from KA server (Try %d/%d)", count, KA_MAX_RETRY); - pid_t pid; /* Process ID of the child process */ - pid_t wpid; /* Process ID from wait() */ - int status; /* Exit status from wait() */ - - pid = fork(); - if ( pid == -1 ) { - fprintf(stderr, "%s: Failed to fork()\n", strerror(errno)); - exit(13); - } else if ( pid == 0 ) { - // close(2); - execv(ka_launch[0], ka_launch); - } else { - // wpid = wait(&status); /* Child's exit status */ - wpid = wait4(-1, &status, 0, NULL); - if ( wpid == -1 ) { - fprintf(stderr,"%s: wait()\n", strerror(errno)); - return RETURN_ERROR; - } else if ( wpid != pid ) - abort(); - else { - if ( WIFEXITED(status) ) { - printf("Exited: $? = %d\n", WEXITSTATUS(status)); - } else if ( WIFSIGNALED(status) ) { - printf("Signal: %d%s\n", WTERMSIG(status), WCOREDUMP(status) ? " with core file." : ""); - } - } - } - - remove_wait_message(); - return RETURN_OK; - // if (!(pid = fork())) { /* Froking current process for running ka-deploy (client side) */ - // close(1); /* Closing stdout */ - // close(2); /* Closing stderr */ - // execve(ka_launch[0], ka_launch,grab_env()); /* Running ka-deploy (client side) */ - // printf("KA: Can't execute %s\n<press Enter>\n", ka_launch[0]); - // log_message("KA: Can't execute %s\n<press Enter>\n", ka_launch[0]); - // my_pause(); - // return KAERR_CANTFORK; - //} - - //while (wait4(-1, &wait_status, 0, NULL) != pid) {}; /* Waiting the end of duplication */ - // log_message("kalaunch ret %d\n", WIFEXITED(wait_status)); - // remove_wait_message(); - //sleep(100000); - // return RETURN_OK; + if (my_mount(ramdisk, STAGE2_LOCATION, "ext2", 1)) {/* Trying to mount the ramdisk */ + return RETURN_ERROR; + } + remove_wait_message(); + + log_message("KA: Waiting for stage 2...."); + wait_message("Waiting for rescue from KA server (Try %d/%d)", count, KA_MAX_RETRY); + pid_t pid; /* Process ID of the child process */ + pid_t wpid; /* Process ID from wait() */ + int status; /* Exit status from wait() */ + + pid = fork(); + if ( pid == -1 ) { + fprintf(stderr, "%s: Failed to fork()\n", strerror(errno)); + exit(13); + } else if ( pid == 0 ) { + // close(2); + execv(ka_launch[0], ka_launch); + } else { + // wpid = wait(&status); /* Child's exit status */ + wpid = wait4(-1, &status, 0, NULL); + if ( wpid == -1 ) { + fprintf(stderr,"%s: wait()\n", strerror(errno)); + return RETURN_ERROR; + } else if ( wpid != pid ) + abort(); + else { + if ( WIFEXITED(status) ) { + printf("Exited: $? = %d\n", WEXITSTATUS(status)); + } else if ( WIFSIGNALED(status) ) { + printf("Signal: %d%s\n", WTERMSIG(status), WCOREDUMP(status) ? " with core file." : ""); + } + } + } + + remove_wait_message(); + return RETURN_OK; + // if (!(pid = fork())) { /* Froking current process for running ka-deploy (client side) */ + // close(1); /* Closing stdout */ + // close(2); /* Closing stderr */ + // execve(ka_launch[0], ka_launch,grab_env()); /* Running ka-deploy (client side) */ + // printf("KA: Can't execute %s\n<press Enter>\n", ka_launch[0]); + // log_message("KA: Can't execute %s\n<press Enter>\n", ka_launch[0]); + // my_pause(); + // return KAERR_CANTFORK; + //} + + //while (wait4(-1, &wait_status, 0, NULL) != pid) {}; /* Waiting the end of duplication */ + // log_message("kalaunch ret %d\n", WIFEXITED(wait_status)); + // remove_wait_message(); + //sleep(100000); + // return RETURN_OK; } enum return_type perform_ka(void) { - enum return_type results; - int server_failure = 1; /* Number of time we've failed to find a ka server */ - FILE *f = fopen ("/ka/tftpserver","w"); - - if (f != NULL) { - /* Writing the NEXT_SERVER value of the DHCP Request in the /ka/tftpserver file */ - fprintf(f,"%s\n",inet_ntoa(next_server)); - fclose(f); - } - - log_message("KA: Trying to retrieve stage2 from server"); - log_message("KA: ka_wait_for_stage2"); - do { - /* We are trying to get a valid stage 2 (rescue) */ - results=ka_wait_for_stage2(server_failure); - if (results != RETURN_OK) { - return results; - } else { - /* Trying to open STAGE2_LOCATION/ka directory */ - char dir[255] = STAGE2_LOCATION; - strcat(dir,"/ka"); - DIR *dp = opendir(dir); - - /* Does the STAGE2_LOCATION/ka directory exists ? = Does the rescue with ka well downloaded ?*/ - if (!dp) { - log_message("KA: Server not found !"); - /* Be sure that the STAGE2_LOCATION isn't mounted after receiving a wrong rescue */ - if (umount (STAGE2_LOCATION)) { - log_perror("KA: Unable to umount STAGE2"); - } - int cpt; - - if (server_failure++ == KA_MAX_RETRY){ - /* if the KA server can't be reach KA_MAX_RETRY times */ - char * reboot_launch[] = { "/sbin/reboot", NULL}; - for (cpt=5; cpt>0; cpt--) { - wait_message("!!! Can't reach a valid KA server !!! (Rebooting in %d sec)",cpt); - sleep (1); - } - /* Rebooting the computer to avoid infinite loop on ka mode */ - execv(reboot_launch[0], reboot_launch); - } - - for (cpt=5; cpt>0; cpt--) { - wait_message("KA server not found ! (Try %d/%d in %d sec)",server_failure,KA_MAX_RETRY,cpt); - log_message("Ka not found %d/%d", server_failure,KA_MAX_RETRY); - sleep (1); - } - remove_wait_message(); - /* We should try another time*/ - results=RETURN_BACK; - continue; - } - - if (dp) { - log_message("KA: Stage 2 downloaded successfully"); - closedir(dp); /* Closing the /ka directory */ - server_failure=1; /* Resetting server_failure */ - results = RETURN_OK; - } - } - - log_message("KA: Preparing chroot"); - return RETURN_OK; - - // if (IS_RESCUE) { /* if we are in rescue mode */ - // save_stuff_for_rescue(); /* Saving resolve.conf */ - // if (umount (STAGE2_LOCATION)) { /* Unmounting STAGE2 elseif kernel can't mount it ! */ - // log_perror("KA: Unable to umount STAGE2"); - // return RETURN_ERROR; - // } - // } - } while (results == RETURN_BACK); - - // method_name = strdup("ka"); - return RETURN_OK; + enum return_type results; + int server_failure = 1; /* Number of time we've failed to find a ka server */ + FILE *f = fopen ("/ka/tftpserver","w"); + + if (f != NULL) { + /* Writing the NEXT_SERVER value of the DHCP Request in the /ka/tftpserver file */ + fprintf(f,"%s\n",inet_ntoa(next_server)); + fclose(f); + } + + log_message("KA: Trying to retrieve stage2 from server"); + log_message("KA: ka_wait_for_stage2"); + do { + /* We are trying to get a valid stage 2 (rescue) */ + results=ka_wait_for_stage2(server_failure); + if (results != RETURN_OK) { + return results; + } else { + /* Trying to open STAGE2_LOCATION/ka directory */ + char dir[255] = STAGE2_LOCATION; + strcat(dir,"/ka"); + DIR *dp = opendir(dir); + + /* Does the STAGE2_LOCATION/ka directory exists ? = Does the rescue with ka well downloaded ?*/ + if (!dp) { + log_message("KA: Server not found !"); + /* Be sure that the STAGE2_LOCATION isn't mounted after receiving a wrong rescue */ + if (umount (STAGE2_LOCATION)) { + log_perror("KA: Unable to umount STAGE2"); + } + int cpt; + + if (server_failure++ == KA_MAX_RETRY){ + /* if the KA server can't be reach KA_MAX_RETRY times */ + char * reboot_launch[] = { "/sbin/reboot", NULL}; + for (cpt=5; cpt>0; cpt--) { + wait_message("!!! Can't reach a valid KA server !!! (Rebooting in %d sec)",cpt); + sleep (1); + } + /* Rebooting the computer to avoid infinite loop on ka mode */ + execv(reboot_launch[0], reboot_launch); + } + + for (cpt=5; cpt>0; cpt--) { + wait_message("KA server not found ! (Try %d/%d in %d sec)",server_failure,KA_MAX_RETRY,cpt); + log_message("Ka not found %d/%d", server_failure,KA_MAX_RETRY); + sleep (1); + } + remove_wait_message(); + /* We should try another time*/ + results=RETURN_BACK; + continue; + } + + if (dp) { + log_message("KA: Stage 2 downloaded successfully"); + closedir(dp); /* Closing the /ka directory */ + server_failure=1; /* Resetting server_failure */ + results = RETURN_OK; + } + } + + log_message("KA: Preparing chroot"); + return RETURN_OK; + + // if (IS_RESCUE) { /* if we are in rescue mode */ + // save_stuff_for_rescue(); /* Saving resolve.conf */ + // if (umount (STAGE2_LOCATION)) { /* Unmounting STAGE2 elseif kernel can't mount it ! */ + // log_perror("KA: Unable to umount STAGE2"); + // return RETURN_ERROR; + // } + // } + } while (results == RETURN_BACK); + + // method_name = strdup("ka"); + return RETURN_OK; } diff --git a/mdk-stage1/log.c b/mdk-stage1/log.c index cb3f741dc..56a13da93 100644 --- a/mdk-stage1/log.c +++ b/mdk-stage1/log.c @@ -37,58 +37,58 @@ static FILE * logfile = NULL; void vlog_message(const char * s, va_list args) { - va_list args_copy; - va_copy(args_copy, args); + va_list args_copy; + va_copy(args_copy, args); - if (logfile) { - fprintf(logfile, "* "); - vfprintf(logfile, s, args); - fprintf(logfile, "\n"); - fflush(logfile); - } - if (logtty) { - fprintf(logtty, "* "); - vfprintf(logtty, s, args_copy); - fprintf(logtty, "\n"); - fflush(logtty); - } + if (logfile) { + fprintf(logfile, "* "); + vfprintf(logfile, s, args); + fprintf(logfile, "\n"); + fflush(logfile); + } + if (logtty) { + fprintf(logtty, "* "); + vfprintf(logtty, s, args_copy); + fprintf(logtty, "\n"); + fflush(logtty); + } - va_end(args_copy); + va_end(args_copy); } void log_message(const char * s, ...) { - va_list args; - va_start(args, s); - vlog_message(s, args); - va_end(args); - - return; + va_list args; + va_start(args, s); + vlog_message(s, args); + va_end(args); + + return; } void log_perror(const char *msg) { - log_message("%s: %s", msg, strerror(errno)); + log_message("%s: %s", msg, strerror(errno)); } void open_log(void) { - if (!IS_TESTING) { - logtty = fopen("/dev/tty3", "w"); - logfile = fopen("/tmp/stage1.log", "w"); - } - else - logfile = fopen("debug.log", "w"); + if (!IS_TESTING) { + logtty = fopen("/dev/tty3", "w"); + logfile = fopen("/tmp/stage1.log", "w"); + } + else + logfile = fopen("debug.log", "w"); } void close_log(void) { - if (logfile) { - log_message("stage1: disconnecting life support systems"); - fclose(logfile); - if (logtty) - fclose(logtty); - } + if (logfile) { + log_message("stage1: disconnecting life support systems"); + fclose(logfile); + if (logtty) + fclose(logtty); + } } diff --git a/mdk-stage1/lomount.c b/mdk-stage1/lomount.c index b7d61f24b..74a409e0b 100644 --- a/mdk-stage1/lomount.c +++ b/mdk-stage1/lomount.c @@ -35,90 +35,90 @@ #include "lomount.h" -#define LO_NAME_SIZE 64 -#define LO_KEY_SIZE 32 +#define LO_NAME_SIZE 64 +#define LO_KEY_SIZE 32 struct loop_info { - int lo_number; /* ioctl r/o */ - dev_t lo_device; /* ioctl r/o */ - unsigned long lo_inode; /* ioctl r/o */ - dev_t lo_rdevice; /* ioctl r/o */ - int lo_offset; - int lo_encrypt_type; - int lo_encrypt_key_size; /* ioctl w/o */ - int lo_flags; /* ioctl r/o */ - char lo_name[LO_NAME_SIZE]; - unsigned char lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */ - unsigned long lo_init[2]; - char reserved[4]; + int lo_number; /* ioctl r/o */ + dev_t lo_device; /* ioctl r/o */ + unsigned long lo_inode; /* ioctl r/o */ + dev_t lo_rdevice; /* ioctl r/o */ + int lo_offset; + int lo_encrypt_type; + int lo_encrypt_key_size; /* ioctl w/o */ + int lo_flags; /* ioctl r/o */ + char lo_name[LO_NAME_SIZE]; + unsigned char lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */ + unsigned long lo_init[2]; + char reserved[4]; }; -#define LOOP_SET_FD 0x4C00 -#define LOOP_CLR_FD 0x4C01 -#define LOOP_SET_STATUS 0x4C02 -#define LOOP_GET_STATUS 0x4C03 +#define LOOP_SET_FD 0x4C00 +#define LOOP_CLR_FD 0x4C01 +#define LOOP_SET_STATUS 0x4C02 +#define LOOP_GET_STATUS 0x4C03 int set_loop (const char *device, const char *file) { - struct loop_info loopinfo; - int fd, ffd, mode; + struct loop_info loopinfo; + int fd, ffd, mode; - mode = O_RDONLY; + mode = O_RDONLY; - if ((ffd = open (file, mode)) < 0) - return 1; + if ((ffd = open (file, mode)) < 0) + return 1; - if ((fd = open (device, mode)) < 0) { - close(ffd); - return 1; - } + if ((fd = open (device, mode)) < 0) { + close(ffd); + return 1; + } - memset(&loopinfo, 0, sizeof (loopinfo)); - strncpy(loopinfo.lo_name, file, LO_NAME_SIZE); - loopinfo.lo_name[LO_NAME_SIZE - 1] = 0; - loopinfo.lo_offset = 0; + memset(&loopinfo, 0, sizeof (loopinfo)); + strncpy(loopinfo.lo_name, file, LO_NAME_SIZE); + loopinfo.lo_name[LO_NAME_SIZE - 1] = 0; + loopinfo.lo_offset = 0; #ifdef MCL_FUTURE - /* - * Oh-oh, sensitive data coming up. Better lock into memory to prevent - * passwd etc being swapped out and left somewhere on disk. - */ + /* + * Oh-oh, sensitive data coming up. Better lock into memory to prevent + * passwd etc being swapped out and left somewhere on disk. + */ - if(mlockall(MCL_CURRENT|MCL_FUTURE)) { - log_message("CRITICAL Couldn't lock into memory! %s (memlock)", strerror(errno)); - return 1; - } + if(mlockall(MCL_CURRENT|MCL_FUTURE)) { + log_message("CRITICAL Couldn't lock into memory! %s (memlock)", strerror(errno)); + return 1; + } #endif - if (ioctl(fd, LOOP_SET_FD, ffd) < 0) { - close(fd); - close(ffd); - return 1; - } - - if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) { - (void) ioctl (fd, LOOP_CLR_FD, 0); - close(fd); - close(ffd); - return 1; - } - - close(fd); - close(ffd); - return 0; + if (ioctl(fd, LOOP_SET_FD, ffd) < 0) { + close(fd); + close(ffd); + return 1; + } + + if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) { + (void) ioctl (fd, LOOP_CLR_FD, 0); + close(fd); + close(ffd); + return 1; + } + + close(fd); + close(ffd); + return 0; } char* find_free_loop() { - struct loop_info loopinfo; + struct loop_info loopinfo; int i; for (i=0; i<256; i++) { int fd; - char ldev[100]; - sprintf(ldev, "/dev/loop%d", i); + char ldev[100]; + sprintf(ldev, "/dev/loop%d", i); ensure_dev_exists(ldev); fd = open(ldev, O_RDONLY); if (!ioctl(fd, LOOP_GET_STATUS, &loopinfo)) { @@ -141,54 +141,54 @@ char* find_free_loop() void del_loop(char * loopdev) { - int fd; + int fd; if (!loopdev) return; - if ((fd = open (loopdev, O_RDONLY)) < 0) - return; + if ((fd = open (loopdev, O_RDONLY)) < 0) + return; - if (ioctl (fd, LOOP_CLR_FD, 0) < 0) - return; + if (ioctl (fd, LOOP_CLR_FD, 0) < 0) + return; - close (fd); + close (fd); } int lomount(char *loopfile, char *where, char **dev, int compressed) { - long int flag; + long int flag; char * loopdev; - flag = MS_MGC_VAL; - flag |= MS_RDONLY; + flag = MS_MGC_VAL; + flag |= MS_RDONLY; - my_insmod("loop", ANY_DRIVER_TYPE, "max_loop=256", 1); - if (compressed) { - my_insmod("squashfs", ANY_DRIVER_TYPE, NULL, 1); - } + my_insmod("loop", ANY_DRIVER_TYPE, "max_loop=256", 1); + if (compressed) { + my_insmod("squashfs", ANY_DRIVER_TYPE, NULL, 1); + } if (!(loopdev = find_free_loop())) { - log_message("could not find a free loop"); - return 1; + log_message("could not find a free loop"); + return 1; } if (dev) *dev = loopdev; - if (set_loop(loopdev, loopfile)) { - log_message("set_loop failed on %s (%s)", loopdev, strerror(errno)); - return 1; - } + if (set_loop(loopdev, loopfile)) { + log_message("set_loop failed on %s (%s)", loopdev, strerror(errno)); + return 1; + } - if (my_mount(loopdev, where, compressed ? "squashfs" : "iso9660", 0)) { - del_loop(loopdev); - return 1; - } + if (my_mount(loopdev, where, compressed ? "squashfs" : "iso9660", 0)) { + del_loop(loopdev); + return 1; + } - log_message("lomount succeeded for %s on %s", loopfile, where); - return 0; + log_message("lomount succeeded for %s on %s", loopfile, where); + return 0; } diff --git a/mdk-stage1/modules.c b/mdk-stage1/modules.c index 745070052..ec03233ae 100644 --- a/mdk-stage1/modules.c +++ b/mdk-stage1/modules.c @@ -52,247 +52,247 @@ extern long init_module(void *, unsigned long, const char *); static const char *moderror(int err) { - switch (err) { - case ENOEXEC: - return "Invalid module format"; - case ENOENT: - return "Unknown symbol in module"; - case ESRCH: - return "Module has wrong symbol version"; - case EINVAL: - return "Invalid parameters"; - default: - return strerror(err); - } + switch (err) { + case ENOEXEC: + return "Invalid module format"; + case ENOENT: + return "Unknown symbol in module"; + case ESRCH: + return "Module has wrong symbol version"; + case EINVAL: + return "Invalid parameters"; + default: + return strerror(err); + } } int insmod_local_file(char * path, char * options) { - void *file; - unsigned long len; - int rc; + void *file; + unsigned long len; + int rc; - if (IS_TESTING) - return 0; + if (IS_TESTING) + return 0; - file = grab_file(path, &len); + file = grab_file(path, &len); - if (!file) { - log_perror(asprintf_("\terror reading %s", path)); - return -1; - } + if (!file) { + log_perror(asprintf_("\terror reading %s", path)); + return -1; + } - rc = init_module(file, len, options ? options : ""); - if (rc) - log_message("\terror: %s", moderror(errno)); - return rc; + rc = init_module(file, len, options ? options : ""); + if (rc) + log_message("\terror: %s", moderror(errno)); + return rc; } static char *kernel_module_extension(void) { - return ".ko.xz"; + return ".ko.xz"; } static char *filename2modname(char * filename) { - char *modname, *p; + char *modname, *p; - modname = strdup(basename(filename)); - if (strstr(modname, kernel_module_extension())) { - modname[strlen(modname)-strlen(kernel_module_extension())] = '\0'; /* remove trailing .ko.gz */ - } + modname = strdup(basename(filename)); + if (strstr(modname, kernel_module_extension())) { + modname[strlen(modname)-strlen(kernel_module_extension())] = '\0'; /* remove trailing .ko.gz */ + } - p = modname; - while (p && *p) { - if (*p == '-') - *p = '_'; - p++; - } + p = modname; + while (p && *p) { + if (*p == '-') + *p = '_'; + p++; + } - return modname; + return modname; } static void find_modules_directory(void) { - struct utsname kernel_uname; - char * prefix = "/lib/modules"; - char * release; - if (uname(&kernel_uname)) { - fatal_error("uname failed"); - } - release = kernel_uname.release; - sprintf(modules_directory , "%s/%s", prefix, release); + struct utsname kernel_uname; + char * prefix = "/lib/modules"; + char * release; + if (uname(&kernel_uname)) { + fatal_error("uname failed"); + } + release = kernel_uname.release; + sprintf(modules_directory , "%s/%s", prefix, release); } static int load_modules_dependencies(void) { - char * deps_file = asprintf_("%s/%s", modules_directory, "modules.dep"); - char * buf, * ptr, * start, * end; - struct stat s; - int line, i; - - log_message("loading modules dependencies"); - buf = cat_file(deps_file, &s); - if (!buf) - return -1; - line = line_counts(buf); - modules_deps = malloc(sizeof(*modules_deps) * (line+1)); - - start = buf; - line = 0; - while (start < (buf+s.st_size) && *start) { - char * tmp_deps[50]; - - end = strchr(start, '\n'); - *end = '\0'; - - ptr = strchr(start, ':'); - if (!ptr) { - start = end + 1; - continue; - } - *ptr = '\0'; - ptr++; - - while (*ptr && (*ptr == ' ')) ptr++; - - /* sort of a good line */ - modules_deps[line].filename = start[0] == '/' ? strdup(start) : asprintf_("%s/%s", modules_directory, start); - modules_deps[line].modname = filename2modname(start); - - start = ptr; - i = 0; - while (start && *start && i < sizeof(tmp_deps)/sizeof(char *)) { - ptr = strchr(start, ' '); - if (ptr) *ptr = '\0'; - tmp_deps[i++] = filename2modname(start); - if (ptr) - start = ptr + 1; - else - start = NULL; - while (start && *start && *start == ' ') - start++; - } - if(i >= sizeof(tmp_deps)/sizeof(char *)-1) { - log_message("warning, more than %zu dependencies for module %s", - sizeof(tmp_deps)/sizeof(char *)-1, - modules_deps[line].modname); - i = sizeof(tmp_deps)/sizeof(char *)-1; - } - tmp_deps[i++] = NULL; - - modules_deps[line].deps = _memdup(tmp_deps, sizeof(char *) * i); - - line++; - start = end + 1; - } - modules_deps[line].modname = NULL; - - free(buf); - - return 0; + char * deps_file = asprintf_("%s/%s", modules_directory, "modules.dep"); + char * buf, * ptr, * start, * end; + struct stat s; + int line, i; + + log_message("loading modules dependencies"); + buf = cat_file(deps_file, &s); + if (!buf) + return -1; + line = line_counts(buf); + modules_deps = malloc(sizeof(*modules_deps) * (line+1)); + + start = buf; + line = 0; + while (start < (buf+s.st_size) && *start) { + char * tmp_deps[50]; + + end = strchr(start, '\n'); + *end = '\0'; + + ptr = strchr(start, ':'); + if (!ptr) { + start = end + 1; + continue; + } + *ptr = '\0'; + ptr++; + + while (*ptr && (*ptr == ' ')) ptr++; + + /* sort of a good line */ + modules_deps[line].filename = start[0] == '/' ? strdup(start) : asprintf_("%s/%s", modules_directory, start); + modules_deps[line].modname = filename2modname(start); + + start = ptr; + i = 0; + while (start && *start && i < sizeof(tmp_deps)/sizeof(char *)) { + ptr = strchr(start, ' '); + if (ptr) *ptr = '\0'; + tmp_deps[i++] = filename2modname(start); + if (ptr) + start = ptr + 1; + else + start = NULL; + while (start && *start && *start == ' ') + start++; + } + if(i >= sizeof(tmp_deps)/sizeof(char *)-1) { + log_message("warning, more than %zu dependencies for module %s", + sizeof(tmp_deps)/sizeof(char *)-1, + modules_deps[line].modname); + i = sizeof(tmp_deps)/sizeof(char *)-1; + } + tmp_deps[i++] = NULL; + + modules_deps[line].deps = _memdup(tmp_deps, sizeof(char *) * i); + + line++; + start = end + 1; + } + modules_deps[line].modname = NULL; + + free(buf); + + return 0; } static int load_modules_descriptions(void) { - char * descr_file = asprintf_("%s/%s", modules_directory, "modules.description"); - char * buf, * ptr, * start, * end; - struct stat s; - int line; - - log_message("loading modules descriptions"); - - buf = cat_file(descr_file, &s); - if (!buf) - return -1; - line = line_counts(buf); - modules_descr = malloc(sizeof(*modules_descr) * (line+1)); - - start = buf; - line = 0; - while (start < (buf+s.st_size) && *start) { - end = strchr(start, '\n'); - *end = '\0'; - - ptr = strchr(start, '\t'); - if (!ptr) { - start = end + 1; - continue; - } - *ptr = '\0'; - ptr++; - - modules_descr[line].modname = filename2modname(start); - modules_descr[line].description = strndup(ptr, 50); - - line++; - start = end + 1; - } - modules_descr[line].modname = NULL; - - free(buf); - - return 0; + char * descr_file = asprintf_("%s/%s", modules_directory, "modules.description"); + char * buf, * ptr, * start, * end; + struct stat s; + int line; + + log_message("loading modules descriptions"); + + buf = cat_file(descr_file, &s); + if (!buf) + return -1; + line = line_counts(buf); + modules_descr = malloc(sizeof(*modules_descr) * (line+1)); + + start = buf; + line = 0; + while (start < (buf+s.st_size) && *start) { + end = strchr(start, '\n'); + *end = '\0'; + + ptr = strchr(start, '\t'); + if (!ptr) { + start = end + 1; + continue; + } + *ptr = '\0'; + ptr++; + + modules_descr[line].modname = filename2modname(start); + modules_descr[line].description = strndup(ptr, 50); + + line++; + start = end + 1; + } + modules_descr[line].modname = NULL; + + free(buf); + + return 0; } void init_firmware_loader(void) { - int fd = open(UEVENT_HELPER_FILE, O_WRONLY|O_TRUNC, 0666); - if (!fd) { - log_message("warning, unable to set firmware loader"); - return; - } - write(fd, UEVENT_HELPER_VALUE, strlen(UEVENT_HELPER_VALUE)); - close(fd); + int fd = open(UEVENT_HELPER_FILE, O_WRONLY|O_TRUNC, 0666); + if (!fd) { + log_message("warning, unable to set firmware loader"); + return; + } + write(fd, UEVENT_HELPER_VALUE, strlen(UEVENT_HELPER_VALUE)); + close(fd); } void init_modules_insmoding(void) { - find_modules_directory(); - if (load_modules_dependencies()) { - fatal_error("warning, error initing modules stuff, modules loading disabled"); - } - if (load_modules_descriptions()) { - log_message("warning, error initing modules stuff"); - } + find_modules_directory(); + if (load_modules_dependencies()) { + fatal_error("warning, error initing modules stuff, modules loading disabled"); + } + if (load_modules_descriptions()) { + log_message("warning, error initing modules stuff"); + } } static void add_modules_conf(char * str) { - static char data[5000] = ""; - char * target = "/tmp/modules.conf"; - int fd; + static char data[5000] = ""; + char * target = "/tmp/modules.conf"; + int fd; - if (strlen(data) + strlen(str) >= sizeof(data)) - return; + if (strlen(data) + strlen(str) >= sizeof(data)) + return; - strcat(data, str); - strcat(data, "\n"); + strcat(data, str); + strcat(data, "\n"); - fd = open(target, O_CREAT|O_WRONLY|O_TRUNC, 00660); - - if (fd == -1) { - log_perror(str); - return; - } + fd = open(target, O_CREAT|O_WRONLY|O_TRUNC, 00660); + + if (fd == -1) { + log_perror(str); + return; + } - if (write(fd, data, strlen(data) + 1) != (ssize_t) (strlen(data) + 1)) - log_perror(str); + if (write(fd, data, strlen(data) + 1) != (ssize_t) (strlen(data) + 1)) + log_perror(str); - close(fd); + close(fd); } int module_already_present(const char * name) { - FILE * f; - struct stat sb; - char *path; - int answ = 0; + FILE * f; + struct stat sb; + char *path; + int answ = 0; - if ((f = fopen("/proc/modules", "rb"))) { + if ((f = fopen("/proc/modules", "rb"))) { while (1) { char buf[500]; if (!fgets(buf, sizeof(buf), f)) break; @@ -302,51 +302,51 @@ int module_already_present(const char * name) fclose(f); } - /* built-in module case. try to find them through sysfs */ - if (!answ) { - asprintf(&path, "/sys/module/%s", name); - if (!stat(path, &sb)) - answ = 1; - free(path); - } - return answ; + /* built-in module case. try to find them through sysfs */ + if (!answ) { + asprintf(&path, "/sys/module/%s", name); + if (!stat(path, &sb)) + answ = 1; + free(path); + } + return answ; } #ifndef ENABLE_NETWORK_STANDALONE static enum insmod_return insmod_with_deps(const char * mod_name, char * options, int allow_modules_floppy) { - struct module_deps_elem * dep; - const char * filename; - - dep = modules_deps; - while (dep && dep->modname && strcmp(dep->modname, mod_name)) dep++; - - if (dep && dep->modname && dep->deps) { - char ** one_dep; - one_dep = dep->deps; - while (*one_dep) { - /* here, we can fail but we don't care, if the error is - * important, the desired module will fail also */ - insmod_with_deps(*one_dep, NULL, allow_modules_floppy); - one_dep++; - } - } + struct module_deps_elem * dep; + const char * filename; + + dep = modules_deps; + while (dep && dep->modname && strcmp(dep->modname, mod_name)) dep++; + + if (dep && dep->modname && dep->deps) { + char ** one_dep; + one_dep = dep->deps; + while (*one_dep) { + /* here, we can fail but we don't care, if the error is + * important, the desired module will fail also */ + insmod_with_deps(*one_dep, NULL, allow_modules_floppy); + one_dep++; + } + } - if (dep && dep->filename) { - filename = dep->filename; - } else { - log_message("warning: unable to get module filename for %s", mod_name); - filename = mod_name; - } - - if (module_already_present(mod_name)) - return INSMOD_OK; - - log_message("needs %s", filename); - { - return insmod_local_file((char *) filename, options); - } + if (dep && dep->filename) { + filename = dep->filename; + } else { + log_message("warning: unable to get module filename for %s", mod_name); + filename = mod_name; + } + + if (module_already_present(mod_name)) + return INSMOD_OK; + + log_message("needs %s", filename); + { + return insmod_local_file((char *) filename, options); + } } #endif @@ -357,84 +357,84 @@ enum insmod_return my_insmod(const char * mod_name, enum driver_type type, char enum insmod_return my_insmod(const char * mod_name, enum driver_type type __attribute__ ((unused)), char * options, int allow_modules_floppy) #endif { - int i; + int i; #ifndef DISABLE_NETWORK - char ** net_devices = NULL; /* fucking compiler */ + char ** net_devices = NULL; /* fucking compiler */ #endif - if (module_already_present(mod_name)) - return INSMOD_OK; + if (module_already_present(mod_name)) + return INSMOD_OK; - log_message("have to insmod %s", mod_name); + log_message("have to insmod %s", mod_name); #ifndef DISABLE_NETWORK - if (type == NETWORK_DEVICES) - net_devices = get_net_devices(); + if (type == NETWORK_DEVICES) + net_devices = get_net_devices(); #endif #ifdef ENABLE_NETWORK_STANDALONE - { - char *cmd = options ? asprintf_("/sbin/modprobe %s %s", mod_name, options) : - asprintf_("/sbin/modprobe %s", mod_name); - log_message("running %s", cmd); - i = system(cmd); - } + { + char *cmd = options ? asprintf_("/sbin/modprobe %s %s", mod_name, options) : + asprintf_("/sbin/modprobe %s", mod_name); + log_message("running %s", cmd); + i = system(cmd); + } #else - i = insmod_with_deps(mod_name, options, allow_modules_floppy); + i = insmod_with_deps(mod_name, options, allow_modules_floppy); #endif - if (i == 0) { - log_message("\tsucceeded %s", mod_name); + if (i == 0) { + log_message("\tsucceeded %s", mod_name); #ifndef DISABLE_NETWORK - if (type == NETWORK_DEVICES) { - char ** new_net_devices = get_net_devices(); - while (new_net_devices && *new_net_devices) { - char alias[500]; - char ** ptr = net_devices; - while (ptr && *ptr) { - if (!strcmp(*new_net_devices, *ptr)) - goto already_present; - ptr++; - } - sprintf(alias, "alias %s %s", *new_net_devices, mod_name); - add_modules_conf(alias); - log_message("NET: %s", alias); - net_discovered_interface(*new_net_devices); - - already_present: - new_net_devices++; - } - } + if (type == NETWORK_DEVICES) { + char ** new_net_devices = get_net_devices(); + while (new_net_devices && *new_net_devices) { + char alias[500]; + char ** ptr = net_devices; + while (ptr && *ptr) { + if (!strcmp(*new_net_devices, *ptr)) + goto already_present; + ptr++; + } + sprintf(alias, "alias %s %s", *new_net_devices, mod_name); + add_modules_conf(alias); + log_message("NET: %s", alias); + net_discovered_interface(*new_net_devices); + + already_present: + new_net_devices++; + } + } #endif - } else - log_message("warning, insmod failed (%s %s) (%d)", mod_name, options, i); - - return i; + } else + log_message("warning, insmod failed (%s %s) (%d)", mod_name, options, i); + + return i; } static enum return_type insmod_with_options(char * mod, enum driver_type type) { - char * questions[] = { "Options", NULL }; - static char ** answers = NULL; - enum return_type results; - char options[500] = "options "; - - results = ask_from_entries("Please enter the parameters to give to the kernel:", questions, &answers, 24, NULL); - if (results != RETURN_OK) - return results; - - strcat(options, mod); - strcat(options, " "); - strcat(options, answers[0]); // because my_insmod will eventually modify the string - - if (my_insmod(mod, type, answers[0], 1) != INSMOD_OK) { - stg1_error_message("Insmod failed."); - return RETURN_ERROR; - } - - add_modules_conf(options); - - return RETURN_OK; + char * questions[] = { "Options", NULL }; + static char ** answers = NULL; + enum return_type results; + char options[500] = "options "; + + results = ask_from_entries("Please enter the parameters to give to the kernel:", questions, &answers, 24, NULL); + if (results != RETURN_OK) + return results; + + strcat(options, mod); + strcat(options, " "); + strcat(options, answers[0]); // because my_insmod will eventually modify the string + + if (my_insmod(mod, type, answers[0], 1) != INSMOD_OK) { + stg1_error_message("Insmod failed."); + return RETURN_ERROR; + } + + add_modules_conf(options); + + return RETURN_OK; } static int strsortfunc(const void *a, const void *b) @@ -444,58 +444,58 @@ static int strsortfunc(const void *a, const void *b) enum return_type ask_insmod(enum driver_type type) { - enum return_type results; - char * choice; - char ** dlist = list_directory(modules_directory); - char ** modules = alloca(sizeof(char *) * (string_array_length(dlist) + 1)); - char ** descrs = alloca(sizeof(char *) * (string_array_length(dlist) + 1)); - char ** p_dlist = dlist; - char ** p_modules = modules; - char ** p_descrs = descrs; - - qsort(dlist, string_array_length(dlist), sizeof(char *), strsortfunc); - - unset_automatic(); /* we are in a fallback mode */ - - while (p_dlist && *p_dlist) { - struct module_descr_elem * descr; - if (!strstr(*p_dlist, kernel_module_extension())) { - p_dlist++; - continue; - } - *p_modules = *p_dlist; - *p_descrs = NULL; - (*p_modules)[strlen(*p_modules)-strlen(kernel_module_extension())] = '\0'; /* remove trailing .ko.gz */ - - descr = modules_descr; - while (descr && descr->modname && strcmp(descr->modname, *p_modules)) descr++; - if (descr) - *p_descrs = descr->description; - - p_dlist++; - p_modules++; - p_descrs++; - } - *p_modules = NULL; - *p_descrs = NULL; - - if (modules && *modules) { - char * mytype; - char msg[200]; - if (type == MEDIA_ADAPTERS) - mytype = "MEDIA"; - else if (type == NETWORK_DEVICES) - mytype = "NET"; - else - return RETURN_ERROR; - - snprintf(msg, sizeof(msg), "Which driver should I try to gain %s access?", mytype); - results = ask_from_list_comments(msg, modules, descrs, &choice); - if (results == RETURN_OK) - return insmod_with_options(choice, type); - else - return results; - } else { - return RETURN_BACK; - } + enum return_type results; + char * choice; + char ** dlist = list_directory(modules_directory); + char ** modules = alloca(sizeof(char *) * (string_array_length(dlist) + 1)); + char ** descrs = alloca(sizeof(char *) * (string_array_length(dlist) + 1)); + char ** p_dlist = dlist; + char ** p_modules = modules; + char ** p_descrs = descrs; + + qsort(dlist, string_array_length(dlist), sizeof(char *), strsortfunc); + + unset_automatic(); /* we are in a fallback mode */ + + while (p_dlist && *p_dlist) { + struct module_descr_elem * descr; + if (!strstr(*p_dlist, kernel_module_extension())) { + p_dlist++; + continue; + } + *p_modules = *p_dlist; + *p_descrs = NULL; + (*p_modules)[strlen(*p_modules)-strlen(kernel_module_extension())] = '\0'; /* remove trailing .ko.gz */ + + descr = modules_descr; + while (descr && descr->modname && strcmp(descr->modname, *p_modules)) descr++; + if (descr) + *p_descrs = descr->description; + + p_dlist++; + p_modules++; + p_descrs++; + } + *p_modules = NULL; + *p_descrs = NULL; + + if (modules && *modules) { + char * mytype; + char msg[200]; + if (type == MEDIA_ADAPTERS) + mytype = "MEDIA"; + else if (type == NETWORK_DEVICES) + mytype = "NET"; + else + return RETURN_ERROR; + + snprintf(msg, sizeof(msg), "Which driver should I try to gain %s access?", mytype); + results = ask_from_list_comments(msg, modules, descrs, &choice); + if (results == RETURN_OK) + return insmod_with_options(choice, type); + else + return results; + } else { + return RETURN_BACK; + } } diff --git a/mdk-stage1/mount.c b/mdk-stage1/mount.c index 918f5d1a2..b481052c7 100644 --- a/mdk-stage1/mount.c +++ b/mdk-stage1/mount.c @@ -37,237 +37,225 @@ /* WARNING: this won't work if the argument is not /dev/ based */ int ensure_dev_exists(const char * dev) { - int major, minor; - int type = S_IFBLK; /* my default type is block. don't forget to change for chars */ - const char * name; - struct stat buf; - char * ptr; - - name = &dev[5]; /* we really need that dev be passed as /dev/something.. */ + int major, minor; + int type = S_IFBLK; /* my default type is block. don't forget to change for chars */ + const char * name; + struct stat buf; + char * ptr; + + name = &dev[5]; /* we really need that dev be passed as /dev/something.. */ - if (!stat(dev, &buf)) - return 0; /* if the file already exists, we assume it's correct */ + if (!stat(dev, &buf)) + return 0; /* if the file already exists, we assume it's correct */ - if (ptr_begins_static_str(name, "sd")) { - /* SCSI disks */ - major = 8; - minor = (name[2] - 'a') << 4; - if (name[3] && name[4]) { - minor += 10 + (name[4] - '0'); - if (name[3] > 1 || name[4] > 5) { - log_message("I don't know how to create device %s, please post bugreport to me!", dev); - return -1; - } - } else if (name[3]) - minor += (name[3] - '0'); - } else if (ptr_begins_static_str(name, "vd")) { - /* Virtual disks */ - major = 252; - minor = (name[2] - 'a') << 4; - if (name[3] && name[4]) { - minor += 10 + (name[4] - '0'); - if (name[3] > 1 || name[4] > 5) { - log_message("I don't know how to create device %s, please post bugreport to me!", dev); - return -1; - } - } else if (name[3]) - minor += (name[3] - '0'); - } else if (ptr_begins_static_str(name, "xvd")) { - /* Virtual disks */ - major = 202; - minor = (name[2] - 'a') << 4; - if (name[4] && name[5]) { - minor += 10 + (name[5] - '0'); - if (name[4] > 1 || name[5] > 5) { - log_message("I don't know how to create device %s, please post bugreport to me!", dev); - return -1; - } - } else if (name[4]) - minor += (name[4] - '0'); - } else if (ptr_begins_static_str(name, "hd")) { - /* IDE disks/cd's */ - if (name[2] == 'a') - major = 3, minor = 0; - else if (name[2] == 'b') - major = 3, minor = 64; - else if (name[2] == 'c') - major = 22, minor = 0; - else if (name[2] == 'd') - major = 22, minor = 64; - else if (name[2] == 'e') - major = 33, minor = 0; - else if (name[2] == 'f') - major = 33, minor = 64; - else if (name[2] == 'g') - major = 34, minor = 0; - else if (name[2] == 'h') - major = 34, minor = 64; - else if (name[2] == 'i') - major = 56, minor = 0; - else if (name[2] == 'j') - major = 56, minor = 64; - else if (name[2] == 'k') - major = 57, minor = 0; - else if (name[2] == 'l') - major = 57, minor = 64; - else if (name[2] == 'm') - major = 88, minor = 0; - else if (name[2] == 'n') - major = 88, minor = 64; - else if (name[2] == 'o') - major = 89, minor = 0; - else if (name[2] == 'p') - major = 89, minor = 64; - else if (name[2] == 'q') - major = 90, minor = 0; - else if (name[2] == 'r') - major = 90, minor = 64; - else if (name[2] == 's') - major = 91, minor = 0; - else if (name[2] == 't') - major = 91, minor = 64; - else - return -1; - - if (name[3] && name[4]) - minor += 10 + (name[4] - '0'); - else if (name[3]) - minor += (name[3] - '0'); - } else if (ptr_begins_static_str(name , "sr")) { - /* SCSI cd's */ - major = 11; - minor = name[2] - '0'; - } else if (ptr_begins_static_str(name, "ida/") || - ptr_begins_static_str(name, "cciss/")) { - /* Compaq Smart Array "ida/c0d0{p1}" */ - ptr = strchr(name, '/'); - mkdir("/dev/ida", 0755); - mkdir("/dev/cciss", 0755); - major = ptr_begins_static_str(name, "ida/") ? 72 : 104 + charstar_to_int(ptr+2); - ptr = strchr(ptr, 'd'); - minor = 16 * charstar_to_int(ptr+1); - ptr = strchr(ptr, 'p'); - minor += charstar_to_int(ptr+1); - } else if (ptr_begins_static_str(name, "rd/")) { - /* DAC960 "rd/cXdXXpX" */ - mkdir("/dev/rd", 0755); - major = 48 + charstar_to_int(name+4); - ptr = strchr(name+4, 'd'); - minor = 8 * charstar_to_int(ptr+1); - ptr = strchr(ptr, 'p'); - minor += charstar_to_int(ptr+1); - } else if (ptr_begins_static_str(name, "loop")) { - major = 7; - minor = name[4] - '0'; - } else if (ptr_begins_static_str(name, "chloop")) { - major = 100; - minor = name[6] - '0'; - } else { - log_message("I don't know how to create device %s, please post bugreport to me!", dev); - return -1; - } + if (ptr_begins_static_str(name, "sd")) { + /* SCSI disks */ + major = 8; + minor = (name[2] - 'a') << 4; + if (name[3] && name[4]) { + minor += 10 + (name[4] - '0'); + if (name[3] > 1 || name[4] > 5) { + log_message("I don't know how to create device %s, please post bugreport to me!", dev); + return -1; + } + } else if (name[3]) + minor += (name[3] - '0'); + } else if (ptr_begins_static_str(name, "vd")) { + /* Virtual disks */ + major = 252; + minor = (name[2] - 'a') << 4; + if (name[3] && name[4]) { + minor += 10 + (name[4] - '0'); + if (name[3] > 1 || name[4] > 5) { + log_message("I don't know how to create device %s, please post bugreport to me!", dev); + return -1; + } + } else if (name[3]) + minor += (name[3] - '0'); + } else if (ptr_begins_static_str(name, "hd")) { + /* IDE disks/cd's */ + if (name[2] == 'a') + major = 3, minor = 0; + else if (name[2] == 'b') + major = 3, minor = 64; + else if (name[2] == 'c') + major = 22, minor = 0; + else if (name[2] == 'd') + major = 22, minor = 64; + else if (name[2] == 'e') + major = 33, minor = 0; + else if (name[2] == 'f') + major = 33, minor = 64; + else if (name[2] == 'g') + major = 34, minor = 0; + else if (name[2] == 'h') + major = 34, minor = 64; + else if (name[2] == 'i') + major = 56, minor = 0; + else if (name[2] == 'j') + major = 56, minor = 64; + else if (name[2] == 'k') + major = 57, minor = 0; + else if (name[2] == 'l') + major = 57, minor = 64; + else if (name[2] == 'm') + major = 88, minor = 0; + else if (name[2] == 'n') + major = 88, minor = 64; + else if (name[2] == 'o') + major = 89, minor = 0; + else if (name[2] == 'p') + major = 89, minor = 64; + else if (name[2] == 'q') + major = 90, minor = 0; + else if (name[2] == 'r') + major = 90, minor = 64; + else if (name[2] == 's') + major = 91, minor = 0; + else if (name[2] == 't') + major = 91, minor = 64; + else + return -1; + + if (name[3] && name[4]) + minor += 10 + (name[4] - '0'); + else if (name[3]) + minor += (name[3] - '0'); + } else if (ptr_begins_static_str(name , "sr")) { + /* SCSI cd's */ + major = 11; + minor = name[2] - '0'; + } else if (ptr_begins_static_str(name, "ida/") || + ptr_begins_static_str(name, "cciss/")) { + /* Compaq Smart Array "ida/c0d0{p1}" */ + ptr = strchr(name, '/'); + mkdir("/dev/ida", 0755); + mkdir("/dev/cciss", 0755); + major = ptr_begins_static_str(name, "ida/") ? 72 : 104 + charstar_to_int(ptr+2); + ptr = strchr(ptr, 'd'); + minor = 16 * charstar_to_int(ptr+1); + ptr = strchr(ptr, 'p'); + minor += charstar_to_int(ptr+1); + } else if (ptr_begins_static_str(name, "rd/")) { + /* DAC960 "rd/cXdXXpX" */ + mkdir("/dev/rd", 0755); + major = 48 + charstar_to_int(name+4); + ptr = strchr(name+4, 'd'); + minor = 8 * charstar_to_int(ptr+1); + ptr = strchr(ptr, 'p'); + minor += charstar_to_int(ptr+1); + } else if (ptr_begins_static_str(name, "loop")) { + major = 7; + minor = name[4] - '0'; + } else if (ptr_begins_static_str(name, "chloop")) { + major = 100; + minor = name[6] - '0'; + } else { + log_message("I don't know how to create device %s, please post bugreport to me!", dev); + return -1; + } - if (mknod(dev, type | 0600, makedev(major, minor))) { - log_perror(dev); - return -1; - } - - return 0; + if (mknod(dev, type | 0600, makedev(major, minor))) { + log_perror(dev); + return -1; + } + + return 0; } /* mounts, creating the device if needed+possible */ int my_mount(char *dev, char *location, char *fs, int force_rw) { - unsigned long flags = MS_MGC_VAL | (force_rw ? 0 : MS_RDONLY); - char * opts = NULL; - struct stat buf; - int rc; + unsigned long flags = MS_MGC_VAL | (force_rw ? 0 : MS_RDONLY); + char * opts = NULL; + struct stat buf; + int rc; - if (strcmp(fs, "nfs")) { - rc = ensure_dev_exists(dev); - if (rc != 0) { - log_message("could not create required device file"); - return -1; - } - } + if (strcmp(fs, "nfs")) { + rc = ensure_dev_exists(dev); + if (rc != 0) { + log_message("could not create required device file"); + return -1; + } + } - log_message("mounting %s on %s as type %s", dev, location, fs); + log_message("mounting %s on %s as type %s", dev, location, fs); - if (stat(location, &buf)) { - if (mkdir(location, 0755)) { - log_perror("could not create location dir"); - return -1; - } - } else if (!S_ISDIR(buf.st_mode)) { - log_message("not a dir %s, will unlink and mkdir", location); - if (unlink(location)) { - log_perror("could not unlink"); - return -1; - } - if (mkdir(location, 0755)) { - log_perror("could not create location dir"); - return -1; - } - } + if (stat(location, &buf)) { + if (mkdir(location, 0755)) { + log_perror("could not create location dir"); + return -1; + } + } else if (!S_ISDIR(buf.st_mode)) { + log_message("not a dir %s, will unlink and mkdir", location); + if (unlink(location)) { + log_perror("could not unlink"); + return -1; + } + if (mkdir(location, 0755)) { + log_perror("could not create location dir"); + return -1; + } + } - if (!strcmp(fs, "supermount")) { - my_insmod("supermount", ANY_DRIVER_TYPE, NULL, 1); - my_insmod("isofs", ANY_DRIVER_TYPE, NULL, 1); - opts = alloca(500); + if (!strcmp(fs, "supermount")) { + my_insmod("supermount", ANY_DRIVER_TYPE, NULL, 1); + my_insmod("isofs", ANY_DRIVER_TYPE, NULL, 1); + opts = alloca(500); sprintf(opts, "dev=%s,fs=iso9660,tray_lock=always", dev); dev = "none"; - } + } #ifndef DISABLE_MEDIAS - if (!strcmp(fs, "vfat")) { - my_insmod("nls_cp437", ANY_DRIVER_TYPE, NULL, 1); - my_insmod("nls_iso8859_1", ANY_DRIVER_TYPE, NULL, 1); - my_insmod("vfat", ANY_DRIVER_TYPE, NULL, 1); - opts = "check=relaxed"; - } + if (!strcmp(fs, "vfat")) { + my_insmod("nls_cp437", ANY_DRIVER_TYPE, NULL, 1); + my_insmod("nls_iso8859_1", ANY_DRIVER_TYPE, NULL, 1); + my_insmod("vfat", ANY_DRIVER_TYPE, NULL, 1); + opts = "check=relaxed"; + } - if (!strcmp(fs, "ntfs")) { - my_insmod("ntfs", ANY_DRIVER_TYPE, NULL, 1); - } + if (!strcmp(fs, "ntfs")) { + my_insmod("ntfs", ANY_DRIVER_TYPE, NULL, 1); + } - if (!strcmp(fs, "reiserfs")) - my_insmod("reiserfs", ANY_DRIVER_TYPE, NULL, 1); + if (!strcmp(fs, "reiserfs")) + my_insmod("reiserfs", ANY_DRIVER_TYPE, NULL, 1); - if (!strcmp(fs, "reiser4")) - my_insmod("reiser4", ANY_DRIVER_TYPE, NULL, 1); + if (!strcmp(fs, "reiser4")) + my_insmod("reiser4", ANY_DRIVER_TYPE, NULL, 1); - if (!strcmp(fs, "jfs")) - my_insmod("jfs", ANY_DRIVER_TYPE, NULL, 1); + if (!strcmp(fs, "jfs")) + my_insmod("jfs", ANY_DRIVER_TYPE, NULL, 1); - if (!strcmp(fs, "xfs")) - my_insmod("xfs", ANY_DRIVER_TYPE, NULL, 1); + if (!strcmp(fs, "xfs")) + my_insmod("xfs", ANY_DRIVER_TYPE, NULL, 1); - if (!strcmp(fs, "ext4")) - my_insmod("ext4", ANY_DRIVER_TYPE, NULL, 1); + if (!strcmp(fs, "ext4")) + my_insmod("ext4", ANY_DRIVER_TYPE, NULL, 1); - if (!strcmp(fs, "btrfs")) - my_insmod("btrfs", ANY_DRIVER_TYPE, NULL, 1); + if (!strcmp(fs, "btrfs")) + my_insmod("btrfs", ANY_DRIVER_TYPE, NULL, 1); #endif - if (!strcmp(fs, "iso9660")) - my_insmod("isofs", ANY_DRIVER_TYPE, NULL, 1); + if (!strcmp(fs, "iso9660")) + my_insmod("isofs", ANY_DRIVER_TYPE, NULL, 1); #ifndef DISABLE_NETWORK - if (!strcmp(fs, "nfs")) { - my_insmod("nfs", ANY_DRIVER_TYPE, NULL, 1); - log_message("preparing nfsmount for %s", dev); - rc = nfsmount_prepare(dev, &opts); - if (rc != 0) - return rc; - } + if (!strcmp(fs, "nfs")) { + my_insmod("nfs", ANY_DRIVER_TYPE, NULL, 1); + log_message("preparing nfsmount for %s", dev); + rc = nfsmount_prepare(dev, &opts); + if (rc != 0) + return rc; + } #endif - rc = mount(dev, location, fs, flags, opts); - if (rc != 0) { - log_perror("mount failed"); - rmdir(location); - } + rc = mount(dev, location, fs, flags, opts); + if (rc != 0) { + log_perror("mount failed"); + rmdir(location); + } - return rc; + return rc; } diff --git a/mdk-stage1/network.c b/mdk-stage1/network.c index 9030fbbde..b86cc1e61 100644 --- a/mdk-stage1/network.c +++ b/mdk-stage1/network.c @@ -59,136 +59,136 @@ static void error_message_net(void) /* reduce code size */ { - stg1_error_message("Could not configure network."); + stg1_error_message("Could not configure network."); } int configure_net_device(struct interface_info * intf) { - struct ifreq req; - struct rtentry route; - int s; - struct sockaddr_in addr; - struct in_addr ia; - char ip[20], nm[20], nw[20], bc[20]; - - addr.sin_family = AF_INET; - addr.sin_port = 0; - - memcpy(&ia, &intf->ip, sizeof(intf->ip)); - strcpy(ip, inet_ntoa(ia)); - - memcpy(&ia, &intf->netmask, sizeof(intf->netmask)); - strcpy(nm, inet_ntoa(ia)); - - memcpy(&ia, &intf->broadcast, sizeof(intf->broadcast)); - strcpy(bc, inet_ntoa(ia)); - - memcpy(&ia, &intf->network, sizeof(intf->network)); - strcpy(nw, inet_ntoa(ia)); - - log_message("configuring device %s ip: %s nm: %s nw: %s bc: %s", intf->device, ip, nm, nw, bc); - - if (IS_TESTING) - return 0; - - s = socket(AF_INET, SOCK_DGRAM, 0); - if (s < 0) { - log_perror("socket"); - error_message_net(); - return 1; - } - - strcpy(req.ifr_name, intf->device); - - if (intf->is_up == 1) { - log_message("interface already up, downing before reconfigure"); - - req.ifr_flags = 0; - if (ioctl(s, SIOCSIFFLAGS, &req)) { - close(s); - log_perror("SIOCSIFFLAGS (downing)"); - error_message_net(); - return 1; - } - } - - /* sets IP address */ - addr.sin_port = 0; - memcpy(&addr.sin_addr, &intf->ip, sizeof(intf->ip)); - memcpy(&req.ifr_addr, &addr, sizeof(addr)); - if (ioctl(s, SIOCSIFADDR, &req)) { - close(s); - log_perror("SIOCSIFADDR"); - error_message_net(); - return 1; - } - - /* sets broadcast */ - memcpy(&addr.sin_addr, &intf->broadcast, sizeof(intf->broadcast)); - memcpy(&req.ifr_broadaddr, &addr, sizeof(addr)); - if (ioctl(s, SIOCSIFBRDADDR, &req)) { - close(s); - log_perror("SIOCSIFBRDADDR"); - error_message_net(); - return 1; - } - - /* sets netmask */ - memcpy(&addr.sin_addr, &intf->netmask, sizeof(intf->netmask)); - memcpy(&req.ifr_netmask, &addr, sizeof(addr)); - if (ioctl(s, SIOCSIFNETMASK, &req)) { - close(s); - log_perror("SIOCSIFNETMASK"); - error_message_net(); - return 1; - } - - if (intf->is_ptp) - req.ifr_flags = IFF_UP | IFF_RUNNING | IFF_POINTOPOINT | IFF_NOARP; - else - req.ifr_flags = IFF_UP | IFF_RUNNING | IFF_BROADCAST; - - /* brings up networking! */ - if (ioctl(s, SIOCSIFFLAGS, &req)) { - close(s); - log_perror("SIOCSIFFLAGS (upping)"); - error_message_net(); - return 1; - } - - memset(&route, 0, sizeof(route)); - route.rt_dev = intf->device; - route.rt_flags = RTF_UP; - - memcpy(&addr.sin_addr, &intf->network, sizeof(intf->network)); - memcpy(&route.rt_dst, &addr, sizeof(addr)); - - memcpy(&addr.sin_addr, &intf->netmask, sizeof(intf->netmask)); - memcpy(&route.rt_genmask, &addr, sizeof(addr)); - - /* adds route */ - if (ioctl(s, SIOCADDRT, &route)) { - close(s); - log_perror("SIOCADDRT"); - error_message_net(); - return 1; - } - - close(s); - - intf->is_up = 1; - - if (intf->boot_proto != BOOTPROTO_DHCP && !streq(intf->device, "lo")) { - /* I need to sleep a bit in order for kernel to finish - init of the network device; if not, first sendto() for - gethostbyaddr will get an EINVAL. */ - wait_message("Bringing up networking..."); - sleep(2); - remove_wait_message(); - } - - return 0; + struct ifreq req; + struct rtentry route; + int s; + struct sockaddr_in addr; + struct in_addr ia; + char ip[20], nm[20], nw[20], bc[20]; + + addr.sin_family = AF_INET; + addr.sin_port = 0; + + memcpy(&ia, &intf->ip, sizeof(intf->ip)); + strcpy(ip, inet_ntoa(ia)); + + memcpy(&ia, &intf->netmask, sizeof(intf->netmask)); + strcpy(nm, inet_ntoa(ia)); + + memcpy(&ia, &intf->broadcast, sizeof(intf->broadcast)); + strcpy(bc, inet_ntoa(ia)); + + memcpy(&ia, &intf->network, sizeof(intf->network)); + strcpy(nw, inet_ntoa(ia)); + + log_message("configuring device %s ip: %s nm: %s nw: %s bc: %s", intf->device, ip, nm, nw, bc); + + if (IS_TESTING) + return 0; + + s = socket(AF_INET, SOCK_DGRAM, 0); + if (s < 0) { + log_perror("socket"); + error_message_net(); + return 1; + } + + strcpy(req.ifr_name, intf->device); + + if (intf->is_up == 1) { + log_message("interface already up, downing before reconfigure"); + + req.ifr_flags = 0; + if (ioctl(s, SIOCSIFFLAGS, &req)) { + close(s); + log_perror("SIOCSIFFLAGS (downing)"); + error_message_net(); + return 1; + } + } + + /* sets IP address */ + addr.sin_port = 0; + memcpy(&addr.sin_addr, &intf->ip, sizeof(intf->ip)); + memcpy(&req.ifr_addr, &addr, sizeof(addr)); + if (ioctl(s, SIOCSIFADDR, &req)) { + close(s); + log_perror("SIOCSIFADDR"); + error_message_net(); + return 1; + } + + /* sets broadcast */ + memcpy(&addr.sin_addr, &intf->broadcast, sizeof(intf->broadcast)); + memcpy(&req.ifr_broadaddr, &addr, sizeof(addr)); + if (ioctl(s, SIOCSIFBRDADDR, &req)) { + close(s); + log_perror("SIOCSIFBRDADDR"); + error_message_net(); + return 1; + } + + /* sets netmask */ + memcpy(&addr.sin_addr, &intf->netmask, sizeof(intf->netmask)); + memcpy(&req.ifr_netmask, &addr, sizeof(addr)); + if (ioctl(s, SIOCSIFNETMASK, &req)) { + close(s); + log_perror("SIOCSIFNETMASK"); + error_message_net(); + return 1; + } + + if (intf->is_ptp) + req.ifr_flags = IFF_UP | IFF_RUNNING | IFF_POINTOPOINT | IFF_NOARP; + else + req.ifr_flags = IFF_UP | IFF_RUNNING | IFF_BROADCAST; + + /* brings up networking! */ + if (ioctl(s, SIOCSIFFLAGS, &req)) { + close(s); + log_perror("SIOCSIFFLAGS (upping)"); + error_message_net(); + return 1; + } + + memset(&route, 0, sizeof(route)); + route.rt_dev = intf->device; + route.rt_flags = RTF_UP; + + memcpy(&addr.sin_addr, &intf->network, sizeof(intf->network)); + memcpy(&route.rt_dst, &addr, sizeof(addr)); + + memcpy(&addr.sin_addr, &intf->netmask, sizeof(intf->netmask)); + memcpy(&route.rt_genmask, &addr, sizeof(addr)); + + /* adds route */ + if (ioctl(s, SIOCADDRT, &route)) { + close(s); + log_perror("SIOCADDRT"); + error_message_net(); + return 1; + } + + close(s); + + intf->is_up = 1; + + if (intf->boot_proto != BOOTPROTO_DHCP && !streq(intf->device, "lo")) { + /* I need to sleep a bit in order for kernel to finish + init of the network device; if not, first sendto() for + gethostbyaddr will get an EINVAL. */ + wait_message("Bringing up networking..."); + sleep(2); + remove_wait_message(); + } + + return 0; } /* host network informations */ @@ -200,420 +200,420 @@ struct in_addr dns_server2 = { 0 }; static int add_default_route(void) { - int s; - struct rtentry route; - struct sockaddr_in addr; - - if (IS_TESTING) - return 0; - - if (gateway.s_addr == 0) { - log_message("no gateway provided, can't add default route"); - return 0; - } - - s = socket(AF_INET, SOCK_DGRAM, 0); - if (s < 0) { - close(s); - log_perror("socket"); - error_message_net(); - return 1; - } - - memset(&route, 0, sizeof(route)); - - addr.sin_family = AF_INET; - addr.sin_port = 0; - addr.sin_addr = gateway; - memcpy(&route.rt_gateway, &addr, sizeof(addr)); - - addr.sin_addr.s_addr = INADDR_ANY; - memcpy(&route.rt_dst, &addr, sizeof(addr)); - memcpy(&route.rt_genmask, &addr, sizeof(addr)); - - route.rt_flags = RTF_UP | RTF_GATEWAY; - route.rt_metric = 0; - - if (ioctl(s, SIOCADDRT, &route)) { - close(s); - log_perror("SIOCADDRT"); - error_message_net(); - return 1; - } - - close(s); - - return 0; + int s; + struct rtentry route; + struct sockaddr_in addr; + + if (IS_TESTING) + return 0; + + if (gateway.s_addr == 0) { + log_message("no gateway provided, can't add default route"); + return 0; + } + + s = socket(AF_INET, SOCK_DGRAM, 0); + if (s < 0) { + close(s); + log_perror("socket"); + error_message_net(); + return 1; + } + + memset(&route, 0, sizeof(route)); + + addr.sin_family = AF_INET; + addr.sin_port = 0; + addr.sin_addr = gateway; + memcpy(&route.rt_gateway, &addr, sizeof(addr)); + + addr.sin_addr.s_addr = INADDR_ANY; + memcpy(&route.rt_dst, &addr, sizeof(addr)); + memcpy(&route.rt_genmask, &addr, sizeof(addr)); + + route.rt_flags = RTF_UP | RTF_GATEWAY; + route.rt_metric = 0; + + if (ioctl(s, SIOCADDRT, &route)) { + close(s); + log_perror("SIOCADDRT"); + error_message_net(); + return 1; + } + + close(s); + + return 0; } static int write_resolvconf(void) { - char * filename = "/etc/resolv.conf"; - FILE * f; - - if (dns_server.s_addr == 0) { - log_message("resolvconf needs a dns server"); - return -1; - } - - f = fopen(filename, "w"); - if (!f) { - log_perror(filename); - return -1; - } - - if (domain) - fprintf(f, "search %s\n", domain); /* we can live without the domain search (user will have to enter fully-qualified names) */ - fprintf(f, "nameserver %s\n", inet_ntoa(dns_server)); - if (dns_server2.s_addr != 0) - fprintf(f, "nameserver %s\n", inet_ntoa(dns_server2)); - - fclose(f); - res_init(); /* reinit the resolver so DNS changes take affect */ - - return 0; + char * filename = "/etc/resolv.conf"; + FILE * f; + + if (dns_server.s_addr == 0) { + log_message("resolvconf needs a dns server"); + return -1; + } + + f = fopen(filename, "w"); + if (!f) { + log_perror(filename); + return -1; + } + + if (domain) + fprintf(f, "search %s\n", domain); /* we can live without the domain search (user will have to enter fully-qualified names) */ + fprintf(f, "nameserver %s\n", inet_ntoa(dns_server)); + if (dns_server2.s_addr != 0) + fprintf(f, "nameserver %s\n", inet_ntoa(dns_server2)); + + fclose(f); + res_init(); /* reinit the resolver so DNS changes take affect */ + + return 0; } static int save_netinfo(struct interface_info * intf) { - char * file_network = "/tmp/network"; - char file_intf[500]; - FILE * f; - - f = fopen(file_network, "w"); - if (!f) { - log_perror(file_network); - return -1; - } - - fprintf(f, "NETWORKING=yes\n"); - fprintf(f, "FORWARD_IPV4=false\n"); - - if (hostname && !intf->boot_proto == BOOTPROTO_DHCP) - fprintf(f, "HOSTNAME=%s\n", hostname); - if (gateway.s_addr != 0) - fprintf(f, "GATEWAY=%s\n", inet_ntoa(gateway)); - - fclose(f); - - - strcpy(file_intf, "/tmp/ifcfg-"); - strcat(file_intf, intf->device); - - f = fopen(file_intf, "w"); - if (!f) { - log_perror(file_intf); - return -1; - } - - fprintf(f, "DEVICE=%s\n", intf->device); - - if (intf->boot_proto == BOOTPROTO_DHCP) { - fprintf(f, "BOOTPROTO=dhcp\n"); - if (dhcp_hostname && !streq(dhcp_hostname, "")) - fprintf(f, "DHCP_HOSTNAME=%s\n", dhcp_hostname); - } else if (intf->boot_proto == BOOTPROTO_STATIC) { - fprintf(f, "BOOTPROTO=static\n"); - fprintf(f, "IPADDR=%s\n", inet_ntoa(intf->ip)); - fprintf(f, "NETMASK=%s\n", inet_ntoa(intf->netmask)); - fprintf(f, "NETWORK=%s\n", inet_ntoa(intf->network)); - fprintf(f, "BROADCAST=%s\n", inet_ntoa(intf->broadcast)); - if (domain) - fprintf(f, "DOMAIN=%s\n", domain); - if (dns_server.s_addr != 0) - fprintf(f, "DNS1=%s\n", inet_ntoa(dns_server)); - if (dns_server2.s_addr != 0) - fprintf(f, "DNS2=%s\n", inet_ntoa(dns_server2)); - } else if (intf->boot_proto == BOOTPROTO_ADSL_PPPOE) { - fprintf(f, "BOOTPROTO=adsl_pppoe\n"); - fprintf(f, "USER=%s\n", intf->user); - fprintf(f, "PASS=%s\n", intf->pass); - fprintf(f, "ACNAME=%s\n", intf->acname); - } - - fclose(f); - - return 0; + char * file_network = "/tmp/network"; + char file_intf[500]; + FILE * f; + + f = fopen(file_network, "w"); + if (!f) { + log_perror(file_network); + return -1; + } + + fprintf(f, "NETWORKING=yes\n"); + fprintf(f, "FORWARD_IPV4=false\n"); + + if (hostname && !intf->boot_proto == BOOTPROTO_DHCP) + fprintf(f, "HOSTNAME=%s\n", hostname); + if (gateway.s_addr != 0) + fprintf(f, "GATEWAY=%s\n", inet_ntoa(gateway)); + + fclose(f); + + + strcpy(file_intf, "/tmp/ifcfg-"); + strcat(file_intf, intf->device); + + f = fopen(file_intf, "w"); + if (!f) { + log_perror(file_intf); + return -1; + } + + fprintf(f, "DEVICE=%s\n", intf->device); + + if (intf->boot_proto == BOOTPROTO_DHCP) { + fprintf(f, "BOOTPROTO=dhcp\n"); + if (dhcp_hostname && !streq(dhcp_hostname, "")) + fprintf(f, "DHCP_HOSTNAME=%s\n", dhcp_hostname); + } else if (intf->boot_proto == BOOTPROTO_STATIC) { + fprintf(f, "BOOTPROTO=static\n"); + fprintf(f, "IPADDR=%s\n", inet_ntoa(intf->ip)); + fprintf(f, "NETMASK=%s\n", inet_ntoa(intf->netmask)); + fprintf(f, "NETWORK=%s\n", inet_ntoa(intf->network)); + fprintf(f, "BROADCAST=%s\n", inet_ntoa(intf->broadcast)); + if (domain) + fprintf(f, "DOMAIN=%s\n", domain); + if (dns_server.s_addr != 0) + fprintf(f, "DNS1=%s\n", inet_ntoa(dns_server)); + if (dns_server2.s_addr != 0) + fprintf(f, "DNS2=%s\n", inet_ntoa(dns_server2)); + } else if (intf->boot_proto == BOOTPROTO_ADSL_PPPOE) { + fprintf(f, "BOOTPROTO=adsl_pppoe\n"); + fprintf(f, "USER=%s\n", intf->user); + fprintf(f, "PASS=%s\n", intf->pass); + fprintf(f, "ACNAME=%s\n", intf->acname); + } + + fclose(f); + + return 0; } char * guess_netmask(char * ip_addr) { - struct in_addr addr; - unsigned long int tmp; - - if (streq(ip_addr, "") || !inet_aton(ip_addr, &addr)) - return ""; - - log_message("guessing netmask"); - - tmp = ntohl(addr.s_addr); - - if (((tmp & 0xFF000000) >> 24) <= 127) - return "255.0.0.0"; - else if (((tmp & 0xFF000000) >> 24) <= 191) - return "255.255.0.0"; - else - return "255.255.255.0"; + struct in_addr addr; + unsigned long int tmp; + + if (streq(ip_addr, "") || !inet_aton(ip_addr, &addr)) + return ""; + + log_message("guessing netmask"); + + tmp = ntohl(addr.s_addr); + + if (((tmp & 0xFF000000) >> 24) <= 127) + return "255.0.0.0"; + else if (((tmp & 0xFF000000) >> 24) <= 191) + return "255.255.0.0"; + else + return "255.255.255.0"; } char * guess_domain_from_hostname(char *hostname) { - char *domain = strchr(strdup(hostname), '.'); - if (!domain || domain[1] == '\0') { - log_message("unable to guess domain from hostname: %s", hostname); - return NULL; - } - return domain + 1; /* skip '.' */ + char *domain = strchr(strdup(hostname), '.'); + if (!domain || domain[1] == '\0') { + log_message("unable to guess domain from hostname: %s", hostname); + return NULL; + } + return domain + 1; /* skip '.' */ } static void static_ip_callback(char ** strings) { - struct in_addr addr; + struct in_addr addr; static int done = 0; if (done) return; - if (streq(strings[0], "") || !inet_aton(strings[0], &addr)) - return; + if (streq(strings[0], "") || !inet_aton(strings[0], &addr)) + return; done = 1; - if (!strcmp(strings[1], "")) { - char * ptr; - strings[1] = strdup(strings[0]); - ptr = strrchr(strings[1], '.'); - if (ptr) - *(ptr+1) = '\0'; - } + if (!strcmp(strings[1], "")) { + char * ptr; + strings[1] = strdup(strings[0]); + ptr = strrchr(strings[1], '.'); + if (ptr) + *(ptr+1) = '\0'; + } - if (!strcmp(strings[2], "")) - strings[2] = strdup(strings[1]); + if (!strcmp(strings[2], "")) + strings[2] = strdup(strings[1]); - if (!strcmp(strings[3], "")) - strings[3] = strdup(guess_netmask(strings[0])); + if (!strcmp(strings[3], "")) + strings[3] = strdup(guess_netmask(strings[0])); } static enum return_type setup_network_interface(struct interface_info * intf) { - enum return_type results; - char * bootprotos[] = { "DHCP", "Static", "ADSL", NULL }; - char * bootprotos_auto[] = { "dhcp", "static", "adsl" }; - char * choice; - - results = ask_from_list_auto("Please select your network connection type.", bootprotos, &choice, "network", bootprotos_auto); - if (results != RETURN_OK) - return results; - - if (!strcmp(choice, "Static")) { - char * questions[] = { "IP of this machine", "IP of DNS", "IP of default gateway", "Netmask", NULL }; - char * questions_auto[] = { "ip", "dns", "gateway", "netmask" }; - static char ** answers = NULL; - struct in_addr addr; - - results = ask_from_entries_auto("Please enter the network information. (leave netmask blank for Internet standard)", - questions, &answers, 16, questions_auto, static_ip_callback); - if (results != RETURN_OK) - return setup_network_interface(intf); - - if (streq(answers[0], "") || !inet_aton(answers[0], &addr)) { - stg1_error_message("Invalid IP address."); - return setup_network_interface(intf); - } - memcpy(&intf->ip, &addr, sizeof(addr)); - - if (!inet_aton(answers[1], &dns_server)) { - log_message("invalid DNS"); - dns_server.s_addr = 0; /* keep an understandable state */ - } - - if (streq(answers[0], answers[1])) { - log_message("IP and DNS are the same, guess you don't want a DNS, disabling it"); - dns_server.s_addr = 0; /* keep an understandable state */ - } - - if (!inet_aton(answers[2], &gateway)) { - log_message("invalid gateway"); - gateway.s_addr = 0; /* keep an understandable state */ - } - - if ((streq(answers[3], "") && inet_aton(guess_netmask(answers[0]), &addr)) - || inet_aton(answers[3], &addr)) - memcpy(&intf->netmask, &addr, sizeof(addr)); - else { - stg1_error_message("Invalid netmask."); - return setup_network_interface(intf); - } - - *((uint32_t *) &intf->broadcast) = (*((uint32_t *) &intf->ip) & - *((uint32_t *) &intf->netmask)) | ~(*((uint32_t *) &intf->netmask)); - - inet_aton("255.255.255.255", &addr); - if (!memcmp(&addr, &intf->netmask, sizeof(addr))) { - log_message("netmask is 255.255.255.255 -> point to point device"); - intf->network = gateway; - intf->is_ptp = 1; - } else { - *((uint32_t *) &intf->network) = *((uint32_t *) &intf->ip) & *((uint32_t *) &intf->netmask); - intf->is_ptp = 0; - } - intf->boot_proto = BOOTPROTO_STATIC; - - if (configure_net_device(intf)) - return RETURN_ERROR; - - } else if (streq(choice, "DHCP")) { - results = perform_dhcp(intf); - - if (results == RETURN_BACK) - return setup_network_interface(intf); - if (results == RETURN_ERROR) - return results; - intf->boot_proto = BOOTPROTO_DHCP; - - if (configure_net_device(intf)) - return RETURN_ERROR; - - } else if (streq(choice, "ADSL")) { - results = perform_adsl(intf); - - if (results == RETURN_BACK) - return setup_network_interface(intf); - if (results == RETURN_ERROR) - return results; - } else - return RETURN_ERROR; - - return add_default_route(); + enum return_type results; + char * bootprotos[] = { "DHCP", "Static", "ADSL", NULL }; + char * bootprotos_auto[] = { "dhcp", "static", "adsl" }; + char * choice; + + results = ask_from_list_auto("Please select your network connection type.", bootprotos, &choice, "network", bootprotos_auto); + if (results != RETURN_OK) + return results; + + if (!strcmp(choice, "Static")) { + char * questions[] = { "IP of this machine", "IP of DNS", "IP of default gateway", "Netmask", NULL }; + char * questions_auto[] = { "ip", "dns", "gateway", "netmask" }; + static char ** answers = NULL; + struct in_addr addr; + + results = ask_from_entries_auto("Please enter the network information. (leave netmask blank for Internet standard)", + questions, &answers, 16, questions_auto, static_ip_callback); + if (results != RETURN_OK) + return setup_network_interface(intf); + + if (streq(answers[0], "") || !inet_aton(answers[0], &addr)) { + stg1_error_message("Invalid IP address."); + return setup_network_interface(intf); + } + memcpy(&intf->ip, &addr, sizeof(addr)); + + if (!inet_aton(answers[1], &dns_server)) { + log_message("invalid DNS"); + dns_server.s_addr = 0; /* keep an understandable state */ + } + + if (streq(answers[0], answers[1])) { + log_message("IP and DNS are the same, guess you don't want a DNS, disabling it"); + dns_server.s_addr = 0; /* keep an understandable state */ + } + + if (!inet_aton(answers[2], &gateway)) { + log_message("invalid gateway"); + gateway.s_addr = 0; /* keep an understandable state */ + } + + if ((streq(answers[3], "") && inet_aton(guess_netmask(answers[0]), &addr)) + || inet_aton(answers[3], &addr)) + memcpy(&intf->netmask, &addr, sizeof(addr)); + else { + stg1_error_message("Invalid netmask."); + return setup_network_interface(intf); + } + + *((uint32_t *) &intf->broadcast) = (*((uint32_t *) &intf->ip) & + *((uint32_t *) &intf->netmask)) | ~(*((uint32_t *) &intf->netmask)); + + inet_aton("255.255.255.255", &addr); + if (!memcmp(&addr, &intf->netmask, sizeof(addr))) { + log_message("netmask is 255.255.255.255 -> point to point device"); + intf->network = gateway; + intf->is_ptp = 1; + } else { + *((uint32_t *) &intf->network) = *((uint32_t *) &intf->ip) & *((uint32_t *) &intf->netmask); + intf->is_ptp = 0; + } + intf->boot_proto = BOOTPROTO_STATIC; + + if (configure_net_device(intf)) + return RETURN_ERROR; + + } else if (streq(choice, "DHCP")) { + results = perform_dhcp(intf); + + if (results == RETURN_BACK) + return setup_network_interface(intf); + if (results == RETURN_ERROR) + return results; + intf->boot_proto = BOOTPROTO_DHCP; + + if (configure_net_device(intf)) + return RETURN_ERROR; + + } else if (streq(choice, "ADSL")) { + results = perform_adsl(intf); + + if (results == RETURN_BACK) + return setup_network_interface(intf); + if (results == RETURN_ERROR) + return results; + } else + return RETURN_ERROR; + + return add_default_route(); } static enum return_type configure_network(struct interface_info * intf) { - char * dnshostname; - - if (hostname && domain) - return RETURN_OK; - - dnshostname = mygethostbyaddr(inet_ntoa(intf->ip)); - - if (dnshostname) { - if (intf->boot_proto == BOOTPROTO_STATIC) - hostname = strdup(dnshostname); - domain = guess_domain_from_hostname(dnshostname); - if (domain) { - log_message("got hostname and domain from dns entry, %s and %s", dnshostname, domain); - return RETURN_OK; - } - } else - log_message("reverse name lookup on self failed"); - - if (domain) - return RETURN_OK; - - dnshostname = NULL; - if (dns_server.s_addr != 0) { - wait_message("Trying to resolve dns..."); - dnshostname = mygethostbyaddr(inet_ntoa(dns_server)); - remove_wait_message(); - if (dnshostname) { - log_message("got DNS fullname, %s", dnshostname); - domain = guess_domain_from_hostname(dnshostname); - } else - log_message("reverse name lookup on DNS failed"); - } else - log_message("no DNS, unable to guess domain"); - - if (domain) { - log_message("got domain from DNS fullname, %s", domain); - } else { - enum return_type results; - char * questions[] = { "Host name", "Domain name", NULL }; - char * questions_auto[] = { "hostname", "domain" }; - static char ** answers = NULL; - char * boulet; - - if (dhcp_hostname || dhcp_domain) { - answers = (char **) malloc(sizeof(questions)); - answers[0] = strdup(dhcp_hostname); - answers[1] = strdup(dhcp_domain); - } - - if (!dhcp_hostname || !dhcp_domain) { - results = ask_from_entries_auto("I could not guess hostname and domain name; please fill in this information. " - "Valid answers are for example: `mybox' for hostname and `mynetwork.com' for " - "domain name, for a machine called `mybox.mynetwork.com' on the Internet.", - questions, &answers, 32, questions_auto, NULL); - if (results != RETURN_OK) - return results; - } - - hostname = answers[0]; - if ((boulet = strchr(hostname, '.')) != NULL) - boulet[0] = '\0'; - domain = answers[1]; - } - - log_message("using hostname %s", hostname); - log_message("using domain %s", domain); - - return RETURN_OK; + char * dnshostname; + + if (hostname && domain) + return RETURN_OK; + + dnshostname = mygethostbyaddr(inet_ntoa(intf->ip)); + + if (dnshostname) { + if (intf->boot_proto == BOOTPROTO_STATIC) + hostname = strdup(dnshostname); + domain = guess_domain_from_hostname(dnshostname); + if (domain) { + log_message("got hostname and domain from dns entry, %s and %s", dnshostname, domain); + return RETURN_OK; + } + } else + log_message("reverse name lookup on self failed"); + + if (domain) + return RETURN_OK; + + dnshostname = NULL; + if (dns_server.s_addr != 0) { + wait_message("Trying to resolve dns..."); + dnshostname = mygethostbyaddr(inet_ntoa(dns_server)); + remove_wait_message(); + if (dnshostname) { + log_message("got DNS fullname, %s", dnshostname); + domain = guess_domain_from_hostname(dnshostname); + } else + log_message("reverse name lookup on DNS failed"); + } else + log_message("no DNS, unable to guess domain"); + + if (domain) { + log_message("got domain from DNS fullname, %s", domain); + } else { + enum return_type results; + char * questions[] = { "Host name", "Domain name", NULL }; + char * questions_auto[] = { "hostname", "domain" }; + static char ** answers = NULL; + char * boulet; + + if (dhcp_hostname || dhcp_domain) { + answers = (char **) malloc(sizeof(questions)); + answers[0] = strdup(dhcp_hostname); + answers[1] = strdup(dhcp_domain); + } + + if (!dhcp_hostname || !dhcp_domain) { + results = ask_from_entries_auto("I could not guess hostname and domain name; please fill in this information. " + "Valid answers are for example: `mybox' for hostname and `mynetwork.com' for " + "domain name, for a machine called `mybox.mynetwork.com' on the Internet.", + questions, &answers, 32, questions_auto, NULL); + if (results != RETURN_OK) + return results; + } + + hostname = answers[0]; + if ((boulet = strchr(hostname, '.')) != NULL) + boulet[0] = '\0'; + domain = answers[1]; + } + + log_message("using hostname %s", hostname); + log_message("using domain %s", domain); + + return RETURN_OK; } static enum return_type bringup_networking(struct interface_info * intf) { - static struct interface_info loopback; - enum return_type results; - int fd; - - /* try to find if module already loaded or built-in to avoid failing */ - /* badly */ - fd = open("/proc/net/packet", O_RDONLY); - if (fd < 0) - my_insmod("af_packet", ANY_DRIVER_TYPE, NULL, 1); - else - close(fd); - - do { - results = configure_wireless(intf->device); - } while (results == RETURN_ERROR); - - if (results == RETURN_BACK) - return RETURN_BACK; - - do { - results = setup_network_interface(intf); - if (results != RETURN_OK) - return results; - write_resolvconf(); - results = configure_network(intf); - } while (results == RETURN_ERROR); - - if (results == RETURN_BACK) - return bringup_networking(intf); - - write_resolvconf(); /* maybe we have now domain to write also */ - - if (loopback.is_up == 0) { - int rc; - strcpy(loopback.device, "lo"); - loopback.is_ptp = 0; - loopback.is_up = 0; - loopback.ip.s_addr = htonl(0x7f000001); - loopback.netmask.s_addr = htonl(0xff000000); - loopback.broadcast.s_addr = htonl(0x7fffffff); - loopback.network.s_addr = htonl(0x7f000000); - rc = configure_net_device(&loopback); - if (rc) - return RETURN_ERROR; - } - - return RETURN_OK; + static struct interface_info loopback; + enum return_type results; + int fd; + + /* try to find if module already loaded or built-in to avoid failing */ + /* badly */ + fd = open("/proc/net/packet", O_RDONLY); + if (fd < 0) + my_insmod("af_packet", ANY_DRIVER_TYPE, NULL, 1); + else + close(fd); + + do { + results = configure_wireless(intf->device); + } while (results == RETURN_ERROR); + + if (results == RETURN_BACK) + return RETURN_BACK; + + do { + results = setup_network_interface(intf); + if (results != RETURN_OK) + return results; + write_resolvconf(); + results = configure_network(intf); + } while (results == RETURN_ERROR); + + if (results == RETURN_BACK) + return bringup_networking(intf); + + write_resolvconf(); /* maybe we have now domain to write also */ + + if (loopback.is_up == 0) { + int rc; + strcpy(loopback.device, "lo"); + loopback.is_ptp = 0; + loopback.is_up = 0; + loopback.ip.s_addr = htonl(0x7f000001); + loopback.netmask.s_addr = htonl(0xff000000); + loopback.broadcast.s_addr = htonl(0x7fffffff); + loopback.network.s_addr = htonl(0x7f000000); + rc = configure_net_device(&loopback); + if (rc) + return RETURN_ERROR; + } + + return RETURN_OK; } @@ -622,272 +622,272 @@ static char * auto_select_up_intf(int detection_mode) #define SIOCETHTOOL 0x8946 #define ETHTOOL_GLINK 0x0000000a /* Get link status (ethtool_value) */ - struct ethtool_value { - uint32_t cmd; - uint32_t data; - }; - - char ** interfaces, ** ptr; - interfaces = get_net_devices(); - - int s; - s = socket(AF_INET, SOCK_DGRAM, 0); - if (s < 0) { - return NULL; - } - - ptr = interfaces; - while (ptr && *ptr) { - if (detection_mode != AUTO_DETECTION_WIRED || !wireless_is_aware(s, *interfaces)) { - struct ifreq ifr; - struct ethtool_value edata; - strncpy(ifr.ifr_name, *ptr, IFNAMSIZ); - edata.cmd = ETHTOOL_GLINK; - ifr.ifr_data = (caddr_t)&edata; - if (ioctl(s, SIOCETHTOOL, &ifr) == 0 && edata.data) { - close(s); - log_message("NETWORK: choosing interface %s (link beat detected)", *ptr); - return *ptr; - } - } - ptr++; - } - - log_message("NETWORK: no interface has a link beat"); - - if (detection_mode == AUTO_DETECTION_WIRED) { - ptr = interfaces; - while (ptr && *ptr) { - if (!wireless_is_aware(s, *interfaces)) { - close(s); - log_message("NETWORK: choosing interface %s (wired interface)", *ptr); - return *ptr; - } - ptr++; - } - log_message("NETWORK: no interface is wired"); - } - - close(s); - - return NULL; + struct ethtool_value { + uint32_t cmd; + uint32_t data; + }; + + char ** interfaces, ** ptr; + interfaces = get_net_devices(); + + int s; + s = socket(AF_INET, SOCK_DGRAM, 0); + if (s < 0) { + return NULL; + } + + ptr = interfaces; + while (ptr && *ptr) { + if (detection_mode != AUTO_DETECTION_WIRED || !wireless_is_aware(s, *interfaces)) { + struct ifreq ifr; + struct ethtool_value edata; + strncpy(ifr.ifr_name, *ptr, IFNAMSIZ); + edata.cmd = ETHTOOL_GLINK; + ifr.ifr_data = (caddr_t)&edata; + if (ioctl(s, SIOCETHTOOL, &ifr) == 0 && edata.data) { + close(s); + log_message("NETWORK: choosing interface %s (link beat detected)", *ptr); + return *ptr; + } + } + ptr++; + } + + log_message("NETWORK: no interface has a link beat"); + + if (detection_mode == AUTO_DETECTION_WIRED) { + ptr = interfaces; + while (ptr && *ptr) { + if (!wireless_is_aware(s, *interfaces)) { + close(s); + log_message("NETWORK: choosing interface %s (wired interface)", *ptr); + return *ptr; + } + ptr++; + } + log_message("NETWORK: no interface is wired"); + } + + close(s); + + return NULL; } static char * interface_select(void) { - char ** interfaces, ** ptr; - char * descriptions[50]; - char * choice; - int i, count = 0; - enum return_type results; - - interfaces = get_net_devices(); - - ptr = interfaces; - while (ptr && *ptr) { - count++; - ptr++; - } - - if (count == 0) { - stg1_error_message("No NET device found."); - i = ask_insmod(NETWORK_DEVICES); - if (i == RETURN_BACK) - return NULL; - return interface_select(); - } - - if (count == 1) - return *interfaces; - - /* this can't be done in ask_from_list_comments_auto because "auto" and "wired" are not in the interfaces list */ - if (IS_AUTOMATIC) { - enum auto_detection_type auto_detect = AUTO_DETECTION_NONE; - if (streq(get_auto_value("interface"), "auto")) - auto_detect = AUTO_DETECTION_ALL; - else if (streq(get_auto_value("interface"), "wired")) - auto_detect = AUTO_DETECTION_WIRED; - if (auto_detect != AUTO_DETECTION_NONE) { - choice = auto_select_up_intf(auto_detect); - if (choice) - return choice; - } - } - - i = 0; - while (interfaces[i]) { - descriptions[i] = get_net_intf_description(interfaces[i]); - i++; - } - - results = ask_from_list_comments_auto("Please choose the NET device to use for the installation.", - interfaces, descriptions, &choice, "interface", interfaces); - - if (results != RETURN_OK) - return NULL; - - return choice; + char ** interfaces, ** ptr; + char * descriptions[50]; + char * choice; + int i, count = 0; + enum return_type results; + + interfaces = get_net_devices(); + + ptr = interfaces; + while (ptr && *ptr) { + count++; + ptr++; + } + + if (count == 0) { + stg1_error_message("No NET device found."); + i = ask_insmod(NETWORK_DEVICES); + if (i == RETURN_BACK) + return NULL; + return interface_select(); + } + + if (count == 1) + return *interfaces; + + /* this can't be done in ask_from_list_comments_auto because "auto" and "wired" are not in the interfaces list */ + if (IS_AUTOMATIC) { + enum auto_detection_type auto_detect = AUTO_DETECTION_NONE; + if (streq(get_auto_value("interface"), "auto")) + auto_detect = AUTO_DETECTION_ALL; + else if (streq(get_auto_value("interface"), "wired")) + auto_detect = AUTO_DETECTION_WIRED; + if (auto_detect != AUTO_DETECTION_NONE) { + choice = auto_select_up_intf(auto_detect); + if (choice) + return choice; + } + } + + i = 0; + while (interfaces[i]) { + descriptions[i] = get_net_intf_description(interfaces[i]); + i++; + } + + results = ask_from_list_comments_auto("Please choose the NET device to use for the installation.", + interfaces, descriptions, &choice, "interface", interfaces); + + if (results != RETURN_OK) + return NULL; + + return choice; } static enum return_type get_http_proxy(char **http_proxy_host, char **http_proxy_port) { - char *questions[] = { "HTTP proxy host", "HTTP proxy port", NULL }; - char *questions_auto[] = { "proxy_host", "proxy_port", NULL }; - static char ** answers = NULL; - enum return_type results; - - results = ask_from_entries_auto("Please enter HTTP proxy host and port if you need it, else leave them blank or cancel.", - questions, &answers, 40, questions_auto, NULL); - if (results == RETURN_OK) { - *http_proxy_host = answers[0]; - *http_proxy_port = answers[1]; - } else { - *http_proxy_host = NULL; - *http_proxy_port = NULL; - } - - return results; + char *questions[] = { "HTTP proxy host", "HTTP proxy port", NULL }; + char *questions_auto[] = { "proxy_host", "proxy_port", NULL }; + static char ** answers = NULL; + enum return_type results; + + results = ask_from_entries_auto("Please enter HTTP proxy host and port if you need it, else leave them blank or cancel.", + questions, &answers, 40, questions_auto, NULL); + if (results == RETURN_OK) { + *http_proxy_host = answers[0]; + *http_proxy_port = answers[1]; + } else { + *http_proxy_host = NULL; + *http_proxy_port = NULL; + } + + return results; } static int url_split(const char *url, const char *protocol, char **host, char **path) { - char *protocol_sep, *host_sep; + char *protocol_sep, *host_sep; - protocol_sep = strstr(url, "://"); - if (!protocol_sep) { - log_message("NETWORK: no protocol in \"%s\"", url); - return -1; - } + protocol_sep = strstr(url, "://"); + if (!protocol_sep) { + log_message("NETWORK: no protocol in \"%s\"", url); + return -1; + } - if (strncmp(protocol, url, protocol_sep - url)) - return -1; + if (strncmp(protocol, url, protocol_sep - url)) + return -1; - url = protocol_sep + 3; - host_sep = strchr(url, '/'); - if (!host_sep || host_sep == url) { - log_message("NETWORK: no hostname in \"%s\"", url); - return -1; - } + url = protocol_sep + 3; + host_sep = strchr(url, '/'); + if (!host_sep || host_sep == url) { + log_message("NETWORK: no hostname in \"%s\"", url); + return -1; + } - *host = strndup(url, host_sep - url); - *path = strdup(host_sep); + *host = strndup(url, host_sep - url); + *path = strdup(host_sep); - return 0; + return 0; } #define MIRRORLIST_MAX_ITEMS 500 typedef char *mirrorlist_t[2][MIRRORLIST_MAX_ITEMS+1]; static enum return_type get_mirrorlist(mirrorlist_t mirrorlist, int start, char *version, const char *protocol, char *http_proxy_host, char *http_proxy_port) { - int fd, size, line_pos = 0; - char path[1024]; - char line[1024]; - char type[100] = DISTRIB_TYPE; - int mirror_idx = start; - - int use_http_proxy = http_proxy_host && http_proxy_port && !streq(http_proxy_host, "") && !streq(http_proxy_port, ""); - lowercase(type); - snprintf(path, sizeof(path), "%s/%s.%s.%s.list", MIRRORLIST_PATH, type, version, ARCH); - - fd = http_download_file(MIRRORLIST_HOST, path, &size, use_http_proxy ? "http" : NULL, http_proxy_host, http_proxy_port); - if (fd < 0) { - log_message("HTTP: unable to get mirrors list from %s (%s)", MIRRORLIST_HOST, path); - return RETURN_ERROR; - } - - while (read(fd, line + line_pos, 1) > 0) { - if (line[line_pos] == '\n') { - char *url; - line[line_pos] = '\0'; - line_pos = 0; - - /* skip medium if it does not look like a distrib path */ - if (!strstr(line, ",type=distrib,")) - continue; - - url = strstr(line, ",url="); - if (!url) - continue; - url += 5; - - if (url_split(url, protocol, &mirrorlist[0][mirror_idx], &mirrorlist[1][mirror_idx]) < 0) - continue; - - mirror_idx++; - } else { - line_pos++; - } - - if (mirror_idx >= MIRRORLIST_MAX_ITEMS) - break; - } - close(fd); - - mirrorlist[0][mirror_idx] = NULL; - mirrorlist[1][mirror_idx] = NULL; + int fd, size, line_pos = 0; + char path[1024]; + char line[1024]; + char type[100] = DISTRIB_TYPE; + int mirror_idx = start; + + int use_http_proxy = http_proxy_host && http_proxy_port && !streq(http_proxy_host, "") && !streq(http_proxy_port, ""); + lowercase(type); + snprintf(path, sizeof(path), "%s/%s.%s.%s.list", MIRRORLIST_PATH, type, version, ARCH); + + fd = http_download_file(MIRRORLIST_HOST, path, &size, use_http_proxy ? "http" : NULL, http_proxy_host, http_proxy_port); + if (fd < 0) { + log_message("HTTP: unable to get mirrors list from %s (%s)", MIRRORLIST_HOST, path); + return RETURN_ERROR; + } + + while (read(fd, line + line_pos, 1) > 0) { + if (line[line_pos] == '\n') { + char *url; + line[line_pos] = '\0'; + line_pos = 0; + + /* skip medium if it does not look like a distrib path */ + if (!strstr(line, ",type=distrib,")) + continue; + + url = strstr(line, ",url="); + if (!url) + continue; + url += 5; + + if (url_split(url, protocol, &mirrorlist[0][mirror_idx], &mirrorlist[1][mirror_idx]) < 0) + continue; + + mirror_idx++; + } else { + line_pos++; + } + + if (mirror_idx >= MIRRORLIST_MAX_ITEMS) + break; + } + close(fd); + + mirrorlist[0][mirror_idx] = NULL; + mirrorlist[1][mirror_idx] = NULL; return RETURN_OK; } static int choose_mirror_from_host_list(mirrorlist_t mirrorlist, char **selected_host, char **filepath) { - enum return_type results; - int mirror_idx = 0; - - do { - results = ask_from_list_index("Please select a mirror from the list below.", - mirrorlist[0], NULL, &mirror_idx); - - if (results == RETURN_BACK) { - return RETURN_ERROR; - } else if (results == RETURN_OK) { - if (mirror_idx == 0) { - /* enter the mirror manually */ - return RETURN_OK; - } - *selected_host = strdup(mirrorlist[0][mirror_idx]); - *filepath = strdup(mirrorlist[1][mirror_idx]); - return RETURN_OK; - } - } while (results == RETURN_ERROR); - - return RETURN_ERROR; + enum return_type results; + int mirror_idx = 0; + + do { + results = ask_from_list_index("Please select a mirror from the list below.", + mirrorlist[0], NULL, &mirror_idx); + + if (results == RETURN_BACK) { + return RETURN_ERROR; + } else if (results == RETURN_OK) { + if (mirror_idx == 0) { + /* enter the mirror manually */ + return RETURN_OK; + } + *selected_host = strdup(mirrorlist[0][mirror_idx]); + *filepath = strdup(mirrorlist[1][mirror_idx]); + return RETURN_OK; + } + } while (results == RETURN_ERROR); + + return RETURN_ERROR; } static int choose_mirror_from_list(char *http_proxy_host, char *http_proxy_port, const char *protocol, char **selected_host, char **filepath) { - enum return_type results; - char *versions[] = { "Specify the mirror manually", DISTRIB_NAME " " DISTRIB_VERSION, NULL }; - char *version = DISTRIB_NAME " " DISTRIB_VERSION; - - do { - results = ask_from_list("Please select a medium from the list below.", versions, &version); - - if (results == RETURN_BACK) { - return RETURN_BACK; - } else if (results == RETURN_OK) { - if (!strcmp(version, versions[0])) { - /* enter the mirror manually */ - return RETURN_OK; - } else { - /* a medium has been selected */ - mirrorlist_t mirrorlist; - mirrorlist[0][0] = "Specify the mirror manually"; - mirrorlist[1][0] = NULL; - - results = get_mirrorlist(mirrorlist, 1, DISTRIB_VERSION, protocol, http_proxy_host, http_proxy_port); - if (results == RETURN_ERROR) - return RETURN_ERROR; - - results = choose_mirror_from_host_list(mirrorlist, selected_host, filepath); - } - } - } while (results == RETURN_ERROR); - - return results; + enum return_type results; + char *versions[] = { "Specify the mirror manually", DISTRIB_NAME " " DISTRIB_VERSION, NULL }; + char *version = DISTRIB_NAME " " DISTRIB_VERSION; + + do { + results = ask_from_list("Please select a medium from the list below.", versions, &version); + + if (results == RETURN_BACK) { + return RETURN_BACK; + } else if (results == RETURN_OK) { + if (!strcmp(version, versions[0])) { + /* enter the mirror manually */ + return RETURN_OK; + } else { + /* a medium has been selected */ + mirrorlist_t mirrorlist; + mirrorlist[0][0] = "Specify the mirror manually"; + mirrorlist[1][0] = NULL; + + results = get_mirrorlist(mirrorlist, 1, DISTRIB_VERSION, protocol, http_proxy_host, http_proxy_port); + if (results == RETURN_ERROR) + return RETURN_ERROR; + + results = choose_mirror_from_host_list(mirrorlist, selected_host, filepath); + } + } + } while (results == RETURN_ERROR); + + return results; } @@ -896,150 +896,149 @@ static int choose_mirror_from_list(char *http_proxy_host, char *http_proxy_port, enum return_type intf_select_and_up() { - static struct interface_info intf[20]; - static int num_interfaces = 0; - struct interface_info * sel_intf = NULL; - int i; - enum return_type results; - char * iface = interface_select(); - - if (iface == NULL) - return RETURN_BACK; - - for (i = 0; i < num_interfaces ; i++) - if (!strcmp(intf[i].device, iface)) - sel_intf = &(intf[i]); - - if (sel_intf == NULL) { - sel_intf = &(intf[num_interfaces]); - strcpy(sel_intf->device, iface); - sel_intf->is_up = 0; - num_interfaces++; - } - - results = bringup_networking(sel_intf); - - if (results == RETURN_OK) - save_netinfo(sel_intf); - - return results; + static struct interface_info intf[20]; + static int num_interfaces = 0; + struct interface_info * sel_intf = NULL; + int i; + enum return_type results; + char * iface = interface_select(); + + if (iface == NULL) + return RETURN_BACK; + + for (i = 0; i < num_interfaces ; i++) + if (!strcmp(intf[i].device, iface)) + sel_intf = &(intf[i]); + + if (sel_intf == NULL) { + sel_intf = &(intf[num_interfaces]); + strcpy(sel_intf->device, iface); + sel_intf->is_up = 0; + num_interfaces++; + } + + results = bringup_networking(sel_intf); + + if (results == RETURN_OK) + save_netinfo(sel_intf); + + return results; } enum return_type nfs_prepare(void) { - char * questions[] = { "NFS server name", DISTRIB_NAME " directory", NULL }; - char * questions_auto[] = { "server", "directory", NULL }; - static char ** answers = NULL; - char * nfsmount_location; - enum return_type results = intf_select_and_up(NULL, NULL); - - if (results != RETURN_OK) - return results; - - do { - results = ask_from_entries_auto("Please enter the name or IP address of your NFS server, " - "and the directory containing the " DISTRIB_NAME " Distribution.", - questions, &answers, 40, questions_auto, NULL); - if (results != RETURN_OK || streq(answers[0], "")) { - unset_automatic(); /* we are in a fallback mode */ - return nfs_prepare(); - } - - nfsmount_location = malloc(strlen(answers[0]) + strlen(answers[1]) + 2); - strcpy(nfsmount_location, answers[0]); - strcat(nfsmount_location, ":"); - strcat(nfsmount_location, answers[1]); - - if (my_mount(nfsmount_location, MEDIA_LOCATION, "nfs", 0) == -1) { - stg1_error_message("I can't mount the directory from the NFS server."); - results = RETURN_BACK; - continue; - } - free(nfsmount_location); nfsmount_location = NULL; - - results = try_with_directory(MEDIA_LOCATION, "nfs", "nfs-iso"); - if (results != RETURN_OK) - umount(MEDIA_LOCATION); - if (results == RETURN_ERROR) + char * questions[] = { "NFS server name", DISTRIB_NAME " directory", NULL }; + char * questions_auto[] = { "server", "directory", NULL }; + static char ** answers = NULL; + char * nfsmount_location; + enum return_type results = intf_select_and_up(NULL, NULL); + + if (results != RETURN_OK) + return results; + + do { + results = ask_from_entries_auto("Please enter the name or IP address of your NFS server, " + "and the directory containing the " DISTRIB_NAME " Distribution.", + questions, &answers, 40, questions_auto, NULL); + if (results != RETURN_OK || streq(answers[0], "")) { + unset_automatic(); /* we are in a fallback mode */ + return nfs_prepare(); + } + + nfsmount_location = malloc(strlen(answers[0]) + strlen(answers[1]) + 2); + strcpy(nfsmount_location, answers[0]); + strcat(nfsmount_location, ":"); + strcat(nfsmount_location, answers[1]); + + if (my_mount(nfsmount_location, MEDIA_LOCATION, "nfs", 0) == -1) { + stg1_error_message("I can't mount the directory from the NFS server."); + results = RETURN_BACK; + continue; + } + free(nfsmount_location); nfsmount_location = NULL; + + results = try_with_directory(MEDIA_LOCATION, "nfs", "nfs-iso"); + if (results != RETURN_OK) + umount(MEDIA_LOCATION); + if (results == RETURN_ERROR) return RETURN_ERROR; - } - while (results == RETURN_BACK); + } + while (results == RETURN_BACK); - return RETURN_OK; + return RETURN_OK; } enum return_type ftp_prepare(void) { - char * questions[] = { "FTP server", DISTRIB_NAME " directory", "Login", "Password", NULL }; - char * questions_auto[] = { "server", "directory", "user", "pass", NULL }; - static char ** answers = NULL; - enum return_type results; - struct utsname kernel_uname; - char *http_proxy_host, *http_proxy_port; - int use_http_proxy; + char * questions[] = { "FTP server", DISTRIB_NAME " directory", "Login", "Password", NULL }; + char * questions_auto[] = { "server", "directory", "user", "pass", NULL }; + static char ** answers = NULL; + enum return_type results; + struct utsname kernel_uname; + char *http_proxy_host, *http_proxy_port; + int use_http_proxy; - if (!ramdisk_possible()) { - stg1_error_message("FTP install needs more than %d Mbytes of memory (detected %d Mbytes). You may want to try an NFS install.", - MEM_LIMIT_DRAKX, total_memory()); - return RETURN_ERROR; - } + if (!ramdisk_possible()) { + stg1_error_message("FTP install needs more than %d Mbytes of memory (detected %d Mbytes). You may want to try an NFS install.", + MEM_LIMIT_DRAKX, total_memory()); + return RETURN_ERROR; + } - results = intf_select_and_up(); + results = intf_select_and_up(); - if (results != RETURN_OK) - return results; + if (results != RETURN_OK) + return results; - get_http_proxy(&http_proxy_host, &http_proxy_port); - use_http_proxy = http_proxy_host && http_proxy_port && !streq(http_proxy_host, "") && !streq(http_proxy_port, ""); + get_http_proxy(&http_proxy_host, &http_proxy_port); + use_http_proxy = http_proxy_host && http_proxy_port && !streq(http_proxy_host, "") && !streq(http_proxy_port, ""); - uname(&kernel_uname); + uname(&kernel_uname); - do { - char location_full[500]; - int ftp_serv_response = -1; - int fd, size; - int need_arch = 0; - char ftp_hostname[500]; + do { + char location_full[500]; + int ftp_serv_response = -1; + int fd, size; + char ftp_hostname[500]; - if (!IS_AUTOMATIC) { - if (answers == NULL) - answers = (char **) malloc(sizeof(questions)); + if (!IS_AUTOMATIC) { + if (answers == NULL) + answers = (char **) malloc(sizeof(questions)); - results = choose_mirror_from_list(http_proxy_host, http_proxy_port, "ftp", &answers[0], &answers[1]); + results = choose_mirror_from_list(http_proxy_host, http_proxy_port, "ftp", &answers[0], &answers[1]); - if (results == RETURN_BACK) - return ftp_prepare(); + if (results == RETURN_BACK) + return ftp_prepare(); if (use_http_proxy) { results = ask_yes_no("Do you want to use this HTTP proxy for FTP connections too ?"); - if (results == RETURN_BACK) - return ftp_prepare(); + if (results == RETURN_BACK) + return ftp_prepare(); use_http_proxy = results == RETURN_OK; } - } - - results = ask_from_entries_auto("Please enter the name or IP address of the FTP server, " - "the directory containing the " DISTRIB_NAME " Distribution, " - "and the login/pass if necessary (leave login blank for anonymous). ", - questions, &answers, 40, questions_auto, NULL); - if (results != RETURN_OK || streq(answers[0], "")) { - unset_automatic(); /* we are in a fallback mode */ - return ftp_prepare(); - } - - strcpy(location_full, answers[1][0] == '/' ? "" : "/"); - strcat(location_full, answers[1]); - - if (use_http_proxy) { - log_message("FTP: don't connect to %s directly, will use proxy", answers[0]); - } else { - log_message("FTP: trying to connect to %s", answers[0]); - ftp_serv_response = ftp_open_connection(answers[0], answers[2], answers[3], ""); + } + + results = ask_from_entries_auto("Please enter the name or IP address of the FTP server, " + "the directory containing the " DISTRIB_NAME " Distribution, " + "and the login/pass if necessary (leave login blank for anonymous). ", + questions, &answers, 40, questions_auto, NULL); + if (results != RETURN_OK || streq(answers[0], "")) { + unset_automatic(); /* we are in a fallback mode */ + return ftp_prepare(); + } + + strcpy(location_full, answers[1][0] == '/' ? "" : "/"); + strcat(location_full, answers[1]); + + if (use_http_proxy) { + log_message("FTP: don't connect to %s directly, will use proxy", answers[0]); + } else { + log_message("FTP: trying to connect to %s", answers[0]); + ftp_serv_response = ftp_open_connection(answers[0], answers[2], answers[3], ""); if (ftp_serv_response < 0) { log_message("FTP: error connect %d", ftp_serv_response); if (ftp_serv_response == FTPERR_BAD_HOSTNAME) @@ -1053,199 +1052,186 @@ enum return_type ftp_prepare(void) } } - strcat(location_full, COMPRESSED_FILE_REL("/")); - - log_message("FTP: trying to retrieve %s", location_full); - - if (use_http_proxy) { - if (strcmp(answers[2], "")) { - strcpy(ftp_hostname, answers[2]); /* user name */ - strcat(ftp_hostname, ":"); - strcat(ftp_hostname, answers[3]); /* password */ - strcat(ftp_hostname, "@"); - } else { - strcpy(ftp_hostname, ""); - } - strcat(ftp_hostname, answers[0]); - fd = http_download_file(ftp_hostname, location_full, &size, "ftp", http_proxy_host, http_proxy_port); - } else { - fd = ftp_start_download(ftp_serv_response, location_full, &size); - } - - /* Try arched directory */ - if (fd < 0) { + strcat(location_full, COMPRESSED_FILE_REL("/")); + + log_message("FTP: trying to retrieve %s", location_full); + + if (use_http_proxy) { + if (strcmp(answers[2], "")) { + strcpy(ftp_hostname, answers[2]); /* user name */ + strcat(ftp_hostname, ":"); + strcat(ftp_hostname, answers[3]); /* password */ + strcat(ftp_hostname, "@"); + } else { + strcpy(ftp_hostname, ""); + } + strcat(ftp_hostname, answers[0]); + fd = http_download_file(ftp_hostname, location_full, &size, "ftp", http_proxy_host, http_proxy_port); + } else { + fd = ftp_start_download(ftp_serv_response, location_full, &size); + } + + /* Try arched directory */ + if (fd < 0) { log_message("%s failed.", location_full); char *with_arch = asprintf_("%s%s/%s/%s", answers[1][0] == '/' ? "" : "/", answers[1], ARCH, COMPRESSED_FILE_REL("/")); log_message("trying %s...", with_arch); - if (use_http_proxy) - fd = http_download_file(answers[0], with_arch, &size, use_http_proxy ? "http" : NULL, http_proxy_host, http_proxy_port); - else - fd = ftp_start_download(ftp_serv_response, with_arch, &size); - if (0 < fd) { + fd = http_download_file(answers[0], with_arch, &size, use_http_proxy ? "http" : NULL, http_proxy_host, http_proxy_port); + if (0 < fd) strcpy(location_full, with_arch); - need_arch = 1; - } } - if (fd < 0) { - char *msg = str_ftp_error(fd); - log_message("FTP: error get %d for remote file %s", fd, location_full); - stg1_error_message("Error: %s.", msg ? msg : "couldn't retrieve Installation program"); - results = RETURN_BACK; - continue; - } - - log_message("FTP: size of download %d bytes", size); - - results = load_compressed_fd(fd, size); - if (results == RETURN_OK) { - if (!use_http_proxy) - ftp_end_data_command(ftp_serv_response); - } else { - unset_automatic(); /* we are in a fallback mode */ - return results; - } - - if (use_http_proxy) { + if (fd < 0) { + char *msg = str_ftp_error(fd); + log_message("FTP: error get %d for remote file %s", fd, location_full); + stg1_error_message("Error: %s.", msg ? msg : "couldn't retrieve Installation program"); + results = RETURN_BACK; + continue; + } + + log_message("FTP: size of download %d bytes", size); + + results = load_compressed_fd(fd, size); + if (results == RETURN_OK) { + if (!use_http_proxy) + ftp_end_data_command(ftp_serv_response); + } else { + unset_automatic(); /* we are in a fallback mode */ + return results; + } + + if (use_http_proxy) { add_to_env("METHOD", "http"); - sprintf(location_full, "ftp://%s%s", ftp_hostname, answers[1]); - if (need_arch) - strcat(location_full, "/" ARCH); - add_to_env("URLPREFIX", location_full); - add_to_env("PROXY", http_proxy_host); - add_to_env("PROXYPORT", http_proxy_port); - } else { + sprintf(location_full, "ftp://%s%s", ftp_hostname, answers[1]); + add_to_env("URLPREFIX", location_full); + add_to_env("PROXY", http_proxy_host); + add_to_env("PROXYPORT", http_proxy_port); + } else { add_to_env("METHOD", "ftp"); - add_to_env("HOST", answers[0]); - if (need_arch) - strcat(answers[1], "/" ARCH); - add_to_env("PREFIX", answers[1]); - if (!streq(answers[2], "")) { - add_to_env("LOGIN", answers[2]); - add_to_env("PASSWORD", answers[3]); - } - } - } - while (results == RETURN_BACK); - - return RETURN_OK; + add_to_env("HOST", answers[0]); + add_to_env("PREFIX", answers[1]); + if (!streq(answers[2], "")) { + add_to_env("LOGIN", answers[2]); + add_to_env("PASSWORD", answers[3]); + } + } + } + while (results == RETURN_BACK); + + return RETURN_OK; } enum return_type http_prepare(void) { - char * questions[] = { "HTTP server", DISTRIB_NAME " directory", NULL }; - char * questions_auto[] = { "server", "directory", NULL }; - static char ** answers = NULL; - enum return_type results; - char *http_proxy_host, *http_proxy_port; + char * questions[] = { "HTTP server", DISTRIB_NAME " directory", NULL }; + char * questions_auto[] = { "server", "directory", NULL }; + static char ** answers = NULL; + enum return_type results; + char *http_proxy_host, *http_proxy_port; - if (!ramdisk_possible()) { - stg1_error_message("HTTP install needs more than %d Mbytes of memory (detected %d Mbytes). You may want to try an NFS install.", - MEM_LIMIT_DRAKX, total_memory()); - return RETURN_ERROR; - } + if (!ramdisk_possible()) { + stg1_error_message("HTTP install needs more than %d Mbytes of memory (detected %d Mbytes). You may want to try an NFS install.", + MEM_LIMIT_DRAKX, total_memory()); + return RETURN_ERROR; + } - results = intf_select_and_up(); + results = intf_select_and_up(); - if (results != RETURN_OK) - return results; + if (results != RETURN_OK) + return results; get_http_proxy(&http_proxy_host, &http_proxy_port); - do { - char location_full[500]; - int fd, size, need_arch = 0; - int use_http_proxy; + do { + char location_full[500]; + int fd, size; + int use_http_proxy; - if (!IS_AUTOMATIC) { - if (answers == NULL) - answers = (char **) malloc(sizeof(questions)); + if (!IS_AUTOMATIC) { + if (answers == NULL) + answers = (char **) malloc(sizeof(questions)); - results = choose_mirror_from_list(http_proxy_host, http_proxy_port, "http", &answers[0], &answers[1]); + results = choose_mirror_from_list(http_proxy_host, http_proxy_port, "http", &answers[0], &answers[1]); - if (results == RETURN_BACK) - return http_prepare(); - } + if (results == RETURN_BACK) + return ftp_prepare(); + } - results = ask_from_entries_auto("Please enter the name or IP address of the HTTP server, " - "and the directory containing the " DISTRIB_NAME " Distribution.", - questions, &answers, 40, questions_auto, NULL); - if (results != RETURN_OK || streq(answers[0], "")) { - unset_automatic(); /* we are in a fallback mode */ - return http_prepare(); - } + results = ask_from_entries_auto("Please enter the name or IP address of the HTTP server, " + "and the directory containing the " DISTRIB_NAME " Distribution.", + questions, &answers, 40, questions_auto, NULL); + if (results != RETURN_OK || streq(answers[0], "")) { + unset_automatic(); /* we are in a fallback mode */ + return http_prepare(); + } - strcpy(location_full, answers[1][0] == '/' ? "" : "/"); - strcat(location_full, answers[1]); - strcat(location_full, COMPRESSED_FILE_REL("/")); + strcpy(location_full, answers[1][0] == '/' ? "" : "/"); + strcat(location_full, answers[1]); + strcat(location_full, COMPRESSED_FILE_REL("/")); - log_message("HTTP: trying to retrieve %s from %s", location_full, answers[0]); - - use_http_proxy = http_proxy_host && http_proxy_port && !streq(http_proxy_host, "") && !streq(http_proxy_port, ""); + log_message("HTTP: trying to retrieve %s from %s", location_full, answers[0]); + + use_http_proxy = http_proxy_host && http_proxy_port && !streq(http_proxy_host, "") && !streq(http_proxy_port, ""); - fd = http_download_file(answers[0], location_full, &size, use_http_proxy ? "http" : NULL, http_proxy_host, http_proxy_port); + fd = http_download_file(answers[0], location_full, &size, use_http_proxy ? "http" : NULL, http_proxy_host, http_proxy_port); - /* Try arched directory */ - if (fd < 0) { + /* Try arched directory */ + if (fd < 0) { log_message("%s failed.", location_full); char *with_arch = asprintf_("%s%s/%s/%s", answers[1][0] == '/' ? "" : "/", answers[1], ARCH, COMPRESSED_FILE_REL("/")); log_message("trying %s...", with_arch); fd = http_download_file(answers[0], with_arch, &size, use_http_proxy ? "http" : NULL, http_proxy_host, http_proxy_port); - if (0 < fd) { + if (0 < fd) strcpy(location_full, with_arch); - need_arch = 1; - } } - if (fd < 0) { - log_message("HTTP: error %d", fd); - if (fd == FTPERR_FAILED_CONNECT) - stg1_error_message("Error: couldn't connect to server."); - else - stg1_error_message("Error: couldn't get file (%s).", location_full); - results = RETURN_BACK; - continue; - } - - log_message("HTTP: size of download %d bytes", size); - - if (load_compressed_fd(fd, size) != RETURN_OK) { - unset_automatic(); /* we are in a fallback mode */ - return RETURN_ERROR; + if (fd < 0) { + log_message("HTTP: error %d", fd); + if (fd == FTPERR_FAILED_CONNECT) + stg1_error_message("Error: couldn't connect to server."); + else + stg1_error_message("Error: couldn't get file (%s).", location_full); + results = RETURN_BACK; + continue; + } + + log_message("HTTP: size of download %d bytes", size); + + if (load_compressed_fd(fd, size) != RETURN_OK) { + unset_automatic(); /* we are in a fallback mode */ + return RETURN_ERROR; } add_to_env("METHOD", "http"); - sprintf(location_full, "http://%s%s%s", answers[0], answers[1][0] == '/' ? "" : "/", answers[1]); - if (need_arch) - strcat(location_full, "/" ARCH); - add_to_env("URLPREFIX", location_full); + sprintf(location_full, "http://%s%s%s", answers[0], answers[1][0] == '/' ? "" : "/", answers[1]); + add_to_env("URLPREFIX", location_full); if (!streq(http_proxy_host, "")) - add_to_env("PROXY", http_proxy_host); + add_to_env("PROXY", http_proxy_host); if (!streq(http_proxy_port, "")) - add_to_env("PROXYPORT", http_proxy_port); - } - while (results == RETURN_BACK); + add_to_env("PROXYPORT", http_proxy_port); + } + while (results == RETURN_BACK); - return RETURN_OK; + return RETURN_OK; } #ifndef DISABLE_KA enum return_type ka_prepare(void) { - enum return_type results; + enum return_type results; - if (!ramdisk_possible()) { - stg1_error_message("KA install needs more than %d Mbytes of memory (detected %d Mbytes).", - MEM_LIMIT_DRAKX, total_memory()); - return RETURN_ERROR; - } + if (!ramdisk_possible()) { + stg1_error_message("KA install needs more than %d Mbytes of memory (detected %d Mbytes).", + MEM_LIMIT_DRAKX, total_memory()); + return RETURN_ERROR; + } - results = intf_select_and_up(); + results = intf_select_and_up(); - if (results != RETURN_OK) - return results; + if (results != RETURN_OK) + return results; - return perform_ka(); + return perform_ka(); } #endif diff --git a/mdk-stage1/newt-frontend.c b/mdk-stage1/newt-frontend.c index 6bdded9d3..b24577911 100644 --- a/mdk-stage1/newt-frontend.c +++ b/mdk-stage1/newt-frontend.c @@ -32,7 +32,7 @@ #include <stdio.h> #include <stdarg.h> #include <sys/time.h> -#include <newt.h> +#include "newt/newt.h" #include <probing.h> @@ -40,82 +40,82 @@ void init_frontend(char * welcome_msg) { - int i; - for (i=0; i<38; i++) printf("\n"); - newtInit(); - newtCls(); - - if (welcome_msg[0]) { - char *msg; - int cols, rows; - newtGetScreenSize(&cols, &rows); - asprintf(&msg, " %-*s", cols - 1, welcome_msg); - newtDrawRootText(0, 0, msg); - free(msg); - newtPushHelpLine(" <Alt-F1> for here, <Alt-F3> to see the logs, <Alt-F4> for kernel msg"); - } - newtRefresh(); + int i; + for (i=0; i<38; i++) printf("\n"); + newtInit(); + newtCls(); + + if (welcome_msg[0]) { + char *msg; + int cols, rows; + newtGetScreenSize(&cols, &rows); + asprintf(&msg, " %-*s", cols - 1, welcome_msg); + newtDrawRootText(0, 0, msg); + free(msg); + newtPushHelpLine(" <Alt-F1> for here, <Alt-F3> to see the logs, <Alt-F4> for kernel msg"); + } + newtRefresh(); } void finish_frontend(void) { - newtFinished(); + newtFinished(); } void verror_message(char *msg, va_list ap) { - newtWinMessagev("Error", "Ok", msg, ap); + newtWinMessagev("Error", "Ok", msg, ap); } void vinfo_message(char *msg, va_list ap) { - newtWinMessagev("Notice", "Ok", msg, ap); + newtWinMessagev("Notice", "Ok", msg, ap); } void vwait_message(char *msg, va_list ap) { - int width, height; - char * title = "Please wait..."; - newtComponent c, f; - newtGrid grid; - char * buf = NULL; - char * flowed; - int size = 0; - int i = 0; - - do { - size += 1000; - if (buf) free(buf); - buf = malloc(size); - i = vsnprintf(buf, size, msg, ap); - } while (i >= size || i == -1); - - flowed = newtReflowText(buf, 60, 5, 5, &width, &height); - - c = newtTextbox(-1, -1, width, height, NEWT_TEXTBOX_WRAP); - newtTextboxSetText(c, flowed); - - grid = newtCreateGrid(1, 1); - newtGridSetField(grid, 0, 0, NEWT_GRID_COMPONENT, c, 0, 0, 0, 0, 0, 0); - newtGridWrappedWindow(grid, title); - - free(flowed); - free(buf); - - f = newtForm(NULL, NULL, 0); - newtFormAddComponent(f, c); - - newtDrawForm(f); - newtRefresh(); - newtFormDestroy(f); + int width, height; + char * title = "Please wait..."; + newtComponent c, f; + newtGrid grid; + char * buf = NULL; + char * flowed; + int size = 0; + int i = 0; + + do { + size += 1000; + if (buf) free(buf); + buf = malloc(size); + i = vsnprintf(buf, size, msg, ap); + } while (i >= size || i == -1); + + flowed = newtReflowText(buf, 60, 5, 5, &width, &height); + + c = newtTextbox(-1, -1, width, height, NEWT_TEXTBOX_WRAP); + newtTextboxSetText(c, flowed); + + grid = newtCreateGrid(1, 1); + newtGridSetField(grid, 0, 0, NEWT_GRID_COMPONENT, c, 0, 0, 0, 0, 0, 0); + newtGridWrappedWindow(grid, title); + + free(flowed); + free(buf); + + f = newtForm(NULL, NULL, 0); + newtFormAddComponent(f, c); + + newtDrawForm(f); + newtRefresh(); + newtFormDestroy(f); } void remove_wait_message(void) { - newtPopWindow(); + newtPopWindow(); } @@ -126,101 +126,101 @@ static char * msg_progress; void init_progression_raw(char *msg, int size) { - size_progress = size; - if (size) { - actually_drawn = 0; - newtCenteredWindow(70, 5, "Please wait..."); - form = newtForm(NULL, NULL, 0); - newtFormAddComponent(form, newtLabel(1, 1, msg)); - scale = newtScale(1, 3, 68, size); - newtFormAddComponent(form, scale); - newtDrawForm(form); - newtRefresh(); - } - else { - wait_message(msg); - msg_progress = msg; - } + size_progress = size; + if (size) { + actually_drawn = 0; + newtCenteredWindow(70, 5, "Please wait..."); + form = newtForm(NULL, NULL, 0); + newtFormAddComponent(form, newtLabel(1, 1, msg)); + scale = newtScale(1, 3, 68, size); + newtFormAddComponent(form, scale); + newtDrawForm(form); + newtRefresh(); + } + else { + wait_message(msg); + msg_progress = msg; + } } void update_progression_raw(int current_size) { - if (size_progress) { - if (current_size <= size_progress) - newtScaleSet(scale, current_size); - newtRefresh(); - } - else { - struct timeval t; - int time; - static int last_time = -1; - gettimeofday(&t, NULL); - time = t.tv_sec*3 + t.tv_usec/300000; - if (time != last_time) { - char msg_prog_final[500]; - sprintf(msg_prog_final, "%s (%d bytes read) ", msg_progress, current_size); - remove_wait_message(); - wait_message(msg_prog_final); - } - last_time = time; - } + if (size_progress) { + if (current_size <= size_progress) + newtScaleSet(scale, current_size); + newtRefresh(); + } + else { + struct timeval t; + int time; + static int last_time = -1; + gettimeofday(&t, NULL); + time = t.tv_sec*3 + t.tv_usec/300000; + if (time != last_time) { + char msg_prog_final[500]; + sprintf(msg_prog_final, "%s (%d bytes read) ", msg_progress, current_size); + remove_wait_message(); + wait_message(msg_prog_final); + } + last_time = time; + } } void end_progression_raw(void) { - if (size_progress) { - newtPopWindow(); - newtFormDestroy(form); - } - else - remove_wait_message(); + if (size_progress) { + newtPopWindow(); + newtFormDestroy(form); + } + else + remove_wait_message(); } enum return_type ask_from_list_index(char *msg, char ** elems, char ** elems_comments, int * answer) { - char * items[50000]; - int rc; - - if (elems_comments) { - int i; - - i = 0; - while (elems && *elems) { - int j = (*elems_comments) ? strlen(*elems_comments) : 0; - items[i] = malloc(sizeof(char) * (strlen(*elems) + j + 4)); - strcpy(items[i], *elems); - if (*elems_comments) { - strcat(items[i], " ("); - strcat(items[i], *elems_comments); - strcat(items[i], ")"); - } - elems_comments++; - i++; - elems++; - } - items[i] = NULL; - } - - rc = newtWinMenu("Please choose...", msg, 52, 5, 5, 7, elems_comments ? items : elems, answer, "Ok", "Cancel", NULL); - - if (rc == 2) - return RETURN_BACK; - - return RETURN_OK; + char * items[50000]; + int rc; + + if (elems_comments) { + int i; + + i = 0; + while (elems && *elems) { + int j = (*elems_comments) ? strlen(*elems_comments) : 0; + items[i] = malloc(sizeof(char) * (strlen(*elems) + j + 4)); + strcpy(items[i], *elems); + if (*elems_comments) { + strcat(items[i], " ("); + strcat(items[i], *elems_comments); + strcat(items[i], ")"); + } + elems_comments++; + i++; + elems++; + } + items[i] = NULL; + } + + rc = newtWinMenu("Please choose...", msg, 52, 5, 5, 7, elems_comments ? items : elems, answer, "Ok", "Cancel", NULL); + + if (rc == 2) + return RETURN_BACK; + + return RETURN_OK; } enum return_type ask_yes_no(char *msg) { - int rc; + int rc; - rc = newtWinTernary("Please answer...", "Yes", "No", "Back", msg); + rc = newtWinTernary("Please answer...", "Yes", "No", "Back", msg); - if (rc == 1) - return RETURN_OK; - else if (rc == 3) - return RETURN_BACK; - else return RETURN_ERROR; + if (rc == 1) + return RETURN_OK; + else if (rc == 3) + return RETURN_BACK; + else return RETURN_ERROR; } @@ -228,160 +228,160 @@ static void (*callback_real_function)(char ** strings) = NULL; static void default_callback(newtComponent co __attribute__ ((unused)), void * data) { - newtComponent * entries = data; - char * strings[50], ** ptr; - - if (!callback_real_function) - return; - - ptr = strings; - while (entries && *entries) { - *ptr = newtEntryGetValue(*entries); - entries++; - ptr++; - } - - callback_real_function(strings); - - ptr = strings; - entries = data; - while (entries && *entries) { - newtEntrySet(*entries, strdup(*ptr), 1); - entries++; - ptr++; - } + newtComponent * entries = data; + char * strings[50], ** ptr; + + if (!callback_real_function) + return; + + ptr = strings; + while (entries && *entries) { + *ptr = newtEntryGetValue(*entries); + entries++; + ptr++; + } + + callback_real_function(strings); + + ptr = strings; + entries = data; + while (entries && *entries) { + newtEntrySet(*entries, strdup(*ptr), 1); + entries++; + ptr++; + } } /* only supports up to 50 buttons and entries -- shucks! */ static int mynewtWinEntries(char * title, char * text, int suggestedWidth, int flexDown, - int flexUp, int dataWidth, void (*callback_func)(char ** strings), - struct newtWinEntry * items, char * button1, ...) { - newtComponent buttons[50], result, form, textw; - newtGrid grid, buttonBar, subgrid; - int numItems; - int rc, i; - int numButtons; - char * buttonName; - newtComponent entries[50]; - - va_list args; - - textw = newtTextboxReflowed(-1, -1, text, suggestedWidth, flexDown, - flexUp, 0); - - for (numItems = 0; items[numItems].text; numItems++); - - buttonName = button1, numButtons = 0; - va_start(args, button1); - while (buttonName) { - buttons[numButtons] = newtButton(-1, -1, buttonName); - numButtons++; - buttonName = va_arg(args, char *); - } - - va_end(args); - - buttonBar = newtCreateGrid(numButtons, 1); - for (i = 0; i < numButtons; i++) { - newtGridSetField(buttonBar, i, 0, NEWT_GRID_COMPONENT, - buttons[i], - i ? 1 : 0, 0, 0, 0, 0, 0); - } - - if (callback_func) { - callback_real_function = callback_func; - entries[numItems] = NULL; - } - else - callback_real_function = NULL; - - subgrid = newtCreateGrid(2, numItems); - for (i = 0; i < numItems; i++) { - newtComponent entr = newtEntry(-1, -1, items[i].value ? - *items[i].value : NULL, dataWidth, - (const char**)items[i].value, items[i].flags); - - newtGridSetField(subgrid, 0, i, NEWT_GRID_COMPONENT, - newtLabel(-1, -1, items[i].text), - 0, 0, 0, 0, NEWT_ANCHOR_LEFT, 0); - newtGridSetField(subgrid, 1, i, NEWT_GRID_COMPONENT, - entr, - 1, 0, 0, 0, 0, 0); - if (callback_func) { - entries[i] = entr; - newtComponentAddCallback(entr, default_callback, entries); - } - } - - - grid = newtCreateGrid(1, 3); - form = newtForm(NULL, 0, 0); - newtGridSetField(grid, 0, 0, NEWT_GRID_COMPONENT, textw, - 0, 0, 0, 0, NEWT_ANCHOR_LEFT, 0); - newtGridSetField(grid, 0, 1, NEWT_GRID_SUBGRID, subgrid, - 0, 1, 0, 0, 0, 0); - newtGridSetField(grid, 0, 2, NEWT_GRID_SUBGRID, buttonBar, - 0, 1, 0, 0, 0, NEWT_GRID_FLAG_GROWX); - newtGridAddComponentsToForm(grid, form, 1); - newtGridWrappedWindow(grid, title); - newtGridFree(grid, 1); - - result = newtRunForm(form); - - for (rc = 0; rc < numItems; rc++) - *items[rc].value = strdup(*items[rc].value); - - for (rc = 0; result != buttons[rc] && rc < numButtons; rc++); - if (rc == numButtons) - rc = 0; /* F12 */ - else - rc++; - - newtFormDestroy(form); - newtPopWindow(); - - return rc; + int flexUp, int dataWidth, void (*callback_func)(char ** strings), + struct newtWinEntry * items, char * button1, ...) { + newtComponent buttons[50], result, form, textw; + newtGrid grid, buttonBar, subgrid; + int numItems; + int rc, i; + int numButtons; + char * buttonName; + newtComponent entries[50]; + + va_list args; + + textw = newtTextboxReflowed(-1, -1, text, suggestedWidth, flexDown, + flexUp, 0); + + for (numItems = 0; items[numItems].text; numItems++); + + buttonName = button1, numButtons = 0; + va_start(args, button1); + while (buttonName) { + buttons[numButtons] = newtButton(-1, -1, buttonName); + numButtons++; + buttonName = va_arg(args, char *); + } + + va_end(args); + + buttonBar = newtCreateGrid(numButtons, 1); + for (i = 0; i < numButtons; i++) { + newtGridSetField(buttonBar, i, 0, NEWT_GRID_COMPONENT, + buttons[i], + i ? 1 : 0, 0, 0, 0, 0, 0); + } + + if (callback_func) { + callback_real_function = callback_func; + entries[numItems] = NULL; + } + else + callback_real_function = NULL; + + subgrid = newtCreateGrid(2, numItems); + for (i = 0; i < numItems; i++) { + newtComponent entr = newtEntry(-1, -1, items[i].value ? + *items[i].value : NULL, dataWidth, + items[i].value, items[i].flags); + + newtGridSetField(subgrid, 0, i, NEWT_GRID_COMPONENT, + newtLabel(-1, -1, items[i].text), + 0, 0, 0, 0, NEWT_ANCHOR_LEFT, 0); + newtGridSetField(subgrid, 1, i, NEWT_GRID_COMPONENT, + entr, + 1, 0, 0, 0, 0, 0); + if (callback_func) { + entries[i] = entr; + newtComponentAddCallback(entr, default_callback, entries); + } + } + + + grid = newtCreateGrid(1, 3); + form = newtForm(NULL, 0, 0); + newtGridSetField(grid, 0, 0, NEWT_GRID_COMPONENT, textw, + 0, 0, 0, 0, NEWT_ANCHOR_LEFT, 0); + newtGridSetField(grid, 0, 1, NEWT_GRID_SUBGRID, subgrid, + 0, 1, 0, 0, 0, 0); + newtGridSetField(grid, 0, 2, NEWT_GRID_SUBGRID, buttonBar, + 0, 1, 0, 0, 0, NEWT_GRID_FLAG_GROWX); + newtGridAddComponentsToForm(grid, form, 1); + newtGridWrappedWindow(grid, title); + newtGridFree(grid, 1); + + result = newtRunForm(form); + + for (rc = 0; rc < numItems; rc++) + *items[rc].value = strdup(*items[rc].value); + + for (rc = 0; result != buttons[rc] && rc < numButtons; rc++); + if (rc == numButtons) + rc = 0; /* F12 */ + else + rc++; + + newtFormDestroy(form); + newtPopWindow(); + + return rc; } enum return_type ask_from_entries(char *msg, char ** questions, char *** answers, int entry_size, void (*callback_func)(char ** strings)) { - struct newtWinEntry entries[50]; - int j, i = 0; - int rc; - char ** already_answers = NULL; - - while (questions && *questions) { - entries[i].text = *questions; - entries[i].flags = NEWT_FLAG_SCROLL | (!strcmp(*questions, "Password") ? NEWT_FLAG_PASSWORD : 0); - i++; - questions++; - } - entries[i].text = NULL; - entries[i].value = NULL; - - if (*answers == NULL) - *answers = (char **) malloc(sizeof(char *) * i); - else - already_answers = *answers; - - for (j = 0 ; j < i ; j++) { - entries[j].value = &((*answers)[j]); - if (already_answers && *already_answers) { - *(entries[j].value) = *already_answers; - already_answers++; - } else - *(entries[j].value) = NULL; - } - - rc = mynewtWinEntries("Please fill in entries...", msg, 52, 5, 5, entry_size, callback_func, entries, "Ok", "Cancel", NULL); - - if (rc == 3) - return RETURN_BACK; - if (rc != 1) - return RETURN_ERROR; - - return RETURN_OK; + struct newtWinEntry entries[50]; + int j, i = 0; + int rc; + char ** already_answers = NULL; + + while (questions && *questions) { + entries[i].text = *questions; + entries[i].flags = NEWT_FLAG_SCROLL | (!strcmp(*questions, "Password") ? NEWT_FLAG_PASSWORD : 0); + i++; + questions++; + } + entries[i].text = NULL; + entries[i].value = NULL; + + if (*answers == NULL) + *answers = (char **) malloc(sizeof(char *) * i); + else + already_answers = *answers; + + for (j = 0 ; j < i ; j++) { + entries[j].value = &((*answers)[j]); + if (already_answers && *already_answers) { + *(entries[j].value) = *already_answers; + already_answers++; + } else + *(entries[j].value) = NULL; + } + + rc = mynewtWinEntries("Please fill in entries...", msg, 52, 5, 5, entry_size, callback_func, entries, "Ok", "Cancel", NULL); + + if (rc == 3) + return RETURN_BACK; + if (rc != 1) + return RETURN_ERROR; + + return RETURN_OK; } diff --git a/mdk-stage1/nfsmount.c b/mdk-stage1/nfsmount.c index 0345098f9..0ad52265a 100644 --- a/mdk-stage1/nfsmount.c +++ b/mdk-stage1/nfsmount.c @@ -96,98 +96,98 @@ static char *nfs_strerror(int stat); -#define MAKE_VERSION(p,q,r) (65536*(p) + 256*(q) + (r)) +#define MAKE_VERSION(p,q,r) (65536*(p) + 256*(q) + (r)) #define MAX_NFSPROT ((nfs_mount_version >= 4) ? 3 : 2) bool_t xdr_fhandle3 (XDR *xdrs, fhandle3 *objp) { - if (!xdr_bytes (xdrs, (char **)&objp->fhandle3_val, (u_int *) &objp->fhandle3_len, FHSIZE3)) - return FALSE; - return TRUE; + if (!xdr_bytes (xdrs, (char **)&objp->fhandle3_val, (u_int *) &objp->fhandle3_len, FHSIZE3)) + return FALSE; + return TRUE; } bool_t xdr_mountstat3 (XDR *xdrs, mountstat3 *objp) { - if (!xdr_enum (xdrs, (enum_t *) objp)) - return FALSE; - return TRUE; + if (!xdr_enum (xdrs, (enum_t *) objp)) + return FALSE; + return TRUE; } bool_t xdr_mountres3_ok (XDR *xdrs, mountres3_ok *objp) { - if (!xdr_fhandle3 (xdrs, &objp->fhandle)) - return FALSE; - if (!xdr_array (xdrs, (char **)&objp->auth_flavours.auth_flavours_val, (u_int *) &objp->auth_flavours.auth_flavours_len, ~0, - sizeof (int), (xdrproc_t) xdr_int)) - return FALSE; - return TRUE; + if (!xdr_fhandle3 (xdrs, &objp->fhandle)) + return FALSE; + if (!xdr_array (xdrs, (char **)&objp->auth_flavours.auth_flavours_val, (u_int *) &objp->auth_flavours.auth_flavours_len, ~0, + sizeof (int), (xdrproc_t) xdr_int)) + return FALSE; + return TRUE; } bool_t xdr_mountres3 (XDR *xdrs, mountres3 *objp) { - if (!xdr_mountstat3 (xdrs, &objp->fhs_status)) - return FALSE; - switch (objp->fhs_status) { - case MNT_OK: - if (!xdr_mountres3_ok (xdrs, &objp->mountres3_u.mountinfo)) - return FALSE; - break; - default: - break; - } - return TRUE; + if (!xdr_mountstat3 (xdrs, &objp->fhs_status)) + return FALSE; + switch (objp->fhs_status) { + case MNT_OK: + if (!xdr_mountres3_ok (xdrs, &objp->mountres3_u.mountinfo)) + return FALSE; + break; + default: + break; + } + return TRUE; } bool_t xdr_dirpath (XDR *xdrs, dirpath *objp) { - if (!xdr_string (xdrs, objp, MNTPATHLEN)) - return FALSE; - return TRUE; + if (!xdr_string (xdrs, objp, MNTPATHLEN)) + return FALSE; + return TRUE; } bool_t xdr_fhandle (XDR *xdrs, fhandle objp) { - if (!xdr_opaque (xdrs, objp, FHSIZE)) - return FALSE; - return TRUE; + if (!xdr_opaque (xdrs, objp, FHSIZE)) + return FALSE; + return TRUE; } bool_t xdr_fhstatus (XDR *xdrs, fhstatus *objp) { - if (!xdr_u_int (xdrs, &objp->fhs_status)) - return FALSE; - switch (objp->fhs_status) { - case 0: - if (!xdr_fhandle (xdrs, objp->fhstatus_u.fhs_fhandle)) - return FALSE; - break; - default: - break; - } - return TRUE; + if (!xdr_u_int (xdrs, &objp->fhs_status)) + return FALSE; + switch (objp->fhs_status) { + case 0: + if (!xdr_fhandle (xdrs, objp->fhstatus_u.fhs_fhandle)) + return FALSE; + break; + default: + break; + } + return TRUE; } static int linux_version_code(void) { - struct utsname my_utsname; - int p, q, r; - - if (uname(&my_utsname) == 0) { - p = atoi(strtok(my_utsname.release, ".")); - q = atoi(strtok(NULL, ".")); - r = atoi(strtok(NULL, ".")); - return MAKE_VERSION(p,q,r); - } - return 0; + struct utsname my_utsname; + int p, q, r; + + if (uname(&my_utsname) == 0) { + p = atoi(strtok(my_utsname.release, ".")); + q = atoi(strtok(NULL, ".")); + r = atoi(strtok(NULL, ".")); + return MAKE_VERSION(p,q,r); + } + return 0; } /* @@ -197,33 +197,33 @@ linux_version_code(void) { * and figure out what version the kernel expects. * * Variables: - * NFS_MOUNT_VERSION: these nfsmount sources at compile time - * nfs_mount_version: version this source and running kernel can handle + * NFS_MOUNT_VERSION: these nfsmount sources at compile time + * nfs_mount_version: version this source and running kernel can handle */ static int find_kernel_nfs_mount_version(void) { - static int kernel_version = -1; - int nfs_mount_version = NFS_MOUNT_VERSION; - - if (kernel_version == -1) - kernel_version = linux_version_code(); - - if (kernel_version) { - if (kernel_version < MAKE_VERSION(2,1,32)) - nfs_mount_version = 1; - else if (kernel_version < MAKE_VERSION(2,2,18)) - nfs_mount_version = 3; - else if (kernel_version < MAKE_VERSION(2,3,0)) - nfs_mount_version = 4; /* since 2.2.18pre9 */ - else if (kernel_version < MAKE_VERSION(2,3,99)) - nfs_mount_version = 3; - else - nfs_mount_version = 4; /* since 2.3.99pre4 */ - } - if (nfs_mount_version > NFS_MOUNT_VERSION) - nfs_mount_version = NFS_MOUNT_VERSION; + static int kernel_version = -1; + int nfs_mount_version = NFS_MOUNT_VERSION; + + if (kernel_version == -1) + kernel_version = linux_version_code(); + + if (kernel_version) { + if (kernel_version < MAKE_VERSION(2,1,32)) + nfs_mount_version = 1; + else if (kernel_version < MAKE_VERSION(2,2,18)) + nfs_mount_version = 3; + else if (kernel_version < MAKE_VERSION(2,3,0)) + nfs_mount_version = 4; /* since 2.2.18pre9 */ + else if (kernel_version < MAKE_VERSION(2,3,99)) + nfs_mount_version = 3; + else + nfs_mount_version = 4; /* since 2.3.99pre4 */ + } + if (nfs_mount_version > NFS_MOUNT_VERSION) + nfs_mount_version = NFS_MOUNT_VERSION; log_message("nfsmount: kernel_nfs_mount_version: %d", nfs_mount_version); - return nfs_mount_version; + return nfs_mount_version; } static struct pmap * @@ -234,307 +234,307 @@ get_mountport(struct sockaddr_in *server_addr, long unsigned port, int nfs_mount_version) { - struct pmaplist *pmap; - static struct pmap p = {0, 0, 0, 0}; - - if (version > MAX_NFSPROT) - version = MAX_NFSPROT; - if (!prog) - prog = MOUNTPROG; - p.pm_prog = prog; - p.pm_vers = version; - p.pm_prot = proto; - p.pm_port = port; - - server_addr->sin_port = PMAPPORT; - pmap = pmap_getmaps(server_addr); - - while (pmap) { - if (pmap->pml_map.pm_prog != prog) - goto next; - if (!version && p.pm_vers > pmap->pml_map.pm_vers) - goto next; - if (version > 2 && pmap->pml_map.pm_vers != version) - goto next; - if (version && version <= 2 && pmap->pml_map.pm_vers > 2) - goto next; - if (pmap->pml_map.pm_vers > MAX_NFSPROT || - (proto && p.pm_prot && pmap->pml_map.pm_prot != proto) || - (port && pmap->pml_map.pm_port != port)) - goto next; - memcpy(&p, &pmap->pml_map, sizeof(p)); - next: - pmap = pmap->pml_next; - } - if (!p.pm_vers) - p.pm_vers = MOUNTVERS; - if (!p.pm_prot) - p.pm_prot = IPPROTO_TCP; - return &p; + struct pmaplist *pmap; + static struct pmap p = {0, 0, 0, 0}; + + if (version > MAX_NFSPROT) + version = MAX_NFSPROT; + if (!prog) + prog = MOUNTPROG; + p.pm_prog = prog; + p.pm_vers = version; + p.pm_prot = proto; + p.pm_port = port; + + server_addr->sin_port = PMAPPORT; + pmap = pmap_getmaps(server_addr); + + while (pmap) { + if (pmap->pml_map.pm_prog != prog) + goto next; + if (!version && p.pm_vers > pmap->pml_map.pm_vers) + goto next; + if (version > 2 && pmap->pml_map.pm_vers != version) + goto next; + if (version && version <= 2 && pmap->pml_map.pm_vers > 2) + goto next; + if (pmap->pml_map.pm_vers > MAX_NFSPROT || + (proto && p.pm_prot && pmap->pml_map.pm_prot != proto) || + (port && pmap->pml_map.pm_port != port)) + goto next; + memcpy(&p, &pmap->pml_map, sizeof(p)); + next: + pmap = pmap->pml_next; + } + if (!p.pm_vers) + p.pm_vers = MOUNTVERS; + if (!p.pm_prot) + p.pm_prot = IPPROTO_TCP; + return &p; } int nfsmount_prepare(const char *spec, char **mount_opts) { - char hostdir[1024]; - CLIENT *mclient; - char *hostname, *dirname, *mounthost = NULL; - struct timeval total_timeout; - enum clnt_stat clnt_stat; - static struct nfs_mount_data data; - int nfs_mount_version; - struct sockaddr_in server_addr; - struct sockaddr_in mount_server_addr; - struct pmap *pm_mnt; - int msock, fsock; - struct timeval retry_timeout; - union { - struct fhstatus nfsv2; - struct mountres3 nfsv3; - } status; - char *s; - int port, mountport, proto, soft, intr; - int posix, nocto, noac, broken_suid, nolock; - int tcp; - int mountprog, mountvers, nfsprog, nfsvers; - int retval; - time_t t; - time_t prevt; - - nfs_mount_version = find_kernel_nfs_mount_version(); - - retval = -1; - msock = fsock = -1; - mclient = NULL; - if (strlen(spec) >= sizeof(hostdir)) { - log_message("nfsmount: excessively long host:dir argument"); - goto fail; - } - strcpy(hostdir, spec); - if ((s = strchr(hostdir, ':'))) { - hostname = hostdir; - dirname = s + 1; - *s = '\0'; - } else { - log_message("nfsmount: directory to mount not in host:dir format"); - goto fail; - } - - server_addr.sin_family = AF_INET; + char hostdir[1024]; + CLIENT *mclient; + char *hostname, *dirname, *mounthost = NULL; + struct timeval total_timeout; + enum clnt_stat clnt_stat; + static struct nfs_mount_data data; + int nfs_mount_version; + struct sockaddr_in server_addr; + struct sockaddr_in mount_server_addr; + struct pmap *pm_mnt; + int msock, fsock; + struct timeval retry_timeout; + union { + struct fhstatus nfsv2; + struct mountres3 nfsv3; + } status; + char *s; + int port, mountport, proto, soft, intr; + int posix, nocto, noac, broken_suid, nolock; + int tcp; + int mountprog, mountvers, nfsprog, nfsvers; + int retval; + time_t t; + time_t prevt; + + nfs_mount_version = find_kernel_nfs_mount_version(); + + retval = -1; + msock = fsock = -1; + mclient = NULL; + if (strlen(spec) >= sizeof(hostdir)) { + log_message("nfsmount: excessively long host:dir argument"); + goto fail; + } + strcpy(hostdir, spec); + if ((s = strchr(hostdir, ':'))) { + hostname = hostdir; + dirname = s + 1; + *s = '\0'; + } else { + log_message("nfsmount: directory to mount not in host:dir format"); + goto fail; + } + + server_addr.sin_family = AF_INET; #ifdef HAVE_inet_aton - if (!inet_aton(hostname, &server_addr.sin_addr)) + if (!inet_aton(hostname, &server_addr.sin_addr)) #endif - { - if (mygethostbyname(hostname, &server_addr.sin_addr)) { - log_message("nfsmount: can't get address for %s", hostname); - goto fail; - } - } - - memcpy (&mount_server_addr, &server_addr, sizeof (mount_server_addr)); - - - - /* Set default options. - * rsize/wsize are set to 8192 to enable nfs install on - * old i586 machines - * timeo is filled in after we know whether it'll be TCP or UDP. */ - memset(&data, 0, sizeof(data)); - data.rsize = 8192; - data.wsize = 8192; - data.retrans = 30; - data.acregmin = 3; - data.acregmax = 60; - data.acdirmin = 30; - data.acdirmax = 60; + { + if (mygethostbyname(hostname, &server_addr.sin_addr)) { + log_message("nfsmount: can't get address for %s", hostname); + goto fail; + } + } + + memcpy (&mount_server_addr, &server_addr, sizeof (mount_server_addr)); + + + + /* Set default options. + * rsize/wsize are set to 8192 to enable nfs install on + * old i586 machines + * timeo is filled in after we know whether it'll be TCP or UDP. */ + memset(&data, 0, sizeof(data)); + data.rsize = 8192; + data.wsize = 8192; + data.retrans = 30; + data.acregmin = 3; + data.acregmax = 60; + data.acdirmin = 30; + data.acdirmax = 60; #if NFS_MOUNT_VERSION >= 2 - data.namlen = NAME_MAX; + data.namlen = NAME_MAX; #endif - soft = 1; - intr = 0; - posix = 0; - nocto = 0; - nolock = 1; - broken_suid = 0; - noac = 0; - tcp = 0; + soft = 1; + intr = 0; + posix = 0; + nocto = 0; + nolock = 1; + broken_suid = 0; + noac = 0; + tcp = 0; - mountprog = MOUNTPROG; - mountvers = 0; - port = 0; - mountport = 0; - nfsprog = NFS_PROGRAM; - nfsvers = 0; + mountprog = MOUNTPROG; + mountvers = 0; + port = 0; + mountport = 0; + nfsprog = NFS_PROGRAM; + nfsvers = 0; retry_mount: - proto = (tcp) ? IPPROTO_TCP : IPPROTO_UDP; + proto = (tcp) ? IPPROTO_TCP : IPPROTO_UDP; - data.flags = (soft ? NFS_MOUNT_SOFT : 0) - | (intr ? NFS_MOUNT_INTR : 0) - | (posix ? NFS_MOUNT_POSIX : 0) - | (nocto ? NFS_MOUNT_NOCTO : 0) - | (noac ? NFS_MOUNT_NOAC : 0); + data.flags = (soft ? NFS_MOUNT_SOFT : 0) + | (intr ? NFS_MOUNT_INTR : 0) + | (posix ? NFS_MOUNT_POSIX : 0) + | (nocto ? NFS_MOUNT_NOCTO : 0) + | (noac ? NFS_MOUNT_NOAC : 0); #if NFS_MOUNT_VERSION >= 2 - if (nfs_mount_version >= 2) - data.flags |= (tcp ? NFS_MOUNT_TCP : 0); + if (nfs_mount_version >= 2) + data.flags |= (tcp ? NFS_MOUNT_TCP : 0); #endif #if NFS_MOUNT_VERSION >= 3 - if (nfs_mount_version >= 3) - data.flags |= (nolock ? NFS_MOUNT_NONLM : 0); + if (nfs_mount_version >= 3) + data.flags |= (nolock ? NFS_MOUNT_NONLM : 0); #endif #if NFS_MOUNT_VERSION >= 4 - if (nfs_mount_version >= 4) - data.flags |= (broken_suid ? NFS_MOUNT_BROKEN_SUID : 0); + if (nfs_mount_version >= 4) + data.flags |= (broken_suid ? NFS_MOUNT_BROKEN_SUID : 0); #endif - if (nfsvers > MAX_NFSPROT) { - log_message("NFSv%d not supported!", nfsvers); - return 0; - } - if (mountvers > MAX_NFSPROT) { - log_message("NFSv%d not supported!", nfsvers); - return 0; - } - if (nfsvers && !mountvers) - mountvers = (nfsvers < 3) ? 1 : nfsvers; - if (nfsvers && nfsvers < mountvers) - mountvers = nfsvers; - - /* Adjust options if none specified */ - if (!data.timeo) - data.timeo = tcp ? 70 : 7; + if (nfsvers > MAX_NFSPROT) { + log_message("NFSv%d not supported!", nfsvers); + return 0; + } + if (mountvers > MAX_NFSPROT) { + log_message("NFSv%d not supported!", nfsvers); + return 0; + } + if (nfsvers && !mountvers) + mountvers = (nfsvers < 3) ? 1 : nfsvers; + if (nfsvers && nfsvers < mountvers) + mountvers = nfsvers; + + /* Adjust options if none specified */ + if (!data.timeo) + data.timeo = tcp ? 70 : 7; #ifdef NFS_MOUNT_DEBUG - log_message("rsize = %d, wsize = %d, timeo = %d, retrans = %d", - data.rsize, data.wsize, data.timeo, data.retrans); - log_message("acreg (min, max) = (%d, %d), acdir (min, max) = (%d, %d)", - data.acregmin, data.acregmax, data.acdirmin, data.acdirmax); - log_message("port = %d, retry = %d, flags = %.8x", - port, retry, data.flags); - log_message("mountprog = %d, mountvers = %d, nfsprog = %d, nfsvers = %d", - mountprog, mountvers, nfsprog, nfsvers); - log_message("soft = %d, intr = %d, posix = %d, nocto = %d, noac = %d", - (data.flags & NFS_MOUNT_SOFT) != 0, - (data.flags & NFS_MOUNT_INTR) != 0, - (data.flags & NFS_MOUNT_POSIX) != 0, - (data.flags & NFS_MOUNT_NOCTO) != 0, - (data.flags & NFS_MOUNT_NOAC) != 0); + log_message("rsize = %d, wsize = %d, timeo = %d, retrans = %d", + data.rsize, data.wsize, data.timeo, data.retrans); + log_message("acreg (min, max) = (%d, %d), acdir (min, max) = (%d, %d)", + data.acregmin, data.acregmax, data.acdirmin, data.acdirmax); + log_message("port = %d, retry = %d, flags = %.8x", + port, retry, data.flags); + log_message("mountprog = %d, mountvers = %d, nfsprog = %d, nfsvers = %d", + mountprog, mountvers, nfsprog, nfsvers); + log_message("soft = %d, intr = %d, posix = %d, nocto = %d, noac = %d", + (data.flags & NFS_MOUNT_SOFT) != 0, + (data.flags & NFS_MOUNT_INTR) != 0, + (data.flags & NFS_MOUNT_POSIX) != 0, + (data.flags & NFS_MOUNT_NOCTO) != 0, + (data.flags & NFS_MOUNT_NOAC) != 0); #if NFS_MOUNT_VERSION >= 2 - log_message("tcp = %d", - (data.flags & NFS_MOUNT_TCP) != 0); + log_message("tcp = %d", + (data.flags & NFS_MOUNT_TCP) != 0); #endif #endif - data.version = nfs_mount_version; - *mount_opts = (char *) &data; + data.version = nfs_mount_version; + *mount_opts = (char *) &data; - /* create mount deamon client */ - /* See if the nfs host = mount host. */ - if (mounthost) { - if (mounthost[0] >= '0' && mounthost[0] <= '9') { - mount_server_addr.sin_family = AF_INET; - mount_server_addr.sin_addr.s_addr = inet_addr(hostname); - } else { + /* create mount deamon client */ + /* See if the nfs host = mount host. */ + if (mounthost) { + if (mounthost[0] >= '0' && mounthost[0] <= '9') { + mount_server_addr.sin_family = AF_INET; + mount_server_addr.sin_addr.s_addr = inet_addr(hostname); + } else { if (mygethostbyname(mounthost, &mount_server_addr.sin_addr)) { - log_message("nfsmount: can't get address for %s", mounthost); - goto fail; - } - } - } - - /* - * The following loop implements the mount retries. On the first - * call, "running_bg" is 0. When the mount times out, and the - * "bg" option is set, the exit status EX_BG will be returned. - * For a backgrounded mount, there will be a second call by the - * child process with "running_bg" set to 1. - * - * The case where the mount point is not present and the "bg" - * option is set, is treated as a timeout. This is done to - * support nested mounts. - * - * The "retry" count specified by the user is the number of - * minutes to retry before giving up. - * - * Only the first error message will be displayed. - */ - retry_timeout.tv_sec = 3; - retry_timeout.tv_usec = 0; - total_timeout.tv_sec = 20; - total_timeout.tv_usec = 0; - prevt = 0; - t = 30; - - - /* be careful not to use too many CPU cycles */ - if (t - prevt < 30) - sleep(30); - - pm_mnt = get_mountport(&mount_server_addr, - mountprog, - mountvers, - proto, - mountport, - nfs_mount_version); - - /* contact the mount daemon via TCP */ - mount_server_addr.sin_port = htons(pm_mnt->pm_port); - msock = RPC_ANYSOCK; - - switch (pm_mnt->pm_prot) { - case IPPROTO_UDP: - mclient = clntudp_create(&mount_server_addr, - pm_mnt->pm_prog, - pm_mnt->pm_vers, - retry_timeout, - &msock); - if (mclient) - break; - mount_server_addr.sin_port = - htons(pm_mnt->pm_port); - msock = RPC_ANYSOCK; - case IPPROTO_TCP: - mclient = clnttcp_create(&mount_server_addr, - pm_mnt->pm_prog, - pm_mnt->pm_vers, - &msock, 0, 0); - break; - default: - mclient = 0; - } - - if (mclient) { - /* try to mount hostname:dirname */ - mclient->cl_auth = authunix_create_default(); - - /* make pointers in xdr_mountres3 NULL so - * that xdr_array allocates memory for us - */ - memset(&status, 0, sizeof(status)); - - log_message("nfsmount: doing client call in nfs version: %ld", pm_mnt->pm_vers); - if (pm_mnt->pm_vers == 3) - clnt_stat = clnt_call(mclient, - MOUNTPROC3_MNT, - (xdrproc_t) xdr_dirpath, - (caddr_t) &dirname, - (xdrproc_t) xdr_mountres3, - (caddr_t) &status, - total_timeout); - else - clnt_stat = clnt_call(mclient, - MOUNTPROC_MNT, - (xdrproc_t) xdr_dirpath, - (caddr_t) &dirname, - (xdrproc_t) xdr_fhstatus, - (caddr_t) &status, - total_timeout); - - if (clnt_stat == RPC_SUCCESS) + log_message("nfsmount: can't get address for %s", mounthost); + goto fail; + } + } + } + + /* + * The following loop implements the mount retries. On the first + * call, "running_bg" is 0. When the mount times out, and the + * "bg" option is set, the exit status EX_BG will be returned. + * For a backgrounded mount, there will be a second call by the + * child process with "running_bg" set to 1. + * + * The case where the mount point is not present and the "bg" + * option is set, is treated as a timeout. This is done to + * support nested mounts. + * + * The "retry" count specified by the user is the number of + * minutes to retry before giving up. + * + * Only the first error message will be displayed. + */ + retry_timeout.tv_sec = 3; + retry_timeout.tv_usec = 0; + total_timeout.tv_sec = 20; + total_timeout.tv_usec = 0; + prevt = 0; + t = 30; + + + /* be careful not to use too many CPU cycles */ + if (t - prevt < 30) + sleep(30); + + pm_mnt = get_mountport(&mount_server_addr, + mountprog, + mountvers, + proto, + mountport, + nfs_mount_version); + + /* contact the mount daemon via TCP */ + mount_server_addr.sin_port = htons(pm_mnt->pm_port); + msock = RPC_ANYSOCK; + + switch (pm_mnt->pm_prot) { + case IPPROTO_UDP: + mclient = clntudp_create(&mount_server_addr, + pm_mnt->pm_prog, + pm_mnt->pm_vers, + retry_timeout, + &msock); + if (mclient) + break; + mount_server_addr.sin_port = + htons(pm_mnt->pm_port); + msock = RPC_ANYSOCK; + case IPPROTO_TCP: + mclient = clnttcp_create(&mount_server_addr, + pm_mnt->pm_prog, + pm_mnt->pm_vers, + &msock, 0, 0); + break; + default: + mclient = 0; + } + + if (mclient) { + /* try to mount hostname:dirname */ + mclient->cl_auth = authunix_create_default(); + + /* make pointers in xdr_mountres3 NULL so + * that xdr_array allocates memory for us + */ + memset(&status, 0, sizeof(status)); + + log_message("nfsmount: doing client call in nfs version: %ld", pm_mnt->pm_vers); + if (pm_mnt->pm_vers == 3) + clnt_stat = clnt_call(mclient, + MOUNTPROC3_MNT, + (xdrproc_t) xdr_dirpath, + (caddr_t) &dirname, + (xdrproc_t) xdr_mountres3, + (caddr_t) &status, + total_timeout); + else + clnt_stat = clnt_call(mclient, + MOUNTPROC_MNT, + (xdrproc_t) xdr_dirpath, + (caddr_t) &dirname, + (xdrproc_t) xdr_fhstatus, + (caddr_t) &status, + total_timeout); + + if (clnt_stat == RPC_SUCCESS) goto succeeded; if (prevt == 0) @@ -543,135 +543,135 @@ retry_mount: clnt_destroy(mclient); mclient = 0; close(msock); - } else { + } else { log_message("could not create rpc client: host probably not found or NFS server is down"); - } - prevt = t; + } + prevt = t; - goto fail; + goto fail; succeeded: - nfsvers = (pm_mnt->pm_vers < 2) ? 2 : pm_mnt->pm_vers; + nfsvers = (pm_mnt->pm_vers < 2) ? 2 : pm_mnt->pm_vers; - if (nfsvers == 2) { - if (status.nfsv2.fhs_status != 0) { - log_message("nfsmount: %s:%s failed, reason given by server: %s", + if (nfsvers == 2) { + if (status.nfsv2.fhs_status != 0) { + log_message("nfsmount: %s:%s failed, reason given by server: %s", hostname, dirname, nfs_strerror(status.nfsv2.fhs_status)); - goto fail; - } - memcpy(data.root.data, - (char *) status.nfsv2.fhstatus_u.fhs_fhandle, - NFS_FHSIZE); + goto fail; + } + memcpy(data.root.data, + (char *) status.nfsv2.fhstatus_u.fhs_fhandle, + NFS_FHSIZE); #if NFS_MOUNT_VERSION >= 4 - data.root.size = NFS_FHSIZE; - memcpy(data.old_root.data, - (char *) status.nfsv2.fhstatus_u.fhs_fhandle, - NFS_FHSIZE); + data.root.size = NFS_FHSIZE; + memcpy(data.old_root.data, + (char *) status.nfsv2.fhstatus_u.fhs_fhandle, + NFS_FHSIZE); #endif - } else { + } else { #if NFS_MOUNT_VERSION >= 4 - fhandle3 *fhandle; - if (status.nfsv3.fhs_status != 0) { - log_message("nfsmount: %s:%s failed, reason given by server: %s", + fhandle3 *fhandle; + if (status.nfsv3.fhs_status != 0) { + log_message("nfsmount: %s:%s failed, reason given by server: %s", hostname, dirname, nfs_strerror(status.nfsv3.fhs_status)); - goto fail; - } - fhandle = &status.nfsv3.mountres3_u.mountinfo.fhandle; - memset(data.old_root.data, 0, NFS_FHSIZE); - memset(&data.root, 0, sizeof(data.root)); - data.root.size = fhandle->fhandle3_len; - memcpy(data.root.data, - (char *) fhandle->fhandle3_val, - fhandle->fhandle3_len); - - data.flags |= NFS_MOUNT_VER3; + goto fail; + } + fhandle = &status.nfsv3.mountres3_u.mountinfo.fhandle; + memset(data.old_root.data, 0, NFS_FHSIZE); + memset(&data.root, 0, sizeof(data.root)); + data.root.size = fhandle->fhandle3_len; + memcpy(data.root.data, + (char *) fhandle->fhandle3_val, + fhandle->fhandle3_len); + + data.flags |= NFS_MOUNT_VER3; #endif - } - - /* create nfs socket for kernel */ - - if (tcp) { - if (nfs_mount_version < 3) { - log_message("NFS over TCP is not supported."); - goto fail; - } - fsock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - } else - fsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (fsock < 0) { - log_perror("nfs socket"); - goto fail; - } - if (bindresvport(fsock, 0) < 0) { - log_perror("nfs bindresvport"); - goto fail; - } - if (port == 0) { - server_addr.sin_port = PMAPPORT; - port = pmap_getport(&server_addr, nfsprog, nfsvers, - tcp ? IPPROTO_TCP : IPPROTO_UDP); + } + + /* create nfs socket for kernel */ + + if (tcp) { + if (nfs_mount_version < 3) { + log_message("NFS over TCP is not supported."); + goto fail; + } + fsock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + } else + fsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (fsock < 0) { + log_perror("nfs socket"); + goto fail; + } + if (bindresvport(fsock, 0) < 0) { + log_perror("nfs bindresvport"); + goto fail; + } + if (port == 0) { + server_addr.sin_port = PMAPPORT; + port = pmap_getport(&server_addr, nfsprog, nfsvers, + tcp ? IPPROTO_TCP : IPPROTO_UDP); #if 1 - /* Here we check to see if user is mounting with the - * tcp option. If so, and if the portmap returns a - * '0' for port (service unavailable), we then notify - * the user, and retry with udp. - */ - if (port == 0 && tcp == 1) { - log_message("NFS server reported TCP not available, retrying with UDP..."); - tcp = 0; - goto retry_mount; - } + /* Here we check to see if user is mounting with the + * tcp option. If so, and if the portmap returns a + * '0' for port (service unavailable), we then notify + * the user, and retry with udp. + */ + if (port == 0 && tcp == 1) { + log_message("NFS server reported TCP not available, retrying with UDP..."); + tcp = 0; + goto retry_mount; + } #endif - if (port == 0) - port = NFS_PORT; + if (port == 0) + port = NFS_PORT; #ifdef NFS_MOUNT_DEBUG - else - log_message("used portmapper to find NFS port"); + else + log_message("used portmapper to find NFS port"); #endif - } + } #ifdef NFS_MOUNT_DEBUG - log_message("using port %d for nfs deamon", port); + log_message("using port %d for nfs deamon", port); #endif - server_addr.sin_port = htons(port); - /* - * connect() the socket for kernels 1.3.10 and below only, - * to avoid problems with multihomed hosts. - * --Swen - */ - if (linux_version_code() <= 66314 - && connect(fsock, (struct sockaddr *) &server_addr, - sizeof (server_addr)) < 0) { - log_perror("nfs connect"); - goto fail; - } - - /* prepare data structure for kernel */ - - data.fd = fsock; - memcpy((char *) &data.addr, (char *) &server_addr, sizeof(data.addr)); - strncpy(data.hostname, hostname, sizeof(data.hostname)); - - /* clean up */ - - auth_destroy(mclient->cl_auth); - clnt_destroy(mclient); - close(msock); - return 0; - - /* abort */ + server_addr.sin_port = htons(port); + /* + * connect() the socket for kernels 1.3.10 and below only, + * to avoid problems with multihomed hosts. + * --Swen + */ + if (linux_version_code() <= 66314 + && connect(fsock, (struct sockaddr *) &server_addr, + sizeof (server_addr)) < 0) { + log_perror("nfs connect"); + goto fail; + } + + /* prepare data structure for kernel */ + + data.fd = fsock; + memcpy((char *) &data.addr, (char *) &server_addr, sizeof(data.addr)); + strncpy(data.hostname, hostname, sizeof(data.hostname)); + + /* clean up */ + + auth_destroy(mclient->cl_auth); + clnt_destroy(mclient); + close(msock); + return 0; + + /* abort */ fail: - if (msock != -1) { - if (mclient) { - auth_destroy(mclient->cl_auth); - clnt_destroy(mclient); - } - close(msock); - } - if (fsock != -1) - close(fsock); - return retval; + if (msock != -1) { + if (mclient) { + auth_destroy(mclient->cl_auth); + clnt_destroy(mclient); + } + close(msock); + } + if (fsock != -1) + close(fsock); + return retval; } /* @@ -684,52 +684,52 @@ retry_mount: */ #ifndef EDQUOT -#define EDQUOT ENOSPC +#define EDQUOT ENOSPC #endif static struct { - enum nfsstat stat; - int errnum; + enum nfsstat stat; + int errnum; } nfs_errtbl[] = { - { NFS_OK, 0 }, - { NFSERR_PERM, EPERM }, - { NFSERR_NOENT, ENOENT }, - { NFSERR_IO, EIO }, - { NFSERR_NXIO, ENXIO }, - { NFSERR_ACCES, EACCES }, - { NFSERR_EXIST, EEXIST }, - { NFSERR_NODEV, ENODEV }, - { NFSERR_NOTDIR, ENOTDIR }, - { NFSERR_ISDIR, EISDIR }, + { NFS_OK, 0 }, + { NFSERR_PERM, EPERM }, + { NFSERR_NOENT, ENOENT }, + { NFSERR_IO, EIO }, + { NFSERR_NXIO, ENXIO }, + { NFSERR_ACCES, EACCES }, + { NFSERR_EXIST, EEXIST }, + { NFSERR_NODEV, ENODEV }, + { NFSERR_NOTDIR, ENOTDIR }, + { NFSERR_ISDIR, EISDIR }, #ifdef NFSERR_INVAL - { NFSERR_INVAL, EINVAL }, /* that Sun forgot */ + { NFSERR_INVAL, EINVAL }, /* that Sun forgot */ #endif - { NFSERR_FBIG, EFBIG }, - { NFSERR_NOSPC, ENOSPC }, - { NFSERR_ROFS, EROFS }, - { NFSERR_NAMETOOLONG, ENAMETOOLONG }, - { NFSERR_NOTEMPTY, ENOTEMPTY }, - { NFSERR_DQUOT, EDQUOT }, - { NFSERR_STALE, ESTALE }, + { NFSERR_FBIG, EFBIG }, + { NFSERR_NOSPC, ENOSPC }, + { NFSERR_ROFS, EROFS }, + { NFSERR_NAMETOOLONG, ENAMETOOLONG }, + { NFSERR_NOTEMPTY, ENOTEMPTY }, + { NFSERR_DQUOT, EDQUOT }, + { NFSERR_STALE, ESTALE }, #ifdef EWFLUSH - { NFSERR_WFLUSH, EWFLUSH }, + { NFSERR_WFLUSH, EWFLUSH }, #endif - /* Throw in some NFSv3 values for even more fun (HP returns these) */ - { 71, EREMOTE }, + /* Throw in some NFSv3 values for even more fun (HP returns these) */ + { 71, EREMOTE }, - { -1, EIO } + { -1, EIO } }; static char *nfs_strerror(int stat) { - int i; - static char buf[256]; - - for (i = 0; nfs_errtbl[i].stat != (unsigned)-1; i++) { - if (nfs_errtbl[i].stat == (unsigned)stat) - return strerror(nfs_errtbl[i].errnum); - } - sprintf(buf, "unknown nfs status return value: %d", stat); - return buf; + int i; + static char buf[256]; + + for (i = 0; nfs_errtbl[i].stat != (unsigned)-1; i++) { + if (nfs_errtbl[i].stat == (unsigned)stat) + return strerror(nfs_errtbl[i].errnum); + } + sprintf(buf, "unknown nfs status return value: %d", stat); + return buf; } diff --git a/mdk-stage1/params.c b/mdk-stage1/params.c index 692c3e511..21898b3ee 100644 --- a/mdk-stage1/params.c +++ b/mdk-stage1/params.c @@ -29,79 +29,79 @@ static int param_number = 0; void process_cmdline(void) { - char buf[512]; - int size, i; - int fd = -1; - - if (IS_TESTING) { - log_message("TESTING: opening cmdline... "); - - if ((fd = open("cmdline", O_RDONLY)) == -1) - log_message("TESTING: could not open cmdline"); - } - - if (fd == -1) { - log_message("opening /proc/cmdline... "); - - if ((fd = open("/proc/cmdline", O_RDONLY)) == -1) - fatal_error("could not open /proc/cmdline"); - } - - size = read(fd, buf, sizeof(buf)); - buf[size-1] = '\0'; // -1 to eat the \n - close(fd); - - log_message("\t%s", buf); - - i = 0; - while (buf[i] != '\0') { - char *name, *value = NULL; - int j = i; - while (buf[i] != ' ' && buf[i] != '=' && buf[i] != '\0') - i++; - if (i == j) { - i++; - continue; - } - name = _memdup(&buf[j], i-j + 1); - name[i-j] = '\0'; - - if (buf[i] == '=') { - int k = i+1; - i++; - while (buf[i] != ' ' && buf[i] != '\0') - i++; - value = _memdup(&buf[k], i-k + 1); - value[i-k] = '\0'; - } - - params[param_number].name = name; - params[param_number].value = value; - param_number++; - if (!strcmp(name, "changedisk")) set_param(MODE_CHANGEDISK); - if (!strcmp(name, "updatemodules") || - !strcmp(name, "thirdparty")) set_param(MODE_THIRDPARTY); - if (!strcmp(name, "rescue") || - !strcmp(name, "kamethod")) set_param(MODE_RESCUE); - if (!strcmp(name, "rescue")) set_param(MODE_RESCUE); - if (!strcmp(name, "keepmounted")) set_param(MODE_KEEP_MOUNTED); - if (!strcmp(name, "noauto")) set_param(MODE_NOAUTO); - if (!strcmp(name, "netauto")) set_param(MODE_NETAUTO); - if (!strcmp(name, "debugstage1")) set_param(MODE_DEBUGSTAGE1); - if (!strcmp(name, "automatic")) { - set_param(MODE_AUTOMATIC); - grab_automatic_params(value); - } - if (buf[i] == '\0') - break; - i++; - } - - if (IS_AUTOMATIC && strcmp(get_auto_value("thirdparty"), "")) { - set_param(MODE_THIRDPARTY); - } - - log_message("\tgot %d args", param_number); + char buf[512]; + int size, i; + int fd = -1; + + if (IS_TESTING) { + log_message("TESTING: opening cmdline... "); + + if ((fd = open("cmdline", O_RDONLY)) == -1) + log_message("TESTING: could not open cmdline"); + } + + if (fd == -1) { + log_message("opening /proc/cmdline... "); + + if ((fd = open("/proc/cmdline", O_RDONLY)) == -1) + fatal_error("could not open /proc/cmdline"); + } + + size = read(fd, buf, sizeof(buf)); + buf[size-1] = '\0'; // -1 to eat the \n + close(fd); + + log_message("\t%s", buf); + + i = 0; + while (buf[i] != '\0') { + char *name, *value = NULL; + int j = i; + while (buf[i] != ' ' && buf[i] != '=' && buf[i] != '\0') + i++; + if (i == j) { + i++; + continue; + } + name = _memdup(&buf[j], i-j + 1); + name[i-j] = '\0'; + + if (buf[i] == '=') { + int k = i+1; + i++; + while (buf[i] != ' ' && buf[i] != '\0') + i++; + value = _memdup(&buf[k], i-k + 1); + value[i-k] = '\0'; + } + + params[param_number].name = name; + params[param_number].value = value; + param_number++; + if (!strcmp(name, "changedisk")) set_param(MODE_CHANGEDISK); + if (!strcmp(name, "updatemodules") || + !strcmp(name, "thirdparty")) set_param(MODE_THIRDPARTY); + if (!strcmp(name, "rescue") || + !strcmp(name, "kamethod")) set_param(MODE_RESCUE); + if (!strcmp(name, "rescue")) set_param(MODE_RESCUE); + if (!strcmp(name, "keepmounted")) set_param(MODE_KEEP_MOUNTED); + if (!strcmp(name, "noauto")) set_param(MODE_NOAUTO); + if (!strcmp(name, "netauto")) set_param(MODE_NETAUTO); + if (!strcmp(name, "debugstage1")) set_param(MODE_DEBUGSTAGE1); + if (!strcmp(name, "automatic")) { + set_param(MODE_AUTOMATIC); + grab_automatic_params(value); + } + if (buf[i] == '\0') + break; + i++; + } + + if (IS_AUTOMATIC && strcmp(get_auto_value("thirdparty"), "")) { + set_param(MODE_THIRDPARTY); + } + + log_message("\tgot %d args", param_number); } @@ -110,68 +110,68 @@ int stage1_mode = 0; int get_param(int i) { #ifdef SPAWN_INTERACTIVE - static int fd = 0; - char buf[5000]; - char * ptr; - int nb; - - if (fd <= 0) { - fd = open(interactive_fifo, O_RDONLY); - if (fd == -1) - return (stage1_mode & i); - fcntl(fd, F_SETFL, O_NONBLOCK); - } - - if (fd > 0) { - if ((nb = read(fd, buf, sizeof(buf))) > 0) { - buf[nb] = '\0'; - ptr = buf; - while ((ptr = strstr(ptr, "+ "))) { - if (!strncmp(ptr+2, "rescue", 6)) set_param(MODE_RESCUE); - ptr++; - } - ptr = buf; - while ((ptr = strstr(ptr, "- "))) { - if (!strncmp(ptr+2, "rescue", 6)) unset_param(MODE_RESCUE); - ptr++; - } - } - } + static int fd = 0; + char buf[5000]; + char * ptr; + int nb; + + if (fd <= 0) { + fd = open(interactive_fifo, O_RDONLY); + if (fd == -1) + return (stage1_mode & i); + fcntl(fd, F_SETFL, O_NONBLOCK); + } + + if (fd > 0) { + if ((nb = read(fd, buf, sizeof(buf))) > 0) { + buf[nb] = '\0'; + ptr = buf; + while ((ptr = strstr(ptr, "+ "))) { + if (!strncmp(ptr+2, "rescue", 6)) set_param(MODE_RESCUE); + ptr++; + } + ptr = buf; + while ((ptr = strstr(ptr, "- "))) { + if (!strncmp(ptr+2, "rescue", 6)) unset_param(MODE_RESCUE); + ptr++; + } + } + } #endif - return (stage1_mode & i); + return (stage1_mode & i); } char * get_param_valued(char *param_name) { - int i; - for (i = 0; i < param_number ; i++) - if (!strcmp(params[i].name, param_name)) - return params[i].value; + int i; + for (i = 0; i < param_number ; i++) + if (!strcmp(params[i].name, param_name)) + return params[i].value; - return NULL; + return NULL; } void set_param_valued(char *param_name, char *param_value) { - params[param_number].name = param_name; - params[param_number].value = param_value; - param_number++; + params[param_number].name = param_name; + params[param_number].value = param_value; + param_number++; } void set_param(int i) { - stage1_mode |= i; + stage1_mode |= i; } void unset_param(int i) { - stage1_mode &= ~i; + stage1_mode &= ~i; } void unset_automatic(void) { - log_message("unsetting automatic"); - unset_param(MODE_AUTOMATIC); - exit_bootsplash(); + log_message("unsetting automatic"); + unset_param(MODE_AUTOMATIC); + exit_bootsplash(); } diff --git a/mdk-stage1/partition.c b/mdk-stage1/partition.c index 83bfc5ce6..c5daf8693 100644 --- a/mdk-stage1/partition.c +++ b/mdk-stage1/partition.c @@ -40,131 +40,131 @@ #include "partition.h" struct partition_detection_anchor { - off_t offset; - const char * anchor; + off_t offset; + const char * anchor; }; static int seek_and_compare(int fd, struct partition_detection_anchor anch) { - char buf[500]; - size_t count; - if (lseek(fd, anch.offset, SEEK_SET) == (off_t)-1) { - log_perror("seek failed"); - return -1; - } - count = read(fd, buf, strlen(anch.anchor)); - if (count != strlen(anch.anchor)) { - log_perror("read failed"); - return -1; - } - buf[count] = '\0'; - if (strcmp(anch.anchor, buf)) - return 1; - return 0; + char buf[500]; + size_t count; + if (lseek(fd, anch.offset, SEEK_SET) == (off_t)-1) { + log_perror("seek failed"); + return -1; + } + count = read(fd, buf, strlen(anch.anchor)); + if (count != strlen(anch.anchor)) { + log_perror("read failed"); + return -1; + } + buf[count] = '\0'; + if (strcmp(anch.anchor, buf)) + return 1; + return 0; } static const char * detect_partition_type(char * dev) { - struct partition_detection_info { - const char * name; - struct partition_detection_anchor anchor0; - struct partition_detection_anchor anchor1; - struct partition_detection_anchor anchor2; - }; - struct partition_detection_info partitions_signatures[] = { - { "Linux Swap", { 4086, "SWAP-SPACE" }, { 0, NULL }, { 0, NULL } }, - { "Linux Swap", { 4086, "SWAPSPACE2" }, { 0, NULL }, { 0, NULL } }, - { "Ext2", { 0x438, "\x53\xEF" }, { 0, NULL }, { 0, NULL } }, - { "ReiserFS", { 0x10034, "ReIsErFs" }, { 0, NULL }, { 0, NULL } }, - { "ReiserFS", { 0x10034, "ReIsEr2Fs" }, { 0, NULL }, { 0, NULL } }, - { "XFS", { 0, "XFSB" }, { 0x200, "XAGF" }, { 0x400, "XAGI" } }, - { "JFS", { 0x8000, "JFS1" }, { 0, NULL }, { 0, NULL } }, - { "NTFS", { 0x1FE, "\x55\xAA" }, { 0x3, "NTFS" }, { 0, NULL } }, - { "FAT32", { 0x1FE, "\x55\xAA" }, { 0x52, "FAT32" }, { 0, NULL } }, - { "FAT", { 0x1FE, "\x55\xAA" }, { 0x36, "FAT" }, { 0, NULL } }, - { "Linux LVM", { 0, "HM\1\0" }, { 0, NULL }, { 0, NULL } } - }; - int partitions_signatures_nb = sizeof(partitions_signatures) / sizeof(struct partition_detection_info); - int i; - int fd; + struct partition_detection_info { + const char * name; + struct partition_detection_anchor anchor0; + struct partition_detection_anchor anchor1; + struct partition_detection_anchor anchor2; + }; + struct partition_detection_info partitions_signatures[] = { + { "Linux Swap", { 4086, "SWAP-SPACE" }, { 0, NULL }, { 0, NULL } }, + { "Linux Swap", { 4086, "SWAPSPACE2" }, { 0, NULL }, { 0, NULL } }, + { "Ext2", { 0x438, "\x53\xEF" }, { 0, NULL }, { 0, NULL } }, + { "ReiserFS", { 0x10034, "ReIsErFs" }, { 0, NULL }, { 0, NULL } }, + { "ReiserFS", { 0x10034, "ReIsEr2Fs" }, { 0, NULL }, { 0, NULL } }, + { "XFS", { 0, "XFSB" }, { 0x200, "XAGF" }, { 0x400, "XAGI" } }, + { "JFS", { 0x8000, "JFS1" }, { 0, NULL }, { 0, NULL } }, + { "NTFS", { 0x1FE, "\x55\xAA" }, { 0x3, "NTFS" }, { 0, NULL } }, + { "FAT32", { 0x1FE, "\x55\xAA" }, { 0x52, "FAT32" }, { 0, NULL } }, + { "FAT", { 0x1FE, "\x55\xAA" }, { 0x36, "FAT" }, { 0, NULL } }, + { "Linux LVM", { 0, "HM\1\0" }, { 0, NULL }, { 0, NULL } } + }; + int partitions_signatures_nb = sizeof(partitions_signatures) / sizeof(struct partition_detection_info); + int i; + int fd; const char *part_type = NULL; - char device_fullname[50]; - strcpy(device_fullname, "/dev/"); - strcat(device_fullname, dev); - - if (ensure_dev_exists(device_fullname)) - return NULL; - log_message("guessing type of %s", device_fullname); - - if ((fd = open(device_fullname, O_RDONLY, 0)) < 0) { - log_perror("open"); - return NULL; - } - - for (i=0; i<partitions_signatures_nb; i++) { - int results = seek_and_compare(fd, partitions_signatures[i].anchor0); - if (results == -1) - goto detect_partition_type_end; - if (results == 1) - continue; - if (!partitions_signatures[i].anchor1.anchor) - goto detect_partition_found_it; - - results = seek_and_compare(fd, partitions_signatures[i].anchor1); - if (results == -1) - goto detect_partition_type_end; - if (results == 1) - continue; - if (!partitions_signatures[i].anchor2.anchor) - goto detect_partition_found_it; - - results = seek_and_compare(fd, partitions_signatures[i].anchor2); - if (results == -1) - goto detect_partition_type_end; - if (results == 1) - continue; - - detect_partition_found_it: - part_type = partitions_signatures[i].name; + char device_fullname[50]; + strcpy(device_fullname, "/dev/"); + strcat(device_fullname, dev); + + if (ensure_dev_exists(device_fullname)) + return NULL; + log_message("guessing type of %s", device_fullname); + + if ((fd = open(device_fullname, O_RDONLY, 0)) < 0) { + log_perror("open"); + return NULL; + } + + for (i=0; i<partitions_signatures_nb; i++) { + int results = seek_and_compare(fd, partitions_signatures[i].anchor0); + if (results == -1) + goto detect_partition_type_end; + if (results == 1) + continue; + if (!partitions_signatures[i].anchor1.anchor) + goto detect_partition_found_it; + + results = seek_and_compare(fd, partitions_signatures[i].anchor1); + if (results == -1) + goto detect_partition_type_end; + if (results == 1) + continue; + if (!partitions_signatures[i].anchor2.anchor) + goto detect_partition_found_it; + + results = seek_and_compare(fd, partitions_signatures[i].anchor2); + if (results == -1) + goto detect_partition_type_end; + if (results == 1) + continue; + + detect_partition_found_it: + part_type = partitions_signatures[i].name; break; - } + } detect_partition_type_end: - close(fd); - return part_type; + close(fd); + return part_type; } int list_partitions(char * dev_name, char ** parts, char ** comments) { - int major, minor, blocks; - char name[100]; - FILE * f; - int i = 0; - char buf[512]; - - if (!(f = fopen("/proc/partitions", "rb")) || !fgets(buf, sizeof(buf), f) || !fgets(buf, sizeof(buf), f)) { - log_perror(dev_name); + int major, minor, blocks; + char name[100]; + FILE * f; + int i = 0; + char buf[512]; + + if (!(f = fopen("/proc/partitions", "rb")) || !fgets(buf, sizeof(buf), f) || !fgets(buf, sizeof(buf), f)) { + log_perror(dev_name); return 1; - } - - while (fgets(buf, sizeof(buf), f)) { - memset(name, 0, sizeof(name)); - sscanf(buf, " %d %d %d %s", &major, &minor, &blocks, name); - if ((strstr(name, dev_name) == name) && (blocks > 1) && (name[strlen(dev_name)] != '\0')) { - const char * partition_type = detect_partition_type(name); - parts[i] = strdup(name); - comments[i] = (char *) malloc(sizeof(char) * 100); - sprintf(comments[i], "size: %d Mbytes", blocks >> 10); - if (partition_type) { - strcat(comments[i], ", type: "); - strcat(comments[i], partition_type); - } - i++; - } - } - parts[i] = NULL; - fclose(f); + } + + while (fgets(buf, sizeof(buf), f)) { + memset(name, 0, sizeof(name)); + sscanf(buf, " %d %d %d %s", &major, &minor, &blocks, name); + if ((strstr(name, dev_name) == name) && (blocks > 1) && (name[strlen(dev_name)] != '\0')) { + const char * partition_type = detect_partition_type(name); + parts[i] = strdup(name); + comments[i] = (char *) malloc(sizeof(char) * 100); + sprintf(comments[i], "size: %d Mbytes", blocks >> 10); + if (partition_type) { + strcat(comments[i], ", type: "); + strcat(comments[i], partition_type); + } + i++; + } + } + parts[i] = NULL; + fclose(f); return 0; } diff --git a/mdk-stage1/pcmcia/probe.c b/mdk-stage1/pcmcia/probe.c index 240fe3a17..222be6239 100644 --- a/mdk-stage1/pcmcia/probe.c +++ b/mdk-stage1/pcmcia/probe.c @@ -12,9 +12,6 @@ * * * Code comes from /anonymous@projects.sourceforge.net:/pub/pcmcia-cs/pcmcia-cs-3.1.29.tar.bz2 - * - * FIXME: resync with latest pcmcia-cs-3.2.8 or with pcmciautils-0.18 (which uses sysfs) - * */ /*====================================================================== @@ -58,15 +55,18 @@ #include <errno.h> #include <fcntl.h> +//mdk-stage1// #include <pcmcia/config.h> #include "log.h" #include "pcmcia.h" /*====================================================================*/ +//mdk-stage1// #ifdef CONFIG_PCI + typedef struct { - u_short vendor, device; - char *modname; - char *name; + u_short vendor, device; + char *modname; + char *name; } pci_id_t; pci_id_t pci_id[] = { @@ -138,40 +138,79 @@ static int pci_probe(void) u_int device, vendor, i; FILE *f; +//mdk-stage1// if (!module) log_message("PCMCIA: probing PCI bus.."); if ((f = fopen("/proc/bus/pci/devices", "r")) != NULL) { - while (fgets(s, 256, f) != NULL) { - u_int n = strtoul(s+5, NULL, 16); - vendor = (n >> 16); device = (n & 0xffff); - if (vendor == 0x1217) { - driver = "yenta_socket"; - name = "O2 Micro|PCMCIA Controller"; - break; - } - for (i = 0; i < PCI_COUNT; i++) - if ((vendor == pci_id[i].vendor) && - (device == pci_id[i].device)) break; - if (i < PCI_COUNT) { - name = pci_id[i].name; - driver = pci_id[i].modname; - } - } + while (fgets(s, 256, f) != NULL) { + u_int n = strtoul(s+5, NULL, 16); + vendor = (n >> 16); device = (n & 0xffff); + if (vendor == 0x1217) { + driver = "yenta_socket"; + name = "O2 Micro|PCMCIA Controller"; + break; + } + for (i = 0; i < PCI_COUNT; i++) + if ((vendor == pci_id[i].vendor) && + (device == pci_id[i].device)) break; + if (i < PCI_COUNT) { + name = pci_id[i].name; + driver = pci_id[i].modname; + } + } } +//mdk-stage1// else if ((f = fopen("/proc/pci", "r")) != NULL) { +//mdk-stage1// while (fgets(s, 256, f) != NULL) { +//mdk-stage1// t = strstr(s, "Device id="); +//mdk-stage1// if (t) { +//mdk-stage1// device = strtoul(t+10, NULL, 16); +//mdk-stage1// t = strstr(s, "Vendor id="); +//mdk-stage1// vendor = strtoul(t+10, NULL, 16); +//mdk-stage1// for (i = 0; i < PCI_COUNT; i++) +//mdk-stage1// if ((vendor == pci_id[i].vendor) && +//mdk-stage1// (device == pci_id[i].device)) break; +//mdk-stage1// } else +//mdk-stage1// for (i = 0; i < PCI_COUNT; i++) +//mdk-stage1// if (strstr(s, pci_id[i].tag) != NULL) break; +//mdk-stage1// if (i != PCI_COUNT) { +//mdk-stage1// name = pci_id[i].name; +//mdk-stage1// break; +//mdk-stage1// } else { +//mdk-stage1// t = strstr(s, "CardBus bridge"); +//mdk-stage1// if (t != NULL) { +//mdk-stage1// name = t + 16; +//mdk-stage1// t = strchr(s, '('); +//mdk-stage1// t[-1] = '\0'; +//mdk-stage1// break; +//mdk-stage1// } +//mdk-stage1// } +//mdk-stage1// } +//mdk-stage1// } fclose(f); if (name) { - log_message("\t%s found, 2 sockets (driver %s).", name, driver); - return 0; +//mdk-stage1// if (module) +//mdk-stage1// printf("i82365\n"); +//mdk-stage1// else + log_message("\t%s found, 2 sockets (driver %s).", name, driver); + return 0; } else { - log_message("\tnot found."); - return -ENODEV; +//mdk-stage1// if (!module) + log_message("\tnot found."); + return -ENODEV; } } +//mdk-stage1// #endif /*====================================================================*/ +//mdk-stage1// #ifdef CONFIG_ISA +//mdk-stage1// +//mdk-stage1// #ifdef __GLIBC__ #include <sys/io.h> +//mdk-stage1// #else +//mdk-stage1// #include <asm/io.h> +//mdk-stage1// #endif typedef u_short ioaddr_t; #include "i82365.h" @@ -212,7 +251,9 @@ int i365_probe(void) int val, sock, done; char *name = "i82365sl"; +//mdk-stage1// if (!module) log_message("PCMCIA: probing for Intel PCIC (ISA).."); +//mdk-stage1// if (verbose) printf("\n"); sock = done = 0; if (ioperm(i365_base, 4, 1)) { @@ -221,35 +262,39 @@ int i365_probe(void) } ioperm(0x80, 1, 1); for (; sock < 2; sock++) { - val = i365_get(sock, I365_IDENT); - switch (val) { - case 0x82: - name = "i82365sl A step"; - break; - case 0x83: - name = "i82365sl B step"; - break; - case 0x84: - name = "VLSI 82C146"; - break; - case 0x88: case 0x89: case 0x8a: - name = "IBM Clone"; - break; - case 0x8b: case 0x8c: - break; - default: - done = 1; - } - if (done) break; + val = i365_get(sock, I365_IDENT); +//mdk-stage1// if (verbose) +//mdk-stage1// printf(" ident(%d)=%#2.2x", sock, val); + switch (val) { + case 0x82: + name = "i82365sl A step"; + break; + case 0x83: + name = "i82365sl B step"; + break; + case 0x84: + name = "VLSI 82C146"; + break; + case 0x88: case 0x89: case 0x8a: + name = "IBM Clone"; + break; + case 0x8b: case 0x8c: + break; + default: + done = 1; + } + if (done) break; } +//mdk-stage1// if (verbose) printf("\n "); if (sock == 0) { - log_message("\tnot found."); - return -ENODEV; +//mdk-stage1// if (!module) + log_message("\tnot found."); + return -ENODEV; } if ((sock == 2) && (strcmp(name, "VLSI 82C146") == 0)) - name = "i82365sl DF"; + name = "i82365sl DF"; /* Check for Vadem chips */ outb(0x0e, i365_base); @@ -257,40 +302,49 @@ int i365_probe(void) i365_bset(0, VG468_MISC, VG468_MISC_VADEMREV); val = i365_get(0, I365_IDENT); if (val & I365_IDENT_VADEM) { - if ((val & 7) < 4) - name = "Vadem VG-468"; - else - name = "Vadem VG-469"; - i365_bclr(0, VG468_MISC, VG468_MISC_VADEMREV); + if ((val & 7) < 4) + name = "Vadem VG-468"; + else + name = "Vadem VG-469"; + i365_bclr(0, VG468_MISC, VG468_MISC_VADEMREV); } /* Check for Cirrus CL-PD67xx chips */ i365_set(0, PD67_CHIP_INFO, 0); val = i365_get(0, PD67_CHIP_INFO); if ((val & PD67_INFO_CHIP_ID) == PD67_INFO_CHIP_ID) { - val = i365_get(0, PD67_CHIP_INFO); - if ((val & PD67_INFO_CHIP_ID) == 0) { - if (val & PD67_INFO_SLOTS) - name = "Cirrus CL-PD672x"; - else { - name = "Cirrus CL-PD6710"; - sock = 1; - } - i365_set(0, PD67_EXT_INDEX, 0xe5); - if (i365_get(0, PD67_EXT_INDEX) != 0xe5) - name = "VIA VT83C469"; - } + val = i365_get(0, PD67_CHIP_INFO); + if ((val & PD67_INFO_CHIP_ID) == 0) { + if (val & PD67_INFO_SLOTS) + name = "Cirrus CL-PD672x"; + else { + name = "Cirrus CL-PD6710"; + sock = 1; + } + i365_set(0, PD67_EXT_INDEX, 0xe5); + if (i365_get(0, PD67_EXT_INDEX) != 0xe5) + name = "VIA VT83C469"; + } } - printf("\t%s found, %d sockets.\n", name, sock); +//mdk-stage1// if (module) +//mdk-stage1// printf("i82365\n"); +//mdk-stage1// else + printf("\t%s found, %d sockets.\n", name, sock); return 0; } /* i365_probe */ +//mdk-stage1//#endif /* CONFIG_ISA */ + /*====================================================================*/ +//mdk-stage1//#ifdef CONFIG_ISA + #include "tcic.h" +//mdk-stage1//static ioaddr_t tcic_base = TCIC_BASE; + static u_char tcic_getb(ioaddr_t base, u_char reg) { u_char val = inb(base+reg); @@ -344,9 +398,10 @@ int tcic_probe_at(ioaddr_t base) /* Anything there?? */ for (i = 0; i < 0x10; i += 2) - if (tcic_getw(base, i) == 0xffff) - return -1; + if (tcic_getw(base, i) == 0xffff) + return -1; +//mdk-stage1// if (!module) log_message("\tat %#3.3x: ", base); fflush(stdout); /* Try to reset the chip */ @@ -357,13 +412,13 @@ int tcic_probe_at(ioaddr_t base) old = tcic_getw(base, TCIC_ADDR); tcic_setw(base, TCIC_ADDR, 0); if (tcic_getw(base, TCIC_ADDR) != 0) { - tcic_setw(base, TCIC_ADDR, old); - return -2; + tcic_setw(base, TCIC_ADDR, old); + return -2; } tcic_setw(base, TCIC_ADDR, 0xc3a5); if (tcic_getw(base, TCIC_ADDR) != 0xc3a5) - return -3; + return -3; return 2; } @@ -372,55 +427,105 @@ int tcic_probe(void) { int sock, id; +//mdk-stage1// if (!module) log_message("PCMCIA: probing for Databook TCIC-2 (ISA).."); fflush(stdout); if (ioperm(TCIC_BASE, 16, 1)) { - log_perror("PCMCIA: ioperm"); - return -1; + log_perror("PCMCIA: ioperm"); + return -1; } ioperm(0x80, 1, 1); sock = tcic_probe_at(TCIC_BASE); if (sock <= 0) { - log_message("\tnot found."); - return -ENODEV; +//mdk-stage1// if (!module) + log_message("\tnot found."); + return -ENODEV; } - id = get_tcic_id(TCIC_BASE); - switch (id) { - case TCIC_ID_DB86082: - log_message("DB86082"); break; - case TCIC_ID_DB86082A: - log_message("DB86082A"); break; - case TCIC_ID_DB86084: - log_message("DB86084"); break; - case TCIC_ID_DB86084A: - log_message("DB86084A"); break; - case TCIC_ID_DB86072: - log_message("DB86072"); break; - case TCIC_ID_DB86184: - log_message("DB86184"); break; - case TCIC_ID_DB86082B: - log_message("DB86082B"); break; - default: - log_message("Unknown TCIC-2 ID 0x%02x", id); - } - log_message(" found at %#6x, %d sockets.", TCIC_BASE, sock); +//mdk-stage1// if (module) +//mdk-stage1// printf("tcic\n"); +//mdk-stage1// else { + id = get_tcic_id(TCIC_BASE); + switch (id) { + case TCIC_ID_DB86082: + log_message("DB86082"); break; + case TCIC_ID_DB86082A: + log_message("DB86082A"); break; + case TCIC_ID_DB86084: + log_message("DB86084"); break; + case TCIC_ID_DB86084A: + log_message("DB86084A"); break; + case TCIC_ID_DB86072: + log_message("DB86072"); break; + case TCIC_ID_DB86184: + log_message("DB86184"); break; + case TCIC_ID_DB86082B: + log_message("DB86082B"); break; + default: + log_message("Unknown TCIC-2 ID 0x%02x", id); + } + log_message(" found at %#6x, %d sockets.", TCIC_BASE, sock); +//mdk-stage1// } return 0; } /* tcic_probe */ +//mdk-stage1// #endif /* CONFIG_ISA */ + +//mdk-stage1// /*====================================================================*/ +//mdk-stage1// +//mdk-stage1// int main(int argc, char *argv[]) +//mdk-stage1// { +//mdk-stage1// int optch, errflg; +//mdk-stage1// extern char *optarg; +//mdk-stage1// int verbose = 0, module = 0; +//mdk-stage1// +//mdk-stage1// errflg = 0; +//mdk-stage1// while ((optch = getopt(argc, argv, "t:vxm")) != -1) { +//mdk-stage1// switch (optch) { +//mdk-stage1// #ifdef CONFIG_ISA +//mdk-stage1// case 't': +//mdk-stage1// tcic_base = strtoul(optarg, NULL, 0); break; +//mdk-stage1// #endif +//mdk-stage1// case 'v': +//mdk-stage1// verbose = 1; break; +//mdk-stage1// case 'm': +//mdk-stage1// module = 1; break; +//mdk-stage1// default: +//mdk-stage1// errflg = 1; break; +//mdk-stage1// } +//mdk-stage1// } +//mdk-stage1// if (errflg || (optind < argc)) { +//mdk-stage1// fprintf(stderr, "usage: %s [-t tcic_base] [-v] [-m]\n", argv[0]); +//mdk-stage1// exit(EXIT_FAILURE); +//mdk-stage1// } +//mdk-stage1// +//mdk-stage1// #ifdef CONFIG_PCI +//mdk-stage1// if (pci_probe(verbose, module) == 0) +//mdk-stage1// exit(EXIT_SUCCESS); +//mdk-stage1// #endif +//mdk-stage1// #ifdef CONFIG_ISA +//mdk-stage1// if (i365_probe(verbose, module) == 0) +//mdk-stage1// exit(EXIT_SUCCESS); +//mdk-stage1// else if (tcic_probe(verbose, module, tcic_base) == 0) +//mdk-stage1// exit(EXIT_SUCCESS); +//mdk-stage1// #endif +//mdk-stage1// exit(EXIT_FAILURE); +//mdk-stage1// return 0; +//mdk-stage1// } + char * pcmcia_probe(void) { - if (!pci_probe()) - return driver; + if (!pci_probe()) + return driver; #if !defined(__x86_64__) - else if (!i365_probe()) - return "pd6729"; - else if (!tcic_probe()) - return "tcic"; + else if (!i365_probe()) + return "pd6729"; + else if (!tcic_probe()) + return "tcic"; #endif - else - return NULL; + else + return NULL; } diff --git a/mdk-stage1/pcmcia/startup.c b/mdk-stage1/pcmcia/startup.c index e9004484a..4112a439c 100644 --- a/mdk-stage1/pcmcia/startup.c +++ b/mdk-stage1/pcmcia/startup.c @@ -1,7 +1,7 @@ /* * Startup tool for non statically mapped PCMCIA sockets * - * (C) 2005 Dominik Brodowski <linux@brodo.de> + * (C) 2005 Dominik Brodowski <linux@brodo.de> * * The initial developer of the original code is David A. Hinds * <dahinds@users.sourceforge.net>. Portions created by David A. Hinds @@ -42,149 +42,149 @@ enum { static const char *resource_files[MAX_RESOURCE_FILES] = { - [RESOURCE_MEM] = "available_resources_mem", - [RESOURCE_IO] = "available_resources_io", + [RESOURCE_MEM] = "available_resources_mem", + [RESOURCE_IO] = "available_resources_io", }; #define PATH_TO_SOCKET "/sys/class/pcmcia_socket/" static int add_available_resource(unsigned int socket_no, unsigned int type, - unsigned int action, - unsigned long start, unsigned long end) + unsigned int action, + unsigned long start, unsigned long end) { - char file[SYSFS_PATH_MAX]; - char content[SYSFS_PATH_MAX]; - struct sysfs_attribute *attr; - int ret; - size_t len; + char file[SYSFS_PATH_MAX]; + char content[SYSFS_PATH_MAX]; + struct sysfs_attribute *attr; + int ret; + size_t len; - if (type >= MAX_RESOURCE_FILES) - return -EINVAL; + if (type >= MAX_RESOURCE_FILES) + return -EINVAL; - if (end <= start) - return -EINVAL; + if (end <= start) + return -EINVAL; - dprintf("%d %d %d 0x%lx 0x%lx\n", socket_no, type, action, start, end); + dprintf("%d %d %d 0x%lx 0x%lx\n", socket_no, type, action, start, end); - snprintf(file, SYSFS_PATH_MAX, PATH_TO_SOCKET "pcmcia_socket%u/%s", - socket_no, resource_files[type]); + snprintf(file, SYSFS_PATH_MAX, PATH_TO_SOCKET "pcmcia_socket%u/%s", + socket_no, resource_files[type]); - switch(action) { - case ADD_MANAGED_RESOURCE: - len = snprintf(content, SYSFS_PATH_MAX, - "0x%08lx - 0x%08lx", start, end); - break; + switch(action) { + case ADD_MANAGED_RESOURCE: + len = snprintf(content, SYSFS_PATH_MAX, + "0x%08lx - 0x%08lx", start, end); + break; - case REMOVE_MANAGED_RESOURCE: - len = snprintf(content, SYSFS_PATH_MAX, - "- 0x%08lx - 0x%08lx", start, end); - break; + case REMOVE_MANAGED_RESOURCE: + len = snprintf(content, SYSFS_PATH_MAX, + "- 0x%08lx - 0x%08lx", start, end); + break; - default: - return -EINVAL; - } + default: + return -EINVAL; + } - dprintf("content is %s\n", content); + dprintf("content is %s\n", content); - dprintf("file is %s\n", file); + dprintf("file is %s\n", file); - attr = sysfs_open_attribute(file); - if (!attr) - return -ENODEV; + attr = sysfs_open_attribute(file); + if (!attr) + return -ENODEV; - dprintf("open, len %d\n", len); + dprintf("open, len %d\n", len); - ret = sysfs_write_attribute(attr, content, len); + ret = sysfs_write_attribute(attr, content, len); - dprintf("ret is %d\n", ret); + dprintf("ret is %d\n", ret); - sysfs_close_attribute(attr); + sysfs_close_attribute(attr); - return (ret); + return (ret); } static int setup_done(unsigned int socket_no) { - int ret; - char file[SYSFS_PATH_MAX]; - struct sysfs_attribute *attr; + int ret; + char file[SYSFS_PATH_MAX]; + struct sysfs_attribute *attr; - snprintf(file, SYSFS_PATH_MAX, PATH_TO_SOCKET - "pcmcia_socket%u/available_resources_setup_done", - socket_no); + snprintf(file, SYSFS_PATH_MAX, PATH_TO_SOCKET + "pcmcia_socket%u/available_resources_setup_done", + socket_no); - attr = sysfs_open_attribute(file); - if (!attr) - return -ENODEV; + attr = sysfs_open_attribute(file); + if (!attr) + return -ENODEV; - ret = sysfs_write_attribute(attr, "42", 2); + ret = sysfs_write_attribute(attr, "42", 2); - sysfs_close_attribute(attr); + sysfs_close_attribute(attr); - return (ret); + return (ret); } static int disallow_irq(unsigned int socket_no, unsigned int irq) { - char file[SYSFS_PATH_MAX]; - char content[SYSFS_PATH_MAX]; - struct sysfs_attribute *attr; - unsigned int mask = 0xfff; - unsigned int new_mask; - int ret; - size_t len; - - if (irq >= 32) - return -EINVAL; - - len = snprintf(file, SYSFS_PATH_MAX, PATH_TO_SOCKET - "pcmcia_socket%u/card_irq_mask", - socket_no); - dprintf("file is %s\n", file); - - attr = sysfs_open_attribute(file); - if (!attr) - return -ENODEV; - - dprintf("open, len %d\n", len); - - ret = sysfs_read_attribute(attr); - if (ret) { - ret = -EINVAL; - goto out; - } + char file[SYSFS_PATH_MAX]; + char content[SYSFS_PATH_MAX]; + struct sysfs_attribute *attr; + unsigned int mask = 0xfff; + unsigned int new_mask; + int ret; + size_t len; + + if (irq >= 32) + return -EINVAL; + + len = snprintf(file, SYSFS_PATH_MAX, PATH_TO_SOCKET + "pcmcia_socket%u/card_irq_mask", + socket_no); + dprintf("file is %s\n", file); + + attr = sysfs_open_attribute(file); + if (!attr) + return -ENODEV; + + dprintf("open, len %d\n", len); + + ret = sysfs_read_attribute(attr); + if (ret) { + ret = -EINVAL; + goto out; + } - if (!attr->value || (attr->len < 6)) { - ret = -EIO; - goto out; - } + if (!attr->value || (attr->len < 6)) { + ret = -EIO; + goto out; + } - ret = sscanf(attr->value, "0x%x\n", &mask); + ret = sscanf(attr->value, "0x%x\n", &mask); - new_mask = 1 << irq; + new_mask = 1 << irq; - mask &= ~new_mask; + mask &= ~new_mask; - len = snprintf(content, SYSFS_PATH_MAX, "0x%04x", mask); + len = snprintf(content, SYSFS_PATH_MAX, "0x%04x", mask); - dprintf("content is %s\n", content); + dprintf("content is %s\n", content); - ret = sysfs_write_attribute(attr, content, len); + ret = sysfs_write_attribute(attr, content, len); out: - sysfs_close_attribute(attr); + sysfs_close_attribute(attr); - return (ret); + return (ret); } static void load_config(void) { if (chdir(configpath) != 0) { - syslog(LOG_ERR, "chdir to %s failed: %m", configpath); - exit(EXIT_FAILURE); + syslog(LOG_ERR, "chdir to %s failed: %m", configpath); + exit(EXIT_FAILURE); } parse_configfile("config.opts"); return; @@ -196,76 +196,76 @@ static void adjust_resources(unsigned int socket_no) adjust_list_t *al; for (al = root_adjust; al; al = al->next) { - switch (al->adj.Resource) { - case RES_MEMORY_RANGE: - add_available_resource(socket_no, RESOURCE_MEM, - al->adj.Action, - al->adj.resource.memory.Base, - al->adj.resource.memory.Base + - al->adj.resource.memory.Size - 1); - break; - case RES_IO_RANGE: - add_available_resource(socket_no, RESOURCE_IO, - al->adj.Action, - al->adj.resource.io.BasePort, - al->adj.resource.io.BasePort + - al->adj.resource.io.NumPorts - 1); - break; - case RES_IRQ: - if(al->adj.Action == REMOVE_MANAGED_RESOURCE) - disallow_irq(socket_no, al->adj.resource.irq.IRQ); - break; - } + switch (al->adj.Resource) { + case RES_MEMORY_RANGE: + add_available_resource(socket_no, RESOURCE_MEM, + al->adj.Action, + al->adj.resource.memory.Base, + al->adj.resource.memory.Base + + al->adj.resource.memory.Size - 1); + break; + case RES_IO_RANGE: + add_available_resource(socket_no, RESOURCE_IO, + al->adj.Action, + al->adj.resource.io.BasePort, + al->adj.resource.io.BasePort + + al->adj.resource.io.NumPorts - 1); + break; + case RES_IRQ: + if(al->adj.Action == REMOVE_MANAGED_RESOURCE) + disallow_irq(socket_no, al->adj.resource.irq.IRQ); + break; + } } } /* mdk-stage1 int main(int argc, char *argv[]) { - char *socket_no; - unsigned long socket, i; - unsigned int all_sockets = 0; - - - if ((socket_no = getenv("SOCKET_NO"))) { - socket = strtoul(socket_no, NULL, 0); - } else if (argc == 2) { - socket = strtoul(argv[1], NULL, 0); - } else if (argc == 1) { - socket = 0; - all_sockets = 1; - } else { - return -EINVAL; - } + char *socket_no; + unsigned long socket, i; + unsigned int all_sockets = 0; + + + if ((socket_no = getenv("SOCKET_NO"))) { + socket = strtoul(socket_no, NULL, 0); + } else if (argc == 2) { + socket = strtoul(argv[1], NULL, 0); + } else if (argc == 1) { + socket = 0; + all_sockets = 1; + } else { + return -EINVAL; + } - load_config(); + load_config(); - for (i = 0; i < MAX_SOCKS; i++) { - if ((socket != i) && (!all_sockets)) - continue; + for (i = 0; i < MAX_SOCKS; i++) { + if ((socket != i) && (!all_sockets)) + continue; - adjust_resources(i); - setup_done(i); - } + adjust_resources(i); + setup_done(i); + } - return 0; + return 0; } */ void pcmcia_socket_startup(int socket_no) { - unsigned long i; - unsigned int all_sockets = 0; + unsigned long i; + unsigned int all_sockets = 0; if (socket_no == -1) - all_sockets = 1; + all_sockets = 1; - load_config(); + load_config(); - for (i = 0; i < MAX_SOCKS; i++) { - if ((socket_no != i) && (!all_sockets)) - continue; + for (i = 0; i < MAX_SOCKS; i++) { + if ((socket_no != i) && (!all_sockets)) + continue; - adjust_resources(i); - setup_done(i); - } + adjust_resources(i); + setup_done(i); + } } diff --git a/mdk-stage1/probe-modules.c b/mdk-stage1/probe-modules.c index ad4f9e4cd..c282a8d1c 100644 --- a/mdk-stage1/probe-modules.c +++ b/mdk-stage1/probe-modules.c @@ -25,46 +25,46 @@ void exit_bootsplash(void) {} void stg1_error_message(char *msg, ...) { - va_list args; - va_start(args, msg); - verror_message(msg, args); - va_end(args); + va_list args; + va_start(args, msg); + verror_message(msg, args); + va_end(args); } void fatal_error(char *msg) { - log_message("FATAL ERROR IN MODULES LOADER: %s\n\nI can't recover from this.\nYou may reboot your system.\n", msg); - exit(EXIT_FAILURE); + log_message("FATAL ERROR IN MODULES LOADER: %s\n\nI can't recover from this.\nYou may reboot your system.\n", msg); + exit(EXIT_FAILURE); } int main(int argc, char **argv, char **env) { - enum media_bus bus = BUS_ANY; - char *module = NULL; - char options[500] = ""; + enum media_bus bus = BUS_ANY; + char *module = NULL; + char options[500] = ""; - if (argc > 1) { - if (streq(argv[1], "--usb")) { - bus = BUS_USB; - } else if (!ptr_begins_static_str(argv[1], "--")) { - int i; - module = argv[1]; - for (i = 2; i < argc; i++) { - strcat(options, argv[i]); - strcat(options, " "); - } - } - } + if (argc > 1) { + if (streq(argv[1], "--usb")) { + bus = BUS_USB; + } else if (!ptr_begins_static_str(argv[1], "--")) { + int i; + module = argv[1]; + for (i = 2; i < argc; i++) { + strcat(options, argv[i]); + strcat(options, " "); + } + } + } - open_log(); - init_modules_insmoding(); + open_log(); + init_modules_insmoding(); - if (module) { - my_insmod(module, ANY_DRIVER_TYPE, options, 0); - } else { - find_media(bus); - } + if (module) { + my_insmod(module, ANY_DRIVER_TYPE, options, 0); + } else { + find_media(bus); + } - close_log(); + close_log(); - return 0; + return 0; } diff --git a/mdk-stage1/probing.c b/mdk-stage1/probing.c index 5f9983efb..4f96c6e6d 100644 --- a/mdk-stage1/probing.c +++ b/mdk-stage1/probing.c @@ -63,29 +63,29 @@ struct media_info { - char * name; - char * model; - enum media_type type; + char * name; + char * model; + enum media_type type; }; static void warning_insmod_failed(enum insmod_return r) { - if (IS_AUTOMATIC && r == INSMOD_FAILED_FILE_NOT_FOUND) - return; - if (r != INSMOD_OK) { - if (r == INSMOD_FAILED_FILE_NOT_FOUND) - stg1_error_message("This floppy doesn't contain the driver."); - else - stg1_error_message("Warning, installation of driver failed. (please include msg from <Alt-F3> for bugreports)"); - } + if (IS_AUTOMATIC && r == INSMOD_FAILED_FILE_NOT_FOUND) + return; + if (r != INSMOD_OK) { + if (r == INSMOD_FAILED_FILE_NOT_FOUND) + stg1_error_message("This floppy doesn't contain the driver."); + else + stg1_error_message("Warning, installation of driver failed. (please include msg from <Alt-F3> for bugreports)"); + } } #ifndef DISABLE_NETWORK struct net_description_elem { - char * intf_name; - char * intf_description; + char * intf_name; + char * intf_description; }; static struct net_description_elem net_descriptions[50]; static int net_descr_number = 0; @@ -95,52 +95,52 @@ static int net_intf_too_early_number = 0; static int net_intf_too_early_ptr = 0; const char * safe_descr(const char * text) { - return text ? text : "unknown"; + return text ? text : "unknown"; } void prepare_intf_descr(const char * intf_descr) { - intf_descr_for_discover = strdup(intf_descr); + intf_descr_for_discover = strdup(intf_descr); } void net_discovered_interface(char * intf_name) { - if (!intf_descr_for_discover) { - net_intf_too_early_name[net_intf_too_early_number++] = strdup(intf_name); - return; - } - if (!intf_name) { - if (net_intf_too_early_ptr >= net_intf_too_early_number) { - log_message("NET: was expecting another network interface (broken net module?)"); - return; - } - net_descriptions[net_descr_number].intf_name = net_intf_too_early_name[net_intf_too_early_ptr++]; - } - else - net_descriptions[net_descr_number].intf_name = strdup(intf_name); - net_descriptions[net_descr_number].intf_description = strdup(intf_descr_for_discover); - intf_descr_for_discover = NULL; - net_descr_number++; + if (!intf_descr_for_discover) { + net_intf_too_early_name[net_intf_too_early_number++] = strdup(intf_name); + return; + } + if (!intf_name) { + if (net_intf_too_early_ptr >= net_intf_too_early_number) { + log_message("NET: was expecting another network interface (broken net module?)"); + return; + } + net_descriptions[net_descr_number].intf_name = net_intf_too_early_name[net_intf_too_early_ptr++]; + } + else + net_descriptions[net_descr_number].intf_name = strdup(intf_name); + net_descriptions[net_descr_number].intf_description = strdup(intf_descr_for_discover); + intf_descr_for_discover = NULL; + net_descr_number++; } char * get_net_intf_description(char * intf_name) { - int i; - for (i = 0; i < net_descr_number ; i++) - if (!strcmp(net_descriptions[i].intf_name, intf_name)) - return net_descriptions[i].intf_description; - return strdup("unknown"); + int i; + for (i = 0; i < net_descr_number ; i++) + if (!strcmp(net_descriptions[i].intf_name, intf_name)) + return net_descriptions[i].intf_description; + return strdup("unknown"); } #endif static int device_match_modules_list(struct pciusb_entry *e, char **modules, unsigned int modules_len) { - int i; - if (!e->module) - return 0; - for (i = 0; i < modules_len; i++) - if (!strcmp(modules[i], e->module)) - return 1; - return 0; + int i; + if (!e->module) + return 0; + for (i = 0; i < modules_len; i++) + if (!strcmp(modules[i], e->module)) + return 1; + return 0; } struct pcitable_entry *detected_devices = NULL; @@ -148,171 +148,171 @@ int detected_devices_len = 0; static void detected_devices_destroy(void) { - if (detected_devices) - free(detected_devices); + if (detected_devices) + free(detected_devices); } static struct pcitable_entry *detected_device_new(void) { - static int detected_devices_maxlen = 0; - if (detected_devices_len >= detected_devices_maxlen) { - detected_devices_maxlen += 32; - if (detected_devices == NULL) - detected_devices = malloc(detected_devices_maxlen * sizeof(*detected_devices)); - else - detected_devices = realloc(detected_devices, detected_devices_maxlen * sizeof(*detected_devices)); - if (detected_devices == NULL) - log_perror("detected_device_new: could not (re)allocate table. Let it crash, sorry"); - } - return &detected_devices[detected_devices_len++]; + static int detected_devices_maxlen = 0; + if (detected_devices_len >= detected_devices_maxlen) { + detected_devices_maxlen += 32; + if (detected_devices == NULL) + detected_devices = malloc(detected_devices_maxlen * sizeof(*detected_devices)); + else + detected_devices = realloc(detected_devices, detected_devices_maxlen * sizeof(*detected_devices)); + if (detected_devices == NULL) + log_perror("detected_device_new: could not (re)allocate table. Let it crash, sorry"); + } + return &detected_devices[detected_devices_len++]; } /* FIXME: factorize with probe_that_type() */ static void add_detected_device(unsigned short vendor, unsigned short device, unsigned int subvendor, unsigned int subdevice, const char *name, const char *module) { - struct pcitable_entry *dev = detected_device_new(); - dev->vendor = vendor; - dev->device = device; - dev->subvendor = subvendor; - dev->subdevice = subdevice; - strncpy(dev->module, module, sizeof(dev->module) - 1); - dev->module[sizeof(dev->module) - 1] = '\0'; - strncpy(dev->description, safe_descr(name), sizeof(dev->description) - 1); - dev->description[sizeof(dev->description) - 1] = '\0'; - log_message("detected device (%04x, %04x, %04x, %04x, %s, %s)", vendor, device, subvendor, subdevice, name, module); + struct pcitable_entry *dev = detected_device_new(); + dev->vendor = vendor; + dev->device = device; + dev->subvendor = subvendor; + dev->subdevice = subdevice; + strncpy(dev->module, module, sizeof(dev->module) - 1); + dev->module[sizeof(dev->module) - 1] = '\0'; + strncpy(dev->description, safe_descr(name), sizeof(dev->description) - 1); + dev->description[sizeof(dev->description) - 1] = '\0'; + log_message("detected device (%04x, %04x, %04x, %04x, %s, %s)", vendor, device, subvendor, subdevice, name, module); } static int add_detected_device_if_match(struct pciusb_entry *e, char **modules, unsigned int modules_len) { - int ret = device_match_modules_list(e, modules, modules_len); - if (ret) - add_detected_device(e->vendor, e->device, e->subvendor, e->subdevice, - e->text, e->module); - return ret; + int ret = device_match_modules_list(e, modules, modules_len); + if (ret) + add_detected_device(e->vendor, e->device, e->subvendor, e->subdevice, + e->text, e->module); + return ret; } void probing_detect_devices() { static int already_detected_devices = 0; - struct pciusb_entries entries; - int i; + struct pciusb_entries entries; + int i; - if (already_detected_devices) - return; + if (already_detected_devices) + return; - entries = pci_probe(); - for (i = 0; i < entries.nb; i++) { - struct pciusb_entry *e = &entries.entries[i]; + entries = pci_probe(); + for (i = 0; i < entries.nb; i++) { + struct pciusb_entry *e = &entries.entries[i]; #ifndef DISABLE_PCIADAPTERS #ifndef DISABLE_MEDIAS - if (add_detected_device_if_match(e, medias_ide_pci_modules, medias_ide_pci_modules_len)) - continue; - if (add_detected_device_if_match(e, medias_other_pci_modules, medias_other_pci_modules_len)) - continue; + if (add_detected_device_if_match(e, medias_ide_pci_modules, medias_ide_pci_modules_len)) + continue; + if (add_detected_device_if_match(e, medias_other_pci_modules, medias_other_pci_modules_len)) + continue; #endif #ifndef DISABLE_NETWORK - if (add_detected_device_if_match(e, network_pci_modules, network_pci_modules_len)) - continue; + if (add_detected_device_if_match(e, network_pci_modules, network_pci_modules_len)) + continue; #endif #ifdef ENABLE_USB - if (add_detected_device_if_match(e, usb_controller_modules, usb_controller_modules_len)) - continue; + if (add_detected_device_if_match(e, usb_controller_modules, usb_controller_modules_len)) + continue; #endif #endif - /* device can't be found in built-in pcitables, but keep it */ - add_detected_device(e->vendor, e->device, e->subvendor, e->subdevice, e->text, e->module); - } - pciusb_free(&entries); + /* device can't be found in built-in pcitables, but keep it */ + add_detected_device(e->vendor, e->device, e->subvendor, e->subdevice, e->text, e->module); + } + pciusb_free(&entries); - already_detected_devices = 1; + already_detected_devices = 1; } void probing_destroy(void) { - detected_devices_destroy(); + detected_devices_destroy(); } #ifndef DISABLE_MEDIAS static const char * get_alternate_module(const char * name) { - struct alternate_mapping { - const char * a; - const char * b; - }; - static struct alternate_mapping mappings[] = { + struct alternate_mapping { + const char * a; + const char * b; + }; + static struct alternate_mapping mappings[] = { { "ahci", "ata_piix" }, }; - int mappings_nb = sizeof(mappings) / sizeof(struct alternate_mapping); + int mappings_nb = sizeof(mappings) / sizeof(struct alternate_mapping); int i; - for (i=0; i<mappings_nb; i++) { - const char * alternate = NULL; - if (streq(name, mappings[i].a)) - alternate = mappings[i].b; - else if (streq(name, mappings[i].b)) - alternate = mappings[i].a; - if (alternate) { - log_message("found alternate module %s for driver %s", alternate, name); - return alternate; - } - } + for (i=0; i<mappings_nb; i++) { + const char * alternate = NULL; + if (streq(name, mappings[i].a)) + alternate = mappings[i].b; + else if (streq(name, mappings[i].b)) + alternate = mappings[i].a; + if (alternate) { + log_message("found alternate module %s for driver %s", alternate, name); + return alternate; + } + } return NULL; } #endif void discovered_device(enum driver_type type, const char * description, const char * driver) { - description = safe_descr(description); + description = safe_descr(description); - enum insmod_return failed = INSMOD_FAILED; + enum insmod_return failed = INSMOD_FAILED; #ifndef DISABLE_MEDIAS - if (type == MEDIA_ADAPTERS) { - const char * alternate = NULL; - wait_message("Loading driver for media adapter:\n \n%s", description); - failed = my_insmod(driver, MEDIA_ADAPTERS, NULL, 1); - alternate = get_alternate_module(driver); - if (!IS_NOAUTO && alternate) { - failed = failed || my_insmod(alternate, MEDIA_ADAPTERS, NULL, 1); - } - remove_wait_message(); - warning_insmod_failed(failed); - } + if (type == MEDIA_ADAPTERS) { + const char * alternate = NULL; + wait_message("Loading driver for media adapter:\n \n%s", description); + failed = my_insmod(driver, MEDIA_ADAPTERS, NULL, 1); + alternate = get_alternate_module(driver); + if (!IS_NOAUTO && alternate) { + failed = failed || my_insmod(alternate, MEDIA_ADAPTERS, NULL, 1); + } + remove_wait_message(); + warning_insmod_failed(failed); + } #endif #ifndef DISABLE_NETWORK - if (type == NETWORK_DEVICES) { - wait_message("Loading driver for network device:\n \n%s", description); - prepare_intf_descr(description); - failed = my_insmod(driver, NETWORK_DEVICES, NULL, 1); - warning_insmod_failed(failed); - remove_wait_message(); - if (intf_descr_for_discover) /* for modules providing more than one net intf */ - net_discovered_interface(NULL); - } + if (type == NETWORK_DEVICES) { + wait_message("Loading driver for network device:\n \n%s", description); + prepare_intf_descr(description); + failed = my_insmod(driver, NETWORK_DEVICES, NULL, 1); + warning_insmod_failed(failed); + remove_wait_message(); + if (intf_descr_for_discover) /* for modules providing more than one net intf */ + net_discovered_interface(NULL); + } #endif #ifdef ENABLE_USB - if (type == USB_CONTROLLERS) + if (type == USB_CONTROLLERS) /* we can't allow additional modules floppy since we need usbhid for keystrokes of usb keyboards */ - failed = my_insmod(driver, USB_CONTROLLERS, NULL, 0); + failed = my_insmod(driver, USB_CONTROLLERS, NULL, 0); #endif } void probe_pci_modules(enum driver_type type, char **pci_modules, unsigned int pci_modules_len) { - struct pciusb_entries entries; - int i; - - entries = pci_probe(); - for (i = 0; i < entries.nb; i++) { - struct pciusb_entry *e = &entries.entries[i]; - if (device_match_modules_list(e, pci_modules, pci_modules_len)) { - log_message("PCI: device %04x %04x %04x %04x is \"%s\", driver is %s", - e->vendor, e->device, e->subvendor, e->subdevice, safe_descr(e->text), e->module); - discovered_device(type, e->text, e->module); - } - } - pciusb_free(&entries); + struct pciusb_entries entries; + int i; + + entries = pci_probe(); + for (i = 0; i < entries.nb; i++) { + struct pciusb_entry *e = &entries.entries[i]; + if (device_match_modules_list(e, pci_modules, pci_modules_len)) { + log_message("PCI: device %04x %04x %04x %04x is \"%s\", driver is %s", + e->vendor, e->device, e->subvendor, e->subdevice, safe_descr(e->text), e->module); + discovered_device(type, e->text, e->module); + } + } + pciusb_free(&entries); } /** Loads modules for known virtio devices @@ -325,46 +325,46 @@ void probe_pci_modules(enum driver_type type, char **pci_modules, unsigned int */ void probe_virtio_modules(void) { - struct pciusb_entries entries; - int i; - char *name; - char *options; - int loaded_pci = 0; - - entries = pci_probe(); - for (i = 0; i < entries.nb; i++) { - struct pciusb_entry *e = &entries.entries[i]; - if (e->vendor == VIRTIO_PCI_VENDOR) { - if (!loaded_pci) { - log_message("loading virtio-pci"); - my_insmod("virtio_pci", ANY_DRIVER_TYPE, NULL, 0); - loaded_pci = 1; - } - - name = NULL; - options = NULL; - - switch (e->subdevice) { - case VIRTIO_ID_NET: - name = "virtio_net"; - options = "csum=0"; - break; - case VIRTIO_ID_BLOCK: - name = "virtio_blk"; - break; - case VIRTIO_ID_BALLOON: - name = "virtio_balloon"; - break; - default: - log_message("warning: unknown virtio device %04x", e->device); - } - if (name) { - log_message("virtio: loading %s", name); - my_insmod(name, ANY_DRIVER_TYPE, options, 0); - } - } - } - pciusb_free(&entries); + struct pciusb_entries entries; + int i; + char *name; + char *options; + int loaded_pci = 0; + + entries = pci_probe(); + for (i = 0; i < entries.nb; i++) { + struct pciusb_entry *e = &entries.entries[i]; + if (e->vendor == VIRTIO_PCI_VENDOR) { + if (!loaded_pci) { + log_message("loading virtio-pci"); + my_insmod("virtio_pci", ANY_DRIVER_TYPE, NULL, 0); + loaded_pci = 1; + } + + name = NULL; + options = NULL; + + switch (e->subdevice) { + case VIRTIO_ID_NET: + name = "virtio_net"; + options = "csum=0"; + break; + case VIRTIO_ID_BLOCK: + name = "virtio_blk"; + break; + case VIRTIO_ID_BALLOON: + name = "virtio_balloon"; + break; + default: + log_message("warning: unknown virtio device %04x", e->device); + } + if (name) { + log_message("virtio: loading %s", name); + my_insmod(name, ANY_DRIVER_TYPE, options, 0); + } + } + } + pciusb_free(&entries); } #ifdef ENABLE_USB @@ -377,167 +377,172 @@ void probe_that_type(enum driver_type type, enum media_bus bus __attribute__ ((u static int already_loaded_usb_scsi = 0; static int already_probed_virtio_devices = 0; - /* ---- PCI probe ---------------------------------------------- */ - if (bus != BUS_USB) { - switch (type) { + /* ---- PCI probe ---------------------------------------------- */ + if (bus != BUS_USB) { + switch (type) { #ifndef DISABLE_PCIADAPTERS #ifndef DISABLE_MEDIAS - static int already_probed_media_adapters = 0; - case MEDIA_ADAPTERS: - if (already_probed_media_adapters) - break; - already_probed_media_adapters = 1; - probe_pci_modules(type, medias_ide_pci_modules, medias_ide_pci_modules_len); - probe_pci_modules(type, medias_other_pci_modules, medias_other_pci_modules_len); - break; + static int already_probed_media_adapters = 0; + case MEDIA_ADAPTERS: + if (already_probed_media_adapters) + break; + already_probed_media_adapters = 1; + probe_pci_modules(type, medias_ide_pci_modules, medias_ide_pci_modules_len); + probe_pci_modules(type, medias_other_pci_modules, medias_other_pci_modules_len); + break; #endif #ifndef DISABLE_NETWORK - case NETWORK_DEVICES: - probe_pci_modules(type, network_pci_modules, network_pci_modules_len); - break; + case NETWORK_DEVICES: + probe_pci_modules(type, network_pci_modules, network_pci_modules_len); + break; #endif #endif #ifdef ENABLE_USB - case USB_CONTROLLERS: - if (already_probed_usb_controllers || IS_NOAUTO) - break; - already_probed_usb_controllers = 1; - probe_pci_modules(type, usb_controller_modules, usb_controller_modules_len); - break; + case USB_CONTROLLERS: + if (already_probed_usb_controllers || IS_NOAUTO) + break; + already_probed_usb_controllers = 1; + probe_pci_modules(type, usb_controller_modules, usb_controller_modules_len); + break; #endif - case VIRTIO_DEVICES: - if (already_probed_virtio_devices) - break; - probe_virtio_modules(); - already_probed_virtio_devices = 1; - break; - default: - break; - } - } + case VIRTIO_DEVICES: + if (already_probed_virtio_devices) + break; + probe_virtio_modules(); + already_probed_virtio_devices = 1; + break; + default: + break; + } + } #ifdef ENABLE_USB - /* ---- USB probe ---------------------------------------------- */ - if ((bus == BUS_USB || bus == BUS_ANY) && !(IS_NOAUTO)) { - static int already_mounted_usbdev = 0; - struct pciusb_entries entries; - int i; - - if (!already_probed_usb_controllers) - probe_that_type(USB_CONTROLLERS, BUS_ANY); - - if (!already_mounted_usbdev) { - already_mounted_usbdev = 1; - wait_message("Detecting USB devices."); - sleep(4); /* sucking background work */ - my_insmod("usbhid", ANY_DRIVER_TYPE, NULL, 0); - remove_wait_message(); - } - - if (type != NETWORK_DEVICES) - goto end_usb_probe; - - entries = usb_probe(); - for (i = 0; i < entries.nb; i++) { - struct pciusb_entry *e = &entries.entries[i]; - if (device_match_modules_list(e, usb_modules, usb_modules_len)) { - log_message("USB: device %04x %04x is \"%s\" (%s)", e->vendor, e->device, safe_descr(e->text), e->module); - discovered_device(type, e->text, e->module); - } - } - pciusb_free(&entries); - end_usb_probe:; - } + /* ---- USB probe ---------------------------------------------- */ + if ((bus == BUS_USB || bus == BUS_ANY) && !(IS_NOAUTO)) { + static int already_mounted_usbdev = 0; + struct pciusb_entries entries; + int i; + + if (!already_probed_usb_controllers) + probe_that_type(USB_CONTROLLERS, BUS_ANY); + + if (!already_mounted_usbdev) { + already_mounted_usbdev = 1; + if (mount("none", "/proc/bus/usb", "usbfs", 0, NULL) && + mount("none", "/proc/bus/usb", "usbdevfs", 0, NULL)) { + log_message("USB: couldn't mount /proc/bus/usb"); + goto end_usb_probe; + } + wait_message("Detecting USB devices."); + sleep(4); /* sucking background work */ + my_insmod("usbhid", ANY_DRIVER_TYPE, NULL, 0); + remove_wait_message(); + } + + if (type != NETWORK_DEVICES) + goto end_usb_probe; + + entries = usb_probe(); + for (i = 0; i < entries.nb; i++) { + struct pciusb_entry *e = &entries.entries[i]; + if (device_match_modules_list(e, usb_modules, usb_modules_len)) { + log_message("USB: device %04x %04x is \"%s\" (%s)", e->vendor, e->device, safe_descr(e->text), e->module); + discovered_device(type, e->text, e->module); + } + } + pciusb_free(&entries); + end_usb_probe:; + } #endif #ifdef ENABLE_PCMCIA - /* ---- PCMCIA probe ---------------------------------------------- */ - if ((bus == BUS_PCMCIA || bus == BUS_ANY) && !(IS_NOAUTO)) { - struct pcmcia_alias * pcmciadb = NULL; - unsigned int len = 0; - char *base = "/sys/bus/pcmcia/devices"; - DIR *dir; - struct dirent *dent; - - dir = opendir(base); - if (dir == NULL) - goto end_pcmcia_probe; - - switch (type) { + /* ---- PCMCIA probe ---------------------------------------------- */ + if ((bus == BUS_PCMCIA || bus == BUS_ANY) && !(IS_NOAUTO)) { + struct pcmcia_alias * pcmciadb = NULL; + unsigned int len = 0; + char *base = "/sys/bus/pcmcia/devices"; + DIR *dir; + struct dirent *dent; + + dir = opendir(base); + if (dir == NULL) + goto end_pcmcia_probe; + + switch (type) { #ifndef DISABLE_MEDIAS - case MEDIA_ADAPTERS: - pcmciadb = medias_pcmcia_ids; - len = medias_pcmcia_num_ids; - break; + case MEDIA_ADAPTERS: + pcmciadb = medias_pcmcia_ids; + len = medias_pcmcia_num_ids; + break; #endif #ifndef DISABLE_NETWORK - case NETWORK_DEVICES: - pcmciadb = network_pcmcia_ids; - len = network_pcmcia_num_ids; - break; + case NETWORK_DEVICES: + pcmciadb = network_pcmcia_ids; + len = network_pcmcia_num_ids; + break; #endif - default: - goto end_pcmcia_probe; + default: + goto end_pcmcia_probe; } for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) { - struct sysfs_attribute *modalias_attr; - char keyfile[256]; - int i, id; - - if (dent->d_name[0] == '.') - continue; - - log_message("PCMCIA: device found %s", dent->d_name); - - snprintf(keyfile, sizeof(keyfile)-1, "%s/%s/modalias", base, dent->d_name); - modalias_attr = sysfs_open_attribute(keyfile); - if (!modalias_attr) - continue; - if (sysfs_read_attribute(modalias_attr) != 0 || !modalias_attr->value) { - sysfs_close_attribute(modalias_attr); - continue; - } - - log_message("PCMCIA: device found %s", modalias_attr->value); - - for (i = 0; i < len; i++) { - if (!fnmatch(pcmciadb[i].modalias, modalias_attr->value, 0)) { - char product[256]; - - log_message("PCMCIA: device found %s (%s)", pcmciadb[i].modalias, pcmciadb[i].module); - strcpy(product, ""); - for (id = 1; id <= 4; id++) { - struct sysfs_attribute *product_attr; - snprintf(keyfile, sizeof(keyfile)-1, "%s/%s/prod_id%d", base, dent->d_name, id); - product_attr = sysfs_open_attribute(keyfile); - if (!product_attr) - continue; - if (sysfs_read_attribute(product_attr) || !product_attr->value) { - sysfs_close_attribute(product_attr); - continue; - } - snprintf(product + strlen(product), sizeof(product)-strlen(product)-1, "%s%s", product[0] ? " " : "", product_attr->value); - if (product[strlen(product)-1] == '\n') - product[strlen(product)-1] = '\0'; - sysfs_close_attribute(product_attr); - } - - if (!product[0]) - strcpy(product, "PCMCIA device"); - - log_message("PCMCIA: device found %s (%s)", product, pcmciadb[i].module); - discovered_device(type, product, pcmciadb[i].module); - } - } - - sysfs_close_attribute(modalias_attr); - } - end_pcmcia_probe:; - if (dir) - closedir(dir); - } + struct sysfs_attribute *modalias_attr; + char keyfile[256]; + int i, id; + + if (dent->d_name[0] == '.') + continue; + + log_message("PCMCIA: device found %s", dent->d_name); + + snprintf(keyfile, sizeof(keyfile)-1, "%s/%s/modalias", base, dent->d_name); + modalias_attr = sysfs_open_attribute(keyfile); + if (!modalias_attr) + continue; + if (sysfs_read_attribute(modalias_attr) != 0 || !modalias_attr->value) { + sysfs_close_attribute(modalias_attr); + continue; + } + + log_message("PCMCIA: device found %s", modalias_attr->value); + + for (i = 0; i < len; i++) { + if (!fnmatch(pcmciadb[i].modalias, modalias_attr->value, 0)) { + char product[256]; + + log_message("PCMCIA: device found %s (%s)", pcmciadb[i].modalias, pcmciadb[i].module); + strcpy(product, ""); + for (id = 1; id <= 4; id++) { + struct sysfs_attribute *product_attr; + snprintf(keyfile, sizeof(keyfile)-1, "%s/%s/prod_id%d", base, dent->d_name, id); + product_attr = sysfs_open_attribute(keyfile); + if (!product_attr) + continue; + if (sysfs_read_attribute(product_attr) || !product_attr->value) { + sysfs_close_attribute(product_attr); + continue; + } + snprintf(product + strlen(product), sizeof(product)-strlen(product)-1, "%s%s", product[0] ? " " : "", product_attr->value); + if (product[strlen(product)-1] == '\n') + product[strlen(product)-1] = '\0'; + sysfs_close_attribute(product_attr); + } + + if (!product[0]) + strcpy(product, "PCMCIA device"); + + log_message("PCMCIA: device found %s (%s)", product, pcmciadb[i].module); + discovered_device(type, product, pcmciadb[i].module); + } + } + + sysfs_close_attribute(modalias_attr); + } + end_pcmcia_probe:; + if (dir) + closedir(dir); + } #endif /* be sure to load usb-storage after media adapters, so that they are in @@ -562,202 +567,202 @@ static struct media_info * medias = NULL; void find_media(enum media_bus bus) { - char b[50]; - char buf[5000]; - struct media_info tmp[50]; - int count = 0; + char b[50]; + char buf[5000]; + struct media_info tmp[50]; + int count = 0; int fd; - if (medias) - free(medias); /* that does not free the strings, by the way */ - - log_message("looking for media adapters"); - probe_that_type(MEDIA_ADAPTERS, bus); - - /* ----------------------------------------------- */ - if (bus != BUS_IDE && bus != BUS_ANY) - goto find_media_after_ide; - log_message("looking for ide media"); - - strcpy(b, "/proc/ide/hd"); - for (b[12] = 'a'; b[12] <= 't'; b[12]++) { - int i; - char ide_disk[] = "disk"; - char ide_cdrom[] = "cdrom"; - char ide_tape[] = "tape"; - char ide_floppy[] = "floppy"; - - /* first, test if file exists (will tell if attached medium exists) */ - b[13] = '\0'; - if (access(b, R_OK)) - continue; - - tmp[count].name = strdup("hda"); - tmp[count].name[2] = b[12]; - - /* media type */ - strcpy(b + 13, "/media"); - fd = open(b, O_RDONLY); - if (fd == -1) { - log_message("failed to open %s for reading", b); - continue; - } - - i = read(fd, buf, sizeof(buf)); - if (i == -1) { - log_message("failed to read %s", b); - continue; - } - buf[i] = '\0'; - close(fd); - - if (ptr_begins_static_str(buf, ide_disk)) - tmp[count].type = DISK; - else if (ptr_begins_static_str(buf, ide_cdrom)) - tmp[count].type = CDROM; - else if (ptr_begins_static_str(buf, ide_tape)) - tmp[count].type = TAPE; - else if (ptr_begins_static_str(buf, ide_floppy)) - tmp[count].type = FLOPPY; - else - tmp[count].type = UNKNOWN_MEDIA; - - /* media model */ - strcpy(b + 13, "/model"); - fd = open(b, O_RDONLY); - if (fd == -1) { - log_message("failed to open %s for reading", b); - continue; - } - - i = read(fd, buf, sizeof(buf)); - if (i <= 0) { - log_message("failed to read %s", b); - tmp[count].model = strdup("(none)"); - } - else { - buf[i-1] = '\0'; /* eat the \n */ - tmp[count].model = strdup(buf); - } - close(fd); - - log_message("IDE/%d: %s is a %s", tmp[count].type, tmp[count].name, tmp[count].model); - count++; - } + if (medias) + free(medias); /* that does not free the strings, by the way */ + + log_message("looking for media adapters"); + probe_that_type(MEDIA_ADAPTERS, bus); + + /* ----------------------------------------------- */ + if (bus != BUS_IDE && bus != BUS_ANY) + goto find_media_after_ide; + log_message("looking for ide media"); + + strcpy(b, "/proc/ide/hd"); + for (b[12] = 'a'; b[12] <= 't'; b[12]++) { + int i; + char ide_disk[] = "disk"; + char ide_cdrom[] = "cdrom"; + char ide_tape[] = "tape"; + char ide_floppy[] = "floppy"; + + /* first, test if file exists (will tell if attached medium exists) */ + b[13] = '\0'; + if (access(b, R_OK)) + continue; + + tmp[count].name = strdup("hda"); + tmp[count].name[2] = b[12]; + + /* media type */ + strcpy(b + 13, "/media"); + fd = open(b, O_RDONLY); + if (fd == -1) { + log_message("failed to open %s for reading", b); + continue; + } + + i = read(fd, buf, sizeof(buf)); + if (i == -1) { + log_message("failed to read %s", b); + continue; + } + buf[i] = '\0'; + close(fd); + + if (ptr_begins_static_str(buf, ide_disk)) + tmp[count].type = DISK; + else if (ptr_begins_static_str(buf, ide_cdrom)) + tmp[count].type = CDROM; + else if (ptr_begins_static_str(buf, ide_tape)) + tmp[count].type = TAPE; + else if (ptr_begins_static_str(buf, ide_floppy)) + tmp[count].type = FLOPPY; + else + tmp[count].type = UNKNOWN_MEDIA; + + /* media model */ + strcpy(b + 13, "/model"); + fd = open(b, O_RDONLY); + if (fd == -1) { + log_message("failed to open %s for reading", b); + continue; + } + + i = read(fd, buf, sizeof(buf)); + if (i <= 0) { + log_message("failed to read %s", b); + tmp[count].model = strdup("(none)"); + } + else { + buf[i-1] = '\0'; /* eat the \n */ + tmp[count].model = strdup(buf); + } + close(fd); + + log_message("IDE/%d: %s is a %s", tmp[count].type, tmp[count].name, tmp[count].model); + count++; + } find_media_after_ide: - /* ----------------------------------------------- */ - if (bus != BUS_SCSI && bus != BUS_USB && bus != BUS_PCMCIA && bus != BUS_ANY) - goto find_media_after_scsi; - log_message("looking for scsi media"); + /* ----------------------------------------------- */ + if (bus != BUS_SCSI && bus != BUS_USB && bus != BUS_PCMCIA && bus != BUS_ANY) + goto find_media_after_scsi; + log_message("looking for scsi media"); - fd = open("/proc/scsi/scsi", O_RDONLY); - if (fd != -1) { + fd = open("/proc/scsi/scsi", O_RDONLY); + if (fd != -1) { FILE * f; - enum { SCSI_TOP, SCSI_HOST, SCSI_VENDOR, SCSI_TYPE } state = SCSI_TOP; - char * start, * chptr, * next, * end; - char scsi_disk_count = 'a'; - char scsi_cdrom_count = '0'; - char scsi_tape_count = '0'; - - char scsi_no_devices[] = "Attached devices: none"; - char scsi_some_devices[] = "Attached devices:"; - char scsi_host[] = "Host: "; - char scsi_vendor[] = " Vendor: "; - - int i = read(fd, &buf, sizeof(buf)-1); - if (i < 1) { - close(fd); - goto end_scsi; - } - close(fd); - buf[i] = '\0'; - - if (ptr_begins_static_str(buf, scsi_no_devices)) - goto end_scsi; - - start = buf; - while (*start) { - char tmp_model[50]; - char tmp_name[10]; - - chptr = start; - while (*chptr != '\n') chptr++; - *chptr = '\0'; - next = chptr + 1; - - switch (state) { - case SCSI_TOP: - if (!ptr_begins_static_str(start, scsi_some_devices)) - goto end_scsi; - state = SCSI_HOST; - break; - - case SCSI_HOST: - if (!ptr_begins_static_str(start, scsi_host)) - goto end_scsi; - state = SCSI_VENDOR; - break; - - case SCSI_VENDOR: - if (!ptr_begins_static_str(start, scsi_vendor)) - goto end_scsi; - - /* (1) Grab Vendor info */ - start += 10; - end = chptr = strstr(start, "Model:"); - if (!chptr) - goto end_scsi; - - chptr--; - while (*chptr == ' ') - chptr--; - if (*chptr == ':') { - chptr++; - *(chptr + 1) = '\0'; - strcpy(tmp_model,"(unknown)"); - } else { - *(chptr + 1) = '\0'; - strcpy(tmp_model, start); - } - - /* (2) Grab Model info */ - start = end; - start += 7; - - chptr = strstr(start, "Rev:"); - if (!chptr) - goto end_scsi; - - chptr--; - while (*chptr == ' ') chptr--; - *(chptr + 1) = '\0'; - - strcat(tmp_model, " "); - strcat(tmp_model, start); - - tmp[count].model = strdup(tmp_model); - - state = SCSI_TYPE; - - break; - - case SCSI_TYPE: - if (strncmp(" Type:", start, 7)) - goto end_scsi; - *tmp_name = '\0'; - - if (strstr(start, "Direct-Access")) { - sprintf(tmp_name, "sd%c", scsi_disk_count++); - tmp[count].type = DISK; - } else if (strstr(start, "Sequential-Access")) { - sprintf(tmp_name, "st%c", scsi_tape_count++); - tmp[count].type = TAPE; - } else if (strstr(start, "CD-ROM")) { - sprintf(tmp_name, "sr%c", scsi_cdrom_count++); - tmp[count].type = CDROM; - } + enum { SCSI_TOP, SCSI_HOST, SCSI_VENDOR, SCSI_TYPE } state = SCSI_TOP; + char * start, * chptr, * next, * end; + char scsi_disk_count = 'a'; + char scsi_cdrom_count = '0'; + char scsi_tape_count = '0'; + + char scsi_no_devices[] = "Attached devices: none"; + char scsi_some_devices[] = "Attached devices:"; + char scsi_host[] = "Host: "; + char scsi_vendor[] = " Vendor: "; + + int i = read(fd, &buf, sizeof(buf)-1); + if (i < 1) { + close(fd); + goto end_scsi; + } + close(fd); + buf[i] = '\0'; + + if (ptr_begins_static_str(buf, scsi_no_devices)) + goto end_scsi; + + start = buf; + while (*start) { + char tmp_model[50]; + char tmp_name[10]; + + chptr = start; + while (*chptr != '\n') chptr++; + *chptr = '\0'; + next = chptr + 1; + + switch (state) { + case SCSI_TOP: + if (!ptr_begins_static_str(start, scsi_some_devices)) + goto end_scsi; + state = SCSI_HOST; + break; + + case SCSI_HOST: + if (!ptr_begins_static_str(start, scsi_host)) + goto end_scsi; + state = SCSI_VENDOR; + break; + + case SCSI_VENDOR: + if (!ptr_begins_static_str(start, scsi_vendor)) + goto end_scsi; + + /* (1) Grab Vendor info */ + start += 10; + end = chptr = strstr(start, "Model:"); + if (!chptr) + goto end_scsi; + + chptr--; + while (*chptr == ' ') + chptr--; + if (*chptr == ':') { + chptr++; + *(chptr + 1) = '\0'; + strcpy(tmp_model,"(unknown)"); + } else { + *(chptr + 1) = '\0'; + strcpy(tmp_model, start); + } + + /* (2) Grab Model info */ + start = end; + start += 7; + + chptr = strstr(start, "Rev:"); + if (!chptr) + goto end_scsi; + + chptr--; + while (*chptr == ' ') chptr--; + *(chptr + 1) = '\0'; + + strcat(tmp_model, " "); + strcat(tmp_model, start); + + tmp[count].model = strdup(tmp_model); + + state = SCSI_TYPE; + + break; + + case SCSI_TYPE: + if (strncmp(" Type:", start, 7)) + goto end_scsi; + *tmp_name = '\0'; + + if (strstr(start, "Direct-Access")) { + sprintf(tmp_name, "sd%c", scsi_disk_count++); + tmp[count].type = DISK; + } else if (strstr(start, "Sequential-Access")) { + sprintf(tmp_name, "st%c", scsi_tape_count++); + tmp[count].type = TAPE; + } else if (strstr(start, "CD-ROM")) { + sprintf(tmp_name, "sr%c", scsi_cdrom_count++); + tmp[count].type = CDROM; + } if (!(f = fopen("/proc/partitions", "rb")) || !fgets(buf, sizeof(buf), f) || !fgets(buf, sizeof(buf), f)) { log_message("Couldn't open /proc/partitions"); @@ -778,7 +783,7 @@ void find_media(enum media_bus bus) if (stat(name, &statbuf)) mkdir(name, 0755); *ptr = '/'; - } + } if (stat(name, &statbuf) && mknod(name, S_IFBLK | 0600, makedev(major, minor))) { log_perror(name); } @@ -786,219 +791,219 @@ void find_media(enum media_bus bus) fclose(f); } - if (*tmp_name) { - tmp[count].name = strdup(tmp_name); - log_message("SCSI/%d: %s is a %s", tmp[count].type, tmp[count].name, tmp[count].model); - count++; - } - - state = SCSI_HOST; - } - - start = next; - } - - end_scsi:; - } - - /* ----------------------------------------------- */ - log_message("looking for Compaq Smart Array media"); - { - char * procfiles[] = { "/proc/driver/cpqarray/ida0", "/proc/driver/cciss/cciss0", // 2.4 style - "/proc/array/ida", "/proc/cciss/cciss", // 2.2 style - NULL }; - static char cpq_descr[] = "Compaq RAID logical disk"; - char ** procfile; - FILE * f; - - for (procfile = procfiles; procfile && *procfile; procfile++) { - if((f = fopen(*procfile, "rb"))) { - while (fgets(buf, sizeof(buf), f)) { - if (ptr_begins_static_str(buf, "ida/") || ptr_begins_static_str(buf, "cciss/")) { - char * end = strchr(buf, ':'); - if (!end) - log_message("Inconsistency in %s, line:\n%s", *procfile, buf); - else { - *end = '\0'; - tmp[count].name = strdup(buf); - tmp[count].type = DISK; - tmp[count].model = cpq_descr; - log_message("CPQ: found %s", tmp[count].name); - count++; - } - } - } - fclose(f); - } - } - } - - /* ----------------------------------------------- */ - log_message("looking for DAC960"); - { - FILE * f; - if ((f = fopen("/tmp/syslog", "rb"))) { - while (fgets(buf, sizeof(buf), f)) { - char * start; - if ((start = strstr(buf, "/dev/rd/"))) { - char * end = strchr(start, ':'); - if (!end) - log_message("Inconsistency in syslog, line:\n%s", buf); - else { - *end = '\0'; - tmp[count].name = strdup(start+5); - tmp[count].type = DISK; - start = end + 2; - end = strchr(start, ','); - if (end) { - *end = '\0'; - tmp[count].model = strdup(start); - } else - tmp[count].model = "(unknown)"; - log_message("DAC960: found %s (%s)", tmp[count].name, tmp[count].model); - count++; - } - } - } - fclose(f); - } - } - /* ----------------------------------------------- */ - log_message("looking for VirtIO"); - { - int fd, i; - char b[50]; - char *name = b+11; - strcpy(b, "/sys/block/vd"); - for (b[13] = 'a'; b[13] <= 'c'; b[13]++) { - /* first, test if file exists (will tell if attached medium exists) */ - b[14] = '\0'; - if (access(b, R_OK)) - continue; - - tmp[count].name = strdup(name); - tmp[count].type = DISK; //UNKNOWN_MEDIA; - tmp[count].model = strdup("VirtIO disk"); - - /* media type */ - strcpy(b + 14, "/capability"); - fd = open(b, O_RDONLY); - if (fd == -1) { - log_message("failed to open %s for reading", b); - //continue; - } - i = read(fd, buf, sizeof(buf)); - if (i == -1) { - log_message("Couldn't read capabilities file (%s)", b); - } else { - if (!strcmp(buf, "10")) - tmp[count].type = DISK; - } - - count++; - } - } + if (*tmp_name) { + tmp[count].name = strdup(tmp_name); + log_message("SCSI/%d: %s is a %s", tmp[count].type, tmp[count].name, tmp[count].model); + count++; + } + + state = SCSI_HOST; + } + + start = next; + } + + end_scsi:; + } + + /* ----------------------------------------------- */ + log_message("looking for Compaq Smart Array media"); + { + char * procfiles[] = { "/proc/driver/cpqarray/ida0", "/proc/driver/cciss/cciss0", // 2.4 style + "/proc/array/ida", "/proc/cciss/cciss", // 2.2 style + NULL }; + static char cpq_descr[] = "Compaq RAID logical disk"; + char ** procfile; + FILE * f; + + for (procfile = procfiles; procfile && *procfile; procfile++) { + if((f = fopen(*procfile, "rb"))) { + while (fgets(buf, sizeof(buf), f)) { + if (ptr_begins_static_str(buf, "ida/") || ptr_begins_static_str(buf, "cciss/")) { + char * end = strchr(buf, ':'); + if (!end) + log_message("Inconsistency in %s, line:\n%s", *procfile, buf); + else { + *end = '\0'; + tmp[count].name = strdup(buf); + tmp[count].type = DISK; + tmp[count].model = cpq_descr; + log_message("CPQ: found %s", tmp[count].name); + count++; + } + } + } + fclose(f); + } + } + } + + /* ----------------------------------------------- */ + log_message("looking for DAC960"); + { + FILE * f; + if ((f = fopen("/tmp/syslog", "rb"))) { + while (fgets(buf, sizeof(buf), f)) { + char * start; + if ((start = strstr(buf, "/dev/rd/"))) { + char * end = strchr(start, ':'); + if (!end) + log_message("Inconsistency in syslog, line:\n%s", buf); + else { + *end = '\0'; + tmp[count].name = strdup(start+5); + tmp[count].type = DISK; + start = end + 2; + end = strchr(start, ','); + if (end) { + *end = '\0'; + tmp[count].model = strdup(start); + } else + tmp[count].model = "(unknown)"; + log_message("DAC960: found %s (%s)", tmp[count].name, tmp[count].model); + count++; + } + } + } + fclose(f); + } + } + /* ----------------------------------------------- */ + log_message("looking for VirtIO"); + { + int fd, i; + char b[50]; + char *name = b+11; + strcpy(b, "/sys/block/vd"); + for (b[13] = 'a'; b[13] <= 'c'; b[13]++) { + /* first, test if file exists (will tell if attached medium exists) */ + b[14] = '\0'; + if (access(b, R_OK)) + continue; + + tmp[count].name = strdup(name); + tmp[count].type = DISK; //UNKNOWN_MEDIA; + tmp[count].model = strdup("VirtIO disk"); + + /* media type */ + strcpy(b + 14, "/capability"); + fd = open(b, O_RDONLY); + if (fd == -1) { + log_message("failed to open %s for reading", b); + //continue; + } + i = read(fd, buf, sizeof(buf)); + if (i == -1) { + log_message("Couldn't read capabilities file (%s)", b); + } else { + if (!strcmp(buf, "10")) + tmp[count].type = DISK; + } + + count++; + } + } find_media_after_scsi: - /* ----------------------------------------------- */ - tmp[count].name = NULL; - count++; + /* ----------------------------------------------- */ + tmp[count].name = NULL; + count++; - medias = _memdup(tmp, sizeof(struct media_info) * count); + medias = _memdup(tmp, sizeof(struct media_info) * count); } /* Finds by media */ void get_medias(enum media_type media, char *** names, char *** models, enum media_bus bus) { - struct media_info * m; - char * tmp_names[50]; - char * tmp_models[50]; - int count; - - find_media(bus); - - m = medias; - - count = 0; - while (m && m->name) { - if (m->type == media) { - tmp_names[count] = strdup(m->name); - tmp_models[count++] = strdup(m->model); - } - m++; - } - tmp_names[count] = NULL; - tmp_models[count++] = NULL; - - *names = _memdup(tmp_names, sizeof(char *) * count); - *models = _memdup(tmp_models, sizeof(char *) * count); + struct media_info * m; + char * tmp_names[50]; + char * tmp_models[50]; + int count; + + find_media(bus); + + m = medias; + + count = 0; + while (m && m->name) { + if (m->type == media) { + tmp_names[count] = strdup(m->name); + tmp_models[count++] = strdup(m->model); + } + m++; + } + tmp_names[count] = NULL; + tmp_models[count++] = NULL; + + *names = _memdup(tmp_names, sizeof(char *) * count); + *models = _memdup(tmp_models, sizeof(char *) * count); } #ifndef DISABLE_NETWORK static int is_net_interface_blacklisted(char *intf) { - /* see detect_devicess::is_lan_interface() */ - char * blacklist[] = { "lo", "ippp", "isdn", "plip", "ppp", "wifi", "sit", NULL }; - char ** ptr = blacklist; + /* see detect_devicess::is_lan_interface() */ + char * blacklist[] = { "lo", "ippp", "isdn", "plip", "ppp", "wifi", "sit", NULL }; + char ** ptr = blacklist; - while (ptr && *ptr) { - if (!strncmp(intf, *ptr, strlen(*ptr))) - return 1; - ptr++; - } + while (ptr && *ptr) { + if (!strncmp(intf, *ptr, strlen(*ptr))) + return 1; + ptr++; + } - return 0; + return 0; } char ** get_net_devices(void) { - char * tmp[50]; - static int already_probed = 0; - FILE * f; - int i = 0; - - if (!already_probed) { - already_probed = 1; /* cut off loop brought by: probe_that_type => my_insmod => get_net_devices */ - probe_that_type(NETWORK_DEVICES, BUS_ANY); - } - - /* use /proc/net/dev since SIOCGIFCONF doesn't work with some drivers (rt2500) */ - f = fopen("/proc/net/dev", "rb"); - if (f) { - char line[128]; - - /* skip the two first lines */ - fgets(line, sizeof(line), f); - fgets(line, sizeof(line), f); - - while (1) { - char *start, *end; - if (!fgets(line, sizeof(line), f)) - break; - start = line; - while (*start == ' ') - start++; - end = strchr(start, ':'); - if (end) - end[0] = '\0'; - if (!is_net_interface_blacklisted(start)) { - log_message("found net interface %s", start); - tmp[i++] = strdup(start); - } else { - log_message("found net interface %s, but blacklisted", start); - } - } - - fclose(f); - } else { - log_message("net: could not open devices file"); - } - - tmp[i++] = NULL; - - return _memdup(tmp, sizeof(char *) * i); + char * tmp[50]; + static int already_probed = 0; + FILE * f; + int i = 0; + + if (!already_probed) { + already_probed = 1; /* cut off loop brought by: probe_that_type => my_insmod => get_net_devices */ + probe_that_type(NETWORK_DEVICES, BUS_ANY); + } + + /* use /proc/net/dev since SIOCGIFCONF doesn't work with some drivers (rt2500) */ + f = fopen("/proc/net/dev", "rb"); + if (f) { + char line[128]; + + /* skip the two first lines */ + fgets(line, sizeof(line), f); + fgets(line, sizeof(line), f); + + while (1) { + char *start, *end; + if (!fgets(line, sizeof(line), f)) + break; + start = line; + while (*start == ' ') + start++; + end = strchr(start, ':'); + if (end) + end[0] = '\0'; + if (!is_net_interface_blacklisted(start)) { + log_message("found net interface %s", start); + tmp[i++] = strdup(start); + } else { + log_message("found net interface %s, but blacklisted", start); + } + } + + fclose(f); + } else { + log_message("net: could not open devices file"); + } + + tmp[i++] = NULL; + + return _memdup(tmp, sizeof(char *) * i); } #endif /* DISABLE_NETWORK */ diff --git a/mdk-stage1/rescue-gui.c b/mdk-stage1/rescue-gui.c index 5a7e10de2..a93a6c14d 100644 --- a/mdk-stage1/rescue-gui.c +++ b/mdk-stage1/rescue-gui.c @@ -35,13 +35,13 @@ #include <sys/syscall.h> -#define LINUX_REBOOT_MAGIC1 0xfee1dead -#define LINUX_REBOOT_MAGIC2 672274793 -#define BMAGIC_REBOOT 0x01234567 +#define LINUX_REBOOT_MAGIC1 0xfee1dead +#define LINUX_REBOOT_MAGIC2 672274793 +#define BMAGIC_REBOOT 0x01234567 static inline long reboot(void) { - return (long) syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, BMAGIC_REBOOT, 0); + return (long) syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, BMAGIC_REBOOT, 0); } #if defined(__i386__) || defined(__x86_64__) @@ -49,16 +49,16 @@ static inline long reboot(void) #endif char * env[] = { - "PATH=/usr/bin:/bin:/sbin:/usr/sbin:/mnt/sbin:/mnt/usr/sbin:/mnt/bin:/mnt/usr/bin", - "LD_LIBRARY_PATH=/lib:/usr/lib:/mnt/lib:/mnt/usr/lib:/usr/X11R6/lib:/mnt/usr/X11R6/lib" + "PATH=/usr/bin:/bin:/sbin:/usr/sbin:/mnt/sbin:/mnt/usr/sbin:/mnt/bin:/mnt/usr/bin", + "LD_LIBRARY_PATH=/lib:/usr/lib:/mnt/lib:/mnt/usr/lib:/usr/X11R6/lib:/mnt/usr/X11R6/lib" #if defined(__x86_64__) || defined(__ppc64__) - ":/lib64:/usr/lib64:/usr/X11R6/lib64:/mnt/lib64:/mnt/usr/lib64:/mnt/usr/X11R6/lib64" + ":/lib64:/usr/lib64:/usr/X11R6/lib64:/mnt/lib64:/mnt/usr/lib64:/mnt/usr/X11R6/lib64" #endif - , - "HOME=/", - "TERM=linux", - "TERMINFO=/etc/terminfo", - NULL + , + "HOME=/", + "TERM=screen", + "TERMINFO=/etc/terminfo", + NULL }; /* pause() already exists and causes the invoking process to sleep @@ -73,96 +73,96 @@ static void PAUSE(void) { /* ------ UUURGH this is duplicated from `init.c', don't edit here........ */ void fatal_error(char *msg) { - printf("FATAL ERROR IN RESCUE: %s\n\nI can't recover from this.\nYou may reboot your system.\n", msg); - while (1); + printf("FATAL ERROR IN RESCUE: %s\n\nI can't recover from this.\nYou may reboot your system.\n", msg); + while (1); } -#define LOOP_CLR_FD 0x4C01 +#define LOOP_CLR_FD 0x4C01 void del_loop(char *device) { - int fd; - if ((fd = open(device, O_RDONLY, 0)) < 0) { - printf("del_loop open failed\n"); - return; - } - - if (ioctl(fd, LOOP_CLR_FD, 0) < 0) { - printf("del_loop ioctl failed"); - return; - } - - close(fd); + int fd; + if ((fd = open(device, O_RDONLY, 0)) < 0) { + printf("del_loop open failed\n"); + return; + } + + if (ioctl(fd, LOOP_CLR_FD, 0) < 0) { + printf("del_loop ioctl failed"); + return; + } + + close(fd); } struct filesystem { char * dev; char * name; char * fs; int mounted; }; void unmount_filesystems(void) { - int fd, size; - char buf[65535]; /* this should be big enough */ - char *p; - struct filesystem fs[500]; - int numfs = 0; - int i, nb; - - printf("unmounting filesystems...\n"); - - fd = open("/proc/mounts", O_RDONLY, 0); - if (fd < 1) { - printf("ERROR: failed to open /proc/mounts"); - sleep(2); - return; - } - - size = read(fd, buf, sizeof(buf) - 1); - buf[size] = '\0'; - - close(fd); - - p = buf; - while (*p) { - fs[numfs].mounted = 1; - fs[numfs].dev = p; - while (*p != ' ') p++; - *p++ = '\0'; - fs[numfs].name = p; - while (*p != ' ') p++; - *p++ = '\0'; - fs[numfs].fs = p; - while (*p != ' ') p++; - *p++ = '\0'; - while (*p != '\n') p++; - p++; - if (strcmp(fs[numfs].name, "/") != 0) numfs++; /* skip if root, no need to take initrd root in account */ - } - - /* Pixel's ultra-optimized sorting algorithm: - multiple passes trying to umount everything until nothing moves - anymore (a.k.a holy shotgun method) */ - do { - nb = 0; - for (i = 0; i < numfs; i++) { - /*printf("trying with %s\n", fs[i].name);*/ - if (fs[i].mounted && umount(fs[i].name) == 0) { - if (strncmp(fs[i].dev + sizeof("/dev/") - 1, "loop", - sizeof("loop") - 1) == 0) - del_loop(fs[i].dev); - - printf("\t%s\n", fs[i].name); - fs[i].mounted = 0; - nb++; - } - } - } while (nb); - - for (i = nb = 0; i < numfs; i++) - if (fs[i].mounted) { - printf("\t%s umount failed\n", fs[i].name); - if (strcmp(fs[i].fs, "ext2") == 0) nb++; /* don't count not-ext2 umount failed */ - } - - if (nb) { - printf("failed to umount some filesystems\n"); - while (1); - } + int fd, size; + char buf[65535]; /* this should be big enough */ + char *p; + struct filesystem fs[500]; + int numfs = 0; + int i, nb; + + printf("unmounting filesystems...\n"); + + fd = open("/proc/mounts", O_RDONLY, 0); + if (fd < 1) { + printf("ERROR: failed to open /proc/mounts"); + sleep(2); + return; + } + + size = read(fd, buf, sizeof(buf) - 1); + buf[size] = '\0'; + + close(fd); + + p = buf; + while (*p) { + fs[numfs].mounted = 1; + fs[numfs].dev = p; + while (*p != ' ') p++; + *p++ = '\0'; + fs[numfs].name = p; + while (*p != ' ') p++; + *p++ = '\0'; + fs[numfs].fs = p; + while (*p != ' ') p++; + *p++ = '\0'; + while (*p != '\n') p++; + p++; + if (strcmp(fs[numfs].name, "/") != 0) numfs++; /* skip if root, no need to take initrd root in account */ + } + + /* Pixel's ultra-optimized sorting algorithm: + multiple passes trying to umount everything until nothing moves + anymore (a.k.a holy shotgun method) */ + do { + nb = 0; + for (i = 0; i < numfs; i++) { + /*printf("trying with %s\n", fs[i].name);*/ + if (fs[i].mounted && umount(fs[i].name) == 0) { + if (strncmp(fs[i].dev + sizeof("/dev/") - 1, "loop", + sizeof("loop") - 1) == 0) + del_loop(fs[i].dev); + + printf("\t%s\n", fs[i].name); + fs[i].mounted = 0; + nb++; + } + } + } while (nb); + + for (i = nb = 0; i < numfs; i++) + if (fs[i].mounted) { + printf("\t%s umount failed\n", fs[i].name); + if (strcmp(fs[i].fs, "ext2") == 0) nb++; /* don't count not-ext2 umount failed */ + } + + if (nb) { + printf("failed to umount some filesystems\n"); + while (1); + } } /* ------ UUURGH -- end */ @@ -174,132 +174,132 @@ void exit_bootsplash(void) {} int main(int argc __attribute__ ((unused)), char **argv __attribute__ ((unused))) { - enum return_type results; + enum return_type results; - char install_bootloader[] = "Re-install Boot Loader"; + char install_bootloader[] = "Re-install Boot Loader"; #if ENABLE_RESCUE_MS_BOOT - char restore_ms_boot[] = "Restore Windows Boot Loader"; + char restore_ms_boot[] = "Restore Windows Boot Loader"; #endif - char mount_parts[] = "Mount your partitions under /mnt"; - char go_to_console[] = "Go to console"; - char reboot_[] = "Reboot"; - char doc[] = "Doc: what's addressed by this Rescue?"; - - char upgrade[] = "Upgrade to New Version"; - char rootpass[] = "Reset Root Password"; - char userpass[] = "Reset User Password"; - char factory[] = "Reset to Factory Defaults"; - char backup[] = "Backup User Files"; - char restore[] = "Restore User Files from Backup"; - char badblocks[] = "Test Key for Badblocks"; - - char * actions_default[] = { install_bootloader, + char mount_parts[] = "Mount your partitions under /mnt"; + char go_to_console[] = "Go to console"; + char reboot_[] = "Reboot"; + char doc[] = "Doc: what's addressed by this Rescue?"; + + char upgrade[] = "Upgrade to New Version"; + char rootpass[] = "Reset Root Password"; + char userpass[] = "Reset User Password"; + char factory[] = "Reset to Factory Defaults"; + char backup[] = "Backup User Files"; + char restore[] = "Restore User Files from Backup"; + char badblocks[] = "Test Key for Badblocks"; + + char * actions_default[] = { install_bootloader, #if ENABLE_RESCUE_MS_BOOT - restore_ms_boot, + restore_ms_boot, #endif - mount_parts, go_to_console, reboot_, doc, NULL }; - char * actions_flash_rescue[] = { rootpass, userpass, factory, backup, restore, - badblocks, go_to_console, reboot_, NULL }; - char * actions_flash_upgrade[] = { upgrade, go_to_console, reboot_, NULL }; + mount_parts, go_to_console, reboot_, doc, NULL }; + char * actions_flash_rescue[] = { rootpass, userpass, factory, backup, restore, + badblocks, go_to_console, reboot_, NULL }; + char * actions_flash_upgrade[] = { upgrade, go_to_console, reboot_, NULL }; - char * flash_mode; - char ** actions; - char * choice; + char * flash_mode; + char ** actions; + char * choice; - process_cmdline(); - flash_mode = get_param_valued("flash"); - actions = !flash_mode ? - actions_default : - streq(flash_mode, "upgrade") ? actions_flash_upgrade : actions_flash_rescue; + process_cmdline(); + flash_mode = get_param_valued("flash"); + actions = !flash_mode ? + actions_default : + streq(flash_mode, "upgrade") ? actions_flash_upgrade : actions_flash_rescue; - init_frontend("Welcome to " DISTRIB_NAME " Rescue (" DISTRIB_VERSION ") " __DATE__ " " __TIME__); + init_frontend("Welcome to " DISTRIB_NAME " Rescue (" DISTRIB_VERSION ") " __DATE__ " " __TIME__); - do { - int pid; - char * binary = NULL; + do { + int pid; + char * binary = NULL; - choice = ""; - results = ask_from_list("Please choose the desired action.", actions, &choice); + choice = ""; + results = ask_from_list("Please choose the desired action.", actions, &choice); - if (ptr_begins_static_str(choice, install_bootloader)) { - binary = "/usr/bin/install_bootloader"; - } + if (ptr_begins_static_str(choice, install_bootloader)) { + binary = "/usr/bin/install_bootloader"; + } #if ENABLE_RESCUE_MS_BOOT - if (ptr_begins_static_str(choice, restore_ms_boot)) { - binary = "/usr/bin/restore_ms_boot"; - } + if (ptr_begins_static_str(choice, restore_ms_boot)) { + binary = "/usr/bin/restore_ms_boot"; + } #endif - if (ptr_begins_static_str(choice, mount_parts)) { - binary = "/usr/bin/guessmounts"; - } - if (ptr_begins_static_str(choice, reboot_)) { - finish_frontend(); + if (ptr_begins_static_str(choice, mount_parts)) { + binary = "/usr/bin/guessmounts"; + } + if (ptr_begins_static_str(choice, reboot_)) { + finish_frontend(); sync(); sync(); sleep(2); - unmount_filesystems(); + unmount_filesystems(); sync(); sync(); - printf("rebooting system\n"); - sleep(2); - reboot(); - } - if (ptr_begins_static_str(choice, doc)) { - binary = "/usr/bin/rescue-doc"; - } - - /* Mandriva Flash entries */ - if (ptr_begins_static_str(choice, rootpass)) { - binary = "/usr/bin/reset_rootpass"; - } - if (ptr_begins_static_str(choice, userpass)) { - binary = "/usr/bin/reset_userpass"; - } - if (ptr_begins_static_str(choice, factory)) { - binary = "/usr/bin/clear_systemloop"; - } - if (ptr_begins_static_str(choice, backup)) { - binary = "/usr/bin/backup_systemloop"; - } - if (ptr_begins_static_str(choice, restore)) { - binary = "/usr/bin/restore_systemloop"; - } - if (ptr_begins_static_str(choice, badblocks)) { - binary = "/usr/bin/test_badblocks"; - } - if (ptr_begins_static_str(choice, upgrade)) { - binary = "/usr/bin/upgrade"; - } - - if (binary) { - int wait_status; - suspend_to_console(); - if (!(pid = fork())) { - - char * child_argv[2]; - child_argv[0] = binary; - child_argv[1] = NULL; - - execve(child_argv[0], child_argv, env); - printf("Can't execute binary (%s)\n<press Enter>\n", binary); - PAUSE(); - - return 33; - } - while (wait4(-1, &wait_status, 0, NULL) != pid) {}; - printf("<press Enter to return to Rescue menu>"); - PAUSE(); - resume_from_suspend(); - if (!WIFEXITED(wait_status) || WEXITSTATUS(wait_status) != 0) { - error_message("Program exited abnormally (return code %d).", WEXITSTATUS(wait_status)); - if (WIFSIGNALED(wait_status)) - error_message("(received signal %d)", WTERMSIG(wait_status)); - } - } - - } while (results == RETURN_OK && !ptr_begins_static_str(choice, go_to_console)); - - finish_frontend(); - printf("Bye.\n"); - - return 0; + printf("rebooting system\n"); + sleep(2); + reboot(); + } + if (ptr_begins_static_str(choice, doc)) { + binary = "/usr/bin/rescue-doc"; + } + + /* Mandriva Flash entries */ + if (ptr_begins_static_str(choice, rootpass)) { + binary = "/usr/bin/reset_rootpass"; + } + if (ptr_begins_static_str(choice, userpass)) { + binary = "/usr/bin/reset_userpass"; + } + if (ptr_begins_static_str(choice, factory)) { + binary = "/usr/bin/clear_systemloop"; + } + if (ptr_begins_static_str(choice, backup)) { + binary = "/usr/bin/backup_systemloop"; + } + if (ptr_begins_static_str(choice, restore)) { + binary = "/usr/bin/restore_systemloop"; + } + if (ptr_begins_static_str(choice, badblocks)) { + binary = "/usr/bin/test_badblocks"; + } + if (ptr_begins_static_str(choice, upgrade)) { + binary = "/usr/bin/upgrade"; + } + + if (binary) { + int wait_status; + suspend_to_console(); + if (!(pid = fork())) { + + char * child_argv[2]; + child_argv[0] = binary; + child_argv[1] = NULL; + + execve(child_argv[0], child_argv, env); + printf("Can't execute binary (%s)\n<press Enter>\n", binary); + PAUSE(); + + return 33; + } + while (wait4(-1, &wait_status, 0, NULL) != pid) {}; + printf("<press Enter to return to Rescue menu>"); + PAUSE(); + resume_from_suspend(); + if (!WIFEXITED(wait_status) || WEXITSTATUS(wait_status) != 0) { + error_message("Program exited abnormally (return code %d).", WEXITSTATUS(wait_status)); + if (WIFSIGNALED(wait_status)) + error_message("(received signal %d)", WTERMSIG(wait_status)); + } + } + + } while (results == RETURN_OK && !ptr_begins_static_str(choice, go_to_console)); + + finish_frontend(); + printf("Bye.\n"); + + return 0; } diff --git a/mdk-stage1/stage1.c b/mdk-stage1/stage1.c index be9b08301..1a9a9d623 100644 --- a/mdk-stage1/stage1.c +++ b/mdk-stage1/stage1.c @@ -72,8 +72,8 @@ void fatal_error(char *msg) { - printf("FATAL ERROR IN STAGE1: %s\n\nI can't recover from this.\nYou may reboot your system.\n", msg); - while (1); + printf("FATAL ERROR IN STAGE1: %s\n\nI can't recover from this.\nYou may reboot your system.\n", msg); + while (1); } @@ -83,33 +83,33 @@ void fatal_error(char *msg) void stg1_error_message(char *msg, ...) { - va_list args; - va_start(args, msg); - unset_automatic(); - verror_message(msg, args); - va_end(args); + va_list args; + va_start(args, msg); + unset_automatic(); + verror_message(msg, args); + va_end(args); } void stg1_fatal_message(char *msg, ...) { - va_list args; - va_start(args, msg); - unset_automatic(); - verror_message(msg, args); - va_end(args); + va_list args; + va_start(args, msg); + unset_automatic(); + verror_message(msg, args); + va_end(args); exit(1); } void stg1_info_message(char *msg, ...) { - va_list args; - va_start(args, msg); - if (IS_AUTOMATIC) { - vlog_message(msg, args); - return; - } - vinfo_message(msg, args); - va_end(args); + va_list args; + va_start(args, msg); + if (IS_AUTOMATIC) { + vlog_message(msg, args); + return; + } + vinfo_message(msg, args); + va_end(args); } @@ -120,39 +120,39 @@ static pid_t shell_pid = 0; * spawns a shell on console #2 */ static void spawn_shell(void) { - int fd; - char * shell_name[] = { "/sbin/sh", NULL }; - - log_message("spawning a shell"); - - if (!IS_TESTING) { - fd = open("/dev/tty2", O_RDWR); - if (fd == -1) { - log_message("cannot open /dev/tty2 -- no shell will be provided"); - return; - } - else if (access(shell_name[0], X_OK)) { - log_message("cannot open shell - %s doesn't exist", shell_name[0]); - return; - } - - if (!(shell_pid = fork())) { - dup2(fd, 0); - dup2(fd, 1); - dup2(fd, 2); - - close(fd); - setsid(); - if (ioctl(0, TIOCSCTTY, NULL)) - log_perror("could not set new controlling tty"); - - execv(shell_name[0], shell_name); - log_message("execve of %s failed: %s", shell_name[0], strerror(errno)); - exit(-1); - } - - close(fd); - } + int fd; + char * shell_name[] = { "/sbin/sh", NULL }; + + log_message("spawning a shell"); + + if (!IS_TESTING) { + fd = open("/dev/tty2", O_RDWR); + if (fd == -1) { + log_message("cannot open /dev/tty2 -- no shell will be provided"); + return; + } + else if (access(shell_name[0], X_OK)) { + log_message("cannot open shell - %s doesn't exist", shell_name[0]); + return; + } + + if (!(shell_pid = fork())) { + dup2(fd, 0); + dup2(fd, 1); + dup2(fd, 2); + + close(fd); + setsid(); + if (ioctl(0, TIOCSCTTY, NULL)) + log_perror("could not set new controlling tty"); + + execv(shell_name[0], shell_name); + log_message("execve of %s failed: %s", shell_name[0], strerror(errno)); + exit(-1); + } + + close(fd); + } } #endif @@ -163,54 +163,54 @@ static pid_t interactive_pid = 0; /* spawns my small interactive on console #6 */ static void spawn_interactive(void) { - int fd; - char * dev = "/dev/tty6"; - - printf("spawning my interactive on %s\n", dev); - - if (!IS_TESTING) { - fd = open(dev, O_RDWR); - if (fd == -1) { - printf("cannot open %s -- no interactive\n", dev); - return; - } - - if (mkfifo(interactive_fifo, O_RDWR)) { - printf("cannot create fifo -- no interactive\n"); - return; - } - - if (!(interactive_pid = fork())) { - int fif_out; - - dup2(fd, 0); - dup2(fd, 1); - dup2(fd, 2); - - close(fd); - setsid(); - if (ioctl(0, TIOCSCTTY, NULL)) - perror("could not set new controlling tty"); - - fif_out = open(interactive_fifo, O_WRONLY); - printf("Please enter your command (availables: [+,-] [rescue]).\n"); - - while (1) { - char s[50]; - int i = 0; - printf("? "); - fflush(stdout); - read(0, &(s[i++]), 1); - fcntl(0, F_SETFL, O_NONBLOCK); - while (read(0, &(s[i++]), 1) > 0 && i < sizeof(s)); - fcntl(0, F_SETFL, 0); - write(fif_out, s, i-2); - printf("Ok.\n"); - } - } - - close(fd); - } + int fd; + char * dev = "/dev/tty6"; + + printf("spawning my interactive on %s\n", dev); + + if (!IS_TESTING) { + fd = open(dev, O_RDWR); + if (fd == -1) { + printf("cannot open %s -- no interactive\n", dev); + return; + } + + if (mkfifo(interactive_fifo, O_RDWR)) { + printf("cannot create fifo -- no interactive\n"); + return; + } + + if (!(interactive_pid = fork())) { + int fif_out; + + dup2(fd, 0); + dup2(fd, 1); + dup2(fd, 2); + + close(fd); + setsid(); + if (ioctl(0, TIOCSCTTY, NULL)) + perror("could not set new controlling tty"); + + fif_out = open(interactive_fifo, O_WRONLY); + printf("Please enter your command (availables: [+,-] [rescue]).\n"); + + while (1) { + char s[50]; + int i = 0; + printf("? "); + fflush(stdout); + read(0, &(s[i++]), 1); + fcntl(0, F_SETFL, O_NONBLOCK); + while (read(0, &(s[i++]), 1) > 0 && i < sizeof(s)); + fcntl(0, F_SETFL, 0); + write(fif_out, s, i-2); + printf("Ok.\n"); + } + } + + close(fd); + } } #endif @@ -220,37 +220,36 @@ static void handle_pcmcia(void) { char * pcmcia_adapter; - pcmcia_adapter = pcmcia_probe(); - if (!pcmcia_adapter) { - log_message("no pcmcia adapter found"); - return; - } - my_insmod("pcmcia_core", ANY_DRIVER_TYPE, NULL, 0); - my_insmod(pcmcia_adapter, ANY_DRIVER_TYPE, NULL, 0); - /* ds is an alias for pcmcia in recent 2.6 kernels + pcmcia_adapter = pcmcia_probe(); + if (!pcmcia_adapter) { + log_message("no pcmcia adapter found"); + return; + } + my_insmod("pcmcia_core", ANY_DRIVER_TYPE, NULL, 0); + my_insmod(pcmcia_adapter, ANY_DRIVER_TYPE, NULL, 0); + /* ds is an alias for pcmcia in recent 2.6 kernels but we don't have modules.alias in install, so try to load both */ - my_insmod("ds", ANY_DRIVER_TYPE, NULL, 0); - my_insmod("pcmcia", ANY_DRIVER_TYPE, NULL, 0); - + my_insmod("ds", ANY_DRIVER_TYPE, NULL, 0); + my_insmod("pcmcia", ANY_DRIVER_TYPE, NULL, 0); + /* setup a dynamic resource database for non statically mapped PCMCIA sockets */ - pcmcia_socket_startup(-1); + pcmcia_socket_startup(-1); - add_to_env("PCMCIA", pcmcia_adapter); + add_to_env("PCMCIA", pcmcia_adapter); } #endif #ifndef ENABLE_NETWORK_STANDALONE static void handle_hid(void) { - struct hid_entries entry_list; - unsigned int i; - - entry_list = hid_probe(); - for (i = 0; i < entry_list.nb; i++) { - if (entry_list.entries[i].module != NULL) - my_insmod(entry_list.entries[i].module, ANY_DRIVER_TYPE, NULL, 0); - } - my_insmod("hid_generic", ANY_DRIVER_TYPE, NULL, 0); + struct hid_entries entry_list; + unsigned int i; + + entry_list = hid_probe(); + for (i = 0; i < entry_list.nb; i++) { + if (entry_list.entries[i].module != NULL) + my_insmod(entry_list.entries[i].module, ANY_DRIVER_TYPE, NULL, 0); + } } @@ -259,85 +258,85 @@ static void handle_hid(void) static void method_select_and_prepare(void) { - enum return_type results; - char * choice; - char * means[10], * means_auto[10]; - int i; + enum return_type results; + char * choice; + char * means[10], * means_auto[10]; + int i; #ifndef DISABLE_DISK - char * disk_install = "Hard disk"; char * disk_install_auto = "disk"; + char * disk_install = "Hard disk"; char * disk_install_auto = "disk"; #endif #ifndef DISABLE_CDROM - char * cdrom_install = "CDROM drive"; char * cdrom_install_auto = "cdrom"; + char * cdrom_install = "CDROM drive"; char * cdrom_install_auto = "cdrom"; #endif #ifndef DISABLE_NETWORK - char * network_nfs_install = "NFS server"; char * network_nfs_install_auto = "nfs"; - char * network_ftp_install = "FTP server"; char * network_ftp_install_auto = "ftp"; - char * network_http_install = "HTTP server"; char * network_http_install_auto = "http"; + char * network_nfs_install = "NFS server"; char * network_nfs_install_auto = "nfs"; + char * network_ftp_install = "FTP server"; char * network_ftp_install_auto = "ftp"; + char * network_http_install = "HTTP server"; char * network_http_install_auto = "http"; #ifndef DISABLE_KA - char * network_ka_install = "KA server"; char * network_ka_install_auto = "ka"; + char * network_ka_install = "KA server"; char * network_ka_install_auto = "ka"; #endif #endif - char * thirdparty_install = "Load third party modules"; char * thirdparty_install_auto = "thirdparty"; + char * thirdparty_install = "Load third party modules"; char * thirdparty_install_auto = "thirdparty"; - i = 0; + i = 0; #ifndef DISABLE_NETWORK - means[i] = network_nfs_install; means_auto[i++] = network_nfs_install_auto; - means[i] = network_ftp_install; means_auto[i++] = network_ftp_install_auto; - means[i] = network_http_install; means_auto[i++] = network_http_install_auto; + means[i] = network_nfs_install; means_auto[i++] = network_nfs_install_auto; + means[i] = network_ftp_install; means_auto[i++] = network_ftp_install_auto; + means[i] = network_http_install; means_auto[i++] = network_http_install_auto; #ifndef DISABLE_KA - means[i] = network_ka_install; means_auto[i++] = network_ka_install_auto; + means[i] = network_ka_install; means_auto[i++] = network_ka_install_auto; #endif #endif #ifndef DISABLE_CDROM - means[i] = cdrom_install; means_auto[i++] = cdrom_install_auto; + means[i] = cdrom_install; means_auto[i++] = cdrom_install_auto; #endif #ifndef DISABLE_DISK - means[i] = disk_install; means_auto[i++] = disk_install_auto; + means[i] = disk_install; means_auto[i++] = disk_install_auto; #endif - means[i] = thirdparty_install; means_auto[i++] = thirdparty_install_auto; - means[i] = NULL; + means[i] = thirdparty_install; means_auto[i++] = thirdparty_install_auto; + means[i] = NULL; - unlink(IMAGE_LOCATION); + unlink(IMAGE_LOCATION); - results = ask_from_list_auto("Please choose the installation method.", means, &choice, "method", means_auto); + results = ask_from_list_auto("Please choose the installation method.", means, &choice, "method", means_auto); - if (results != RETURN_OK) - return method_select_and_prepare(); + if (results != RETURN_OK) + return method_select_and_prepare(); #ifndef DISABLE_CDROM - if (!strcmp(choice, cdrom_install)) - results = cdrom_prepare(); + if (!strcmp(choice, cdrom_install)) + results = cdrom_prepare(); #endif #ifndef DISABLE_DISK - if (!strcmp(choice, disk_install)) - results = disk_prepare(); + if (!strcmp(choice, disk_install)) + results = disk_prepare(); #endif - + #ifndef DISABLE_NETWORK - if (!strcmp(choice, network_nfs_install)) - results = nfs_prepare(); + if (!strcmp(choice, network_nfs_install)) + results = nfs_prepare(); - if (!strcmp(choice, network_ftp_install)) - results = ftp_prepare(); - - if (!strcmp(choice, network_http_install)) - results = http_prepare(); + if (!strcmp(choice, network_ftp_install)) + results = ftp_prepare(); + + if (!strcmp(choice, network_http_install)) + results = http_prepare(); #ifndef DISABLE_KA - if (!strcmp(choice, network_ka_install)) - results = ka_prepare(); + if (!strcmp(choice, network_ka_install)) + results = ka_prepare(); #endif #endif - if (!strcmp(choice, thirdparty_install)) { - thirdparty_load_modules(); - return method_select_and_prepare(); + if (!strcmp(choice, thirdparty_install)) { + thirdparty_load_modules(); + return method_select_and_prepare(); } - if (results != RETURN_OK) - return method_select_and_prepare(); + if (results != RETURN_OK) + return method_select_and_prepare(); /* try to find third party modules on the install media */ thirdparty_load_media_modules(); @@ -356,9 +355,9 @@ static enum return_type create_initial_fs_symlinks(char* symlinks) buf[strlen(buf)-1] = '\0'; // trim \n if (sscanf(buf, "%s %s", oldpath, newpath) != 2) { sprintf(oldpath, "%s%s", STAGE2_LOCATION, buf); - sprintf(newpath, "%s", buf); + sprintf(newpath, "%s", buf); } - recursiveRemove_if_it_exists(newpath); + recursiveRemove_if_it_exists(newpath); log_message("creating symlink %s -> %s", oldpath, newpath); if (scall(symlink(oldpath, newpath), "symlink")) return RETURN_ERROR; @@ -369,23 +368,23 @@ static enum return_type create_initial_fs_symlinks(char* symlinks) void finish_preparing(void) { - recursiveRemove("/init"); + recursiveRemove("/init"); - if (create_initial_fs_symlinks(STAGE2_LOCATION "/usr/share/symlinks") != RETURN_OK) - stg1_fatal_message("Fatal error finishing initialization."); + if (create_initial_fs_symlinks(STAGE2_LOCATION "/usr/share/symlinks") != RETURN_OK) + stg1_fatal_message("Fatal error finishing initialization."); - /* /tmp/syslog is used by the second init, so it must be copied now, not in stage2 */ - /* we remove it to ensure the old one is not copied over it in stage2 */ + /* /tmp/syslog is used by the second init, so it must be copied now, not in stage2 */ + /* we remove it to ensure the old one is not copied over it in stage2 */ #ifdef SPAWN_SHELL - if (shell_pid != 0) { - int fd; - const char *clear = "\033[H\033[J"; - kill(shell_pid, 9); - log_message("killed shell"); - fd = open("/dev/tty2", O_RDWR); - write(fd, clear, strlen(clear)); - close(fd); + if (shell_pid != 0) { + int fd; + const char *clear = "\033[H\033[J"; + kill(shell_pid, 9); + log_message("killed shell"); + fd = open("/dev/tty2", O_RDWR); + write(fd, clear, strlen(clear)); + close(fd); } #endif } @@ -393,83 +392,83 @@ void finish_preparing(void) int main(int argc __attribute__ ((unused)), char **argv __attribute__ ((unused)), char **env) { #ifdef ENABLE_NETWORK_STANDALONE - open_log(); - init_frontend(""); + open_log(); + init_frontend(""); - unlink("/etc/resolv.conf"); /* otherwise it is read-only */ - set_param(MODE_AUTOMATIC); - grab_automatic_params("network:dhcp"); + unlink("/etc/resolv.conf"); /* otherwise it is read-only */ + set_param(MODE_AUTOMATIC); + grab_automatic_params("network:dhcp"); - intf_select_and_up(); - finish_frontend(); - return 0; + intf_select_and_up(); + finish_frontend(); + return 0; #else - if (getenv("DEBUGSTAGE1")) { - set_param(MODE_DEBUGSTAGE1); - set_param(MODE_TESTING); + if (getenv("DEBUGSTAGE1")) { + set_param(MODE_DEBUGSTAGE1); + set_param(MODE_TESTING); } #ifdef SPAWN_INTERACTIVE - spawn_interactive(); + spawn_interactive(); #endif - open_log(); - log_message("welcome to the " DISTRIB_NAME " install (mdk-stage1, version " DISTRIB_VERSION " built " __DATE__ " " __TIME__")"); - process_cmdline(); + open_log(); + log_message("welcome to the " DISTRIB_NAME " install (mdk-stage1, version " DISTRIB_VERSION " built " __DATE__ " " __TIME__")"); + process_cmdline(); #ifdef SPAWN_SHELL - spawn_shell(); + spawn_shell(); #endif - init_modules_insmoding(); - init_firmware_loader(); - init_frontend("Welcome to " DISTRIB_DESCR ", " __DATE__ " " __TIME__); + init_modules_insmoding(); + init_firmware_loader(); + init_frontend("Welcome to " DISTRIB_DESCR ", " __DATE__ " " __TIME__); - probe_that_type(VIRTIO_DEVICES, BUS_ANY); + probe_that_type(VIRTIO_DEVICES, BUS_ANY); /* load usb interface as soon as possible, helps usb mouse detection in stage2 */ - probe_that_type(USB_CONTROLLERS, BUS_USB); + probe_that_type(USB_CONTROLLERS, BUS_USB); - if (IS_THIRDPARTY) - thirdparty_load_modules(); + if (IS_THIRDPARTY) + thirdparty_load_modules(); #ifdef ENABLE_PCMCIA - if (!IS_NOAUTO) - handle_pcmcia(); + if (!IS_NOAUTO) + handle_pcmcia(); #endif - handle_hid(); + handle_hid(); - if (IS_CHANGEDISK) - stg1_info_message("You are starting the installation with an alternate booting method. " - "Please change your disk, and insert the Installation disk."); + if (IS_CHANGEDISK) + stg1_info_message("You are starting the installation with an alternate booting method. " + "Please change your disk, and insert the Installation disk."); - if (IS_RESCUE && total_memory() < MEM_LIMIT_RESCUE) { - stg1_error_message("You are starting the rescue with a low memory configuration. " - "Our experience shows that your system may crash at any point " - "or lock up for no apparent reason. Continue at " - "your own risk. Alternatively, you may reboot your system now."); - } + if (IS_RESCUE && total_memory() < MEM_LIMIT_RESCUE) { + stg1_error_message("You are starting the rescue with a low memory configuration. " + "Our experience shows that your system may crash at any point " + "or lock up for no apparent reason. Continue at " + "your own risk. Alternatively, you may reboot your system now."); + } method_select_and_prepare(); - thirdparty_destroy(); + thirdparty_destroy(); - if (access(STAGE2_LOCATION, R_OK) != 0) - if (symlink(IMAGE_LOCATION_REL "/" LIVE_LOCATION_REL, STAGE2_LOCATION) != 0) - log_perror("symlink from " IMAGE_LOCATION_REL "/" LIVE_LOCATION_REL " to " STAGE2_LOCATION " failed"); + if (access(STAGE2_LOCATION, R_OK) != 0) + if (symlink(IMAGE_LOCATION_REL "/" LIVE_LOCATION_REL, STAGE2_LOCATION) != 0) + log_perror("symlink from " IMAGE_LOCATION_REL "/" LIVE_LOCATION_REL " to " STAGE2_LOCATION " failed"); #ifdef SPAWN_INTERACTIVE - if (interactive_pid != 0) - kill(interactive_pid, 9); + if (interactive_pid != 0) + kill(interactive_pid, 9); #endif - finish_preparing(); + finish_preparing(); - finish_frontend(); - close_log(); + finish_frontend(); + close_log(); - if (IS_RESCUE) - return 66; /* ask init to exec new init */ - else - return 0x35; /* ask init to run stage2 binary */ + if (IS_RESCUE) + return 66; /* ask init to exec new init */ + else + return 0x35; /* ask init to run stage2 binary */ #endif } diff --git a/mdk-stage1/stdio-frontend.c b/mdk-stage1/stdio-frontend.c index d82f4852d..8006947a2 100644 --- a/mdk-stage1/stdio-frontend.c +++ b/mdk-stage1/stdio-frontend.c @@ -34,8 +34,8 @@ void init_frontend(char * welcome_msg) { - printf(welcome_msg); - printf("\n"); + printf(welcome_msg); + printf("\n"); } @@ -45,152 +45,152 @@ void finish_frontend(void) static void get_any_response(void) { - unsigned char t; - printf("\n\t(press <enter> to proceed)"); - fflush(stdout); - read(0, &t, 1); - fcntl(0, F_SETFL, O_NONBLOCK); - while (read(0, &t, 1) > 0); - fcntl(0, F_SETFL, 0); + unsigned char t; + printf("\n\t(press <enter> to proceed)"); + fflush(stdout); + read(0, &t, 1); + fcntl(0, F_SETFL, O_NONBLOCK); + while (read(0, &t, 1) > 0); + fcntl(0, F_SETFL, 0); } static int get_int_response(void) { - char s[50]; - int j = 0; - unsigned int i = 0; /* (0) tied to Cancel */ - fflush(stdout); - read(0, &(s[i++]), 1); - fcntl(0, F_SETFL, O_NONBLOCK); - do { - int v = s[i-1]; - if (v >= '0' && v <= '9') - j = j*10 + (v - '0'); - } while (read(0, &(s[i++]), 1) > 0 && i < sizeof(s)); - fcntl(0, F_SETFL, 0); - return j; + char s[50]; + int j = 0; + unsigned int i = 0; /* (0) tied to Cancel */ + fflush(stdout); + read(0, &(s[i++]), 1); + fcntl(0, F_SETFL, O_NONBLOCK); + do { + int v = s[i-1]; + if (v >= '0' && v <= '9') + j = j*10 + (v - '0'); + } while (read(0, &(s[i++]), 1) > 0 && i < sizeof(s)); + fcntl(0, F_SETFL, 0); + return j; } static char * get_string_response(char * initial_string) { - /* I won't use a scanf/%s since I also want the null string to be accepted -- also, I want the initial_string */ - char s[500]; - int i = 0; - int b_index = 0; - char b; - - struct termios t; - - memset(s, '\0', sizeof(s)); - - if (initial_string) { - printf(initial_string); - strcpy(s, initial_string); - i = strlen(s); - } - - /* from ncurses/tinfo/lib_raw.c:(cbreak) */ - tcgetattr(0, &t); - t.c_lflag &= ~ICANON; - t.c_lflag |= ISIG; - t.c_lflag &= ~ECHO; - t.c_iflag &= ~ICRNL; - t.c_cc[VMIN] = 1; - t.c_cc[VTIME] = 0; - tcsetattr(0, TCSADRAIN, &t); - - fflush(stdout); - - fcntl(0, F_SETFL, O_NONBLOCK); - - while (1) { - if (read(0, &b, 1) > 0) { - if (b_index == 1) { - if (b == 91) { - b_index++; - continue; - } - else - b_index = 0; - } - if (b_index == 2) { - if (b == 67) { - if (s[i] != '\0') { - printf("\033[C"); - i++; - } - } - if (b == 68) { - if (i > 0) { - printf("\033[D"); - i--; - } - } - b_index = 0; - continue; - } - - if (b == 13) - break; - if (b == 127) { - if (i > 0) { - printf("\033[D"); - printf(" "); - printf("\033[D"); - if (s[i] == '\0') - s[i-1] = '\0'; - else - s[i-1] = ' '; - i--; - } - } else if (b == 27) { - b_index++; - } else { - printf("%c", b); - s[i] = b; - i++; - } - } - } - - t.c_lflag |= ICANON; - t.c_lflag |= ECHO; - t.c_iflag |= ICRNL; - tcsetattr(0, TCSADRAIN, &t); - - fcntl(0, F_SETFL, 0); - - printf("\n"); - return strdup(s); + /* I won't use a scanf/%s since I also want the null string to be accepted -- also, I want the initial_string */ + char s[500]; + int i = 0; + int b_index = 0; + char b; + + struct termios t; + + memset(s, '\0', sizeof(s)); + + if (initial_string) { + printf(initial_string); + strcpy(s, initial_string); + i = strlen(s); + } + + /* from ncurses/tinfo/lib_raw.c:(cbreak) */ + tcgetattr(0, &t); + t.c_lflag &= ~ICANON; + t.c_lflag |= ISIG; + t.c_lflag &= ~ECHO; + t.c_iflag &= ~ICRNL; + t.c_cc[VMIN] = 1; + t.c_cc[VTIME] = 0; + tcsetattr(0, TCSADRAIN, &t); + + fflush(stdout); + + fcntl(0, F_SETFL, O_NONBLOCK); + + while (1) { + if (read(0, &b, 1) > 0) { + if (b_index == 1) { + if (b == 91) { + b_index++; + continue; + } + else + b_index = 0; + } + if (b_index == 2) { + if (b == 67) { + if (s[i] != '\0') { + printf("\033[C"); + i++; + } + } + if (b == 68) { + if (i > 0) { + printf("\033[D"); + i--; + } + } + b_index = 0; + continue; + } + + if (b == 13) + break; + if (b == 127) { + if (i > 0) { + printf("\033[D"); + printf(" "); + printf("\033[D"); + if (s[i] == '\0') + s[i-1] = '\0'; + else + s[i-1] = ' '; + i--; + } + } else if (b == 27) { + b_index++; + } else { + printf("%c", b); + s[i] = b; + i++; + } + } + } + + t.c_lflag |= ICANON; + t.c_lflag |= ECHO; + t.c_iflag |= ICRNL; + tcsetattr(0, TCSADRAIN, &t); + + fcntl(0, F_SETFL, 0); + + printf("\n"); + return strdup(s); } static void blocking_msg(char *type, char *fmt, va_list ap) { - printf(type); - vprintf(fmt, ap); - get_any_response(); + printf(type); + vprintf(fmt, ap); + get_any_response(); } void verror_message(char *msg, va_list ap) { - blocking_msg("> Error! ", msg, ap); + blocking_msg("> Error! ", msg, ap); } void vinfo_message(char *msg, va_list ap) { - blocking_msg("> Notice: ", msg, ap); + blocking_msg("> Notice: ", msg, ap); } void vwait_message(char *msg, va_list ap) { - printf("Please wait: "); - vprintf(msg, ap); - fflush(stdout); + printf("Please wait: "); + vprintf(msg, ap); + fflush(stdout); } void remove_wait_message(void) { - printf("\n"); + printf("\n"); } @@ -199,154 +199,154 @@ static int actually_drawn; #define PROGRESS_SIZE 45 void init_progression_raw(char *msg, int size) { - int i; - size_progress = size; - printf("%s ", msg); - if (size) { - actually_drawn = 0; - for (i=0; i<PROGRESS_SIZE; i++) - printf("."); - printf("]\033[G%s [", msg); /* only works on ANSI-compatibles */ - fflush(stdout); - } else - printf("\n"); + int i; + size_progress = size; + printf("%s ", msg); + if (size) { + actually_drawn = 0; + for (i=0; i<PROGRESS_SIZE; i++) + printf("."); + printf("]\033[G%s [", msg); /* only works on ANSI-compatibles */ + fflush(stdout); + } else + printf("\n"); } void update_progression_raw(int current_size) { - if (size_progress) { - if (current_size > size_progress) - current_size = size_progress; - while ((int)((current_size*PROGRESS_SIZE)/size_progress) > actually_drawn) { - printf("*"); - actually_drawn++; - } - } else - printf("\033[GStatus: [%8d] bytes loaded...", current_size); - - fflush(stdout); + if (size_progress) { + if (current_size > size_progress) + current_size = size_progress; + while ((int)((current_size*PROGRESS_SIZE)/size_progress) > actually_drawn) { + printf("*"); + actually_drawn++; + } + } else + printf("\033[GStatus: [%8d] bytes loaded...", current_size); + + fflush(stdout); } void end_progression_raw(void) { - if (size_progress) { - update_progression_raw(size_progress); - printf("]\n"); - } else - printf(" done.\n"); + if (size_progress) { + update_progression_raw(size_progress); + printf("]\n"); + } else + printf(" done.\n"); } enum return_type ask_from_list_index(char *msg, char ** elems, char ** elems_comments, int *answer) { - int justify_number = 1; - void print_choice_number(int i) { - char tmp[500]; - snprintf(tmp, sizeof(tmp), "[%%%dd]", justify_number); - printf(tmp, i); - } - int i = 1; - int j = 0; - - if (string_array_length(elems) >= 10) - justify_number = 2; - - i = 1; - - printf("> %s\n", msg); - print_choice_number(0); - printf(" Cancel"); - - while (elems && *elems) { - if (elems_comments && *elems_comments) { - printf("\n"); - print_choice_number(i); - printf(" %s (%s)", *elems, *elems_comments); - j = 0; - } else { - if (j == 0) - printf("\n"); - print_choice_number(i); - printf(" %-14s ", *elems); - j++; - } - if (j == 4) - j = 0; - - if (elems_comments) - elems_comments++; - i++; - elems++; - } - - printf("\n? "); - - j = get_int_response(); - - if (j == 0) - return RETURN_BACK; - - if (j >= 1 && j <= i) { - *answer = j - 1; - return RETURN_OK; - } - - return RETURN_ERROR; + int justify_number = 1; + void print_choice_number(int i) { + char tmp[500]; + snprintf(tmp, sizeof(tmp), "[%%%dd]", justify_number); + printf(tmp, i); + } + int i = 1; + int j = 0; + + if (string_array_length(elems) >= 10) + justify_number = 2; + + i = 1; + + printf("> %s\n", msg); + print_choice_number(0); + printf(" Cancel"); + + while (elems && *elems) { + if (elems_comments && *elems_comments) { + printf("\n"); + print_choice_number(i); + printf(" %s (%s)", *elems, *elems_comments); + j = 0; + } else { + if (j == 0) + printf("\n"); + print_choice_number(i); + printf(" %-14s ", *elems); + j++; + } + if (j == 4) + j = 0; + + if (elems_comments) + elems_comments++; + i++; + elems++; + } + + printf("\n? "); + + j = get_int_response(); + + if (j == 0) + return RETURN_BACK; + + if (j >= 1 && j <= i) { + *answer = j - 1; + return RETURN_OK; + } + + return RETURN_ERROR; } enum return_type ask_yes_no(char *msg) { - int j; + int j; - printf("> %s\n[0] Yes [1] No [2] Back\n? ", msg); + printf("> %s\n[0] Yes [1] No [2] Back\n? ", msg); - j = get_int_response(); + j = get_int_response(); - if (j == 0) - return RETURN_OK; - else if (j == 2) - return RETURN_BACK; - else return RETURN_ERROR; + if (j == 0) + return RETURN_OK; + else if (j == 2) + return RETURN_BACK; + else return RETURN_ERROR; } enum return_type ask_from_entries(char *msg, char ** questions, char *** answers, int entry_size UNUSED, void (*callback_func)(char ** strings) UNUSED) { - int j, i = 0; - char ** already_answers = NULL; - - printf("> %s\n", msg); - - while (questions && *questions) { - printf("(%c) %s\n", i + 'a', *questions); - i++; - questions++; - } - - if (*answers == NULL) - *answers = (char **) malloc(sizeof(char *) * i); - else - already_answers = *answers; - - while (1) { - int r; - for (j = 0 ; j < i ; j++) { - printf("(%c) ? ", j + 'a'); - if (already_answers && *already_answers) { - (*answers)[j] = get_string_response(*already_answers); - already_answers++; - } else - (*answers)[j] = get_string_response(NULL); - - } - printf("[0] Cancel [1] Accept [2] Re-enter answers\n? "); - r = get_int_response(); - if (r == 0) - return RETURN_BACK; - if (r == 1) - return RETURN_OK; - } + int j, i = 0; + char ** already_answers = NULL; + + printf("> %s\n", msg); + + while (questions && *questions) { + printf("(%c) %s\n", i + 'a', *questions); + i++; + questions++; + } + + if (*answers == NULL) + *answers = (char **) malloc(sizeof(char *) * i); + else + already_answers = *answers; + + while (1) { + int r; + for (j = 0 ; j < i ; j++) { + printf("(%c) ? ", j + 'a'); + if (already_answers && *already_answers) { + (*answers)[j] = get_string_response(*already_answers); + already_answers++; + } else + (*answers)[j] = get_string_response(NULL); + + } + printf("[0] Cancel [1] Accept [2] Re-enter answers\n? "); + r = get_int_response(); + if (r == 0) + return RETURN_BACK; + if (r == 1) + return RETURN_OK; + } } diff --git a/mdk-stage1/thirdparty.c b/mdk-stage1/thirdparty.c index 57f38a2a4..aefe223e0 100644 --- a/mdk-stage1/thirdparty.c +++ b/mdk-stage1/thirdparty.c @@ -40,421 +40,421 @@ static int pcitable_len = 0; static enum return_type thirdparty_choose_device(char ** device, int probe_only) { - char ** medias, ** medias_models; - char ** ptr, ** ptr_models; + char ** medias, ** medias_models; + char ** ptr, ** ptr_models; #ifndef DISABLE_DISK - char ** disk_medias, ** disk_medias_models; - int disk_count; - char * parts[50]; - char * parts_comments[50]; + char ** disk_medias, ** disk_medias_models; + int disk_count; + char * parts[50]; + char * parts_comments[50]; #endif #ifndef DISABLE_CDROM - char ** cdrom_medias, ** cdrom_medias_models; - int cdrom_count; + char ** cdrom_medias, ** cdrom_medias_models; + int cdrom_count; #endif - char * floppy_dev; - enum return_type results; - int count = 0; + char * floppy_dev; + enum return_type results; + int count = 0; - wait_message("Looking for floppy, disk and cdrom devices ..."); + wait_message("Looking for floppy, disk and cdrom devices ..."); #ifndef DISABLE_DISK - disk_count = get_disks(&disk_medias, &disk_medias_models); - count += disk_count; + disk_count = get_disks(&disk_medias, &disk_medias_models); + count += disk_count; #endif #ifndef DISABLE_CDROM cdrom_count = get_cdroms(&cdrom_medias, &cdrom_medias_models); count += cdrom_count; #endif - floppy_dev = floppy_device(); - if (floppy_dev && strstr(floppy_dev, "/dev/") == floppy_dev) { - floppy_dev = floppy_dev + 5; - } - if (floppy_dev) - count += 1; + floppy_dev = floppy_device(); + if (floppy_dev && strstr(floppy_dev, "/dev/") == floppy_dev) { + floppy_dev = floppy_dev + 5; + } + if (floppy_dev) + count += 1; - remove_wait_message(); + remove_wait_message(); - if (count == 0) { - stg1_error_message("I can't find any floppy, disk or cdrom on this system. " - "No third-party kernel modules will be used."); - return RETURN_BACK; - } + if (count == 0) { + stg1_error_message("I can't find any floppy, disk or cdrom on this system. " + "No third-party kernel modules will be used."); + return RETURN_BACK; + } - if (probe_only) { + if (probe_only) { #ifndef DISABLE_DISK - free(disk_medias); - free(disk_medias_models); + free(disk_medias); + free(disk_medias_models); #endif #ifndef DISABLE_CDROM - free(cdrom_medias); - free(cdrom_medias_models); + free(cdrom_medias); + free(cdrom_medias_models); #endif - return RETURN_OK; - } + return RETURN_OK; + } - ptr = medias = malloc((count + 1) * sizeof(char *)); - ptr_models =medias_models = malloc((count + 1) * sizeof(char *)); + ptr = medias = malloc((count + 1) * sizeof(char *)); + ptr_models =medias_models = malloc((count + 1) * sizeof(char *)); #ifndef DISABLE_DISK - memcpy(ptr, disk_medias, disk_count * sizeof(char *)); - memcpy(ptr_models, disk_medias_models, disk_count * sizeof(char *)); - free(disk_medias); - free(disk_medias_models); - ptr += disk_count; - ptr_models += disk_count; + memcpy(ptr, disk_medias, disk_count * sizeof(char *)); + memcpy(ptr_models, disk_medias_models, disk_count * sizeof(char *)); + free(disk_medias); + free(disk_medias_models); + ptr += disk_count; + ptr_models += disk_count; #endif #ifndef DISABLE_CDROM - memcpy(ptr, cdrom_medias, cdrom_count * sizeof(char *)); - memcpy(ptr_models, cdrom_medias_models, cdrom_count * sizeof(char *)); - free(cdrom_medias); - free(cdrom_medias_models); - cdrom_medias = ptr; /* used later to know if a cdrom is selected */ - ptr += cdrom_count; - ptr_models += cdrom_count; + memcpy(ptr, cdrom_medias, cdrom_count * sizeof(char *)); + memcpy(ptr_models, cdrom_medias_models, cdrom_count * sizeof(char *)); + free(cdrom_medias); + free(cdrom_medias_models); + cdrom_medias = ptr; /* used later to know if a cdrom is selected */ + ptr += cdrom_count; + ptr_models += cdrom_count; #endif - if (floppy_dev) { - ptr[0] = floppy_dev; - ptr_models[0] = "Floppy device"; - ptr++; - ptr_models++; - } - ptr[0] = NULL; - ptr_models[0] = NULL; - - if (count == 1) { - *device = medias[0]; - } else { - results = ask_from_list_comments("If you want to insert third-party kernel modules, " - "please select the disk containing the modules.", - medias, medias_models, device); - if (results != RETURN_OK) - return results; - } + if (floppy_dev) { + ptr[0] = floppy_dev; + ptr_models[0] = "Floppy device"; + ptr++; + ptr_models++; + } + ptr[0] = NULL; + ptr_models[0] = NULL; + + if (count == 1) { + *device = medias[0]; + } else { + results = ask_from_list_comments("If you want to insert third-party kernel modules, " + "please select the disk containing the modules.", + medias, medias_models, device); + if (results != RETURN_OK) + return results; + } - if (floppy_dev && streq(*device, floppy_dev)) { - /* a floppy is selected, don't try to list partitions */ - return RETURN_OK; - } + if (floppy_dev && streq(*device, floppy_dev)) { + /* a floppy is selected, don't try to list partitions */ + return RETURN_OK; + } #ifndef DISABLE_CDROM for (ptr = cdrom_medias; ptr < cdrom_medias + cdrom_count; ptr++) { - if (*device == *ptr) { - /* a cdrom is selected, don't try to list partitions */ - log_message("thirdparty: a cdrom is selected, using it (%s)", *device); - return RETURN_OK; - } - } + if (*device == *ptr) { + /* a cdrom is selected, don't try to list partitions */ + log_message("thirdparty: a cdrom is selected, using it (%s)", *device); + return RETURN_OK; + } + } #endif #ifndef DISABLE_DISK - /* a disk or usb key is selected */ - if (list_partitions(*device, parts, parts_comments)) { - stg1_error_message("Could not read partitions information."); - return RETURN_ERROR; - } - - if (parts[0] == NULL) { - stg1_error_message("No partition found."); - return RETURN_ERROR; - } - - /* only one partition has been discovered, don't ask which one to use */ - if (parts[1] == NULL) { - log_message("thirdparty: found only one partition on device (%s)", parts[0]); - *device = parts[0]; - return RETURN_OK; + /* a disk or usb key is selected */ + if (list_partitions(*device, parts, parts_comments)) { + stg1_error_message("Could not read partitions information."); + return RETURN_ERROR; + } + + if (parts[0] == NULL) { + stg1_error_message("No partition found."); + return RETURN_ERROR; + } + + /* only one partition has been discovered, don't ask which one to use */ + if (parts[1] == NULL) { + log_message("thirdparty: found only one partition on device (%s)", parts[0]); + *device = parts[0]; + return RETURN_OK; } - results = ask_from_list_comments("Please select the partition containing " - "the third party modules.", - parts, parts_comments, device); - if (results == RETURN_OK) - return RETURN_OK; + results = ask_from_list_comments("Please select the partition containing " + "the third party modules.", + parts, parts_comments, device); + if (results == RETURN_OK) + return RETURN_OK; #endif - stg1_error_message("Sorry, no third party device can be used."); + stg1_error_message("Sorry, no third party device can be used."); - return RETURN_BACK; + return RETURN_BACK; } static enum return_type thirdparty_mount_device(char * device) { log_message("third party: trying to mount device %s", device); - if (try_mount(device, THIRDPARTY_MOUNT_LOCATION) != 0) { - stg1_error_message("I can't mount the selected device (%s).", device); - return RETURN_ERROR; - } - return RETURN_OK; + if (try_mount(device, THIRDPARTY_MOUNT_LOCATION) != 0) { + stg1_error_message("I can't mount the selected device (%s).", device); + return RETURN_ERROR; + } + return RETURN_OK; } static enum return_type thirdparty_prompt_modules(const char *modules_location, char ** modules_list) { - enum return_type results; - char final_name[500]; - char *module_name; - int rc; - char * questions[] = { "Options", NULL }; - static char ** answers = NULL; - - while (1) { - results = ask_from_list("Which driver would you like to insmod?", modules_list, &module_name); - if (results != RETURN_OK) - break; - - sprintf(final_name, "%s/%s", modules_location, module_name); - - results = ask_from_entries("Please enter the options:", questions, &answers, 24, NULL); - if (results != RETURN_OK) - continue; - - rc = insmod_local_file(final_name, answers[0]); - if (rc) { - log_message("\tfailed"); - stg1_error_message("Insmod failed."); - } - } - return RETURN_OK; + enum return_type results; + char final_name[500]; + char *module_name; + int rc; + char * questions[] = { "Options", NULL }; + static char ** answers = NULL; + + while (1) { + results = ask_from_list("Which driver would you like to insmod?", modules_list, &module_name); + if (results != RETURN_OK) + break; + + sprintf(final_name, "%s/%s", modules_location, module_name); + + results = ask_from_entries("Please enter the options:", questions, &answers, 24, NULL); + if (results != RETURN_OK) + continue; + + rc = insmod_local_file(final_name, answers[0]); + if (rc) { + log_message("\tfailed"); + stg1_error_message("Insmod failed."); + } + } + return RETURN_OK; } static int pcitable_orderer(const void *a, const void *b) { - int ret; - struct pcitable_entry *ap = (struct pcitable_entry *)a; - struct pcitable_entry *bp = (struct pcitable_entry *)b; - - if ((ret = ap->vendor - bp->vendor) != 0) - return ret; - if ((ret = ap->device - bp->device) != 0) - return ret; - if ((ret = ap->subvendor - bp->subvendor) != 0) - return ret; - if ((ret = ap->subdevice - bp->subdevice) != 0) - return ret; - - return 0; + int ret; + struct pcitable_entry *ap = (struct pcitable_entry *)a; + struct pcitable_entry *bp = (struct pcitable_entry *)b; + + if ((ret = ap->vendor - bp->vendor) != 0) + return ret; + if ((ret = ap->device - bp->device) != 0) + return ret; + if ((ret = ap->subvendor - bp->subvendor) != 0) + return ret; + if ((ret = ap->subdevice - bp->subdevice) != 0) + return ret; + + return 0; } static void thirdparty_load_pcitable(const char *modules_location) { - char pcitable_filename[100]; - FILE * f = NULL; - - sprintf(pcitable_filename, "%s/pcitable", modules_location); - if (!(f = fopen(pcitable_filename, "rb"))) { - log_message("third_party: no external pcitable found"); - return; - } - pcitable_len = 0; - while (pcitable_len < N_PCITABLE_ENTRIES) { - char buf[200]; - struct pcitable_entry *e; - if (!fgets(buf, sizeof(buf), f)) break; - e = &pcitable[pcitable_len++]; - if (sscanf(buf, "%hx\t%hx\t\"%[^ \"]\"\t\"%[^\"]\"", &e->vendor, &e->device, e->module, e->description) == 4) - e->subvendor = e->subdevice = PCITABLE_MATCH_ALL; - else - sscanf(buf, "%hx\t%hx\t%x\t%x\t\"%[^ \"]\"\t\"%[^\"]\"", &e->vendor, &e->device, &e->subvendor, &e->subdevice, e->module, e->description); - } - fclose(f); - - /* sort pcitable by most specialised entries first */ - qsort(pcitable, pcitable_len, sizeof(pcitable[0]), pcitable_orderer); + char pcitable_filename[100]; + FILE * f = NULL; + + sprintf(pcitable_filename, "%s/pcitable", modules_location); + if (!(f = fopen(pcitable_filename, "rb"))) { + log_message("third_party: no external pcitable found"); + return; + } + pcitable_len = 0; + while (pcitable_len < N_PCITABLE_ENTRIES) { + char buf[200]; + struct pcitable_entry *e; + if (!fgets(buf, sizeof(buf), f)) break; + e = &pcitable[pcitable_len++]; + if (sscanf(buf, "%hx\t%hx\t\"%[^ \"]\"\t\"%[^\"]\"", &e->vendor, &e->device, e->module, e->description) == 4) + e->subvendor = e->subdevice = PCITABLE_MATCH_ALL; + else + sscanf(buf, "%hx\t%hx\t%x\t%x\t\"%[^ \"]\"\t\"%[^\"]\"", &e->vendor, &e->device, &e->subvendor, &e->subdevice, e->module, e->description); + } + fclose(f); + + /* sort pcitable by most specialised entries first */ + qsort(pcitable, pcitable_len, sizeof(pcitable[0]), pcitable_orderer); } static int thirdparty_is_detected(char *driver) { - int i, j; - - for (i = 0; i < detected_devices_len ; i++) { - /* first look for the IDs in the third-party pcitable */ - for (j = 0; j < pcitable_len ; j++) { - if (pcitable[j].vendor == detected_devices[i].vendor && - pcitable[j].device == detected_devices[i].device && - !strcmp(pcitable[j].module, driver)) { - const int subvendor = pcitable[j].subvendor; - const int subdevice = pcitable[j].subdevice; - if ((subvendor == PCITABLE_MATCH_ALL && subdevice == PCITABLE_MATCH_ALL) || - (subvendor == detected_devices[i].subvendor && subdevice == detected_devices[i].subdevice)) { - log_message("probing: found device for module %s", driver); - return 1; - } - } - } - /* if not found, compare with the detected driver */ - if (!strcmp(detected_devices[i].module, driver)) { - log_message("probing: found device for module %s", driver); - return 1; - } - } - - return 0; + int i, j; + + for (i = 0; i < detected_devices_len ; i++) { + /* first look for the IDs in the third-party pcitable */ + for (j = 0; j < pcitable_len ; j++) { + if (pcitable[j].vendor == detected_devices[i].vendor && + pcitable[j].device == detected_devices[i].device && + !strcmp(pcitable[j].module, driver)) { + const int subvendor = pcitable[j].subvendor; + const int subdevice = pcitable[j].subdevice; + if ((subvendor == PCITABLE_MATCH_ALL && subdevice == PCITABLE_MATCH_ALL) || + (subvendor == detected_devices[i].subvendor && subdevice == detected_devices[i].subdevice)) { + log_message("probing: found device for module %s", driver); + return 1; + } + } + } + /* if not found, compare with the detected driver */ + if (!strcmp(detected_devices[i].module, driver)) { + log_message("probing: found device for module %s", driver); + return 1; + } + } + + return 0; } static enum return_type thirdparty_autoload_modules(const char *modules_location, char ** modules_list, FILE *f, int load_detected_only) { - while (1) { - char final_name[500]; - char module[500]; - char * options; - char ** entry = modules_list; - - if (!fgets(module, sizeof(module), f)) break; - if (module[0] == '#' || strlen(module) == 0) - continue; - - while (module[strlen(module)-1] == '\n') - module[strlen(module)-1] = '\0'; - options = strchr(module, ' '); - if (options) { - options[0] = '\0'; - options++; - } - - if (load_detected_only && !thirdparty_is_detected(module)) { - log_message("third party: no device detected for module %s, skipping", module); - continue; - } - - log_message("third party: auto-loading module (%s) with options (%s)", module, options); - while (entry && *entry) { - if (!strncmp(*entry, module, strlen(module)) && (*entry)[strlen(module)] == '.') { - sprintf(final_name, "%s/%s", modules_location, *entry); - if (insmod_local_file(final_name, options)) { - log_message("\t%s (third party media): failed", *entry); - stg1_error_message("Insmod %s (third party media) failed.", *entry); - } - break; - } - entry++; - } - if (!entry || !*entry) { - enum insmod_return ret = my_insmod(module, ANY_DRIVER_TYPE, options, 0); - if (ret != INSMOD_OK) { - log_message("\t%s (marfile): failed", module); - stg1_error_message("Insmod %s (marfile) failed.", module); - } - } - } - - return RETURN_OK; + while (1) { + char final_name[500]; + char module[500]; + char * options; + char ** entry = modules_list; + + if (!fgets(module, sizeof(module), f)) break; + if (module[0] == '#' || strlen(module) == 0) + continue; + + while (module[strlen(module)-1] == '\n') + module[strlen(module)-1] = '\0'; + options = strchr(module, ' '); + if (options) { + options[0] = '\0'; + options++; + } + + if (load_detected_only && !thirdparty_is_detected(module)) { + log_message("third party: no device detected for module %s, skipping", module); + continue; + } + + log_message("third party: auto-loading module (%s) with options (%s)", module, options); + while (entry && *entry) { + if (!strncmp(*entry, module, strlen(module)) && (*entry)[strlen(module)] == '.') { + sprintf(final_name, "%s/%s", modules_location, *entry); + if (insmod_local_file(final_name, options)) { + log_message("\t%s (third party media): failed", *entry); + stg1_error_message("Insmod %s (third party media) failed.", *entry); + } + break; + } + entry++; + } + if (!entry || !*entry) { + enum insmod_return ret = my_insmod(module, ANY_DRIVER_TYPE, options, 0); + if (ret != INSMOD_OK) { + log_message("\t%s (marfile): failed", module); + stg1_error_message("Insmod %s (marfile) failed.", module); + } + } + } + + return RETURN_OK; } static enum return_type thirdparty_try_directory(char * root_directory, int interactive) { - char modules_location[100]; - char modules_location_release[100]; - char *list_filename; - FILE *f_load, *f_detect; - char **modules_list, **modules_list_release; - struct utsname kernel_uname; - - /* look first in the specific third-party directory */ - snprintf(modules_location, sizeof(modules_location), "%s" THIRDPARTY_DIRECTORY, root_directory); - modules_list = list_directory(modules_location); - - /* if it's empty, look in the root of selected device */ - if (!modules_list || !modules_list[0]) { - modules_location[strlen(root_directory)] = '\0'; - modules_list = list_directory(modules_location); - if (interactive) - add_to_env("THIRDPARTY_DIR", ""); - } else { - if (interactive) - add_to_env("THIRDPARTY_DIR", THIRDPARTY_DIRECTORY); + char modules_location[100]; + char modules_location_release[100]; + char *list_filename; + FILE *f_load, *f_detect; + char **modules_list, **modules_list_release; + struct utsname kernel_uname; + + /* look first in the specific third-party directory */ + snprintf(modules_location, sizeof(modules_location), "%s" THIRDPARTY_DIRECTORY, root_directory); + modules_list = list_directory(modules_location); + + /* if it's empty, look in the root of selected device */ + if (!modules_list || !modules_list[0]) { + modules_location[strlen(root_directory)] = '\0'; + modules_list = list_directory(modules_location); + if (interactive) + add_to_env("THIRDPARTY_DIR", ""); + } else { + if (interactive) + add_to_env("THIRDPARTY_DIR", THIRDPARTY_DIRECTORY); } - if (uname(&kernel_uname)) { - log_perror("uname failed"); - return RETURN_ERROR; - } - snprintf(modules_location_release, sizeof(modules_location_release), "%s/%s", modules_location, kernel_uname.release); - modules_list_release = list_directory(modules_location_release); - if (modules_list_release && modules_list_release[0]) { - strcpy(modules_location, modules_location_release); - modules_list = modules_list_release; - } - - log_message("third party: using modules location %s", modules_location); - - if (!modules_list || !*modules_list) { - log_message("third party: no modules found"); - if (interactive) - stg1_error_message("No modules found on selected device."); - return RETURN_ERROR; + if (uname(&kernel_uname)) { + log_perror("uname failed"); + return RETURN_ERROR; + } + snprintf(modules_location_release, sizeof(modules_location_release), "%s/%s", modules_location, kernel_uname.release); + modules_list_release = list_directory(modules_location_release); + if (modules_list_release && modules_list_release[0]) { + strcpy(modules_location, modules_location_release); + modules_list = modules_list_release; + } + + log_message("third party: using modules location %s", modules_location); + + if (!modules_list || !*modules_list) { + log_message("third party: no modules found"); + if (interactive) + stg1_error_message("No modules found on selected device."); + return RETURN_ERROR; } - list_filename = alloca(strlen(modules_location) + 10 /* max: "/to_detect" */ + 1); - - sprintf(list_filename, "%s/to_load", modules_location); - f_load = fopen(list_filename, "rb"); - if (f_load) { - thirdparty_autoload_modules(modules_location, modules_list, f_load, 0); - fclose(f_load); - } - - sprintf(list_filename, "%s/to_detect", modules_location); - f_detect = fopen(list_filename, "rb"); - if (f_detect) { - probing_detect_devices(); - thirdparty_load_pcitable(modules_location); - thirdparty_autoload_modules(modules_location, modules_list, f_detect, 1); - fclose(f_detect); - } - - if (f_load || f_detect) - return RETURN_OK; - else if (interactive) { - if (IS_AUTOMATIC) - stg1_error_message("I can't find a \"to_load\" file. Please select the modules manually."); - log_message("third party: no \"to_load\" file, prompting for modules"); - return thirdparty_prompt_modules(modules_location, modules_list); - } else { - return RETURN_OK; - } + list_filename = alloca(strlen(modules_location) + 10 /* max: "/to_detect" */ + 1); + + sprintf(list_filename, "%s/to_load", modules_location); + f_load = fopen(list_filename, "rb"); + if (f_load) { + thirdparty_autoload_modules(modules_location, modules_list, f_load, 0); + fclose(f_load); + } + + sprintf(list_filename, "%s/to_detect", modules_location); + f_detect = fopen(list_filename, "rb"); + if (f_detect) { + probing_detect_devices(); + thirdparty_load_pcitable(modules_location); + thirdparty_autoload_modules(modules_location, modules_list, f_detect, 1); + fclose(f_detect); + } + + if (f_load || f_detect) + return RETURN_OK; + else if (interactive) { + if (IS_AUTOMATIC) + stg1_error_message("I can't find a \"to_load\" file. Please select the modules manually."); + log_message("third party: no \"to_load\" file, prompting for modules"); + return thirdparty_prompt_modules(modules_location, modules_list); + } else { + return RETURN_OK; + } } void thirdparty_load_media_modules(void) { - thirdparty_try_directory(IMAGE_LOCATION, 0); + thirdparty_try_directory(IMAGE_LOCATION, 0); } void thirdparty_load_modules(void) { - enum return_type results; - char * device; - - device = NULL; - if (IS_AUTOMATIC) { - device = get_auto_value("thirdparty"); - thirdparty_choose_device(NULL, 1); /* probe only to create devices */ - log_message("third party: trying automatic device %s", device); - if (thirdparty_mount_device(device) != RETURN_OK) - device = NULL; - } - - while (!device || streq(device, "")) { - results = thirdparty_choose_device(&device, 0); - if (results == RETURN_BACK) - return; - if (thirdparty_mount_device(device) != RETURN_OK) - device = NULL; - } - - log_message("third party: using device %s", device); - add_to_env("THIRDPARTY_DEVICE", device); - - results = thirdparty_try_directory(THIRDPARTY_MOUNT_LOCATION, 1); - umount(THIRDPARTY_MOUNT_LOCATION); - - if (results != RETURN_OK) - return thirdparty_load_modules(); + enum return_type results; + char * device; + + device = NULL; + if (IS_AUTOMATIC) { + device = get_auto_value("thirdparty"); + thirdparty_choose_device(NULL, 1); /* probe only to create devices */ + log_message("third party: trying automatic device %s", device); + if (thirdparty_mount_device(device) != RETURN_OK) + device = NULL; + } + + while (!device || streq(device, "")) { + results = thirdparty_choose_device(&device, 0); + if (results == RETURN_BACK) + return; + if (thirdparty_mount_device(device) != RETURN_OK) + device = NULL; + } + + log_message("third party: using device %s", device); + add_to_env("THIRDPARTY_DEVICE", device); + + results = thirdparty_try_directory(THIRDPARTY_MOUNT_LOCATION, 1); + umount(THIRDPARTY_MOUNT_LOCATION); + + if (results != RETURN_OK) + return thirdparty_load_modules(); } void thirdparty_destroy(void) { - probing_destroy(); + probing_destroy(); } diff --git a/mdk-stage1/tools.c b/mdk-stage1/tools.c index 14374661f..5674c4f3b 100644 --- a/mdk-stage1/tools.c +++ b/mdk-stage1/tools.c @@ -49,48 +49,48 @@ int image_has_stage2() { - return access(COMPRESSED_FILE_REL(IMAGE_LOCATION "/"), R_OK) == 0 || - access(IMAGE_LOCATION "/" LIVE_LOCATION_REL, R_OK) == 0; + return access(COMPRESSED_FILE_REL(IMAGE_LOCATION "/"), R_OK) == 0 || + access(IMAGE_LOCATION "/" LIVE_LOCATION_REL, R_OK) == 0; } enum return_type create_IMAGE_LOCATION(char *location_full) { - struct stat statbuf; - int offset = strncmp(location_full, IMAGE_LOCATION_DIR, sizeof(IMAGE_LOCATION_DIR) - 1) == 0 ? sizeof(IMAGE_LOCATION_DIR) - 1 : 0; - char *with_arch = asprintf_("%s/%s", location_full, ARCH); + struct stat statbuf; + int offset = strncmp(location_full, IMAGE_LOCATION_DIR, sizeof(IMAGE_LOCATION_DIR) - 1) == 0 ? sizeof(IMAGE_LOCATION_DIR) - 1 : 0; + char *with_arch = asprintf_("%s/%s", location_full, ARCH); - log_message("trying %s", with_arch); + log_message("trying %s", with_arch); - if (stat(with_arch, &statbuf) == 0 && S_ISDIR(statbuf.st_mode)) - location_full = with_arch; + if (stat(with_arch, &statbuf) == 0 && S_ISDIR(statbuf.st_mode)) + location_full = with_arch; - log_message("assuming %s is a mirror tree", location_full + offset); + log_message("assuming %s is a mirror tree", location_full + offset); - unlink(IMAGE_LOCATION); - if (symlink(location_full + offset, IMAGE_LOCATION) != 0) - return RETURN_ERROR; + unlink(IMAGE_LOCATION); + if (symlink(location_full + offset, IMAGE_LOCATION) != 0) + return RETURN_ERROR; - return RETURN_OK; + return RETURN_OK; } int ramdisk_possible(void) { - if (total_memory() > (IS_RESCUE ? MEM_LIMIT_RESCUE : MEM_LIMIT_DRAKX)) - return 1; - else { - log_message("warning, ramdisk is not possible due to low mem!"); - return 0; - } + if (total_memory() > (IS_RESCUE ? MEM_LIMIT_RESCUE : MEM_LIMIT_DRAKX)) + return 1; + else { + log_message("warning, ramdisk is not possible due to low mem!"); + return 0; + } } int compressed_image_preload(void) { - if (total_memory() > (IS_RESCUE ? MEM_LIMIT_RESCUE_PRELOAD : MEM_LIMIT_DRAKX_PRELOAD)) - return 1; - else { - log_message("warning, not preloading compressed due to low mem"); - return 0; - } + if (total_memory() > (IS_RESCUE ? MEM_LIMIT_RESCUE_PRELOAD : MEM_LIMIT_DRAKX_PRELOAD)) + return 1; + else { + log_message("warning, not preloading compressed due to low mem"); + return 0; + } } enum return_type save_fd(int from_fd, char * to, void (*callback_func)(int overall)) @@ -106,16 +106,16 @@ enum return_type save_fd(int from_fd, char * to, void (*callback_func)(int overa } do { - quantity = read(from_fd, buf, sizeof(buf)); - if (quantity > 0) { + quantity = read(from_fd, buf, sizeof(buf)); + if (quantity > 0) { if (fwrite(buf, 1, quantity, f_to) != quantity) { log_message("short write (%s)", strerror(errno)); goto cleanup; } } else if (quantity == -1) { - log_message("an error occured: %s", strerror(errno)); - goto cleanup; - } + log_message("an error occured: %s", strerror(errno)); + goto cleanup; + } if (callback_func) { overall += quantity; @@ -137,12 +137,12 @@ enum return_type copy_file(char * from, char * to, void (*callback_func)(int ove { int from_fd; - log_message("copy_file: %s -> %s", from, to); + log_message("copy_file: %s -> %s", from, to); - from_fd = open(from, O_RDONLY); - if (from_fd != -1) { - return save_fd(from_fd, to, callback_func); - } else { + from_fd = open(from, O_RDONLY); + if (from_fd != -1) { + return save_fd(from_fd, to, callback_func); + } else { log_perror(from); return RETURN_ERROR; } @@ -150,138 +150,137 @@ enum return_type copy_file(char * from, char * to, void (*callback_func)(int ove enum return_type recursiveRemove(char *file) { - struct stat sb; - - if (lstat(file, &sb) != 0) { - log_message("failed to stat %s: %d", file, errno); - return RETURN_ERROR; - } - - /* only descend into subdirectories if device is same as dir */ - if (S_ISDIR(sb.st_mode)) { - char * strBuf = alloca(strlen(file) + 1024); - DIR * dir; - struct dirent * d; - - if (!(dir = opendir(file))) { - log_message("error opening %s: %d", file, errno); - return RETURN_ERROR; - } - while ((d = readdir(dir))) { - if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, "..")) - continue; - - strcpy(strBuf, file); - strcat(strBuf, "/"); - strcat(strBuf, d->d_name); - - if (recursiveRemove(strBuf) != 0) { - closedir(dir); - return RETURN_ERROR; - } - } - closedir(dir); - - if (rmdir(file)) { - log_message("failed to rmdir %s: %d", file, errno); - return RETURN_ERROR; - } - } else { - if (unlink(file) != 0) { - log_message("failed to remove %s: %d", file, errno); - return RETURN_ERROR; - } - } - return RETURN_OK; + struct stat sb; + + if (lstat(file, &sb) != 0) { + log_message("failed to stat %s: %d", file, errno); + return RETURN_ERROR; + } + + /* only descend into subdirectories if device is same as dir */ + if (S_ISDIR(sb.st_mode)) { + char * strBuf = alloca(strlen(file) + 1024); + DIR * dir; + struct dirent * d; + + if (!(dir = opendir(file))) { + log_message("error opening %s: %d", file, errno); + return RETURN_ERROR; + } + while ((d = readdir(dir))) { + if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, "..")) + continue; + + strcpy(strBuf, file); + strcat(strBuf, "/"); + strcat(strBuf, d->d_name); + + if (recursiveRemove(strBuf) != 0) { + closedir(dir); + return RETURN_ERROR; + } + } + closedir(dir); + + if (rmdir(file)) { + log_message("failed to rmdir %s: %d", file, errno); + return RETURN_ERROR; + } + } else { + if (unlink(file) != 0) { + log_message("failed to remove %s: %d", file, errno); + return RETURN_ERROR; + } + } + return RETURN_OK; } enum return_type recursiveRemove_if_it_exists(char *file) { - struct stat sb; + struct stat sb; - if (lstat(file, &sb) != 0) { - /* if file doesn't exist, simply return OK */ - return RETURN_OK; - } + if (lstat(file, &sb) != 0) { + /* if file doesn't exist, simply return OK */ + return RETURN_OK; + } - return recursiveRemove(file); + return recursiveRemove(file); } enum return_type mount_compressed_image(char *compressed_image, char *location_mount) { - if (lomount(compressed_image, location_mount, NULL, 1)) { + if (lomount(compressed_image, location_mount, NULL, 1)) { stg1_error_message("Could not mount compressed loopback :(."); return RETURN_ERROR; } - return RETURN_OK; + return RETURN_OK; } enum return_type preload_mount_compressed_fd(int compressed_fd, int image_size, char *image_name, char *location_mount) { - int ret; - char *compressed_tmpfs = asprintf_("/tmp/%s", image_name); - char *buf = "Loading program into memory..."; - init_progression(buf, image_size); - ret = save_fd(compressed_fd, compressed_tmpfs, update_progression); - end_progression(); - if (ret != RETURN_OK) - return ret; - - return mount_compressed_image(compressed_tmpfs, location_mount); + int ret; + char *compressed_tmpfs = asprintf_("/tmp/%s", image_name); + char *buf = "Loading program into memory..."; + init_progression(buf, image_size); + ret = save_fd(compressed_fd, compressed_tmpfs, update_progression); + end_progression(); + if (ret != RETURN_OK) + return ret; + + return mount_compressed_image(compressed_tmpfs, location_mount); } enum return_type mount_compressed_image_may_preload(char *image_name, char *location_mount, int preload) { - char *compressed_image = asprintf_("%s/%s", COMPRESSED_LOCATION, image_name); + char *compressed_image = asprintf_("%s/%s", COMPRESSED_LOCATION, image_name); - log_message("mount_compressed_may_preload: %s into %s (preload = %d)", compressed_image, location_mount, preload); + log_message("mount_compressed_may_preload: %s into %s (preload = %d)", compressed_image, location_mount, preload); if (access(compressed_image, R_OK) != 0) return RETURN_ERROR; if (preload) { - int compressed_fd = open(compressed_image, O_RDONLY); - if (compressed_fd != -1) { - return preload_mount_compressed_fd(compressed_fd, file_size(compressed_image), image_name, location_mount); - } else { - log_perror(compressed_image); - return RETURN_ERROR; - } - } else { - return mount_compressed_image(compressed_image, location_mount); - } + int compressed_fd = open(compressed_image, O_RDONLY); + if (compressed_fd != -1) { + return preload_mount_compressed_fd(compressed_fd, file_size(compressed_image), image_name, location_mount); + } else { + log_perror(compressed_image); + return RETURN_ERROR; + } + } else { + return mount_compressed_image(compressed_image, location_mount); + } } enum return_type may_load_compressed_image(void) { - if (!IS_RESCUE && access(IMAGE_LOCATION "/" LIVE_LOCATION_REL, R_OK) == 0) { - /* LIVE install */ - return RETURN_OK; - } else { - /* compressed install */ - return mount_compressed_image_may_preload(COMPRESSED_NAME(""), STAGE2_LOCATION, compressed_image_preload()); - } + if (!IS_RESCUE && access(IMAGE_LOCATION "/" LIVE_LOCATION_REL, R_OK) == 0) { + /* LIVE install */ + return RETURN_OK; + } else { + /* compressed install */ + return mount_compressed_image_may_preload(COMPRESSED_NAME(""), STAGE2_LOCATION, compressed_image_preload()); + } } enum return_type load_compressed_fd(int fd, int size) { - return preload_mount_compressed_fd(fd, size, COMPRESSED_NAME(""), STAGE2_LOCATION); + return preload_mount_compressed_fd(fd, size, COMPRESSED_NAME(""), STAGE2_LOCATION); } -// FIXME: guess right module from partition type (using libblkid?) int try_mount(char * dev, char * location) { - char device_fullname[50]; - snprintf(device_fullname, sizeof(device_fullname), "/dev/%s", dev); - - if (my_mount(device_fullname, location, "ext4", 0) == -1 && - my_mount(device_fullname, location, "btrfs", 0) == -1 && - my_mount(device_fullname, location, "vfat", 0) == -1 && - my_mount(device_fullname, location, "ntfs", 0) == -1 && - my_mount(device_fullname, location, "reiserfs", 0) == -1 && - my_mount(device_fullname, location, "reiser4", 0) == -1 && - my_mount(device_fullname, location, "jfs", 0) == -1 && - my_mount(device_fullname, location, "xfs", 0) == -1 && - my_mount(device_fullname, location, "iso9660", 0) == -1) { + char device_fullname[50]; + snprintf(device_fullname, sizeof(device_fullname), "/dev/%s", dev); + + if (my_mount(device_fullname, location, "ext4", 0) == -1 && + my_mount(device_fullname, location, "btrfs", 0) == -1 && + my_mount(device_fullname, location, "vfat", 0) == -1 && + my_mount(device_fullname, location, "ntfs", 0) == -1 && + my_mount(device_fullname, location, "reiserfs", 0) == -1 && + my_mount(device_fullname, location, "reiser4", 0) == -1 && + my_mount(device_fullname, location, "jfs", 0) == -1 && + my_mount(device_fullname, location, "xfs", 0) == -1 && + my_mount(device_fullname, location, "iso9660", 0) == -1) { return 1; } @@ -291,19 +290,19 @@ int try_mount(char * dev, char * location) #ifndef DISABLE_DISK int get_disks(char *** names, char *** models) { - char ** ptr; - int count = 0; + char ** ptr; + int count = 0; - my_insmod("ide_disk", ANY_DRIVER_TYPE, NULL, 0); - my_insmod("sd_mod", ANY_DRIVER_TYPE, NULL, 0); + my_insmod("ide_disk", ANY_DRIVER_TYPE, NULL, 0); + my_insmod("sd_mod", ANY_DRIVER_TYPE, NULL, 0); - get_medias(DISK, names, models, BUS_ANY); + get_medias(DISK, names, models, BUS_ANY); - ptr = *names; - while (ptr && *ptr) { - count++; - ptr++; - } + ptr = *names; + while (ptr && *ptr) { + count++; + ptr++; + } return count; } @@ -312,21 +311,21 @@ int get_disks(char *** names, char *** models) #ifndef DISABLE_CDROM int get_cdroms(char *** names, char *** models) { - char ** ptr; - int count = 0; + char ** ptr; + int count = 0; - my_insmod("ide_cd_mod", ANY_DRIVER_TYPE, NULL, 0); - my_insmod("sr_mod", ANY_DRIVER_TYPE, NULL, 0); + my_insmod("ide_cd_mod", ANY_DRIVER_TYPE, NULL, 0); + my_insmod("sr_mod", ANY_DRIVER_TYPE, NULL, 0); - get_medias(CDROM, names, models, BUS_ANY); + get_medias(CDROM, names, models, BUS_ANY); - ptr = *names; - while (ptr && *ptr) { - count++; - ptr++; - } + ptr = *names; + while (ptr && *ptr) { + count++; + ptr++; + } - return count; + return count; } #endif @@ -334,7 +333,7 @@ char * floppy_device(void) { char ** names, ** models; int fd; - my_insmod("floppy", ANY_DRIVER_TYPE, NULL, 0); + my_insmod("floppy", ANY_DRIVER_TYPE, NULL, 0); fd = open("/dev/fd0", O_RDONLY|O_NONBLOCK); if (fd != -1) { char drivtyp[17]; @@ -355,8 +354,8 @@ char * floppy_device(void) } log_message("seems that you don't have a regular floppy drive"); my_insmod("sd_mod", ANY_DRIVER_TYPE, NULL, 0); - get_medias(FLOPPY, &names, &models, BUS_ANY); - if (names && *names) + get_medias(FLOPPY, &names, &models, BUS_ANY); + if (names && *names) return asprintf_("/dev/%s", *names); else return NULL; diff --git a/mdk-stage1/url.c b/mdk-stage1/url.c index 3d2846649..305f5ce0f 100644 --- a/mdk-stage1/url.c +++ b/mdk-stage1/url.c @@ -58,503 +58,503 @@ static int ftp_check_response(int sock, char ** str) { - static char buf[BUFFER_SIZE + 1]; - int bufLength = 0; - struct pollfd polls; - char * chptr, * start; - int bytesRead, rc = 0; - int doesContinue = 1; - char errorCode[4]; + static char buf[BUFFER_SIZE + 1]; + int bufLength = 0; + struct pollfd polls; + char * chptr, * start; + int bytesRead, rc = 0; + int doesContinue = 1; + char errorCode[4]; - errorCode[0] = '\0'; + errorCode[0] = '\0'; - do { - polls.fd = sock; - polls.events = POLLIN; - if (poll(&polls, 1, TIMEOUT_SECS*1000) != 1) - return FTPERR_BAD_SERVER_RESPONSE; - - bytesRead = read(sock, buf + bufLength, sizeof(buf) - bufLength - 1); - - bufLength += bytesRead; - - buf[bufLength] = '\0'; - - /* divide the response into lines, checking each one to see if - we are finished or need to continue */ - - start = chptr = buf; - - do { - while (*chptr != '\n' && *chptr) chptr++; - - if (*chptr == '\n') { - *chptr = '\0'; - if (*(chptr - 1) == '\r') *(chptr - 1) = '\0'; - if (str) *str = start; - - if (errorCode[0]) { - if (!strncmp(start, errorCode, 3) && start[3] == ' ') - doesContinue = 0; - } else { - strncpy(errorCode, start, 3); - errorCode[3] = '\0'; - if (start[3] != '-') { - doesContinue = 0; - } - } - - start = chptr + 1; - chptr++; - } else { - chptr++; - } - } while (*chptr); - - if (doesContinue && chptr > start) { - memcpy(buf, start, chptr - start - 1); - bufLength = chptr - start - 1; - } else { - bufLength = 0; - } - } while (doesContinue); - - if (*errorCode == '4' || *errorCode == '5') { - if (!strncmp(errorCode, "550", 3)) { - return FTPERR_FILE_NOT_FOUND; - } - - return FTPERR_BAD_SERVER_RESPONSE; - } - - if (rc) return rc; - - return 0; + do { + polls.fd = sock; + polls.events = POLLIN; + if (poll(&polls, 1, TIMEOUT_SECS*1000) != 1) + return FTPERR_BAD_SERVER_RESPONSE; + + bytesRead = read(sock, buf + bufLength, sizeof(buf) - bufLength - 1); + + bufLength += bytesRead; + + buf[bufLength] = '\0'; + + /* divide the response into lines, checking each one to see if + we are finished or need to continue */ + + start = chptr = buf; + + do { + while (*chptr != '\n' && *chptr) chptr++; + + if (*chptr == '\n') { + *chptr = '\0'; + if (*(chptr - 1) == '\r') *(chptr - 1) = '\0'; + if (str) *str = start; + + if (errorCode[0]) { + if (!strncmp(start, errorCode, 3) && start[3] == ' ') + doesContinue = 0; + } else { + strncpy(errorCode, start, 3); + errorCode[3] = '\0'; + if (start[3] != '-') { + doesContinue = 0; + } + } + + start = chptr + 1; + chptr++; + } else { + chptr++; + } + } while (*chptr); + + if (doesContinue && chptr > start) { + memcpy(buf, start, chptr - start - 1); + bufLength = chptr - start - 1; + } else { + bufLength = 0; + } + } while (doesContinue); + + if (*errorCode == '4' || *errorCode == '5') { + if (!strncmp(errorCode, "550", 3)) { + return FTPERR_FILE_NOT_FOUND; + } + + return FTPERR_BAD_SERVER_RESPONSE; + } + + if (rc) return rc; + + return 0; } static int ftp_command(int sock, char * command, char * param) { - char buf[500]; - int rc; + char buf[500]; + int rc; - snprintf(buf, sizeof(buf), "%s%s%s\r\n", command, param ? " " : "", param ? param : ""); + snprintf(buf, sizeof(buf), "%s%s%s\r\n", command, param ? " " : "", param ? param : ""); - if (write(sock, buf, strlen(buf)) != (ssize_t)strlen(buf)) { - return FTPERR_SERVER_IO_ERROR; - } + if (write(sock, buf, strlen(buf)) != (ssize_t)strlen(buf)) { + return FTPERR_SERVER_IO_ERROR; + } - if ((rc = ftp_check_response(sock, NULL))) - return rc; + if ((rc = ftp_check_response(sock, NULL))) + return rc; - return 0; + return 0; } static int get_host_address(char * host, struct in_addr * address) { - if (isdigit(host[0])) { - if (!inet_aton(host, address)) { - return FTPERR_BAD_HOST_ADDR; - } - } else { - if (mygethostbyname(host, address)) - return FTPERR_BAD_HOSTNAME; - } + if (isdigit(host[0])) { + if (!inet_aton(host, address)) { + return FTPERR_BAD_HOST_ADDR; + } + } else { + if (mygethostbyname(host, address)) + return FTPERR_BAD_HOSTNAME; + } - return 0; + return 0; } int ftp_open_connection(char * host, char * name, char * password, char * proxy) { - int sock; - struct in_addr serverAddress; - struct sockaddr_in destPort; - int rc; - int port = 21; - - if (!strcmp(name, "")) { - name = "anonymous"; - password = "-drakx@"; - } - - if (strcmp(proxy, "")) { - name = asprintf_("%s@%s", name, host); - host = proxy; - } - - if ((rc = get_host_address(host, &serverAddress))) return rc; - - sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); - if (sock < 0) { - return FTPERR_FAILED_CONNECT; - } - - destPort.sin_family = AF_INET; - destPort.sin_port = htons(port); - destPort.sin_addr = serverAddress; - - if (connect(sock, (struct sockaddr *) &destPort, sizeof(destPort))) { - close(sock); - return FTPERR_FAILED_CONNECT; - } - - /* ftpCheckResponse() assumes the socket is nonblocking */ - if (fcntl(sock, F_SETFL, O_NONBLOCK)) { - close(sock); - return FTPERR_FAILED_CONNECT; - } - - if ((rc = ftp_check_response(sock, NULL))) { - return rc; - } - - if ((rc = ftp_command(sock, "USER", name))) { - close(sock); - return rc; - } - - if ((rc = ftp_command(sock, "PASS", password))) { - close(sock); - return rc; - } - - if ((rc = ftp_command(sock, "TYPE", "I"))) { - close(sock); - return rc; - } - - return sock; + int sock; + struct in_addr serverAddress; + struct sockaddr_in destPort; + int rc; + int port = 21; + + if (!strcmp(name, "")) { + name = "anonymous"; + password = "-drakx@"; + } + + if (strcmp(proxy, "")) { + name = asprintf_("%s@%s", name, host); + host = proxy; + } + + if ((rc = get_host_address(host, &serverAddress))) return rc; + + sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); + if (sock < 0) { + return FTPERR_FAILED_CONNECT; + } + + destPort.sin_family = AF_INET; + destPort.sin_port = htons(port); + destPort.sin_addr = serverAddress; + + if (connect(sock, (struct sockaddr *) &destPort, sizeof(destPort))) { + close(sock); + return FTPERR_FAILED_CONNECT; + } + + /* ftpCheckResponse() assumes the socket is nonblocking */ + if (fcntl(sock, F_SETFL, O_NONBLOCK)) { + close(sock); + return FTPERR_FAILED_CONNECT; + } + + if ((rc = ftp_check_response(sock, NULL))) { + return rc; + } + + if ((rc = ftp_command(sock, "USER", name))) { + close(sock); + return rc; + } + + if ((rc = ftp_command(sock, "PASS", password))) { + close(sock); + return rc; + } + + if ((rc = ftp_command(sock, "TYPE", "I"))) { + close(sock); + return rc; + } + + return sock; } int ftp_data_command(int sock, char * command, char * param) { - int dataSocket; - struct sockaddr_in dataAddress; - int i, j; - char * passReply; - char * chptr; - char retrCommand[500]; - int rc; - - if (write(sock, "PASV\r\n", 6) != 6) { - return FTPERR_SERVER_IO_ERROR; - } - if ((rc = ftp_check_response(sock, &passReply))) - return FTPERR_PASSIVE_ERROR; - - chptr = passReply; - while (*chptr && *chptr != '(') chptr++; - if (*chptr != '(') return FTPERR_PASSIVE_ERROR; - chptr++; - passReply = chptr; - while (*chptr && *chptr != ')') chptr++; - if (*chptr != ')') return FTPERR_PASSIVE_ERROR; - *chptr-- = '\0'; - - while (*chptr && *chptr != ',') chptr--; - if (*chptr != ',') return FTPERR_PASSIVE_ERROR; - chptr--; - while (*chptr && *chptr != ',') chptr--; - if (*chptr != ',') return FTPERR_PASSIVE_ERROR; - *chptr++ = '\0'; + int dataSocket; + struct sockaddr_in dataAddress; + int i, j; + char * passReply; + char * chptr; + char retrCommand[500]; + int rc; + + if (write(sock, "PASV\r\n", 6) != 6) { + return FTPERR_SERVER_IO_ERROR; + } + if ((rc = ftp_check_response(sock, &passReply))) + return FTPERR_PASSIVE_ERROR; + + chptr = passReply; + while (*chptr && *chptr != '(') chptr++; + if (*chptr != '(') return FTPERR_PASSIVE_ERROR; + chptr++; + passReply = chptr; + while (*chptr && *chptr != ')') chptr++; + if (*chptr != ')') return FTPERR_PASSIVE_ERROR; + *chptr-- = '\0'; + + while (*chptr && *chptr != ',') chptr--; + if (*chptr != ',') return FTPERR_PASSIVE_ERROR; + chptr--; + while (*chptr && *chptr != ',') chptr--; + if (*chptr != ',') return FTPERR_PASSIVE_ERROR; + *chptr++ = '\0'; - /* now passReply points to the IP portion, and chptr points to the - port number portion */ - - dataAddress.sin_family = AF_INET; - if (sscanf(chptr, "%d,%d", &i, &j) != 2) { - return FTPERR_PASSIVE_ERROR; - } - dataAddress.sin_port = htons((i << 8) + j); - - chptr = passReply; - while (*chptr++) { - if (*chptr == ',') *chptr = '.'; - } - - if (!inet_aton(passReply, &dataAddress.sin_addr)) - return FTPERR_PASSIVE_ERROR; - - dataSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); - if (dataSocket < 0) { - return FTPERR_FAILED_CONNECT; - } - - if (!param) - sprintf(retrCommand, "%s\r\n", command); - else - sprintf(retrCommand, "%s %s\r\n", command, param); - - i = strlen(retrCommand); + /* now passReply points to the IP portion, and chptr points to the + port number portion */ + + dataAddress.sin_family = AF_INET; + if (sscanf(chptr, "%d,%d", &i, &j) != 2) { + return FTPERR_PASSIVE_ERROR; + } + dataAddress.sin_port = htons((i << 8) + j); + + chptr = passReply; + while (*chptr++) { + if (*chptr == ',') *chptr = '.'; + } + + if (!inet_aton(passReply, &dataAddress.sin_addr)) + return FTPERR_PASSIVE_ERROR; + + dataSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); + if (dataSocket < 0) { + return FTPERR_FAILED_CONNECT; + } + + if (!param) + sprintf(retrCommand, "%s\r\n", command); + else + sprintf(retrCommand, "%s %s\r\n", command, param); + + i = strlen(retrCommand); - if (write(sock, retrCommand, i) != i) { - return FTPERR_SERVER_IO_ERROR; - } - - if (connect(dataSocket, (struct sockaddr *) &dataAddress, - sizeof(dataAddress))) { - close(dataSocket); - return FTPERR_FAILED_DATA_CONNECT; - } - - if ((rc = ftp_check_response(sock, NULL))) { - close(dataSocket); - return rc; - } - - return dataSocket; + if (write(sock, retrCommand, i) != i) { + return FTPERR_SERVER_IO_ERROR; + } + + if (connect(dataSocket, (struct sockaddr *) &dataAddress, + sizeof(dataAddress))) { + close(dataSocket); + return FTPERR_FAILED_DATA_CONNECT; + } + + if ((rc = ftp_check_response(sock, NULL))) { + close(dataSocket); + return rc; + } + + return dataSocket; } int ftp_get_filesize(int sock, char * remotename) { - int size = 0; - char buf[2000]; - char file[500]; - char * ptr; - int fd, rc, tot; - int i; - - strcpy(buf, remotename); - ptr = strrchr(buf, '/'); - if (!*ptr) - return -1; - *ptr = '\0'; - - strcpy(file, ptr+1); - - if ((rc = ftp_command(sock, "CWD", buf))) { - return -1; - } - - fd = ftp_data_command(sock, "LIST", file); - if (fd <= 0) { - close(sock); - return -1; - } - - ptr = buf; - while ((tot = read(fd, ptr, sizeof(buf) - (ptr - buf) - 1)) != 0) - ptr += tot; - *ptr = '\0'; - close(fd); - - if (!(ptr = strstr(buf, file))) { - log_message("FTP/get_filesize: Bad mood, directory does not contain searched file (%s)", file); - if (ftp_end_data_command(sock)) - close(sock); - return -1; - } - - for (i=0; i<4; i++) { - while (*ptr && *ptr != ' ') - ptr--; - while (*ptr && *ptr == ' ') - ptr--; - } - while (*ptr && *ptr != ' ') - ptr--; - - if (ptr) - size = charstar_to_int(ptr+1); - else - size = 0; - - if (ftp_end_data_command(sock)) { - close(sock); - return -1; - } - - return size; + int size = 0; + char buf[2000]; + char file[500]; + char * ptr; + int fd, rc, tot; + int i; + + strcpy(buf, remotename); + ptr = strrchr(buf, '/'); + if (!*ptr) + return -1; + *ptr = '\0'; + + strcpy(file, ptr+1); + + if ((rc = ftp_command(sock, "CWD", buf))) { + return -1; + } + + fd = ftp_data_command(sock, "LIST", file); + if (fd <= 0) { + close(sock); + return -1; + } + + ptr = buf; + while ((tot = read(fd, ptr, sizeof(buf) - (ptr - buf) - 1)) != 0) + ptr += tot; + *ptr = '\0'; + close(fd); + + if (!(ptr = strstr(buf, file))) { + log_message("FTP/get_filesize: Bad mood, directory does not contain searched file (%s)", file); + if (ftp_end_data_command(sock)) + close(sock); + return -1; + } + + for (i=0; i<4; i++) { + while (*ptr && *ptr != ' ') + ptr--; + while (*ptr && *ptr == ' ') + ptr--; + } + while (*ptr && *ptr != ' ') + ptr--; + + if (ptr) + size = charstar_to_int(ptr+1); + else + size = 0; + + if (ftp_end_data_command(sock)) { + close(sock); + return -1; + } + + return size; } int ftp_start_download(int sock, char * remotename, int * size) { - if ((*size = ftp_get_filesize(sock, remotename)) == -1) { - log_message("FTP: could not get filesize (trying to continue)"); - *size = 0; - } - return ftp_data_command(sock, "RETR", remotename); + if ((*size = ftp_get_filesize(sock, remotename)) == -1) { + log_message("FTP: could not get filesize (trying to continue)"); + *size = 0; + } + return ftp_data_command(sock, "RETR", remotename); } int ftp_end_data_command(int sock) { - if (ftp_check_response(sock, NULL)) - return FTPERR_BAD_SERVER_RESPONSE; - - return 0; + if (ftp_check_response(sock, NULL)) + return FTPERR_BAD_SERVER_RESPONSE; + + return 0; } char *str_ftp_error(int error) { - return error == FTPERR_PASSIVE_ERROR ? "error with passive connection" : - error == FTPERR_FAILED_CONNECT ? "couldn't connect to server" : - error == FTPERR_FILE_NOT_FOUND ? "file not found" : - error == FTPERR_BAD_SERVER_RESPONSE ? "bad server response (server too busy?)" : - NULL; + return error == FTPERR_PASSIVE_ERROR ? "error with passive connection" : + error == FTPERR_FAILED_CONNECT ? "couldn't connect to server" : + error == FTPERR_FILE_NOT_FOUND ? "file not found" : + error == FTPERR_BAD_SERVER_RESPONSE ? "bad server response (server too busy?)" : + NULL; } static int _http_download_file(char * hostname, char * remotename, int * size, char * proxyprotocol, char * proxyname, char * proxyport, int recursion) { - char * buf; - char headers[4096]; - char * nextChar = headers; - int statusCode; - struct in_addr serverAddress; - struct pollfd polls; - int sock; - int rc; - struct sockaddr_in destPort; - const char * header_content_length = "Content-Length: "; - const char * header_location = "Location: http://"; - char * http_server_name; - int http_server_port; - - if (proxyprotocol) { - http_server_name = proxyname; - http_server_port = atoi(proxyport); - } else { - http_server_name = hostname; - http_server_port = 80; - } - - log_message("HTTP: connecting to server %s:%i (%s)", - http_server_name, http_server_port, - proxyprotocol ? "proxy" : "no proxy"); - - if ((rc = get_host_address(http_server_name, &serverAddress))) return rc; - - sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); - if (sock < 0) { - return FTPERR_FAILED_CONNECT; - } - - destPort.sin_family = AF_INET; - destPort.sin_port = htons(http_server_port); - destPort.sin_addr = serverAddress; - - if (connect(sock, (struct sockaddr *) &destPort, sizeof(destPort))) { - close(sock); - return FTPERR_FAILED_CONNECT; - } + char * buf; + char headers[4096]; + char * nextChar = headers; + int statusCode; + struct in_addr serverAddress; + struct pollfd polls; + int sock; + int rc; + struct sockaddr_in destPort; + const char * header_content_length = "Content-Length: "; + const char * header_location = "Location: http://"; + char * http_server_name; + int http_server_port; + + if (proxyprotocol) { + http_server_name = proxyname; + http_server_port = atoi(proxyport); + } else { + http_server_name = hostname; + http_server_port = 80; + } + + log_message("HTTP: connecting to server %s:%i (%s)", + http_server_name, http_server_port, + proxyprotocol ? "proxy" : "no proxy"); + + if ((rc = get_host_address(http_server_name, &serverAddress))) return rc; + + sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); + if (sock < 0) { + return FTPERR_FAILED_CONNECT; + } + + destPort.sin_family = AF_INET; + destPort.sin_port = htons(http_server_port); + destPort.sin_addr = serverAddress; + + if (connect(sock, (struct sockaddr *) &destPort, sizeof(destPort))) { + close(sock); + return FTPERR_FAILED_CONNECT; + } buf = proxyprotocol ? asprintf_("GET %s://%s%s HTTP/1.0\r\nHost: %s\r\n\r\n", proxyprotocol, hostname, remotename, hostname) : asprintf_("GET %s HTTP/1.0\r\nHost: %s\r\n\r\n", remotename, hostname); - write(sock, buf, strlen(buf)); - - /* This is fun; read the response a character at a time until we: - - 1) Get our first \r\n; which lets us check the return code - 2) Get a \r\n\r\n, which means we're done */ - - *nextChar = '\0'; - statusCode = 0; - while (!strstr(headers, "\r\n\r\n")) { - polls.fd = sock; - polls.events = POLLIN; - rc = poll(&polls, 1, TIMEOUT_SECS*1000); - - if (rc == 0) { - close(sock); - return FTPERR_SERVER_TIMEOUT; - } else if (rc < 0) { - close(sock); - return FTPERR_SERVER_IO_ERROR; - } - - if (read(sock, nextChar, 1) != 1) { - close(sock); - return FTPERR_SERVER_IO_ERROR; - } - - nextChar++; - *nextChar = '\0'; - - if (nextChar - headers == sizeof(headers)) { - close(sock); - return FTPERR_SERVER_IO_ERROR; - } - - if (!statusCode && strstr(headers, "\r\n")) { - char * start, * end; - - start = headers; - while (!isspace(*start) && *start) start++; - if (!*start) { - close(sock); - return FTPERR_SERVER_IO_ERROR; - } - start++; - - end = start; - while (!isspace(*end) && *end) end++; - if (!*end) { - close(sock); - return FTPERR_SERVER_IO_ERROR; - } - - *end = '\0'; + write(sock, buf, strlen(buf)); + + /* This is fun; read the response a character at a time until we: + + 1) Get our first \r\n; which lets us check the return code + 2) Get a \r\n\r\n, which means we're done */ + + *nextChar = '\0'; + statusCode = 0; + while (!strstr(headers, "\r\n\r\n")) { + polls.fd = sock; + polls.events = POLLIN; + rc = poll(&polls, 1, TIMEOUT_SECS*1000); + + if (rc == 0) { + close(sock); + return FTPERR_SERVER_TIMEOUT; + } else if (rc < 0) { + close(sock); + return FTPERR_SERVER_IO_ERROR; + } + + if (read(sock, nextChar, 1) != 1) { + close(sock); + return FTPERR_SERVER_IO_ERROR; + } + + nextChar++; + *nextChar = '\0'; + + if (nextChar - headers == sizeof(headers)) { + close(sock); + return FTPERR_SERVER_IO_ERROR; + } + + if (!statusCode && strstr(headers, "\r\n")) { + char * start, * end; + + start = headers; + while (!isspace(*start) && *start) start++; + if (!*start) { + close(sock); + return FTPERR_SERVER_IO_ERROR; + } + start++; + + end = start; + while (!isspace(*end) && *end) end++; + if (!*end) { + close(sock); + return FTPERR_SERVER_IO_ERROR; + } + + *end = '\0'; log_message("HTTP: server response '%s'", start); - if (streq(start, "404")) { - close(sock); - return FTPERR_FILE_NOT_FOUND; - } else if (streq(start, "302")) { - log_message("HTTP: found, but document has moved"); - statusCode = 302; - } else if (streq(start, "200")) { - statusCode = 200; - } else { - close(sock); - return FTPERR_BAD_SERVER_RESPONSE; - } - - *end = ' '; - } - } - - if (statusCode == 302) { - if (recursion >= HTTP_MAX_RECURSION) { - log_message("HTTP: too many levels of recursion, aborting"); - close(sock); - return FTPERR_UNKNOWN; - } - if ((buf = strstr(headers, header_location))) { - char * found_host; - char *found_file; - found_host = buf + strlen(header_location); - if ((found_file = index(found_host, '/'))) { - if ((buf = index(found_file, '\r'))) { - buf[0] = '\0'; - remotename = strdup(found_file); - found_file[0] = '\0'; - hostname = strdup(found_host); - log_message("HTTP: redirected to new host \"%s\" and file \"%s\"", hostname, remotename); - } - } - - } - /* - * don't fail if new URL can't be parsed, - * asking the same URL may work if the DNS server are doing round-robin - */ - return _http_download_file(hostname, remotename, size, proxyprotocol, proxyname, proxyport, recursion + 1); - } - - if ((buf = strstr(headers, header_content_length))) - *size = charstar_to_int(buf + strlen(header_content_length)); - else - *size = 0; - - return sock; + if (streq(start, "404")) { + close(sock); + return FTPERR_FILE_NOT_FOUND; + } else if (streq(start, "302")) { + log_message("HTTP: found, but document has moved"); + statusCode = 302; + } else if (streq(start, "200")) { + statusCode = 200; + } else { + close(sock); + return FTPERR_BAD_SERVER_RESPONSE; + } + + *end = ' '; + } + } + + if (statusCode == 302) { + if (recursion >= HTTP_MAX_RECURSION) { + log_message("HTTP: too many levels of recursion, aborting"); + close(sock); + return FTPERR_UNKNOWN; + } + if ((buf = strstr(headers, header_location))) { + char * found_host; + char *found_file; + found_host = buf + strlen(header_location); + if ((found_file = index(found_host, '/'))) { + if ((buf = index(found_file, '\r'))) { + buf[0] = '\0'; + remotename = strdup(found_file); + found_file[0] = '\0'; + hostname = strdup(found_host); + log_message("HTTP: redirected to new host \"%s\" and file \"%s\"", hostname, remotename); + } + } + + } + /* + * don't fail if new URL can't be parsed, + * asking the same URL may work if the DNS server are doing round-robin + */ + return _http_download_file(hostname, remotename, size, proxyprotocol, proxyname, proxyport, recursion + 1); + } + + if ((buf = strstr(headers, header_content_length))) + *size = charstar_to_int(buf + strlen(header_content_length)); + else + *size = 0; + + return sock; } int http_download_file(char * hostname, char * remotename, int * size, char * proxyprotocol, char * proxyname, char * proxyport) { - return _http_download_file(hostname, remotename, size, proxyprotocol, proxyname, proxyport, 0); + return _http_download_file(hostname, remotename, size, proxyprotocol, proxyname, proxyport, 0); } diff --git a/mdk-stage1/utils.c b/mdk-stage1/utils.c index af5ee9af3..dc71b6a43 100644 --- a/mdk-stage1/utils.c +++ b/mdk-stage1/utils.c @@ -31,73 +31,73 @@ // - it stops on first non-digit char int charstar_to_int(const char * s) { - int number = 0; - while (*s && isdigit(*s)) { - number = (number * 10) + (*s - '0'); - s++; - } - return number; + int number = 0; + while (*s && isdigit(*s)) { + number = (number * 10) + (*s - '0'); + s++; + } + return number; } off_t file_size(const char * path) { - struct stat statr; - if (stat(path, &statr)) - return -1; + struct stat statr; + if (stat(path, &statr)) + return -1; else return statr.st_size; } char * cat_file(const char * file, struct stat * s) { - char * buf; - int fd = open(file, O_RDONLY); - if (fd == -1) { - log_perror(file); - return NULL; - } - - fstat(fd, s); - buf = malloc(s->st_size + 1); - if (read(fd, buf, s->st_size) != (ssize_t)s->st_size) { - close(fd); - free(buf); - log_perror(file); - return NULL; - } - buf[s->st_size] = '\0'; - close(fd); - - return buf; + char * buf; + int fd = open(file, O_RDONLY); + if (fd == -1) { + log_perror(file); + return NULL; + } + + fstat(fd, s); + buf = malloc(s->st_size + 1); + if (read(fd, buf, s->st_size) != (ssize_t)s->st_size) { + close(fd); + free(buf); + log_perror(file); + return NULL; + } + buf[s->st_size] = '\0'; + close(fd); + + return buf; } int line_counts(const char * buf) { - const char * ptr = buf; - int line = 0; - while (ptr) { - line++; - ptr = strchr(ptr + 1, '\n'); - } - return line; + const char * ptr = buf; + int line = 0; + while (ptr) { + line++; + ptr = strchr(ptr + 1, '\n'); + } + return line; } int total_memory(void) { - int value; + int value; - /* drakx powered: use /proc/kcore and rounds every 4 Mbytes */ - value = 4 * ((int)((float)file_size("/proc/kcore") / 1024 / 1024 / 4 + 0.5)); - log_message("Total Memory: %d Mbytes", value); + /* drakx powered: use /proc/kcore and rounds every 4 Mbytes */ + value = 4 * ((int)((float)file_size("/proc/kcore") / 1024 / 1024 / 4 + 0.5)); + log_message("Total Memory: %d Mbytes", value); - return value; + return value; } /* pixel's */ void * _memdup(void *src, size_t size) { - void * r; - r = malloc(size); - memcpy(r, src, size); - return r; + void * r; + r = malloc(size); + memcpy(r, src, size); + return r; } @@ -115,33 +115,33 @@ void add_to_env(char * name, char * value) char ** list_directory(char * direct) { - char * tmp[50000]; /* in /dev there can be many many files.. */ - int i = 0; - struct dirent *ep; - DIR *dp = opendir(direct); - while (dp && (ep = readdir(dp))) { - if (strcmp(ep->d_name, ".") && strcmp(ep->d_name, "..")) { - tmp[i] = strdup(ep->d_name); - i++; - } - } - if (dp) - closedir(dp); - tmp[i] = NULL; - return _memdup(tmp, sizeof(char*) * (i+1)); + char * tmp[50000]; /* in /dev there can be many many files.. */ + int i = 0; + struct dirent *ep; + DIR *dp = opendir(direct); + while (dp && (ep = readdir(dp))) { + if (strcmp(ep->d_name, ".") && strcmp(ep->d_name, "..")) { + tmp[i] = strdup(ep->d_name); + i++; + } + } + if (dp) + closedir(dp); + tmp[i] = NULL; + return _memdup(tmp, sizeof(char*) * (i+1)); } int string_array_length(char ** a) { - int i = 0; - if (!a) - return -1; - while (a && *a) { - a++; - i++; - } - return i; + int i = 0; + if (!a) + return -1; + while (a && *a) { + a++; + i++; + } + return i; } char * asprintf_(const char *msg, ...) @@ -164,7 +164,7 @@ char * asprintf_(const char *msg, ...) int scall_(int retval, char * msg, char * file, int line) { - char tmp[5000]; + char tmp[5000]; sprintf(tmp, "%s(%s:%d) failed", msg, file, line); if (retval) log_perror(tmp); diff --git a/mdk-stage1/wireless.c b/mdk-stage1/wireless.c index c9e363048..1004ed651 100644 --- a/mdk-stage1/wireless.c +++ b/mdk-stage1/wireless.c @@ -37,124 +37,124 @@ static int wireless_set_essid(int socket, const char *ifname, const char *essid) int wireless_open_socket() { - return socket(AF_INET, SOCK_DGRAM, 0); + return socket(AF_INET, SOCK_DGRAM, 0); } int wireless_close_socket(int socket) { - return close(socket); + return close(socket); } static int wireless_ioctl(int socket, const char *ifname, int request, struct iwreq *wrq) { - strncpy(wrq->ifr_name, ifname, IFNAMSIZ); - return ioctl(socket, request, wrq); + strncpy(wrq->ifr_name, ifname, IFNAMSIZ); + return ioctl(socket, request, wrq); } int wireless_is_aware(int socket, const char *ifname) { - struct iwreq wrq; - return wireless_ioctl(socket, ifname, SIOCGIWNAME, &wrq) == 0; + struct iwreq wrq; + return wireless_ioctl(socket, ifname, SIOCGIWNAME, &wrq) == 0; } static int wireless_set_mode_managed(int socket, const char *ifname) { - struct iwreq wrq; + struct iwreq wrq; - wrq.u.mode = IW_MODE_INFRA; /* managed */ + wrq.u.mode = IW_MODE_INFRA; /* managed */ - return wireless_ioctl(socket, ifname, SIOCSIWMODE, &wrq) == 0; + return wireless_ioctl(socket, ifname, SIOCSIWMODE, &wrq) == 0; } static int wireless_set_essid(int socket, const char *ifname, const char *essid) { - struct iwreq wrq; + struct iwreq wrq; - wrq.u.essid.flags = 1; - wrq.u.essid.pointer = (void *) essid; - wrq.u.essid.length = strlen(essid) + 1; + wrq.u.essid.flags = 1; + wrq.u.essid.pointer = (void *) essid; + wrq.u.essid.length = strlen(essid) + 1; - return wireless_ioctl(socket, ifname, SIOCSIWESSID, &wrq) == 0; + return wireless_ioctl(socket, ifname, SIOCSIWESSID, &wrq) == 0; } static int wireless_disable_key(int socket, const char *ifname) { - struct iwreq wrq; + struct iwreq wrq; - wrq.u.data.flags = IW_ENCODE_DISABLED; - wrq.u.data.pointer = NULL; - wrq.u.data.length = 0; + wrq.u.data.flags = IW_ENCODE_DISABLED; + wrq.u.data.pointer = NULL; + wrq.u.data.length = 0; - return wireless_ioctl(socket, ifname, SIOCSIWENCODE, &wrq) == 0; + return wireless_ioctl(socket, ifname, SIOCSIWENCODE, &wrq) == 0; } static int wireless_set_restricted_key(int socket, const char *ifname, const char *key) { - struct iwreq wrq; - char real_key[IW_ENCODING_TOKEN_MAX]; - int key_len = 0; - unsigned int tmp; + struct iwreq wrq; + char real_key[IW_ENCODING_TOKEN_MAX]; + int key_len = 0; + unsigned int tmp; - while (sscanf(key + 2*key_len, "%2X", &tmp) == 1) - real_key[key_len++] = (char) tmp; + while (sscanf(key + 2*key_len, "%2X", &tmp) == 1) + real_key[key_len++] = (char) tmp; - wrq.u.data.flags = IW_ENCODE_RESTRICTED; - wrq.u.data.pointer = (char *) real_key; - wrq.u.data.length = key_len; + wrq.u.data.flags = IW_ENCODE_RESTRICTED; + wrq.u.data.pointer = (char *) real_key; + wrq.u.data.length = key_len; - return wireless_ioctl(socket, ifname, SIOCSIWENCODE, &wrq) == 0; + return wireless_ioctl(socket, ifname, SIOCSIWENCODE, &wrq) == 0; } enum return_type configure_wireless(const char *ifname) { - enum return_type results; - char * questions[] = { "ESSID", "WEP key", NULL }; - char * questions_auto[] = { "essid", "wep_key" }; - static char ** answers = NULL; - int wsock = wireless_open_socket(); - - if (!wireless_is_aware(wsock, ifname)) { - log_message("interface %s doesn't support wireless", ifname); - wireless_close_socket(wsock); - return RETURN_OK; - } - - results = ask_from_entries_auto("Please enter your wireless settings. " + enum return_type results; + char * questions[] = { "ESSID", "WEP key", NULL }; + char * questions_auto[] = { "essid", "wep_key" }; + static char ** answers = NULL; + int wsock = wireless_open_socket(); + + if (!wireless_is_aware(wsock, ifname)) { + log_message("interface %s doesn't support wireless", ifname); + wireless_close_socket(wsock); + return RETURN_OK; + } + + results = ask_from_entries_auto("Please enter your wireless settings. " "The ESSID is your wireless network identifier. " "The WEP key must be entered in hexadecimal, without any separator.", - questions, &answers, 32, questions_auto, NULL); - if (results != RETURN_OK) { - wireless_close_socket(wsock); - return RETURN_BACK; - } - - if (!wireless_set_mode_managed(wsock, ifname)) { - stg1_error_message("unable to set mode Managed on device \"%s\": %s", ifname, strerror(errno)); - wireless_close_socket(wsock); - return RETURN_ERROR; - } - - if (answers[1] && !streq(answers[1], "")) { - log_message("setting WEP key \"%s\" on device \"%s\"", answers[1], ifname); - if (!wireless_set_restricted_key(wsock, ifname, answers[1])) { - stg1_error_message("unable to set WEP key \"%s\" on device \"%s\": %s", answers[1], ifname, strerror(errno)); - return RETURN_ERROR; - } - } else { - log_message("disabling WEP key on device \"%s\"", ifname); - if (!wireless_disable_key(wsock, ifname)) { - stg1_error_message("unable to disable WEP key on device \"%s\": %s", ifname, strerror(errno)); - return RETURN_ERROR; - } - } + questions, &answers, 32, questions_auto, NULL); + if (results != RETURN_OK) { + wireless_close_socket(wsock); + return RETURN_BACK; + } + + if (!wireless_set_mode_managed(wsock, ifname)) { + stg1_error_message("unable to set mode Managed on device \"%s\": %s", ifname, strerror(errno)); + wireless_close_socket(wsock); + return RETURN_ERROR; + } + + if (answers[1] && !streq(answers[1], "")) { + log_message("setting WEP key \"%s\" on device \"%s\"", answers[1], ifname); + if (!wireless_set_restricted_key(wsock, ifname, answers[1])) { + stg1_error_message("unable to set WEP key \"%s\" on device \"%s\": %s", answers[1], ifname, strerror(errno)); + return RETURN_ERROR; + } + } else { + log_message("disabling WEP key on device \"%s\"", ifname); + if (!wireless_disable_key(wsock, ifname)) { + stg1_error_message("unable to disable WEP key on device \"%s\": %s", ifname, strerror(errno)); + return RETURN_ERROR; + } + } /* most devices perform discovery when ESSID is set, it needs to be last */ - log_message("setting ESSID \"%s\" on device \"%s\"", answers[0], ifname); - if (!wireless_set_essid(wsock, ifname, answers[0])) { - stg1_error_message("unable to set ESSID \"%s\" on device \"%s\": %s", answers[0], ifname, strerror(errno)); - return RETURN_ERROR; - } - - wireless_close_socket(wsock); - return RETURN_OK; + log_message("setting ESSID \"%s\" on device \"%s\"", answers[0], ifname); + if (!wireless_set_essid(wsock, ifname, answers[0])) { + stg1_error_message("unable to set ESSID \"%s\" on device \"%s\": %s", answers[0], ifname, strerror(errno)); + return RETURN_ERROR; + } + + wireless_close_socket(wsock); + return RETURN_OK; } diff --git a/mdk-stage1/zlibsupport.c b/mdk-stage1/zlibsupport.c index 2b171e72d..e201b8217 100644 --- a/mdk-stage1/zlibsupport.c +++ b/mdk-stage1/zlibsupport.c @@ -23,270 +23,270 @@ #include <lzma.h> typedef struct lzma_file { - uint8_t buf[1<<14]; - lzma_stream strm; - FILE *fp; - lzma_bool eof; + uint8_t buf[1<<14]; + lzma_stream strm; + FILE *fp; + lzma_bool eof; } lzma_FILE; #else typedef unsigned char lzma_bool; -typedef int lzma_ret; -#define LZMA_OK 0 +typedef int lzma_ret; +#define LZMA_OK 0 #endif typedef enum xFile_e { - XF_NONE, - XF_GZIP, - XF_XZ, - XF_FAIL + XF_NONE, + XF_GZIP, + XF_XZ, + XF_FAIL } xFile_t; typedef struct xFile_s { - xFile_t type; - lzma_bool eof; - union { - gzFile gz; + xFile_t type; + lzma_bool eof; + union { + gzFile gz; #ifdef CONFIG_USE_LIBLZMA - lzma_FILE *xz; + lzma_FILE *xz; #endif - } f; - FILE *fp; + } f; + FILE *fp; } xFile; #ifdef CONFIG_USE_LIBLZMA static lzma_FILE *lzma_open(lzma_ret *lzma_error, FILE *fp) { - lzma_ret *ret = lzma_error; - lzma_FILE *lzma_file; - lzma_stream tmp = LZMA_STREAM_INIT; + lzma_ret *ret = lzma_error; + lzma_FILE *lzma_file; + lzma_stream tmp = LZMA_STREAM_INIT; - lzma_file = calloc(1, sizeof(*lzma_file)); + lzma_file = calloc(1, sizeof(*lzma_file)); - lzma_file->fp = fp; - lzma_file->eof = 0; - lzma_file->strm = tmp; + lzma_file->fp = fp; + lzma_file->eof = 0; + lzma_file->strm = tmp; - *ret = lzma_auto_decoder(&lzma_file->strm, -1, 0); + *ret = lzma_auto_decoder(&lzma_file->strm, -1, 0); - if (*ret != LZMA_OK) { - (void) fclose(lzma_file->fp); - free(lzma_file); - return NULL; - } - return lzma_file; + if (*ret != LZMA_OK) { + (void) fclose(lzma_file->fp); + free(lzma_file); + return NULL; + } + return lzma_file; } static ssize_t lzma_read(lzma_ret *lzma_error, lzma_FILE *lzma_file, void *buf, size_t len) { - lzma_ret *ret = lzma_error; - lzma_bool eof = 0; - - if (!lzma_file) - return -1; - if (lzma_file->eof) - return 0; - - lzma_file->strm.next_out = buf; - lzma_file->strm.avail_out = len; - for (;;) { - if (!lzma_file->strm.avail_in) { - lzma_file->strm.next_in = (uint8_t *)lzma_file->buf; - lzma_file->strm.avail_in = fread(lzma_file->buf, 1, sizeof(lzma_file->buf), lzma_file->fp); - if (!lzma_file->strm.avail_in) - eof = 1; - } - *ret = lzma_code(&lzma_file->strm, LZMA_RUN); - if (*ret == LZMA_STREAM_END) { - lzma_file->eof = 1; - return len - lzma_file->strm.avail_out; - } - if (*ret != LZMA_OK) - return -1; - if (!lzma_file->strm.avail_out) - return len; - if (eof) - return -1; - } + lzma_ret *ret = lzma_error; + lzma_bool eof = 0; + + if (!lzma_file) + return -1; + if (lzma_file->eof) + return 0; + + lzma_file->strm.next_out = buf; + lzma_file->strm.avail_out = len; + for (;;) { + if (!lzma_file->strm.avail_in) { + lzma_file->strm.next_in = (uint8_t *)lzma_file->buf; + lzma_file->strm.avail_in = fread(lzma_file->buf, 1, sizeof(lzma_file->buf), lzma_file->fp); + if (!lzma_file->strm.avail_in) + eof = 1; + } + *ret = lzma_code(&lzma_file->strm, LZMA_RUN); + if (*ret == LZMA_STREAM_END) { + lzma_file->eof = 1; + return len - lzma_file->strm.avail_out; + } + if (*ret != LZMA_OK) + return -1; + if (!lzma_file->strm.avail_out) + return len; + if (eof) + return -1; + } } #endif static xFile xOpen(int fd, const char *filename) { - xFile xF = {XF_FAIL, 0, {NULL}, NULL}; - lzma_ret ret = LZMA_OK; - unsigned char buf[8]; - - if (fd == -1 && filename != NULL) - if ((fd = open(filename, O_RDONLY)) < 0) - return xF; - if (read(fd, buf, sizeof(buf)) < 0) - return xF; - lseek(fd, 0, SEEK_SET); - if (filename != NULL) { - close(fd); - fd = -1; - } - if (buf[0] == 0xFD && buf[1] == '7' && buf[2] == 'z' && - buf[3] == 'X' && buf[4] == 'Z' && buf[5] == 0x00) - xF.type = XF_XZ; - else if (buf[0] == 0x1F && buf[1] == 0x8B) - xF.type = XF_GZIP; - else - xF.type = XF_NONE; - - switch(xF.type) { - case XF_GZIP: - xF.f.gz = (fd == -1 && filename != NULL) ? gzopen(filename, "rb") : gzdopen(fd, "rb"); - if(xF.f.gz == NULL) - xF.type = XF_FAIL; - break; - case XF_NONE: - xF.fp = (fd == -1 && filename != NULL) ? fopen(filename, "rb") : fdopen(fd, "rb"); - break; + xFile xF = {XF_FAIL, 0, {NULL}, NULL}; + lzma_ret ret = LZMA_OK; + unsigned char buf[8]; + + if (fd == -1 && filename != NULL) + if ((fd = open(filename, O_RDONLY)) < 0) + return xF; + if (read(fd, buf, sizeof(buf)) < 0) + return xF; + lseek(fd, 0, SEEK_SET); + if (filename != NULL) { + close(fd); + fd = -1; + } + if (buf[0] == 0xFD && buf[1] == '7' && buf[2] == 'z' && + buf[3] == 'X' && buf[4] == 'Z' && buf[5] == 0x00) + xF.type = XF_XZ; + else if (buf[0] == 0x1F && buf[1] == 0x8B) + xF.type = XF_GZIP; + else + xF.type = XF_NONE; + + switch(xF.type) { + case XF_GZIP: + xF.f.gz = (fd == -1 && filename != NULL) ? gzopen(filename, "rb") : gzdopen(fd, "rb"); + if(xF.f.gz == NULL) + xF.type = XF_FAIL; + break; + case XF_NONE: + xF.fp = (fd == -1 && filename != NULL) ? fopen(filename, "rb") : fdopen(fd, "rb"); + break; #ifdef CONFIG_USE_LIBLZMA - case XF_XZ: - xF.fp = (fd == -1 && filename != NULL) ? fopen(filename, "rb") : fdopen(fd, "rb"); - if(xF.fp == NULL) - xF.type = XF_FAIL; - if(xF.type == XF_NONE || xF.type == XF_FAIL) break; - xF.f.xz = lzma_open(&ret, xF.fp); - if(ret != LZMA_OK) - xF.type = XF_FAIL; - break; + case XF_XZ: + xF.fp = (fd == -1 && filename != NULL) ? fopen(filename, "rb") : fdopen(fd, "rb"); + if(xF.fp == NULL) + xF.type = XF_FAIL; + if(xF.type == XF_NONE || xF.type == XF_FAIL) break; + xF.f.xz = lzma_open(&ret, xF.fp); + if(ret != LZMA_OK) + xF.type = XF_FAIL; + break; #endif - default: - break; - } + default: + break; + } - return xF; + return xF; } static int xClose(xFile *xF) { - int ret = -1; - switch(xF->type) { - case XF_GZIP: - ret = gzclose(xF->f.gz); - break; + int ret = -1; + switch(xF->type) { + case XF_GZIP: + ret = gzclose(xF->f.gz); + break; #ifdef CONFIG_USE_LIBLZMA - case XF_XZ: - lzma_end(&xF->f.xz->strm); - free(xF->f.xz); + case XF_XZ: + lzma_end(&xF->f.xz->strm); + free(xF->f.xz); #endif - case XF_NONE: - ret = fclose(xF->fp); - break; - default: - break; - } - return ret; + case XF_NONE: + ret = fclose(xF->fp); + break; + default: + break; + } + return ret; } static ssize_t xRead(xFile *xF, lzma_ret *ret, void *buf, size_t len) { - ssize_t sz; - switch(xF->type) { - case XF_GZIP: - sz = gzread(xF->f.gz, buf, len); - xF->eof = gzeof(xF->f.gz); - break; + ssize_t sz; + switch(xF->type) { + case XF_GZIP: + sz = gzread(xF->f.gz, buf, len); + xF->eof = gzeof(xF->f.gz); + break; #ifdef CONFIG_USE_LIBLZMA - case XF_XZ: - sz = lzma_read(ret, xF->f.xz, buf, len); - xF->eof = xF->f.xz->eof; - break; + case XF_XZ: + sz = lzma_read(ret, xF->f.xz, buf, len); + xF->eof = xF->f.xz->eof; + break; #endif - case XF_NONE: - sz = fread(buf, 1, len, xF->fp); - xF->eof = feof(xF->fp); - break; - default: - sz = -1; - break; - } - return sz; + case XF_NONE: + sz = fread(buf, 1, len, xF->fp); + xF->eof = feof(xF->fp); + break; + default: + sz = -1; + break; + } + return sz; } void *grab_contents(xFile *xF, unsigned long *size) { - unsigned int max = 16384; - void *buffer = calloc(1, max); - lzma_ret ret; + unsigned int max = 16384; + void *buffer = calloc(1, max); + lzma_ret ret; - if (!buffer) - return NULL; + if (!buffer) + return NULL; - *size = 0; - while ((ret = xRead(xF, &ret, buffer + *size, max - *size)) > 0) { - *size += ret; - if (*size == max) { - void *p; + *size = 0; + while ((ret = xRead(xF, &ret, buffer + *size, max - *size)) > 0) { + *size += ret; + if (*size == max) { + void *p; - p = realloc(buffer, max *= 2); - if (!p) - goto out_err; + p = realloc(buffer, max *= 2); + if (!p) + goto out_err; - buffer = p; - } - } - if (ret < 0) - goto out_err; + buffer = p; + } + } + if (ret < 0) + goto out_err; - return buffer; + return buffer; out_err: - free(buffer); - return NULL; + free(buffer); + return NULL; } /* gzopen handles uncompressed files transparently. */ void *grab_file(const char *filename, unsigned long *size) { - xFile xF; - void *buffer; - - xF = xOpen(-1, filename); - if (xF.type == XF_FAIL) - return NULL; - buffer = grab_contents(&xF, size); - xClose(&xF); - return buffer; + xFile xF; + void *buffer; + + xF = xOpen(-1, filename); + if (xF.type == XF_FAIL) + return NULL; + buffer = grab_contents(&xF, size); + xClose(&xF); + return buffer; } void release_file(void *data, unsigned long size) { - free(data); + free(data); } #else /* ... !CONFIG_USE_ZLIB */ void *grab_fd(int fd, unsigned long *size) { - struct stat st; - void *map; - int ret; - - ret = fstat(fd, &st); - if (ret < 0) - return NULL; - *size = st.st_size; - map = mmap(0, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0); - if (map == MAP_FAILED) - map = NULL; - return map; + struct stat st; + void *map; + int ret; + + ret = fstat(fd, &st); + if (ret < 0) + return NULL; + *size = st.st_size; + map = mmap(0, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0); + if (map == MAP_FAILED) + map = NULL; + return map; } void *grab_file(const char *filename, unsigned long *size) { - int fd; - void *map; - - fd = open(filename, O_RDONLY, 0); - if (fd < 0) - return NULL; - map = grab_fd(fd, size); - close(fd); - return map; + int fd; + void *map; + + fd = open(filename, O_RDONLY, 0); + if (fd < 0) + return NULL; + map = grab_fd(fd, size); + close(fd); + return map; } void release_file(void *data, unsigned long size) { - munmap(data, size); + munmap(data, size); } #endif |