examples: network: refactor credentials callback The credentials callback reads the username and password via scanf into fixed-length arrays. While these are simply examples and as such not as interesting, the unchecked return value of scanf causes GCC to emit warnings. So while we're busy to shut up GCC, we also fix the possible overflow of scanf by using getline instead.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
diff --git a/examples/network/common.c b/examples/network/common.c
index d123eed..1a81a10 100644
--- a/examples/network/common.c
+++ b/examples/network/common.c
@@ -1,5 +1,7 @@
#include "common.h"
#include <stdio.h>
+#include <string.h>
+#include <errno.h>
/* Shamelessly borrowed from http://stackoverflow.com/questions/3417837/
* with permission of the original author, Martin Pool.
@@ -20,15 +22,27 @@ int cred_acquire_cb(git_cred **out,
unsigned int UNUSED(allowed_types),
void * UNUSED(payload))
{
- char username[128] = {0};
- char password[128] = {0};
+ char *username = NULL, *password = NULL;
+ int error;
printf("Username: ");
- scanf("%s", username);
+ if (getline(&username, NULL, stdin) < 0) {
+ fprintf(stderr, "Unable to read username: %s", strerror(errno));
+ return -1;
+ }
/* Yup. Right there on your terminal. Careful where you copy/paste output. */
printf("Password: ");
- scanf("%s", password);
+ if (getline(&password, NULL, stdin) < 0) {
+ fprintf(stderr, "Unable to read password: %s", strerror(errno));
+ free(username);
+ return -1;
+ }
- return git_cred_userpass_plaintext_new(out, username, password);
+ error = git_cred_userpass_plaintext_new(out, username, password);
+
+ free(username);
+ free(password);
+
+ return error;
}