--- trunk/mkinitrd-magellan/grubby/grubby.c 2009/10/28 13:29:38 926 +++ trunk/grubby/grubby.c 2012/10/01 12:06:26 1931 @@ -36,7 +36,9 @@ #include #include +#ifndef DEBUG #define DEBUG 0 +#endif #if DEBUG #define dbgPrintf(format, args...) fprintf(stderr, format , ## args) @@ -44,11 +46,16 @@ #define dbgPrintf(format, args...) #endif +int debug = 0; /* Currently just for template debugging */ + #define _(A) (A) #define MAX_EXTRA_INITRDS 16 /* code segment checked by --bootloader-probe */ #define CODE_SEG_SIZE 128 /* code segment checked by --bootloader-probe */ +#define NOOP_OPCODE 0x90 +#define JMP_SHORT_OPCODE 0xeb + /* comments get lumped in with indention */ struct lineElement { char * item; @@ -56,22 +63,26 @@ }; enum lineType_e { - LT_WHITESPACE = 1 << 0, - LT_TITLE = 1 << 1, - LT_KERNEL = 1 << 2, - LT_INITRD = 1 << 3, - LT_HYPER = 1 << 4, - LT_DEFAULT = 1 << 5, - LT_MBMODULE = 1 << 6, - LT_ROOT = 1 << 7, - LT_FALLBACK = 1 << 8, - LT_KERNELARGS = 1 << 9, - LT_BOOT = 1 << 10, - LT_BOOTROOT = 1 << 11, - LT_LBA = 1 << 12, - LT_OTHER = 1 << 13, - LT_GENERIC = 1 << 14, - LT_UNKNOWN = 1 << 15, + LT_WHITESPACE = 1 << 0, + LT_TITLE = 1 << 1, + LT_KERNEL = 1 << 2, + LT_INITRD = 1 << 3, + LT_HYPER = 1 << 4, + LT_DEFAULT = 1 << 5, + LT_MBMODULE = 1 << 6, + LT_ROOT = 1 << 7, + LT_FALLBACK = 1 << 8, + LT_KERNELARGS = 1 << 9, + LT_BOOT = 1 << 10, + LT_BOOTROOT = 1 << 11, + LT_LBA = 1 << 12, + LT_OTHER = 1 << 13, + LT_GENERIC = 1 << 14, + LT_ECHO = 1 << 16, + LT_MENUENTRY = 1 << 17, + LT_ENTRY_END = 1 << 18, + LT_SET_VARIABLE = 1 << 19, + LT_UNKNOWN = 1 << 20, }; struct singleLine { @@ -99,9 +110,11 @@ #define NEED_TITLE (1 << 2) #define NEED_ARGS (1 << 3) #define NEED_MB (1 << 4) +#define NEED_END (1 << 5) #define MAIN_DEFAULT (1 << 0) #define DEFAULT_SAVED -2 +#define DEFAULT_SAVED_GRUB2 -3 struct keywordTypes { char * key; @@ -110,16 +123,27 @@ char separatorChar; }; +struct configFileInfo; + +typedef const char *(*findConfigFunc)(struct configFileInfo *); +typedef const int (*writeLineFunc)(struct configFileInfo *, + struct singleLine *line); + struct configFileInfo { char * defaultConfig; + findConfigFunc findConfig; + writeLineFunc writeLine; struct keywordTypes * keywords; int defaultIsIndex; + int defaultIsVariable; int defaultSupportSaved; - enum lineType_e entrySeparator; + enum lineType_e entryStart; + enum lineType_e entryEnd; int needsBootPrefix; int argsInQuotes; int maxTitleLength; int titleBracketed; + int titlePosition; int mbHyperFirst; int mbInitRdIsModule; int mbConcatArgs; @@ -138,20 +162,185 @@ { NULL, 0, 0 }, }; +const char *grubFindConfig(struct configFileInfo *cfi) { + static const char *configFiles[] = { + "/boot/grub/grub.conf", + "/boot/grub/menu.lst", + "/etc/grub.conf", + NULL + }; + static int i = -1; + + if (i == -1) { + for (i = 0; configFiles[i] != NULL; i++) { + dbgPrintf("Checking \"%s\": ", configFiles[i]); + if (!access(configFiles[i], R_OK)) { + dbgPrintf("found\n"); + return configFiles[i]; + } + dbgPrintf("not found\n"); + } + } + return configFiles[i]; +} + struct configFileInfo grubConfigType = { - "/boot/grub/grub.conf", /* defaultConfig */ - grubKeywords, /* keywords */ - 1, /* defaultIsIndex */ - 1, /* defaultSupportSaved */ - LT_TITLE, /* entrySeparator */ - 1, /* needsBootPrefix */ - 0, /* argsInQuotes */ - 0, /* maxTitleLength */ - 0, /* titleBracketed */ - 1, /* mbHyperFirst */ - 1, /* mbInitRdIsModule */ - 0, /* mbConcatArgs */ - 1, /* mbAllowExtraInitRds */ + .findConfig = grubFindConfig, + .keywords = grubKeywords, + .defaultIsIndex = 1, + .defaultSupportSaved = 1, + .entryStart = LT_TITLE, + .needsBootPrefix = 1, + .mbHyperFirst = 1, + .mbInitRdIsModule = 1, + .mbAllowExtraInitRds = 1, +}; + +struct keywordTypes grub2Keywords[] = { + { "menuentry", LT_MENUENTRY, ' ' }, + { "}", LT_ENTRY_END, ' ' }, + { "echo", LT_ECHO, ' ' }, + { "set", LT_SET_VARIABLE,' ', '=' }, + { "root", LT_BOOTROOT, ' ' }, + { "default", LT_DEFAULT, ' ' }, + { "fallback", LT_FALLBACK, ' ' }, + { "linux", LT_KERNEL, ' ' }, + { "linuxefi", LT_KERNEL, ' ' }, + { "initrd", LT_INITRD, ' ', ' ' }, + { "initrdefi", LT_INITRD, ' ', ' ' }, + { "module", LT_MBMODULE, ' ' }, + { "kernel", LT_HYPER, ' ' }, + { NULL, 0, 0 }, +}; + +const char *grub2FindConfig(struct configFileInfo *cfi) { + static const char *configFiles[] = { + "/boot/grub/grub-efi.cfg", + "/boot/grub/grub.cfg", + NULL + }; + static int i = -1; + static const char *grub_cfg = "/boot/grub/grub.cfg"; + + if (i == -1) { + for (i = 0; configFiles[i] != NULL; i++) { + dbgPrintf("Checking \"%s\": ", configFiles[i]); + if (!access(configFiles[i], R_OK)) { + dbgPrintf("found\n"); + return configFiles[i]; + } + } + } + + /* Ubuntu renames grub2 to grub, so check for the grub.d directory + * that isn't in grub1, and if it exists, return the config file path + * that they use. */ + if (configFiles[i] == NULL && !access("/etc/grub.d/", R_OK)) { + dbgPrintf("found\n"); + return grub_cfg; + } + + dbgPrintf("not found\n"); + return configFiles[i]; +} + +int sizeOfSingleLine(struct singleLine * line) { + int count = 0; + + for (int i = 0; i < line->numElements; i++) { + int indentSize = 0; + + count = count + strlen(line->elements[i].item); + + indentSize = strlen(line->elements[i].indent); + if (indentSize > 0) + count = count + indentSize; + else + /* be extra safe and add room for whitespaces */ + count = count + 1; + } + + /* room for trailing terminator */ + count = count + 1; + + return count; +} + +static int isquote(char q) +{ + if (q == '\'' || q == '\"') + return 1; + return 0; +} + +char *grub2ExtractTitle(struct singleLine * line) { + char * current; + char * current_indent; + int current_len; + int current_indent_len; + int i; + + /* bail out if line does not start with menuentry */ + if (strcmp(line->elements[0].item, "menuentry")) + return NULL; + + i = 1; + current = line->elements[i].item; + current_len = strlen(current); + + /* if second word is quoted, strip the quotes and return single word */ + if (isquote(*current) && isquote(current[current_len - 1])) { + char *tmp; + + tmp = strdup(current); + *(tmp + current_len - 1) = '\0'; + return ++tmp; + } + + /* if no quotes, return second word verbatim */ + if (!isquote(*current)) + return current; + + /* second element start with a quote, so we have to find the element + * whose last character is also quote (assuming it's the closing one) */ + int resultMaxSize; + char * result; + + resultMaxSize = sizeOfSingleLine(line); + result = malloc(resultMaxSize); + snprintf(result, resultMaxSize, "%s", ++current); + + i++; + for (; i < line->numElements; ++i) { + current = line->elements[i].item; + current_len = strlen(current); + current_indent = line->elements[i].indent; + current_indent_len = strlen(current_indent); + + strncat(result, current_indent, current_indent_len); + if (!isquote(current[current_len-1])) { + strncat(result, current, current_len); + } else { + strncat(result, current, current_len - 1); + break; + } + } + return result; +} + +struct configFileInfo grub2ConfigType = { + .findConfig = grub2FindConfig, + .keywords = grub2Keywords, + .defaultIsIndex = 1, + .defaultSupportSaved = 1, + .defaultIsVariable = 1, + .entryStart = LT_MENUENTRY, + .entryEnd = LT_ENTRY_END, + .titlePosition = 1, + .needsBootPrefix = 1, + .mbHyperFirst = 1, + .mbInitRdIsModule = 1, + .mbAllowExtraInitRds = 1, }; struct keywordTypes yabootKeywords[] = { @@ -249,99 +438,56 @@ }; int useextlinuxmenu; struct configFileInfo eliloConfigType = { - "/boot/efi/EFI/redhat/elilo.conf", /* defaultConfig */ - eliloKeywords, /* keywords */ - 0, /* defaultIsIndex */ - 0, /* defaultSupportSaved */ - LT_KERNEL, /* entrySeparator */ - 1, /* needsBootPrefix */ - 1, /* argsInQuotes */ - 0, /* maxTitleLength */ - 0, /* titleBracketed */ - 0, /* mbHyperFirst */ - 0, /* mbInitRdIsModule */ - 1, /* mbConcatArgs */ - 0, /* mbAllowExtraInitRds */ + .defaultConfig = "/boot/efi/EFI/redhat/elilo.conf", + .keywords = eliloKeywords, + .entryStart = LT_KERNEL, + .needsBootPrefix = 1, + .argsInQuotes = 1, + .mbConcatArgs = 1, }; struct configFileInfo liloConfigType = { - "/etc/lilo.conf", /* defaultConfig */ - liloKeywords, /* keywords */ - 0, /* defaultIsIndex */ - 0, /* defaultSupportSaved */ - LT_KERNEL, /* entrySeparator */ - 0, /* needsBootPrefix */ - 1, /* argsInQuotes */ - 15, /* maxTitleLength */ - 0, /* titleBracketed */ - 0, /* mbHyperFirst */ - 0, /* mbInitRdIsModule */ - 0, /* mbConcatArgs */ - 0, /* mbAllowExtraInitRds */ + .defaultConfig = "/etc/lilo.conf", + .keywords = liloKeywords, + .entryStart = LT_KERNEL, + .argsInQuotes = 1, + .maxTitleLength = 15, }; struct configFileInfo yabootConfigType = { - "/etc/yaboot.conf", /* defaultConfig */ - yabootKeywords, /* keywords */ - 0, /* defaultIsIndex */ - 0, /* defaultSupportSaved */ - LT_KERNEL, /* entrySeparator */ - 1, /* needsBootPrefix */ - 1, /* argsInQuotes */ - 15, /* maxTitleLength */ - 0, /* titleBracketed */ - 0, /* mbHyperFirst */ - 0, /* mbInitRdIsModule */ - 0, /* mbConcatArgs */ - 1, /* mbAllowExtraInitRds */ + .defaultConfig = "/etc/yaboot.conf", + .keywords = yabootKeywords, + .entryStart = LT_KERNEL, + .needsBootPrefix = 1, + .argsInQuotes = 1, + .maxTitleLength = 15, + .mbAllowExtraInitRds = 1, }; struct configFileInfo siloConfigType = { - "/etc/silo.conf", /* defaultConfig */ - siloKeywords, /* keywords */ - 0, /* defaultIsIndex */ - 0, /* defaultSupportSaved */ - LT_KERNEL, /* entrySeparator */ - 1, /* needsBootPrefix */ - 1, /* argsInQuotes */ - 15, /* maxTitleLength */ - 0, /* titleBracketed */ - 0, /* mbHyperFirst */ - 0, /* mbInitRdIsModule */ - 0, /* mbConcatArgs */ - 0, /* mbAllowExtraInitRds */ + .defaultConfig = "/etc/silo.conf", + .keywords = siloKeywords, + .entryStart = LT_KERNEL, + .needsBootPrefix = 1, + .argsInQuotes = 1, + .maxTitleLength = 15, }; struct configFileInfo ziplConfigType = { - "/etc/zipl.conf", /* defaultConfig */ - ziplKeywords, /* keywords */ - 0, /* defaultIsIndex */ - 0, /* defaultSupportSaved */ - LT_TITLE, /* entrySeparator */ - 0, /* needsBootPrefix */ - 1, /* argsInQuotes */ - 0, /* maxTitleLength */ - 1, /* titleBracketed */ - 0, /* mbHyperFirst */ - 0, /* mbInitRdIsModule */ - 0, /* mbConcatArgs */ - 0, /* mbAllowExtraInitRds */ + .defaultConfig = "/etc/zipl.conf", + .keywords = ziplKeywords, + .entryStart = LT_TITLE, + .argsInQuotes = 1, + .titleBracketed = 1, }; struct configFileInfo extlinuxConfigType = { - "/boot/extlinux/extlinux.conf", /* defaultConfig */ - extlinuxKeywords, /* keywords */ - 0, /* defaultIsIndex */ - 0, /* defaultSupportSaved */ - LT_TITLE, /* entrySeparator */ - 1, /* needsBootPrefix */ - 0, /* argsInQuotes */ - 255, /* maxTitleLength */ - 0, /* titleBracketed */ - 0, /* mbHyperFirst */ - 0, /* mbInitRdIsModule */ - 0, /* mbConcatArgs */ - 1, /* mbAllowExtraInitRds */ + .defaultConfig = "/boot/extlinux/extlinux.conf", + .keywords = extlinuxKeywords, + .entryStart = LT_TITLE, + .needsBootPrefix = 1, + .maxTitleLength = 255, + .mbAllowExtraInitRds = 1, }; struct grubConfig { @@ -356,6 +502,8 @@ struct configFileInfo * cfi; }; +blkid_cache blkid; + struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index); struct singleEntry * findEntryByPath(struct grubConfig * cfg, const char * path, const char * prefix, @@ -369,6 +517,7 @@ static int getNextLine(char ** bufPtr, struct singleLine * line, struct configFileInfo * cfi); static char * getRootSpecifier(char * str); +static void requote(struct singleLine *line, struct configFileInfo * cfi); static void insertElement(struct singleLine * line, const char * item, int insertHere, struct configFileInfo * cfi); @@ -425,27 +574,37 @@ static struct keywordTypes * getKeywordByType(enum lineType_e type, struct configFileInfo * cfi) { - struct keywordTypes * kw; - for (kw = cfi->keywords; kw->key; kw++) { + for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) { if (kw->type == type) return kw; } return NULL; } -static char * getpathbyspec(char *device) { - static blkid_cache blkid; +static char *getKeyByType(enum lineType_e type, struct configFileInfo * cfi) { + struct keywordTypes *kt = getKeywordByType(type, cfi); + if (kt) + return kt->key; + return "unknown"; +} +static char * getpathbyspec(char *device) { if (!blkid) blkid_get_cache(&blkid, NULL); return blkid_get_devname(blkid, device, NULL); } +static char * getuuidbydev(char *device) { + if (!blkid) + blkid_get_cache(&blkid, NULL); + + return blkid_get_tag_value(blkid, "UUID", device); +} + static enum lineType_e getTypeByKeyword(char * keyword, struct configFileInfo * cfi) { - struct keywordTypes * kw; - for (kw = cfi->keywords; kw->key; kw++) { + for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) { if (!strcmp(keyword, kw->key)) return kw->type; } @@ -477,9 +636,9 @@ return 0; } -static int isEntrySeparator(struct singleLine * line, +static int isEntryStart(struct singleLine * line, struct configFileInfo * cfi) { - return line->type == cfi->entrySeparator || line->type == LT_OTHER || + return line->type == cfi->entryStart || line->type == LT_OTHER || (cfi->titleBracketed && isBracketedTitle(line)); } @@ -532,7 +691,6 @@ } struct singleLine * lineDup(struct singleLine * line) { - int i; struct singleLine * newLine = malloc(sizeof(*newLine)); newLine->indent = strdup(line->indent); @@ -542,7 +700,7 @@ newLine->elements = malloc(sizeof(*newLine->elements) * newLine->numElements); - for (i = 0; i < newLine->numElements; i++) { + for (int i = 0; i < newLine->numElements; i++) { newLine->elements[i].indent = strdup(line->elements[i].indent); newLine->elements[i].item = strdup(line->elements[i].item); } @@ -551,11 +709,9 @@ } static void lineFree(struct singleLine * line) { - int i; - if (line->indent) free(line->indent); - for (i = 0; i < line->numElements; i++) { + for (int i = 0; i < line->numElements; i++) { free(line->elements[i].item); free(line->elements[i].indent); } @@ -566,11 +722,21 @@ static int lineWrite(FILE * out, struct singleLine * line, struct configFileInfo * cfi) { - int i; - if (fprintf(out, "%s", line->indent) == -1) return -1; - for (i = 0; i < line->numElements; i++) { + for (int i = 0; i < line->numElements; i++) { + /* Need to handle this, because we strip the quotes from + * menuentry when read it. */ + if (line->type == LT_MENUENTRY && i == 1) { + if(!isquote(*line->elements[i].item)) + fprintf(out, "\'%s\'", line->elements[i].item); + else + fprintf(out, "%s", line->elements[i].item); + fprintf(out, "%s", line->elements[i].indent); + + continue; + } + if (i == 1 && line->type == LT_KERNELARGS && cfi->argsInQuotes) if (fputc('"', out) == EOF) return -1; @@ -664,10 +830,9 @@ if (*line->elements[0].item == '#') { char * fullLine; int len; - int i; len = strlen(line->indent); - for (i = 0; i < line->numElements; i++) + for (int i = 0; i < line->numElements; i++) len += strlen(line->elements[i].item) + strlen(line->elements[i].indent); @@ -676,7 +841,7 @@ free(line->indent); line->indent = fullLine; - for (i = 0; i < line->numElements; i++) { + for (int i = 0; i < line->numElements; i++) { strcat(fullLine, line->elements[i].item); strcat(fullLine, line->elements[i].indent); free(line->elements[i].item); @@ -695,12 +860,10 @@ * elements up more */ if (!isspace(kw->separatorChar)) { - int i; char indent[2] = ""; indent[0] = kw->separatorChar; - for (i = 1; i < line->numElements; i++) { + for (int i = 1; i < line->numElements; i++) { char *p; - int j; int numNewElements; numNewElements = 0; @@ -716,7 +879,7 @@ sizeof(*line->elements) * elementsAlloced); } - for (j = line->numElements; j > i; j--) { + for (int j = line->numElements; j > i; j--) { line->elements[j + numNewElements] = line->elements[j]; } line->numElements += numNewElements; @@ -729,13 +892,11 @@ break; } - free(line->elements[i].indent); + line->elements[i + 1].indent = line->elements[i].indent; line->elements[i].indent = strdup(indent); *p++ = '\0'; i++; line->elements[i].item = strdup(p); - line->elements[i].indent = strdup(""); - p = line->elements[i].item; } } } @@ -756,7 +917,7 @@ struct singleLine * last = NULL, * line, * defaultLine = NULL; char * end; struct singleEntry * entry = NULL; - int i, len; + int len; char * buf; if (!strcmp(inName, "-")) { @@ -802,7 +963,7 @@ cfg->secondaryIndent = strdup(line->indent); } - if (isEntrySeparator(line, cfi)) { + if (isEntryStart(line, cfi) || (cfg->entries && !sawEntry)) { sawEntry = 1; if (!entry) { cfg->entries = malloc(sizeof(*entry)); @@ -818,7 +979,20 @@ entry->next = NULL; } - if (line->type == LT_DEFAULT && line->numElements == 2) { + if (line->type == LT_SET_VARIABLE) { + dbgPrintf("found 'set' command (%d elements): ", line->numElements); + dbgPrintf("%s", line->indent); + for (int i = 0; i < line->numElements; i++) + dbgPrintf("\"%s\"%s", line->elements[i].item, line->elements[i].indent); + dbgPrintf("\n"); + struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi); + if (kwType && line->numElements == 3 && + !strcmp(line->elements[1].item, kwType->key)) { + dbgPrintf("Line sets default config\n"); + cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT; + defaultLine = line; + } + } else if (line->type == LT_DEFAULT && line->numElements == 2) { cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT; defaultLine = line; @@ -836,8 +1010,7 @@ * This only applies to grub, but that's the only place we * should find LT_MBMODULE lines anyway. */ - struct singleLine * l; - for (l = entry->lines; l; l = l->next) { + for (struct singleLine *l = entry->lines; l; l = l->next) { if (l->type == LT_HYPER) break; else if (l->type == LT_KERNEL) { @@ -857,14 +1030,14 @@ } else if (line->type == LT_TITLE && line->numElements > 1) { /* make the title a single argument (undoing our parsing) */ len = 0; - for (i = 1; i < line->numElements; i++) { + for (int i = 1; i < line->numElements; i++) { len += strlen(line->elements[i].item); len += strlen(line->elements[i].indent); } buf = malloc(len + 1); *buf = '\0'; - for (i = 1; i < line->numElements; i++) { + for (int i = 1; i < line->numElements; i++) { strcat(buf, line->elements[i].item); free(line->elements[i].item); @@ -878,7 +1051,71 @@ line->elements[line->numElements - 1].indent; line->elements[1].item = buf; line->numElements = 2; + } else if (line->type == LT_MENUENTRY && line->numElements > 3) { + /* let --remove-kernel="TITLE=what" work */ + len = 0; + char *extras; + char *title; + for (int i = 1; i < line->numElements; i++) { + len += strlen(line->elements[i].item); + len += strlen(line->elements[i].indent); + } + buf = malloc(len + 1); + *buf = '\0'; + + /* allocate mem for extra flags. */ + extras = malloc(len + 1); + *extras = '\0'; + + /* get title. */ + for (int i = 0; i < line->numElements; i++) { + if (!strcmp(line->elements[i].item, "menuentry")) + continue; + if (isquote(*line->elements[i].item)) + title = line->elements[i].item + 1; + else + title = line->elements[i].item; + + len = strlen(title); + if (isquote(title[len-1])) { + strncat(buf, title,len-1); + break; + } else { + strcat(buf, title); + strcat(buf, line->elements[i].indent); + } + } + + /* get extras */ + int count = 0; + for (int i = 0; i < line->numElements; i++) { + if (count >= 2) { + strcat(extras, line->elements[i].item); + strcat(extras, line->elements[i].indent); + } + + if (!strcmp(line->elements[i].item, "menuentry")) + continue; + + /* count ' or ", there should be two in menuentry line. */ + if (isquote(*line->elements[i].item)) + count++; + + len = strlen(line->elements[i].item); + + if (isquote(line->elements[i].item[len -1])) + count++; + + /* ok, we get the final ' or ", others are extras. */ + } + line->elements[1].indent = + line->elements[line->numElements - 2].indent; + line->elements[1].item = buf; + line->elements[2].indent = + line->elements[line->numElements - 2].indent; + line->elements[2].item = extras; + line->numElements = 3; } else if (line->type == LT_KERNELARGS && cfi->argsInQuotes) { /* Strip off any " which may be present; they'll be put back on write. This is one of the few (the only?) places that grubby @@ -887,13 +1124,13 @@ if (line->numElements >= 2) { int last, len; - if (*line->elements[1].item == '"') + if (isquote(*line->elements[1].item)) memmove(line->elements[1].item, line->elements[1].item + 1, strlen(line->elements[1].item + 1) + 1); last = line->numElements - 1; len = strlen(line->elements[last].item) - 1; - if (line->elements[last].item[len] == '"') + if (isquote(line->elements[last].item[len])) line->elements[last].item[len] = '\0'; } } @@ -931,13 +1168,18 @@ entry->lines = line; else last->next = line; - dbgPrintf("readConfig added %d to %p\n", line->type, entry); + dbgPrintf("readConfig added %s to %p\n", getKeyByType(line->type, cfi), entry); + + /* we could have seen this outside of an entry... if so, we + * ignore it like any other line we don't grok */ + if (line->type == LT_ENTRY_END && sawEntry) + sawEntry = 0; } else { if (!cfg->theLines) cfg->theLines = line; else last->next = line; - dbgPrintf("readConfig added %d to cfg\n", line->type); + dbgPrintf("readConfig added %s to cfg\n", getKeyByType(line->type, cfi)); } last = line; @@ -945,15 +1187,30 @@ free(incoming); + dbgPrintf("defaultLine is %s\n", defaultLine ? "set" : "unset"); if (defaultLine) { - if (cfi->defaultSupportSaved && + if (defaultLine->numElements > 2 && + cfi->defaultSupportSaved && + !strncmp(defaultLine->elements[2].item,"\"${saved_entry}\"", 16)) { + cfg->defaultImage = DEFAULT_SAVED_GRUB2; + } else if (cfi->defaultIsVariable) { + char *value = defaultLine->elements[2].item; + while (*value && (*value == '"' || *value == '\'' || + *value == ' ' || *value == '\t')) + value++; + cfg->defaultImage = strtol(value, &end, 10); + while (*end && (*end == '"' || *end == '\'' || + *end == ' ' || *end == '\t')) + end++; + if (*end) cfg->defaultImage = -1; + } else if (cfi->defaultSupportSaved && !strncmp(defaultLine->elements[1].item, "saved", 5)) { cfg->defaultImage = DEFAULT_SAVED; } else if (cfi->defaultIsIndex) { cfg->defaultImage = strtol(defaultLine->elements[1].item, &end, 10); if (*end) cfg->defaultImage = -1; } else if (defaultLine->numElements >= 2) { - i = 0; + int i = 0; while ((entry = findEntryByIndex(cfg, i))) { for (line = entry->lines; line; line = line->next) if (line->type == LT_TITLE) break; @@ -993,10 +1250,17 @@ if (cfg->defaultImage == DEFAULT_SAVED) fprintf(out, "%sdefault%ssaved\n", indent, separator); + else if (cfg->defaultImage == DEFAULT_SAVED_GRUB2) + fprintf(out, "%sset default=\"${saved_entry}\"\n", indent); else if (cfg->defaultImage > -1) { if (cfg->cfi->defaultIsIndex) { - fprintf(out, "%sdefault%s%d\n", indent, separator, - cfg->defaultImage); + if (cfg->cfi->defaultIsVariable) { + fprintf(out, "%sset default=\"%d\"\n", indent, + cfg->defaultImage); + } else { + fprintf(out, "%sdefault%s%d\n", indent, separator, + cfg->defaultImage); + } } else { int image = cfg->defaultImage; @@ -1048,7 +1312,9 @@ /* most likely the symlink is relative, so change our directory to the dir of the symlink */ - rc = chdir(dirname(strdupa(outName))); + char *dir = strdupa(outName); + rc = chdir(dirname(dir)); + free(dir); do { buf = alloca(len + 1); rc = readlink(basename(outName), buf, len); @@ -1086,8 +1352,14 @@ } line = cfg->theLines; + struct keywordTypes *defaultKw = getKeywordByType(LT_DEFAULT, cfg->cfi); while (line) { - if (line->type == LT_DEFAULT) { + if (line->type == LT_SET_VARIABLE && defaultKw && + line->numElements == 3 && + !strcmp(line->elements[1].item, defaultKw->key)) { + writeDefault(out, line->indent, line->elements[0].indent, cfg); + needs &= ~MAIN_DEFAULT; + } else if (line->type == LT_DEFAULT) { writeDefault(out, line->indent, line->elements[0].indent, cfg); needs &= ~MAIN_DEFAULT; } else if (line->type == LT_FALLBACK) { @@ -1155,29 +1427,172 @@ return i; } +static char *findDiskForRoot() +{ + int fd; + char buf[65536]; + char *devname; + char *chptr; + int rc; + + if ((fd = open(_PATH_MOUNTED, O_RDONLY)) < 0) { + fprintf(stderr, "grubby: failed to open %s: %s\n", + _PATH_MOUNTED, strerror(errno)); + return NULL; + } + + rc = read(fd, buf, sizeof(buf) - 1); + if (rc <= 0) { + fprintf(stderr, "grubby: failed to read %s: %s\n", + _PATH_MOUNTED, strerror(errno)); + close(fd); + return NULL; + } + close(fd); + buf[rc] = '\0'; + chptr = buf; + + char *foundanswer = NULL; + + while (chptr && chptr != buf+rc) { + devname = chptr; + + /* + * The first column of a mtab entry is the device, but if the entry is a + * special device it won't start with /, so move on to the next line. + */ + if (*devname != '/') { + chptr = strchr(chptr, '\n'); + if (chptr) + chptr++; + continue; + } + + /* Seek to the next space */ + chptr = strchr(chptr, ' '); + if (!chptr) { + fprintf(stderr, "grubby: error parsing %s: %s\n", + _PATH_MOUNTED, strerror(errno)); + return NULL; + } + + /* + * The second column of a mtab entry is the mount point, we are looking + * for '/' obviously. + */ + if (*(++chptr) == '/' && *(++chptr) == ' ') { + /* remember the last / entry in mtab */ + foundanswer = devname; + } + + /* Next line */ + chptr = strchr(chptr, '\n'); + if (chptr) + chptr++; + } + + /* Return the last / entry found */ + if (foundanswer) { + chptr = strchr(foundanswer, ' '); + *chptr = '\0'; + return strdup(foundanswer); + } + + return NULL; +} + +void printEntry(struct singleEntry * entry) { + int i; + struct singleLine * line; + + for (line = entry->lines; line; line = line->next) { + fprintf(stderr, "DBG: %s", line->indent); + for (i = 0; i < line->numElements; i++) { + /* Need to handle this, because we strip the quotes from + * menuentry when read it. */ + if (line->type == LT_MENUENTRY && i == 1) { + if(!isquote(*line->elements[i].item)) + fprintf(stderr, "\'%s\'", line->elements[i].item); + else + fprintf(stderr, "%s", line->elements[i].item); + fprintf(stderr, "%s", line->elements[i].indent); + + continue; + } + + fprintf(stderr, "%s%s", + line->elements[i].item, line->elements[i].indent); + } + fprintf(stderr, "\n"); + } +} + +void notSuitablePrintf(struct singleEntry * entry, const char *fmt, ...) +{ + va_list argp; + + if (!debug) + return; + + va_start(argp, fmt); + fprintf(stderr, "DBG: Image entry failed: "); + vfprintf(stderr, fmt, argp); + printEntry(entry); + va_end(argp); +} + +#define beginswith(s, c) ((s) && (s)[0] == (c)) + +static int endswith(const char *s, char c) +{ + int slen; + + if (!s || !s[0]) + return 0; + slen = strlen(s) - 1; + + return s[slen] == c; +} + int suitableImage(struct singleEntry * entry, const char * bootPrefix, int skipRemoved, int flags) { struct singleLine * line; char * fullName; int i; - struct stat sb, sb2; char * dev; char * rootspec; + char * rootdev; - if (skipRemoved && entry->skip) return 0; + if (skipRemoved && entry->skip) { + notSuitablePrintf(entry, "marked to skip\n"); + return 0; + } line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines); - if (!line || line->numElements < 2) return 0; + if (!line) { + notSuitablePrintf(entry, "no line found\n"); + return 0; + } + if (line->numElements < 2) { + notSuitablePrintf(entry, "line has only %d elements\n", + line->numElements); + return 0; + } if (flags & GRUBBY_BADIMAGE_OKAY) return 1; fullName = alloca(strlen(bootPrefix) + strlen(line->elements[1].item) + 1); rootspec = getRootSpecifier(line->elements[1].item); - sprintf(fullName, "%s%s", bootPrefix, - line->elements[1].item + (rootspec ? strlen(rootspec) : 0)); - if (access(fullName, R_OK)) return 0; - + int rootspec_offset = rootspec ? strlen(rootspec) : 0; + int hasslash = endswith(bootPrefix, '/') || + beginswith(line->elements[1].item + rootspec_offset, '/'); + sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/", + line->elements[1].item + rootspec_offset); + if (access(fullName, R_OK)) { + notSuitablePrintf(entry, "access to %s failed\n", fullName); + return 0; + } for (i = 2; i < line->numElements; i++) if (!strncasecmp(line->elements[i].item, "root=", 5)) break; if (i < line->numElements) { @@ -1195,13 +1610,17 @@ line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines); /* failed to find one */ - if (!line) return 0; + if (!line) { + notSuitablePrintf(entry, "no line found\n"); + return 0; + } for (i = 1; i < line->numElements; i++) if (!strncasecmp(line->elements[i].item, "root=", 5)) break; if (i < line->numElements) dev = line->elements[i].item + 5; else { + notSuitablePrintf(entry, "no root= entry found\n"); /* it failed too... can't find root= */ return 0; } @@ -1209,17 +1628,33 @@ } dev = getpathbyspec(dev); - if (!dev) + if (!getpathbyspec(dev)) { + notSuitablePrintf(entry, "can't find blkid entry for %s\n", dev); return 0; + } else + dev = getpathbyspec(dev); - i = stat(dev, &sb); - if (i) + rootdev = findDiskForRoot(); + if (!rootdev) { + notSuitablePrintf(entry, "can't find root device\n"); return 0; + } - stat("/", &sb2); + if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) { + notSuitablePrintf(entry, "uuid missing: rootdev %s, dev %s\n", + getuuidbydev(rootdev), getuuidbydev(dev)); + free(rootdev); + return 0; + } - if (sb.st_rdev != sb2.st_dev) + if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) { + notSuitablePrintf(entry, "uuid mismatch: rootdev %s, dev %s\n", + getuuidbydev(rootdev), getuuidbydev(dev)); + free(rootdev); return 0; + } + + free(rootdev); return 1; } @@ -1301,7 +1736,7 @@ if (!strncmp(kernel, "TITLE=", 6)) { prefix = ""; - checkType = LT_TITLE; + checkType = LT_TITLE|LT_MENUENTRY; kernel += 6; } @@ -1317,13 +1752,17 @@ checkType, line); if (!line) break; /* not found in this entry */ - if (line && line->numElements >= 2) { + if (line && line->type != LT_MENUENTRY && + line->numElements >= 2) { rootspec = getRootSpecifier(line->elements[1].item); if (!strcmp(line->elements[1].item + ((rootspec != NULL) ? strlen(rootspec) : 0), kernel + strlen(prefix))) break; } + if(line->type == LT_MENUENTRY && + !strcmp(line->elements[1].item, kernel)) + break; } /* make sure this entry has a kernel identifier; this skips @@ -1415,7 +1854,16 @@ const char * prefix) { struct singleEntry * entry; - if (!image) return; + if (!image) + return; + + /* check and see if we're removing the default image */ + if (isdigit(*image)) { + entry = findEntryByPath(cfg, image, prefix, NULL); + if(entry) + entry->skip = 1; + return; + } while ((entry = findEntryByPath(cfg, image, prefix, NULL))) entry->skip = 1; @@ -1423,13 +1871,19 @@ void setDefaultImage(struct grubConfig * config, int hasNew, const char * defaultKernelPath, int newIsDefault, - const char * prefix, int flags) { + const char * prefix, int flags, int index) { struct singleEntry * entry, * entry2, * newDefault; int i, j; if (newIsDefault) { config->defaultImage = 0; return; + } else if ((index >= 0) && config->cfi->defaultIsIndex) { + if (findEntryByIndex(config, index)) + config->defaultImage = index; + else + config->defaultImage = -1; + return; } else if (defaultKernelPath) { i = 0; if (findEntryByPath(config, defaultKernelPath, prefix, &i)) { @@ -1442,7 +1896,8 @@ /* defaultImage now points to what we'd like to use, but before any order changes */ - if (config->defaultImage == DEFAULT_SAVED) + if ((config->defaultImage == DEFAULT_SAVED) || + (config->defaultImage == DEFAULT_SAVED_GRUB2)) /* default is set to saved, we don't want to change it */ return; @@ -1509,7 +1964,10 @@ return; } - printf("kernel=%s\n", line->elements[1].item); + if (!strncmp(prefix, line->elements[1].item, strlen(prefix))) + printf("kernel=%s\n", line->elements[1].item); + else + printf("kernel=%s%s\n", prefix, line->elements[1].item); if (line->numElements >= 3) { printf("args=\""); @@ -1568,11 +2026,287 @@ line = getLineByType(LT_INITRD, entry->lines); if (line && line->numElements >= 2) { - printf("initrd=%s", prefix); + if (!strncmp(prefix, line->elements[1].item, strlen(prefix))) + printf("initrd="); + else + printf("initrd=%s", prefix); + for (i = 1; i < line->numElements; i++) printf("%s%s", line->elements[i].item, line->elements[i].indent); printf("\n"); } + + line = getLineByType(LT_TITLE, entry->lines); + if (line) { + printf("title=%s\n", line->elements[1].item); + } else { + char * title; + line = getLineByType(LT_MENUENTRY, entry->lines); + title = grub2ExtractTitle(line); + if (title) + printf("title=%s\n", title); + } +} + +int isSuseSystem(void) { + const char * path; + const static char default_path[] = "/etc/SuSE-release"; + + if ((path = getenv("GRUBBY_SUSE_RELEASE")) == NULL) + path = default_path; + + if (!access(path, R_OK)) + return 1; + return 0; +} + +int isSuseGrubConf(const char * path) { + FILE * grubConf; + char * line = NULL; + size_t len = 0, res = 0; + + grubConf = fopen(path, "r"); + if (!grubConf) { + dbgPrintf("Could not open SuSE configuration file '%s'\n", path); + return 0; + } + + while ((res = getline(&line, &len, grubConf)) != -1) { + if (!strncmp(line, "setup", 5)) { + fclose(grubConf); + free(line); + return 1; + } + } + + dbgPrintf("SuSE configuration file '%s' does not appear to be valid\n", + path); + + fclose(grubConf); + free(line); + return 0; +} + +int suseGrubConfGetLba(const char * path, int * lbaPtr) { + FILE * grubConf; + char * line = NULL; + size_t res = 0, len = 0; + + if (!path) return 1; + if (!lbaPtr) return 1; + + grubConf = fopen(path, "r"); + if (!grubConf) return 1; + + while ((res = getline(&line, &len, grubConf)) != -1) { + if (line[res - 1] == '\n') + line[res - 1] = '\0'; + else if (len > res) + line[res] = '\0'; + else { + line = realloc(line, res + 1); + line[res] = '\0'; + } + + if (!strncmp(line, "setup", 5)) { + if (strstr(line, "--force-lba")) { + *lbaPtr = 1; + } else { + *lbaPtr = 0; + } + dbgPrintf("lba: %i\n", *lbaPtr); + break; + } + } + + free(line); + fclose(grubConf); + return 0; +} + +int suseGrubConfGetInstallDevice(const char * path, char ** devicePtr) { + FILE * grubConf; + char * line = NULL; + size_t res = 0, len = 0; + char * lastParamPtr = NULL; + char * secLastParamPtr = NULL; + char installDeviceNumber = '\0'; + char * bounds = NULL; + + if (!path) return 1; + if (!devicePtr) return 1; + + grubConf = fopen(path, "r"); + if (!grubConf) return 1; + + while ((res = getline(&line, &len, grubConf)) != -1) { + if (strncmp(line, "setup", 5)) + continue; + + if (line[res - 1] == '\n') + line[res - 1] = '\0'; + else if (len > res) + line[res] = '\0'; + else { + line = realloc(line, res + 1); + line[res] = '\0'; + } + + lastParamPtr = bounds = line + res; + + /* Last parameter in grub may be an optional IMAGE_DEVICE */ + while (!isspace(*lastParamPtr)) + lastParamPtr--; + lastParamPtr++; + + secLastParamPtr = lastParamPtr - 2; + dbgPrintf("lastParamPtr: %s\n", lastParamPtr); + + if (lastParamPtr + 3 > bounds) { + dbgPrintf("lastParamPtr going over boundary"); + fclose(grubConf); + free(line); + return 1; + } + if (!strncmp(lastParamPtr, "(hd", 3)) + lastParamPtr += 3; + dbgPrintf("lastParamPtr: %c\n", *lastParamPtr); + + /* + * Second last parameter will decide wether last parameter is + * an IMAGE_DEVICE or INSTALL_DEVICE + */ + while (!isspace(*secLastParamPtr)) + secLastParamPtr--; + secLastParamPtr++; + + if (secLastParamPtr + 3 > bounds) { + dbgPrintf("secLastParamPtr going over boundary"); + fclose(grubConf); + free(line); + return 1; + } + dbgPrintf("secLastParamPtr: %s\n", secLastParamPtr); + if (!strncmp(secLastParamPtr, "(hd", 3)) { + secLastParamPtr += 3; + dbgPrintf("secLastParamPtr: %c\n", *secLastParamPtr); + installDeviceNumber = *secLastParamPtr; + } else { + installDeviceNumber = *lastParamPtr; + } + + *devicePtr = malloc(6); + snprintf(*devicePtr, 6, "(hd%c)", installDeviceNumber); + dbgPrintf("installDeviceNumber: %c\n", installDeviceNumber); + fclose(grubConf); + free(line); + return 0; + } + + free(line); + fclose(grubConf); + return 1; +} + +int grubGetBootFromDeviceMap(const char * device, + char ** bootPtr) { + FILE * deviceMap; + char * line = NULL; + size_t res = 0, len = 0; + char * devicePtr; + char * bounds = NULL; + const char * path; + const static char default_path[] = "/boot/grub/device.map"; + + if (!device) return 1; + if (!bootPtr) return 1; + + if ((path = getenv("GRUBBY_GRUB_DEVICE_MAP")) == NULL) + path = default_path; + + dbgPrintf("opening grub device.map file from: %s\n", path); + deviceMap = fopen(path, "r"); + if (!deviceMap) + return 1; + + while ((res = getline(&line, &len, deviceMap)) != -1) { + if (!strncmp(line, "#", 1)) + continue; + + if (line[res - 1] == '\n') + line[res - 1] = '\0'; + else if (len > res) + line[res] = '\0'; + else { + line = realloc(line, res + 1); + line[res] = '\0'; + } + + devicePtr = line; + bounds = line + res; + + while ((isspace(*line) && ((devicePtr + 1) <= bounds))) + devicePtr++; + dbgPrintf("device: %s\n", devicePtr); + + if (!strncmp(devicePtr, device, strlen(device))) { + devicePtr += strlen(device); + while (isspace(*devicePtr) && ((devicePtr + 1) <= bounds)) + devicePtr++; + + *bootPtr = strdup(devicePtr); + break; + } + } + + free(line); + fclose(deviceMap); + return 0; +} + +int suseGrubConfGetBoot(const char * path, char ** bootPtr) { + char * grubDevice; + + if (suseGrubConfGetInstallDevice(path, &grubDevice)) + dbgPrintf("error looking for grub installation device\n"); + else + dbgPrintf("grubby installation device: %s\n", grubDevice); + + if (grubGetBootFromDeviceMap(grubDevice, bootPtr)) + dbgPrintf("error looking for grub boot device\n"); + else + dbgPrintf("grubby boot device: %s\n", *bootPtr); + + free(grubDevice); + return 0; +} + +int parseSuseGrubConf(int * lbaPtr, char ** bootPtr) { + /* + * This SuSE grub configuration file at this location is not your average + * grub configuration file, but instead the grub commands used to setup + * grub on that system. + */ + const char * path; + const static char default_path[] = "/etc/grub.conf"; + + if ((path = getenv("GRUBBY_SUSE_GRUB_CONF")) == NULL) + path = default_path; + + if (!isSuseGrubConf(path)) return 1; + + if (lbaPtr) { + *lbaPtr = 0; + if (suseGrubConfGetLba(path, lbaPtr)) + return 1; + } + + if (bootPtr) { + *bootPtr = NULL; + suseGrubConfGetBoot(path, bootPtr); + } + + return 0; } int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) { @@ -1623,12 +2357,25 @@ } void dumpSysconfigGrub(void) { - char * boot; + char * boot = NULL; int lba; - if (!parseSysconfigGrub(&lba, &boot)) { - if (lba) printf("lba\n"); - if (boot) printf("boot=%s\n", boot); + if (isSuseSystem()) { + if (parseSuseGrubConf(&lba, &boot)) { + free(boot); + return; + } + } else { + if (parseSysconfigGrub(&lba, &boot)) { + free(boot); + return; + } + } + + if (lba) printf("lba\n"); + if (boot) { + printf("boot=%s\n", boot); + free(boot); } } @@ -1733,9 +2480,36 @@ sprintf(tmpl.elements[0].item, "[%s]", val); tmpl.elements[0].indent = ""; val = NULL; + } else if (type == LT_MENUENTRY) { + char *lineend = "--class gnu-linux --class gnu --class os {"; + if (!val) { + fprintf(stderr, "Line type LT_MENUENTRY requires a value\n"); + abort(); + } + kw = getKeywordByType(type, cfi); + if (!kw) { + fprintf(stderr, "Looking up keyword for unknown type %d\n", type); + abort(); + } + tmpl.indent = ""; + tmpl.type = type; + tmpl.numElements = 3; + tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements); + tmpl.elements[0].item = kw->key; + tmpl.elements[0].indent = alloca(2); + sprintf(tmpl.elements[0].indent, "%c", kw->nextChar); + tmpl.elements[1].item = (char *)val; + tmpl.elements[1].indent = alloca(2); + sprintf(tmpl.elements[1].indent, "%c", kw->nextChar); + tmpl.elements[2].item = alloca(strlen(lineend)+1); + strcpy(tmpl.elements[2].item, lineend); + tmpl.elements[2].indent = ""; } else { kw = getKeywordByType(type, cfi); - if (!kw) abort(); + if (!kw) { + fprintf(stderr, "Looking up keyword for unknown type %d\n", type); + abort(); + } tmpl.type = type; tmpl.numElements = val ? 2 : 1; tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements); @@ -1759,10 +2533,21 @@ if (!line->next && !prev) prev = line; } - if (prev == entry->lines) - tmpl.indent = defaultIndent ?: ""; - else - tmpl.indent = prev->indent; + struct singleLine *menuEntry; + menuEntry = getLineByType(LT_MENUENTRY, entry->lines); + if (tmpl.type == LT_ENTRY_END) { + if (menuEntry) + tmpl.indent = menuEntry->indent; + else + tmpl.indent = defaultIndent ?: ""; + } else if (tmpl.type != LT_MENUENTRY) { + if (menuEntry) + tmpl.indent = "\t"; + else if (prev == entry->lines) + tmpl.indent = defaultIndent ?: ""; + else + tmpl.indent = prev->indent; + } return addLineTmpl(entry, &tmpl, prev, val, cfi); } @@ -1789,6 +2574,68 @@ free(line); } +static void requote(struct singleLine *tmplLine, struct configFileInfo * cfi) +{ + struct singleLine newLine = { + .indent = tmplLine->indent, + .type = tmplLine->type, + .next = tmplLine->next, + }; + int firstQuotedItem = -1; + int quoteLen = 0; + int j; + int element = 0; + char *c; + + c = malloc(strlen(tmplLine->elements[0].item) + 1); + strcpy(c, tmplLine->elements[0].item); + insertElement(&newLine, c, element++, cfi); + free(c); + c = NULL; + + for (j = 1; j < tmplLine->numElements; j++) { + if (firstQuotedItem == -1) { + quoteLen += strlen(tmplLine->elements[j].item); + + if (isquote(tmplLine->elements[j].item[0])) { + firstQuotedItem = j; + quoteLen += strlen(tmplLine->elements[j].indent); + } else { + c = malloc(quoteLen + 1); + strcpy(c, tmplLine->elements[j].item); + insertElement(&newLine, c, element++, cfi); + free(c); + quoteLen = 0; + } + } else { + int itemlen = strlen(tmplLine->elements[j].item); + quoteLen += itemlen; + quoteLen += strlen(tmplLine->elements[j].indent); + + if (isquote(tmplLine->elements[j].item[itemlen - 1])) { + c = malloc(quoteLen + 1); + c[0] = '\0'; + for (int i = firstQuotedItem; i < j+1; i++) { + strcat(c, tmplLine->elements[i].item); + strcat(c, tmplLine->elements[i].indent); + } + insertElement(&newLine, c, element++, cfi); + free(c); + + firstQuotedItem = -1; + quoteLen = 0; + } + } + } + while (tmplLine->numElements) + removeElement(tmplLine, 0); + if (tmplLine->elements) + free(tmplLine->elements); + + tmplLine->numElements = newLine.numElements; + tmplLine->elements = newLine.elements; +} + static void insertElement(struct singleLine * line, const char * item, int insertHere, struct configFileInfo * cfi) @@ -1895,7 +2742,7 @@ const char ** arg; int useKernelArgs, useRoot; int firstElement; - int *usedElements, *usedArgs; + int *usedElements; int doreplace; if (!image) return 0; @@ -1930,9 +2777,6 @@ useRoot = (getKeywordByType(LT_ROOT, cfg->cfi) && !multibootArgs); - for (k = 0, arg = newArgs; *arg; arg++, k++) ; - usedArgs = calloc(k, sizeof(*usedArgs)); - for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) { if (multibootArgs && !entry->multiboot) @@ -2008,7 +2852,6 @@ usedElements = calloc(line->numElements, sizeof(*usedElements)); for (k = 0, arg = newArgs; *arg; arg++, k++) { - if (usedArgs[k]) continue; doreplace = 1; for (i = firstElement; i < line->numElements; i++) { @@ -2023,7 +2866,6 @@ continue; if (!argMatch(line->elements[i].item, *arg)) { usedElements[i]=1; - usedArgs[k]=1; break; } } @@ -2093,7 +2935,6 @@ } } - free(usedArgs); free(newArgs); free(oldArgs); @@ -2119,6 +2960,44 @@ return rc; } +int updateInitrd(struct grubConfig * cfg, const char * image, + const char * prefix, const char * initrd) { + struct singleEntry * entry; + struct singleLine * line, * kernelLine, *endLine = NULL; + int index = 0; + + if (!image) return 0; + + for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) { + kernelLine = getLineByType(LT_KERNEL, entry->lines); + if (!kernelLine) continue; + + line = getLineByType(LT_INITRD, entry->lines); + if (line) + removeLine(entry, line); + if (prefix) { + int prefixLen = strlen(prefix); + if (!strncmp(initrd, prefix, prefixLen)) + initrd += prefixLen; + } + endLine = getLineByType(LT_ENTRY_END, entry->lines); + if (endLine) + removeLine(entry, endLine); + line = addLine(entry, cfg->cfi, LT_INITRD, kernelLine->indent, initrd); + if (!line) + return 1; + if (endLine) { + line = addLine(entry, cfg->cfi, LT_ENTRY_END, "", NULL); + if (!line) + return 1; + } + + break; + } + + return 0; +} + int checkDeviceBootloader(const char * device, const unsigned char * boot) { int fd; unsigned char bootSect[512]; @@ -2142,12 +3021,22 @@ if (memcmp(boot, bootSect, 3)) return 0; - if (boot[1] == 0xeb) { + if (boot[1] == JMP_SHORT_OPCODE) { offset = boot[2] + 2; } else if (boot[1] == 0xe8 || boot[1] == 0xe9) { offset = (boot[3] << 8) + boot[2] + 2; - } else if (boot[0] == 0xeb) { - offset = boot[1] + 2; + } else if (boot[0] == JMP_SHORT_OPCODE) { + offset = boot[1] + 2; + /* + * it looks like grub, when copying stage1 into the mbr, patches stage1 + * right after the JMP location, replacing other instructions such as + * JMPs for NOOPs. So, relax the check a little bit by skipping those + * different bytes. + */ + if ((bootSect[offset + 1] == NOOP_OPCODE) + && (bootSect[offset + 2] == NOOP_OPCODE)) { + offset = offset + 3; + } } else if (boot[0] == 0xe8 || boot[0] == 0xe9) { offset = (boot[2] << 8) + boot[1] + 2; } else { @@ -2289,13 +3178,27 @@ return checkDeviceBootloader(line->elements[1].item, boot); } +int checkForGrub2(struct grubConfig * config) { + if (!access("/etc/grub.d/", R_OK)) + return 2; + + return 1; +} + int checkForGrub(struct grubConfig * config) { int fd; unsigned char bootSect[512]; char * boot; + int onSuse = isSuseSystem(); - if (parseSysconfigGrub(NULL, &boot)) - return 0; + + if (onSuse) { + if (parseSuseGrubConf(NULL, &boot)) + return 0; + } else { + if (parseSysconfigGrub(NULL, &boot)) + return 0; + } /* assume grub is not installed -- not an error condition */ if (!boot) @@ -2314,6 +3217,12 @@ } close(fd); + /* The more elaborate checks do not work on SuSE. The checks done + * seem to be reasonble (at least for now), so just return success + */ + if (onSuse) + return 2; + return checkDeviceBootloader(boot, bootSect); } @@ -2347,6 +3256,30 @@ return checkDeviceBootloader(boot, bootSect); } +int checkForYaboot(struct grubConfig * config) { + /* + * This is a simplistic check that we consider good enough for own puporses + * + * If we were to properly check if yaboot is *installed* we'd need to: + * 1) get the system boot device (LT_BOOT) + * 2) considering it's a raw filesystem, check if the yaboot binary matches + * the content on the boot device + * 3) if not, copy the binary to a temporary file and run "addnote" on it + * 4) check again if binary and boot device contents match + */ + if (!access("/etc/yaboot.conf", R_OK)) + return 2; + + return 1; +} + +int checkForElilo(struct grubConfig * config) { + if (!access("/etc/elilo.conf", R_OK)) + return 2; + + return 1; +} + static char * getRootSpecifier(char * str) { char * idx, * rootspec = NULL; @@ -2361,7 +3294,7 @@ static char * getInitrdVal(struct grubConfig * config, const char * prefix, struct singleLine *tmplLine, const char * newKernelInitrd, - char ** extraInitrds, int extraInitrdCount) + const char ** extraInitrds, int extraInitrdCount) { char *initrdVal, *end; int i; @@ -2406,10 +3339,10 @@ int addNewKernel(struct grubConfig * config, struct singleEntry * template, const char * prefix, - char * newKernelPath, char * newKernelTitle, - char * newKernelArgs, char * newKernelInitrd, - char ** extraInitrds, int extraInitrdCount, - char * newMBKernel, char * newMBKernelArgs) { + const char * newKernelPath, const char * newKernelTitle, + const char * newKernelArgs, const char * newKernelInitrd, + const char ** extraInitrds, int extraInitrdCount, + const char * newMBKernel, const char * newMBKernelArgs) { struct singleEntry * new; struct singleLine * newLine = NULL, * tmplLine = NULL, * masterLine = NULL; int needs; @@ -2464,7 +3397,7 @@ if (*chptr == '#') continue; if (tmplLine->type == LT_KERNEL && - tmplLine->numElements >= 2) { + tmplLine->numElements >= 2) { if (!template->multiboot && (needs & NEED_MB)) { /* it's not a multiboot template and this is the kernel * line. Try to be intelligent about inserting the @@ -2590,6 +3523,16 @@ needs &= ~NEED_INITRD; } + } else if (tmplLine->type == LT_MENUENTRY && + (needs & NEED_TITLE)) { + requote(tmplLine, config->cfi); + char *nkt = malloc(strlen(newKernelTitle)+3); + strcpy(nkt, "'"); + strcat(nkt, newKernelTitle); + strcat(nkt, "'"); + newLine = addLineTmpl(new, tmplLine, newLine, nkt, config->cfi); + free(nkt); + needs &= ~NEED_TITLE; } else if (tmplLine->type == LT_TITLE && (needs & NEED_TITLE)) { if (tmplLine->numElements >= 2) { @@ -2603,7 +3546,26 @@ tmplLine->indent, newKernelTitle); needs &= ~NEED_TITLE; } - + } else if (tmplLine->type == LT_ECHO) { + requote(tmplLine, config->cfi); + static const char *prefix = "'Loading "; + if (tmplLine->numElements > 1 && + strstr(tmplLine->elements[1].item, prefix) && + masterLine->next && masterLine->next->type == LT_KERNEL) { + char *newTitle = malloc(strlen(prefix) + + strlen(newKernelTitle) + 2); + + strcpy(newTitle, prefix); + strcat(newTitle, newKernelTitle); + strcat(newTitle, "'"); + newLine = addLine(new, config->cfi, LT_ECHO, + tmplLine->indent, newTitle); + free(newTitle); + } else { + /* pass through other lines from the template */ + newLine = addLineTmpl(new, tmplLine, newLine, NULL, + config->cfi); + } } else { /* pass through other lines from the template */ newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi); @@ -2614,7 +3576,7 @@ /* don't have a template, so start the entry with the * appropriate starting line */ - switch (config->cfi->entrySeparator) { + switch (config->cfi->entryStart) { case LT_KERNEL: if (new->multiboot && config->cfi->mbHyperFirst) { /* fall through to LT_HYPER */ @@ -2633,6 +3595,18 @@ needs &= ~NEED_MB; break; + case LT_MENUENTRY: { + char *nkt = malloc(strlen(newKernelTitle)+3); + strcpy(nkt, "'"); + strcat(nkt, newKernelTitle); + strcat(nkt, "'"); + newLine = addLine(new, config->cfi, LT_MENUENTRY, + config->primaryIndent, nkt); + free(nkt); + needs &= ~NEED_TITLE; + needs |= NEED_END; + break; + } case LT_TITLE: if( useextlinuxmenu != 0 ){ // We just need useextlinuxmenu to not be zero (set above) char * templabel; @@ -2666,7 +3640,7 @@ /* add the remainder of the lines, i.e. those that either * weren't present in the template, or in the case of no template, - * all the lines following the entrySeparator. + * all the lines following the entryStart. */ if (needs & NEED_TITLE) { newLine = addLine(new, config->cfi, LT_TITLE, @@ -2707,6 +3681,11 @@ free(initrdVal); needs &= ~NEED_INITRD; } + if (needs & NEED_END) { + newLine = addLine(new, config->cfi, LT_ENTRY_END, + config->secondaryIndent, NULL); + needs &= ~NEED_END; + } if (needs) { printf(_("grubby: needs=%d, aborting\n"), needs); @@ -2736,11 +3715,12 @@ int main(int argc, const char ** argv) { poptContext optCon; - char * grubConfig = NULL; + const char * grubConfig = NULL; char * outputFile = NULL; int arg = 0; int flags = 0; int badImageOkay = 0; + int configureGrub2 = 0; int configureLilo = 0, configureELilo = 0, configureGrub = 0; int configureYaboot = 0, configureSilo = 0, configureZipl = 0; int configureExtLinux = 0; @@ -2768,6 +3748,9 @@ struct singleEntry * template = NULL; int copyDefault = 0, makeDefault = 0; int displayDefault = 0; + int displayDefaultIndex = 0; + int displayDefaultTitle = 0; + int defaultIndex = -1; struct poptOption options[] = { { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0, _("add an entry for the specified kernel"), _("kernel-path") }, @@ -2785,9 +3768,9 @@ { "boot-filesystem", 0, POPT_ARG_STRING, &bootPrefix, 0, _("filestystem which contains /boot directory (for testing only)"), _("bootfs") }, -#if defined(__i386__) || defined(__x86_64__) +#if defined(__i386__) || defined(__x86_64__) || defined (__powerpc64__) || defined (__ia64__) { "bootloader-probe", 0, POPT_ARG_NONE, &bootloaderProbe, 0, - _("check if lilo is installed on lilo.conf boot sector") }, + _("check which bootloader is installed on boot sector") }, #endif { "config-file", 'c', POPT_ARG_STRING, &grubConfig, 0, _("path to grub config file to update (\"-\" for stdin)"), @@ -2798,14 +3781,22 @@ "the kernel referenced by the default image does not exist, " "the first linux entry whose kernel does exist is used as the " "template"), NULL }, + { "debug", 0, 0, &debug, 0, + _("print debugging information for failures") }, { "default-kernel", 0, 0, &displayDefault, 0, _("display the path of the default kernel") }, + { "default-index", 0, 0, &displayDefaultIndex, 0, + _("display the index of the default kernel") }, + { "default-title", 0, 0, &displayDefaultTitle, 0, + _("display the title of the default kernel") }, { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0, _("configure elilo bootloader") }, { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0, _("configure extlinux bootloader (from syslinux)") }, { "grub", 0, POPT_ARG_NONE, &configureGrub, 0, _("configure grub bootloader") }, + { "grub2", 0, POPT_ARG_NONE, &configureGrub2, 0, + _("configure grub2 bootloader") }, { "info", 0, POPT_ARG_STRING, &kernelInfo, 0, _("display boot information for specified kernel"), _("kernel-path") }, @@ -2832,6 +3823,9 @@ { "set-default", 0, POPT_ARG_STRING, &defaultKernel, 0, _("make the first entry referencing the specified kernel " "the default"), _("kernel-path") }, + { "set-default-index", 0, POPT_ARG_INT, &defaultIndex, 0, + _("make the given entry index the default entry"), + _("entry-index") }, { "silo", 0, POPT_ARG_NONE, &configureSilo, 0, _("configure silo bootloader") }, { "title", 0, POPT_ARG_STRING, &newKernelTitle, 0, @@ -2885,7 +3879,7 @@ return 1; } - if ((configureLilo + configureGrub + configureELilo + + if ((configureLilo + configureGrub2 + configureGrub + configureELilo + configureYaboot + configureSilo + configureZipl + configureExtLinux ) > 1) { fprintf(stderr, _("grubby: cannot specify multiple bootloaders\n")); @@ -2894,6 +3888,8 @@ fprintf(stderr, _("grubby: cannot specify config file with --bootloader-probe\n")); return 1; + } else if (configureGrub2) { + cfi = &grub2ConfigType; } else if (configureLilo) { cfi = &liloConfigType; } else if (configureGrub) { @@ -2912,27 +3908,35 @@ } if (!cfi) { + if (grub2FindConfig(&grub2ConfigType)) + cfi = &grub2ConfigType; + else #ifdef __ia64__ - cfi = &eliloConfigType; + cfi = &eliloConfigType; #elif __powerpc__ - cfi = &yabootConfigType; + cfi = &yabootConfigType; #elif __sparc__ - cfi = &siloConfigType; + cfi = &siloConfigType; #elif __s390__ - cfi = &ziplConfigType; + cfi = &ziplConfigType; #elif __s390x__ - cfi = &ziplConfigtype; + cfi = &ziplConfigtype; #else - cfi = &grubConfigType; + cfi = &grubConfigType; #endif } - if (!grubConfig) - grubConfig = cfi->defaultConfig; + if (!grubConfig) { + if (cfi->findConfig) + grubConfig = cfi->findConfig(cfi); + if (!grubConfig) + grubConfig = cfi->defaultConfig; + } if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion || - newKernelPath || removeKernelPath || makeDefault || - defaultKernel)) { + newKernelPath || removeKernelPath || makeDefault || + defaultKernel || displayDefaultIndex || displayDefaultTitle || + (defaultIndex >= 0))) { fprintf(stderr, _("grubby: --bootloader-probe may not be used with " "specified option")); return 1; @@ -2948,8 +3952,8 @@ if (newKernelPath && !newKernelTitle) { fprintf(stderr, _("grubby: kernel title must be specified\n")); return 1; - } else if (!newKernelPath && (newKernelTitle || newKernelInitrd || - newKernelInitrd || copyDefault || + } else if (!newKernelPath && (newKernelTitle || copyDefault || + (newKernelInitrd && !updateKernelPath)|| makeDefault || extraInitrdCount > 0)) { fprintf(stderr, _("grubby: kernel path expected\n")); return 1; @@ -2974,16 +3978,22 @@ makeDefault = 1; defaultKernel = NULL; } + else if (defaultKernel && (defaultIndex >= 0)) { + fprintf(stderr, _("grubby: --set-default and --set-default-index " + "may not be used together\n")); + return 1; + } - if (!strcmp(grubConfig, "-") && !outputFile) { + if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) { fprintf(stderr, _("grubby: output file must be specified if stdin " "is used\n")); return 1; } if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel - && !kernelInfo && !bootloaderProbe && !updateKernelPath - && !removeMBKernel) { + && !kernelInfo && !bootloaderProbe && !updateKernelPath + && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle + && (defaultIndex == -1)) { fprintf(stderr, _("grubby: no action specified\n")); return 1; } @@ -3010,11 +4020,21 @@ } if (bootloaderProbe) { - int lrc = 0, grc = 0, erc = 0; - struct grubConfig * lconfig, * gconfig; + int lrc = 0, grc = 0, gr2c = 0, extrc = 0, yrc = 0, erc = 0; + struct grubConfig * lconfig, * gconfig, * yconfig, * econfig; + + const char *grub2config = grub2FindConfig(&grub2ConfigType); + if (grub2config) { + gconfig = readConfig(grub2config, &grub2ConfigType); + if (!gconfig) + gr2c = 1; + else + gr2c = checkForGrub2(gconfig); + } - if (!access(grubConfigType.defaultConfig, F_OK)) { - gconfig = readConfig(grubConfigType.defaultConfig, &grubConfigType); + const char *grubconfig = grubFindConfig(&grubConfigType); + if (!access(grubconfig, F_OK)) { + gconfig = readConfig(grubconfig, &grubConfigType); if (!gconfig) grc = 1; else @@ -3029,19 +4049,43 @@ lrc = checkForLilo(lconfig); } + if (!access(eliloConfigType.defaultConfig, F_OK)) { + econfig = readConfig(eliloConfigType.defaultConfig, + &eliloConfigType); + if (!econfig) + erc = 1; + else + erc = checkForElilo(econfig); + } + if (!access(extlinuxConfigType.defaultConfig, F_OK)) { lconfig = readConfig(extlinuxConfigType.defaultConfig, &extlinuxConfigType); if (!lconfig) - erc = 1; + extrc = 1; else - erc = checkForExtLinux(lconfig); + extrc = checkForExtLinux(lconfig); } - if (lrc == 1 || grc == 1) return 1; + + if (!access(yabootConfigType.defaultConfig, F_OK)) { + yconfig = readConfig(yabootConfigType.defaultConfig, + &yabootConfigType); + if (!yconfig) + yrc = 1; + else + yrc = checkForYaboot(yconfig); + } + + if (lrc == 1 || grc == 1 || gr2c == 1 || extrc == 1 || yrc == 1 || + erc == 1) + return 1; if (lrc == 2) printf("lilo\n"); + if (gr2c == 2) printf("grub2\n"); if (grc == 2) printf("grub\n"); - if (erc == 2) printf("extlinux\n"); + if (extrc == 2) printf("extlinux\n"); + if (yrc == 2) printf("yaboot\n"); + if (erc == 2) printf("elilo\n"); return 0; } @@ -3067,6 +4111,36 @@ ((rootspec != NULL) ? strlen(rootspec) : 0)); return 0; + + } else if (displayDefaultTitle) { + struct singleLine * line; + struct singleEntry * entry; + + if (config->defaultImage == -1) return 0; + entry = findEntryByIndex(config, config->defaultImage); + if (!entry) return 0; + + if (!configureGrub2) { + line = getLineByType(LT_TITLE, entry->lines); + if (!line) return 0; + printf("%s\n", line->elements[1].item); + + } else { + char * title; + + dbgPrintf("This is GRUB2, default title is embeded in menuentry\n"); + line = getLineByType(LT_MENUENTRY, entry->lines); + if (!line) return 0; + title = grub2ExtractTitle(line); + if (title) + printf("%s\n", title); + } + return 0; + + } else if (displayDefaultIndex) { + if (config->defaultImage == -1) return 0; + printf("%i\n", config->defaultImage); + } else if (kernelInfo) return displayInfo(config, kernelInfo, bootPrefix); @@ -3078,13 +4152,17 @@ markRemovedImage(config, removeKernelPath, bootPrefix); markRemovedImage(config, removeMBKernel, bootPrefix); setDefaultImage(config, newKernelPath != NULL, defaultKernel, makeDefault, - bootPrefix, flags); + bootPrefix, flags, defaultIndex); setFallbackImage(config, newKernelPath != NULL); if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs, removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1; + if (updateKernelPath && newKernelInitrd) { + if (updateInitrd(config, updateKernelPath, bootPrefix, + newKernelInitrd)) return 1; + } if (addNewKernel(config, template, bootPrefix, newKernelPath, newKernelTitle, newKernelArgs, newKernelInitrd, - extraInitrds, extraInitrdCount, + (const char **)extraInitrds, extraInitrdCount, newMBKernel, newMBKernelArgs)) return 1; @@ -3095,7 +4173,7 @@ } if (!outputFile) - outputFile = grubConfig; + outputFile = (char *)grubConfig; return writeConfig(config, outputFile, bootPrefix); }