Some hosts don't have TIOCSCTTY. Don't try to use it on them.
[sgt/putty] / unix / uxstore.c
index 3d2e241..85d72ca 100644 (file)
@@ -85,6 +85,8 @@ static void make_filename(char *filename, int index, const char *subname)
     char *home;
     int len;
     home = getenv("HOME");
+    if (!home)
+        home="/";
     strncpy(filename, home, FILENAME_MAX);
     len = strlen(filename);
     if (index == INDEX_SESSION) {
@@ -105,29 +107,6 @@ static void make_filename(char *filename, int index, const char *subname)
     filename[FILENAME_MAX-1] = '\0';
 }
 
-/*
- * Read an entire line of text from a file. Return a buffer
- * malloced to be as big as necessary (caller must free).
- */
-static char *fgetline(FILE *fp)
-{
-    char *ret = snewn(512, char);
-    int size = 512, len = 0;
-    while (fgets(ret + len, size - len, fp)) {
-       len += strlen(ret + len);
-       if (ret[len-1] == '\n')
-           break;                     /* got a newline, we're done */
-       size = len + 512;
-       ret = sresize(ret, size, char);
-    }
-    if (len == 0) {                   /* first fgets returned NULL */
-       sfree(ret);
-       return NULL;
-    }
-    ret[len] = '\0';
-    return ret;
-}
-
 void *open_settings_w(const char *sessionname, char **errmsg)
 {
     char filename[FILENAME_MAX];
@@ -507,24 +486,30 @@ void store_host_key(const char *hostname, int port,
     /*
      * Open both the old file and a new file.
      */
-    make_filename(filename, INDEX_HOSTKEYS, NULL);
-    rfp = fopen(filename, "r");
-    if (!rfp)
-       return;
     make_filename(tmpfilename, INDEX_HOSTKEYS_TMP, NULL);
     wfp = fopen(tmpfilename, "w");
     if (!wfp) {
-       fclose(rfp);
-       return;
+        char dir[FILENAME_MAX];
+
+        make_filename(dir, INDEX_DIR, NULL);
+        mkdir(dir, 0700);
+        wfp = fopen(tmpfilename, "w");
     }
+    if (!wfp)
+       return;
+    make_filename(filename, INDEX_HOSTKEYS, NULL);
+    rfp = fopen(filename, "r");
 
     /*
      * Copy all lines from the old file to the new one that _don't_
      * involve the same host key identifier as the one we're adding.
      */
-    while ( (line = fgetline(rfp)) ) {
-       if (strncmp(line, newtext, headerlen))
-           fputs(line, wfp);
+    if (rfp) {
+        while ( (line = fgetline(rfp)) ) {
+            if (strncmp(line, newtext, headerlen))
+                fputs(line, wfp);
+        }
+        fclose(rfp);
     }
 
     /*
@@ -532,7 +517,6 @@ void store_host_key(const char *hostname, int port,
      */
     fputs(newtext, wfp);
 
-    fclose(rfp);
     fclose(wfp);
 
     rename(tmpfilename, filename);