xref: /petsc/src/sys/webclient/google.c (revision 10450e9e44b354a0a3da7bbd573407bdf051df10)
10efc6a03SBarry Smith 
20efc6a03SBarry Smith #include <petscwebclient.h>
31c7e414eSJacob Faibussowitsch PETSC_PRAGMA_DIAGNOSTIC_IGNORED_BEGIN("-Wdeprecated-declarations")
40efc6a03SBarry Smith 
50efc6a03SBarry Smith /*
60efc6a03SBarry Smith    These variables identify the code as a PETSc application to Google.
70efc6a03SBarry Smith 
8a8d69d7bSBarry Smith    See -   https://stackoverflow.com/questions/4616553/using-oauth-in-free-open-source-software
90efc6a03SBarry Smith    Users can get their own application IDs - https://code.google.com/p/google-apps-manager/wiki/GettingAnOAuthConsoleKey
100efc6a03SBarry Smith 
110efc6a03SBarry Smith */
120efc6a03SBarry Smith #define PETSC_GOOGLE_CLIENT_ID "521429262559-i19i57eek8tnt9ftpp4p91rcl0bo9ag5.apps.googleusercontent.com"
130efc6a03SBarry Smith #define PETSC_GOOGLE_CLIENT_ST "vOds_A71I3_S_aHMq_kZAI0t"
145708bc22SBarry Smith #define PETSC_GOOGLE_API_KEY   "AIzaSyDRZsOcySpWVzsUvIBL2UG3J2tcg-MXbyk"
150efc6a03SBarry Smith 
160efc6a03SBarry Smith /*@C
170efc6a03SBarry Smith   PetscGoogleDriveRefresh - Get a new authorization token for accessing Google drive from PETSc from a refresh token
180efc6a03SBarry Smith 
1920f4b53cSBarry Smith   Not Collective, only the first process in the `MPI_Comm` does anything
200efc6a03SBarry Smith 
210efc6a03SBarry Smith   Input Parameters:
220efc6a03SBarry Smith + comm          - MPI communicator
23aec76313SJacob Faibussowitsch . refresh_token - obtained with `PetscGoogleDriveAuthorize()`, if NULL PETSc will first look for one in the options data
24811af0c4SBarry Smith                     if not found it will call `PetscGoogleDriveAuthorize()`
250efc6a03SBarry Smith - tokensize     - size of the output string access_token
260efc6a03SBarry Smith 
270efc6a03SBarry Smith   Output Parameter:
28811af0c4SBarry Smith . access_token - token that can be passed to `PetscGoogleDriveUpload()`
290efc6a03SBarry Smith 
30811af0c4SBarry Smith   Options Database Key:
31811af0c4SBarry Smith . -google_refresh_token XXX - where XXX was obtained from `PetscGoogleDriveAuthorize()`
324a285bdaSBarry Smith 
332b26979fSBarry Smith   Level: intermediate
344a285bdaSBarry Smith 
35c30dda00SJacob Faibussowitsch .seealso: `PetscGoogleDriveAuthorize()`, `PetscGoogleDriveUpload()`
360efc6a03SBarry Smith @*/
37d71ae5a4SJacob Faibussowitsch PetscErrorCode PetscGoogleDriveRefresh(MPI_Comm comm, const char refresh_token[], char access_token[], size_t tokensize)
38d71ae5a4SJacob Faibussowitsch {
390efc6a03SBarry Smith   SSL_CTX    *ctx;
400efc6a03SBarry Smith   SSL        *ssl;
410efc6a03SBarry Smith   int         sock;
425dc0f0a4SBarry Smith   char        buff[8 * 1024], body[1024];
430efc6a03SBarry Smith   PetscMPIInt rank;
440efc6a03SBarry Smith   char       *refreshtoken = (char *)refresh_token;
455dc0f0a4SBarry Smith   PetscBool   found;
460efc6a03SBarry Smith 
470efc6a03SBarry Smith   PetscFunctionBegin;
489566063dSJacob Faibussowitsch   PetscCallMPI(MPI_Comm_rank(comm, &rank));
49dd400576SPatrick Sanan   if (rank == 0) {
500efc6a03SBarry Smith     if (!refresh_token) {
510efc6a03SBarry Smith       PetscBool set;
529566063dSJacob Faibussowitsch       PetscCall(PetscMalloc1(512, &refreshtoken));
539566063dSJacob Faibussowitsch       PetscCall(PetscOptionsGetString(NULL, NULL, "-google_refresh_token", refreshtoken, sizeof(refreshtoken), &set));
540efc6a03SBarry Smith       if (!set) {
559566063dSJacob Faibussowitsch         PetscCall(PetscGoogleDriveAuthorize(comm, access_token, refreshtoken, 512 * sizeof(char)));
569566063dSJacob Faibussowitsch         PetscCall(PetscFree(refreshtoken));
573ba16761SJacob Faibussowitsch         PetscFunctionReturn(PETSC_SUCCESS);
580efc6a03SBarry Smith       }
590efc6a03SBarry Smith     }
609566063dSJacob Faibussowitsch     PetscCall(PetscSSLInitializeContext(&ctx));
619566063dSJacob Faibussowitsch     PetscCall(PetscHTTPSConnect("accounts.google.com", 443, ctx, &sock, &ssl));
62c6a7a370SJeremy L Thompson     PetscCall(PetscStrncpy(body, "client_id=", sizeof(body)));
63c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body, PETSC_GOOGLE_CLIENT_ID, sizeof(body)));
64c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body, "&client_secret=", sizeof(body)));
65c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body, PETSC_GOOGLE_CLIENT_ST, sizeof(body)));
66c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body, "&refresh_token=", sizeof(body)));
67c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body, refreshtoken, sizeof(body)));
689566063dSJacob Faibussowitsch     if (!refresh_token) PetscCall(PetscFree(refreshtoken));
69c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body, "&grant_type=refresh_token", sizeof(body)));
700efc6a03SBarry Smith 
719566063dSJacob Faibussowitsch     PetscCall(PetscHTTPSRequest("POST", "accounts.google.com/o/oauth2/token", NULL, "application/x-www-form-urlencoded", body, ssl, buff, sizeof(buff)));
729566063dSJacob Faibussowitsch     PetscCall(PetscSSLDestroyContext(ctx));
730efc6a03SBarry Smith     close(sock);
740efc6a03SBarry Smith 
759566063dSJacob Faibussowitsch     PetscCall(PetscPullJSONValue(buff, "access_token", access_token, tokensize, &found));
7628b400f6SJacob Faibussowitsch     PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_LIB, "Google drive did not return access_token");
770efc6a03SBarry Smith   }
783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
790efc6a03SBarry Smith }
800efc6a03SBarry Smith 
810efc6a03SBarry Smith #include <sys/stat.h>
820efc6a03SBarry Smith 
830efc6a03SBarry Smith /*@C
840efc6a03SBarry Smith   PetscGoogleDriveUpload - Loads a file to the Google Drive
850efc6a03SBarry Smith 
8620f4b53cSBarry Smith   Not Collective, only the first process in the `MPI_Comm` uploads the file
870efc6a03SBarry Smith 
880efc6a03SBarry Smith   Input Parameters:
890efc6a03SBarry Smith + comm         - MPI communicator
9020f4b53cSBarry Smith . access_token - obtained with PetscGoogleDriveRefresh(), pass `NULL` to have PETSc generate one
910efc6a03SBarry Smith - filename     - file to upload; if you upload multiple times it will have different names each time on Google Drive
920efc6a03SBarry Smith 
93811af0c4SBarry Smith   Options Database Key:
94147403d9SBarry Smith . -google_refresh_token XXX - pass the access token for the operation
950efc6a03SBarry Smith 
96*10450e9eSJacob Faibussowitsch   Example Usage:
97811af0c4SBarry Smith .vb
984a285bdaSBarry Smith     With PETSc option -google_refresh_token  XXX given
990efc6a03SBarry Smith     PetscGoogleDriveUpload(comm,NULL,filename);        will upload file with no user interaction
1000efc6a03SBarry Smith 
1014a285bdaSBarry Smith     Without PETSc option -google_refresh_token XXX given
1024683183fSBarry Smith     PetscGoogleDriveUpload(comm,NULL,filename);        for first use will prompt user to authorize access to Google Drive with their browser
1030efc6a03SBarry Smith 
1044a285bdaSBarry Smith     With PETSc option -google_refresh_token  XXX given
1050efc6a03SBarry Smith     PetscGoogleDriveRefresh(comm,NULL,access_token,sizeof(access_token));
1060efc6a03SBarry Smith     PetscGoogleDriveUpload(comm,access_token,filename);
1070efc6a03SBarry Smith 
1080efc6a03SBarry Smith     With refresh token entered in some way by the user
1090efc6a03SBarry Smith     PetscGoogleDriveRefresh(comm,refresh_token,access_token,sizeof(access_token));
1100efc6a03SBarry Smith     PetscGoogleDriveUpload(comm,access_token,filename);
1110efc6a03SBarry Smith 
1120efc6a03SBarry Smith     PetscGoogleDriveAuthorize(comm,access_token,refresh_token,sizeof(access_token));
1130efc6a03SBarry Smith     PetscGoogleDriveUpload(comm,access_token,filename);
114811af0c4SBarry Smith .ve
1150efc6a03SBarry Smith 
1162b26979fSBarry Smith   Level: intermediate
1172b26979fSBarry Smith 
118c30dda00SJacob Faibussowitsch .seealso: `PetscGoogleDriveAuthorize()`, `PetscGoogleDriveRefresh()`
1190efc6a03SBarry Smith @*/
120d71ae5a4SJacob Faibussowitsch PetscErrorCode PetscGoogleDriveUpload(MPI_Comm comm, const char access_token[], const char filename[])
121d71ae5a4SJacob Faibussowitsch {
1220efc6a03SBarry Smith   SSL_CTX    *ctx;
1230efc6a03SBarry Smith   SSL        *ssl;
1240efc6a03SBarry Smith   int         sock;
1250efc6a03SBarry Smith   char        head[1024], buff[8 * 1024], *body, *title;
1260efc6a03SBarry Smith   PetscMPIInt rank;
1270efc6a03SBarry Smith   struct stat sb;
1280efc6a03SBarry Smith   size_t      len, blen, rd;
1290efc6a03SBarry Smith   FILE       *fd;
1302da392ccSBarry Smith   int         err;
1310efc6a03SBarry Smith 
1320efc6a03SBarry Smith   PetscFunctionBegin;
1339566063dSJacob Faibussowitsch   PetscCallMPI(MPI_Comm_rank(comm, &rank));
134dd400576SPatrick Sanan   if (rank == 0) {
135c6a7a370SJeremy L Thompson     PetscCall(PetscStrncpy(head, "Authorization: Bearer ", sizeof(head)));
136c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(head, access_token, sizeof(head)));
137c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(head, "\r\n", sizeof(head)));
138c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(head, "uploadType: multipart\r\n", sizeof(head)));
1390efc6a03SBarry Smith 
1402da392ccSBarry Smith     err = stat(filename, &sb);
14128b400f6SJacob Faibussowitsch     PetscCheck(!err, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Unable to stat file: %s", filename);
1420efc6a03SBarry Smith     len = 1024 + sb.st_size;
1439566063dSJacob Faibussowitsch     PetscCall(PetscMalloc1(len, &body));
144c6a7a370SJeremy L Thompson     PetscCall(PetscStrncpy(body,
1450efc6a03SBarry Smith                            "--foo_bar_baz\r\n"
146c6a7a370SJeremy L Thompson                            "Content-Type: application/json\r\n\r\n"
147c6a7a370SJeremy L Thompson                            "{",
148c6a7a370SJeremy L Thompson                            sizeof(body)));
149c6a7a370SJeremy L Thompson     PetscCall(PetscPushJSONValue(body, "title", filename, len));
150c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body, ",", sizeof(body)));
151c6a7a370SJeremy L Thompson     PetscCall(PetscPushJSONValue(body, "mimeType", "text.html", len));
152c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body, ",", sizeof(body)));
153c6a7a370SJeremy L Thompson     PetscCall(PetscPushJSONValue(body, "description", "a file", len));
154c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body,
155c6a7a370SJeremy L Thompson                            "}\r\n\r\n"
156c6a7a370SJeremy L Thompson                            "--foo_bar_baz\r\n"
157c6a7a370SJeremy L Thompson                            "Content-Type: text/html\r\n\r\n",
158c6a7a370SJeremy L Thompson                            sizeof(body)));
1599566063dSJacob Faibussowitsch     PetscCall(PetscStrlen(body, &blen));
1600efc6a03SBarry Smith     fd = fopen(filename, "r");
16128b400f6SJacob Faibussowitsch     PetscCheck(fd, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Unable to open file: %s", filename);
1620efc6a03SBarry Smith     rd = fread(body + blen, sizeof(unsigned char), sb.st_size, fd);
163d8174014SToby Isaac     PetscCheck(rd == (size_t)sb.st_size, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Unable to read entire file: %s %d %d", filename, (int)rd, (int)sb.st_size);
1640efc6a03SBarry Smith     fclose(fd);
1650efc6a03SBarry Smith     body[blen + rd] = 0;
166c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body,
167c6a7a370SJeremy L Thompson                            "\r\n\r\n"
168c6a7a370SJeremy L Thompson                            "--foo_bar_baz\r\n",
169c6a7a370SJeremy L Thompson                            sizeof(body)));
1709566063dSJacob Faibussowitsch     PetscCall(PetscSSLInitializeContext(&ctx));
1719566063dSJacob Faibussowitsch     PetscCall(PetscHTTPSConnect("www.googleapis.com", 443, ctx, &sock, &ssl));
1729566063dSJacob Faibussowitsch     PetscCall(PetscHTTPSRequest("POST", "www.googleapis.com/upload/drive/v2/files/", head, "multipart/related; boundary=\"foo_bar_baz\"", body, ssl, buff, sizeof(buff)));
1739566063dSJacob Faibussowitsch     PetscCall(PetscFree(body));
1749566063dSJacob Faibussowitsch     PetscCall(PetscSSLDestroyContext(ctx));
1750efc6a03SBarry Smith     close(sock);
1769566063dSJacob Faibussowitsch     PetscCall(PetscStrstr(buff, "\"title\"", &title));
17728b400f6SJacob Faibussowitsch     PetscCheck(title, PETSC_COMM_SELF, PETSC_ERR_LIB, "Upload of file %s failed", filename);
1780efc6a03SBarry Smith   }
1793ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1800efc6a03SBarry Smith }
1810efc6a03SBarry Smith 
18268e69593SBarry Smith #if defined(PETSC_HAVE_UNISTD_H)
18368e69593SBarry Smith   #include <unistd.h>
18468e69593SBarry Smith #endif
18568e69593SBarry Smith 
1860efc6a03SBarry Smith /*@C
1870efc6a03SBarry Smith   PetscGoogleDriveAuthorize - Get authorization and refresh token for accessing Google drive from PETSc
1880efc6a03SBarry Smith 
18920f4b53cSBarry Smith   Not Collective, only the first process in `MPI_Comm` does anything
1900efc6a03SBarry Smith 
1910efc6a03SBarry Smith   Input Parameters:
1920efc6a03SBarry Smith + comm      - the MPI communicator
1930efc6a03SBarry Smith - tokensize - size of the token arrays
1940efc6a03SBarry Smith 
1950efc6a03SBarry Smith   Output Parameters:
196811af0c4SBarry Smith + access_token  - can be used with `PetscGoogleDriveUpload()` for this one session
197811af0c4SBarry Smith - refresh_token - can be used for ever to obtain new access_tokens with `PetscGoogleDriveRefresh()`, guard this like a password
1980efc6a03SBarry Smith                    it gives access to your Google Drive
1990efc6a03SBarry Smith 
20020f4b53cSBarry Smith   Level: intermediate
20120f4b53cSBarry Smith 
20295452b02SPatrick Sanan   Notes:
20320f4b53cSBarry Smith   This call requires `stdout` and `stdin` access from process 0 on the MPI communicator
2040efc6a03SBarry Smith 
205c4762a1bSJed Brown   You can run src/sys/webclient/tutorials/googleobtainrefreshtoken to get a refresh token and then in the future pass it to
20620f4b53cSBarry Smith   PETSc programs with `-google_refresh_token XXX`
2072b26979fSBarry Smith 
208c30dda00SJacob Faibussowitsch .seealso: `PetscGoogleDriveRefresh()`, `PetscGoogleDriveUpload()`
2090efc6a03SBarry Smith @*/
210d71ae5a4SJacob Faibussowitsch PetscErrorCode PetscGoogleDriveAuthorize(MPI_Comm comm, char access_token[], char refresh_token[], size_t tokensize)
211d71ae5a4SJacob Faibussowitsch {
2120efc6a03SBarry Smith   SSL_CTX    *ctx;
2130efc6a03SBarry Smith   SSL        *ssl;
2140efc6a03SBarry Smith   int         sock;
2155dc0f0a4SBarry Smith   char        buff[8 * 1024], *ptr, body[1024];
2160efc6a03SBarry Smith   PetscMPIInt rank;
2170efc6a03SBarry Smith   size_t      len;
2185dc0f0a4SBarry Smith   PetscBool   found;
2190efc6a03SBarry Smith 
2200efc6a03SBarry Smith   PetscFunctionBegin;
2219566063dSJacob Faibussowitsch   PetscCallMPI(MPI_Comm_rank(comm, &rank));
222dd400576SPatrick Sanan   if (rank == 0) {
223cc73adaaSBarry Smith     PetscCheck(isatty(fileno(PETSC_STDOUT)), PETSC_COMM_SELF, PETSC_ERR_USER, "Requires users input/output");
224d0609cedSBarry Smith     PetscCall(PetscPrintf(comm, "Cut and paste the following into your browser:\n\n"
2250efc6a03SBarry Smith                                 "https://accounts.google.com/o/oauth2/auth?"
2260efc6a03SBarry Smith                                 "scope=https%%3A%%2F%%2Fwww.googleapis.com%%2Fauth%%2Fdrive.file&"
2270efc6a03SBarry Smith                                 "redirect_uri=urn:ietf:wg:oauth:2.0:oob&"
2280efc6a03SBarry Smith                                 "response_type=code&"
2299371c9d4SSatish Balay                                 "client_id=" PETSC_GOOGLE_CLIENT_ID "\n\n"));
2309566063dSJacob Faibussowitsch     PetscCall(PetscPrintf(comm, "Paste the result here:"));
2310efc6a03SBarry Smith     ptr = fgets(buff, 1024, stdin);
23228b400f6SJacob Faibussowitsch     PetscCheck(ptr, PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Error reading from stdin: %d", errno);
2339566063dSJacob Faibussowitsch     PetscCall(PetscStrlen(buff, &len));
2340efc6a03SBarry Smith     buff[len - 1] = 0; /* remove carriage return at end of line */
2350efc6a03SBarry Smith 
2369566063dSJacob Faibussowitsch     PetscCall(PetscSSLInitializeContext(&ctx));
2379566063dSJacob Faibussowitsch     PetscCall(PetscHTTPSConnect("accounts.google.com", 443, ctx, &sock, &ssl));
238c6a7a370SJeremy L Thompson     PetscCall(PetscStrncpy(body, "code=", sizeof(body)));
239c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body, buff, sizeof(body)));
240c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body, "&client_id=", sizeof(body)));
241c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body, PETSC_GOOGLE_CLIENT_ID, sizeof(body)));
242c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body, "&client_secret=", sizeof(body)));
243c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body, PETSC_GOOGLE_CLIENT_ST, sizeof(body)));
244c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body, "&redirect_uri=urn:ietf:wg:oauth:2.0:oob&", sizeof(body)));
245c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(body, "grant_type=authorization_code", sizeof(body)));
2460efc6a03SBarry Smith 
2479566063dSJacob Faibussowitsch     PetscCall(PetscHTTPSRequest("POST", "accounts.google.com/o/oauth2/token", NULL, "application/x-www-form-urlencoded", body, ssl, buff, sizeof(buff)));
2489566063dSJacob Faibussowitsch     PetscCall(PetscSSLDestroyContext(ctx));
2490efc6a03SBarry Smith     close(sock);
2500efc6a03SBarry Smith 
2519566063dSJacob Faibussowitsch     PetscCall(PetscPullJSONValue(buff, "access_token", access_token, tokensize, &found));
25228b400f6SJacob Faibussowitsch     PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_LIB, "Google drive did not return access_token");
2539566063dSJacob Faibussowitsch     PetscCall(PetscPullJSONValue(buff, "refresh_token", refresh_token, tokensize, &found));
25428b400f6SJacob Faibussowitsch     PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_LIB, "Google drive did not return refresh_token");
2550efc6a03SBarry Smith 
2569566063dSJacob Faibussowitsch     PetscCall(PetscPrintf(comm, "Here is your Google refresh token, save it in a save place, in the future you can run PETSc\n"));
2579566063dSJacob Faibussowitsch     PetscCall(PetscPrintf(comm, "programs with the option -google_refresh_token %s\n", refresh_token));
2589566063dSJacob Faibussowitsch     PetscCall(PetscPrintf(comm, "to access Google Drive automatically\n"));
2590efc6a03SBarry Smith   }
2603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2610efc6a03SBarry Smith }
262