@@ -330,38 +330,64 @@ static int readline(char **out)
330330 return error ;
331331}
332332
333+ static int ask (char * * out , const char * prompt , char optional )
334+ {
335+ printf ("%s " , prompt );
336+ fflush (stdout );
337+
338+ if (!readline (out ) && !optional ) {
339+ fprintf (stderr , "Could not read response: %s" , strerror (errno ));
340+ return -1 ;
341+ }
342+
343+ return 0 ;
344+ }
345+
333346int cred_acquire_cb (git_cred * * out ,
334347 const char * url ,
335348 const char * username_from_url ,
336349 unsigned int allowed_types ,
337350 void * payload )
338351{
339- char * username = NULL , * password = NULL ;
340- int error ;
352+ char * username = NULL , * password = NULL , * privkey = NULL , * pubkey = NULL ;
353+ int error = 1 ;
341354
342355 UNUSED (url );
343- UNUSED (username_from_url );
344- UNUSED (allowed_types );
345356 UNUSED (payload );
346357
347- printf ("Username: " );
348- if (readline (& username ) < 0 ) {
349- fprintf (stderr , "Unable to read username: %s" , strerror (errno ));
350- return -1 ;
358+ if (username_from_url ) {
359+ if ((username = strdup (username_from_url )) == NULL )
360+ goto out ;
361+ } else if ((error = ask (& username , "Username:" , 0 )) < 0 ) {
362+ goto out ;
351363 }
352364
353- /* Yup. Right there on your terminal. Careful where you copy/paste output. */
354- printf ("Password: " );
355- if (readline (& password ) < 0 ) {
356- fprintf (stderr , "Unable to read password: %s" , strerror (errno ));
357- free (username );
358- return -1 ;
359- }
365+ if (allowed_types & GIT_CREDTYPE_SSH_KEY ) {
366+ int n ;
367+
368+ if ((error = ask (& privkey , "SSH Key:" , 0 )) < 0 ||
369+ (error = ask (& password , "Password:" , 1 )) < 0 )
370+ goto out ;
360371
361- error = git_cred_userpass_plaintext_new (out , username , password );
372+ if ((n = snprintf (NULL , 0 , "%s.pub" , privkey )) < 0 ||
373+ (pubkey = malloc (n + 1 )) == NULL ||
374+ (n = snprintf (pubkey , n + 1 , "%s.pub" , privkey )) < 0 )
375+ goto out ;
362376
377+ error = git_cred_ssh_key_new (out , username , pubkey , privkey , password );
378+ } else if (allowed_types & GIT_CREDTYPE_USERPASS_PLAINTEXT ) {
379+ if ((error = ask (& password , "Password:" , 1 )) < 0 )
380+ goto out ;
381+
382+ error = git_cred_userpass_plaintext_new (out , username , password );
383+ } else if (allowed_types & GIT_CREDTYPE_USERNAME ) {
384+ error = git_cred_username_new (out , username );
385+ }
386+
387+ out :
363388 free (username );
364389 free (password );
365-
390+ free (privkey );
391+ free (pubkey );
366392 return error ;
367393}
0 commit comments