- if (length == i)
- {
- // end of file
- if (length != 0) mDNSMacOSXParseEtcHostsLine(m, readBuf, length, auth);
- break;
- }
-
- // increment our offset by the number of bytes we read
- offset += length - i;
-
- // loop through the buffer looking for end of lines
- for (linestart = 0; i < length; i++)
- {
- if (readBuf[i] == '#' || readBuf[i] == '\r' || readBuf[i] == '\n')
- {
- int parseline = i - linestart > 0 && comment == 0;
- comment = readBuf[i] == '#';
- if (parseline)
- {
- readBuf[i] = 0;
- mDNSMacOSXParseEtcHostsLine(m, &readBuf[linestart], i - linestart, auth);
- }
- linestart = i + 1;
- }
- }
-
- // prepare to read the next chunk of the file
- if (linestart == 0)
- {
- // single line was larger than our buffer, we're going to ignore it
- comment = 1; // treat remainder of line as comment
- i = 0;
- }
- else
- {
- i = length - linestart;
- if (i) memmove(readBuf, &readBuf[linestart], i);
- }
+ good = (fgets(buf, ETCHOSTS_BUFSIZE, fp) != NULL);
+ if (!good) break;
+
+ // skip comment and empty lines
+ if (buf[0] == '#' || buf[0] == '\r' || buf[0] == '\n')
+ continue;
+
+ len = strlen(buf);
+ if (!len) break; // sanity check
+
+ if (buf[len - 1] == '\r' || buf[len - 1] == '\n')
+ buf[len - 1] = '\0';
+
+ // fgets always null terminates and hence even if we have no
+ // newline at the end, it is null terminated. The callee expects
+ // the length to be such that buf[length] to be zero and hence
+ // we pass len - 1.
+ mDNSMacOSXParseEtcHostsLine(m, buf, len - 1, auth);