changeset 24:9d5da43c0e83

sqlickrypt.c: begin converting to parametrized queries. Switch the check() function to use parametrized SQL queries instead of contructing statements with strcat(), for obvious reasons.
author John "Elwin" Edwards <elwin@sdf.org>
date Sun, 03 Jun 2012 17:08:40 -0700
parents 21de24c08aed
children f275d816e857
files sqlickrypt.c
diffstat 1 files changed, 33 insertions(+), 15 deletions(-) [+]
line wrap: on
line diff
--- a/sqlickrypt.c	Thu May 24 11:36:57 2012 -0700
+++ b/sqlickrypt.c	Sun Jun 03 17:08:40 2012 -0700
@@ -30,31 +30,49 @@
 }
 
 int check(char *uname, char *pw) {
-  char finduser_sql[160];
-  char *pwhash = NULL, *comphash;
+  char *pwhash, *comphash;
+  char *query = "SELECT password FROM dglusers WHERE username=?;";
   int status;
   sqlite3 *db;
-
-  strcpy(finduser_sql, "SELECT * FROM dglusers WHERE username='");
-  strncat(finduser_sql, uname, 40);
-  strcat(finduser_sql, "';");
+  sqlite3_stmt *qstmt;
 
   status = sqlite3_open(DATABASE, &db);
   if (status) {
     sqlite3_close(db);
-    return 1;
+    return 3;
+  }
+  sqlite3_prepare_v2(db, query, -1, &qstmt, NULL);
+  if (qstmt == NULL) {
+    sqlite3_close(db);
+    return 3;
   }
-  sqlite3_exec(db, finduser_sql, xcallback, (void *) &pwhash, NULL);
-
+  status = sqlite3_bind_text(qstmt, 1, uname, -1, SQLITE_TRANSIENT);
+  if (status) {
+    sqlite3_finalize(qstmt);
+    sqlite3_close(db);
+    return 3;
+  }
+  status = sqlite3_step(qstmt);
+  if (status != SQLITE_ROW) {
+    sqlite3_finalize(qstmt);
+    sqlite3_close(db);
+    if (status == SQLITE_DONE)
+      return 2; /* User not found */
+    return 3;
+  }
+  pwhash = strdup((char *) sqlite3_column_text(qstmt, 0));
+  /* Clean up */
+  sqlite3_finalize(qstmt);
   sqlite3_close(db);
-  /* Now check the password. */
-  if (pwhash == NULL) {
-    return 2;
-  }
+
+  /* Check the password */
   comphash = crypt(pw, pwhash);
   if (!strcmp(pwhash, comphash))
-    return 0;
-  return 1;
+    status = 0;
+  else
+    status = 1;
+  free(pwhash);
+  return status;
 }
 
 int insertuser(char *uname, char *pw, char *email) {