xref: /petsc/src/sys/webclient/google.c (revision b8abcfde4cf799610cd89775278ac4145d1798ce)
1 
2 #include <petscwebclient.h>
3 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
4 #pragma gcc diagnostic ignored "-Wdeprecated-declarations"
5 
6 /*
7    These variables identify the code as a PETSc application to Google.
8 
9    See -   https://stackoverflow.com/questions/4616553/using-oauth-in-free-open-source-software
10    Users can get their own application IDs - https://code.google.com/p/google-apps-manager/wiki/GettingAnOAuthConsoleKey
11 
12 */
13 #define PETSC_GOOGLE_CLIENT_ID  "521429262559-i19i57eek8tnt9ftpp4p91rcl0bo9ag5.apps.googleusercontent.com"
14 #define PETSC_GOOGLE_CLIENT_ST  "vOds_A71I3_S_aHMq_kZAI0t"
15 #define PETSC_GOOGLE_API_KEY    "AIzaSyDRZsOcySpWVzsUvIBL2UG3J2tcg-MXbyk"
16 
17 /*@C
18      PetscGoogleDriveRefresh - Get a new authorization token for accessing Google drive from PETSc from a refresh token
19 
20    Not collective, only the first process in the MPI_Comm does anything
21 
22    Input Parameters:
23 +   comm - MPI communicator
24 .   refresh token - obtained with PetscGoogleDriveAuthorize(), if NULL PETSc will first look for one in the options data
25                     if not found it will call PetscGoogleDriveAuthorize()
26 -   tokensize - size of the output string access_token
27 
28    Output Parameter:
29 .   access_token - token that can be passed to PetscGoogleDriveUpload()
30 
31    Options Database:
32 .  -google_refresh_token XXX - where XXX was obtained from PetscGoogleDriveAuthorize()
33 
34    Level: intermediate
35 
36 .seealso: PetscURLShorten(), PetscGoogleDriveAuthorize(), PetscGoogleDriveUpload()
37 
38 @*/
39 PetscErrorCode PetscGoogleDriveRefresh(MPI_Comm comm,const char refresh_token[],char access_token[],size_t tokensize)
40 {
41   SSL_CTX        *ctx;
42   SSL            *ssl;
43   int            sock;
44   char           buff[8*1024],body[1024];
45   PetscMPIInt    rank;
46   char           *refreshtoken = (char*)refresh_token;
47   PetscBool      found;
48 
49   PetscFunctionBegin;
50   PetscCallMPI(MPI_Comm_rank(comm,&rank));
51   if (rank == 0) {
52     if (!refresh_token) {
53       PetscBool set;
54       PetscCall(PetscMalloc1(512,&refreshtoken));
55       PetscCall(PetscOptionsGetString(NULL,NULL,"-google_refresh_token",refreshtoken,sizeof(refreshtoken),&set));
56       if (!set) {
57         PetscCall(PetscGoogleDriveAuthorize(comm,access_token,refreshtoken,512*sizeof(char)));
58         PetscCall(PetscFree(refreshtoken));
59         PetscFunctionReturn(0);
60       }
61     }
62     PetscCall(PetscSSLInitializeContext(&ctx));
63     PetscCall(PetscHTTPSConnect("accounts.google.com",443,ctx,&sock,&ssl));
64     PetscCall(PetscStrcpy(body,"client_id="));
65     PetscCall(PetscStrcat(body,PETSC_GOOGLE_CLIENT_ID));
66     PetscCall(PetscStrcat(body,"&client_secret="));
67     PetscCall(PetscStrcat(body,PETSC_GOOGLE_CLIENT_ST));
68     PetscCall(PetscStrcat(body,"&refresh_token="));
69     PetscCall(PetscStrcat(body,refreshtoken));
70     if (!refresh_token) PetscCall(PetscFree(refreshtoken));
71     PetscCall(PetscStrcat(body,"&grant_type=refresh_token"));
72 
73     PetscCall(PetscHTTPSRequest("POST","accounts.google.com/o/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff)));
74     PetscCall(PetscSSLDestroyContext(ctx));
75     close(sock);
76 
77     PetscCall(PetscPullJSONValue(buff,"access_token",access_token,tokensize,&found));
78     PetscCheck(found,PETSC_COMM_SELF,PETSC_ERR_LIB,"Google drive did not return access_token");
79   }
80   PetscFunctionReturn(0);
81 }
82 
83 #include <sys/stat.h>
84 
85 /*@C
86      PetscGoogleDriveUpload - Loads a file to the Google Drive
87 
88      Not collective, only the first process in the MPI_Comm uploads the file
89 
90   Input Parameters:
91 +   comm - MPI communicator
92 .   access_token - obtained with PetscGoogleDriveRefresh(), pass NULL to have PETSc generate one
93 -   filename - file to upload; if you upload multiple times it will have different names each time on Google Drive
94 
95   Options Database:
96 .  -google_refresh_token XXX - pass the access token for the operation
97 
98   Usage Patterns:
99     With PETSc option -google_refresh_token  XXX given
100     PetscGoogleDriveUpload(comm,NULL,filename);        will upload file with no user interaction
101 
102     Without PETSc option -google_refresh_token XXX given
103     PetscGoogleDriveUpload(comm,NULL,filename);        for first use will prompt user to authorize access to Google Drive with their browser
104 
105     With PETSc option -google_refresh_token  XXX given
106     PetscGoogleDriveRefresh(comm,NULL,access_token,sizeof(access_token));
107     PetscGoogleDriveUpload(comm,access_token,filename);
108 
109     With refresh token entered in some way by the user
110     PetscGoogleDriveRefresh(comm,refresh_token,access_token,sizeof(access_token));
111     PetscGoogleDriveUpload(comm,access_token,filename);
112 
113     PetscGoogleDriveAuthorize(comm,access_token,refresh_token,sizeof(access_token));
114     PetscGoogleDriveUpload(comm,access_token,filename);
115 
116    Level: intermediate
117 
118 .seealso: PetscURLShorten(), PetscGoogleDriveAuthorize(), PetscGoogleDriveRefresh()
119 
120 @*/
121 PetscErrorCode PetscGoogleDriveUpload(MPI_Comm comm,const char access_token[],const char filename[])
122 {
123   SSL_CTX        *ctx;
124   SSL            *ssl;
125   int            sock;
126   PetscErrorCode ierr;
127   char           head[1024],buff[8*1024],*body,*title;
128   PetscMPIInt    rank;
129   struct stat    sb;
130   size_t         len,blen,rd;
131   FILE           *fd;
132   int            err;
133 
134   PetscFunctionBegin;
135   PetscCallMPI(MPI_Comm_rank(comm,&rank));
136   if (rank == 0) {
137     PetscCall(PetscStrcpy(head,"Authorization: Bearer "));
138     PetscCall(PetscStrcat(head,access_token));
139     PetscCall(PetscStrcat(head,"\r\n"));
140     PetscCall(PetscStrcat(head,"uploadType: multipart\r\n"));
141 
142     err = stat(filename,&sb);
143     PetscCheck(!err,PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Unable to stat file: %s",filename);
144     len = 1024 + sb.st_size;
145     PetscCall(PetscMalloc1(len,&body));
146     ierr = PetscStrcpy(body,"--foo_bar_baz\r\n"
147                             "Content-Type: application/json\r\n\r\n"
148                             "{");PetscCall(ierr);
149     PetscCall(PetscPushJSONValue(body,"title",filename,len));
150     PetscCall(PetscStrcat(body,","));
151     PetscCall(PetscPushJSONValue(body,"mimeType","text.html",len));
152     PetscCall(PetscStrcat(body,","));
153     PetscCall(PetscPushJSONValue(body,"description","a file",len));
154     ierr = PetscStrcat(body,"}\r\n\r\n"
155                             "--foo_bar_baz\r\n"
156                             "Content-Type: text/html\r\n\r\n");PetscCall(ierr);
157     PetscCall(PetscStrlen(body,&blen));
158     fd = fopen (filename, "r");
159     PetscCheck(fd,PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Unable to open file: %s",filename);
160     rd = fread (body+blen, sizeof (unsigned char), sb.st_size, fd);
161     PetscCheckFalse(rd != (size_t) sb.st_size,PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Unable to read entire file: %s %d %d",filename,(int)rd,sb.st_size);
162     fclose(fd);
163     body[blen + rd] = 0;
164     ierr = PetscStrcat(body,"\r\n\r\n"
165                             "--foo_bar_baz\r\n");PetscCall(ierr);
166     PetscCall(PetscSSLInitializeContext(&ctx));
167     PetscCall(PetscHTTPSConnect("www.googleapis.com",443,ctx,&sock,&ssl));
168     PetscCall(PetscHTTPSRequest("POST","www.googleapis.com/upload/drive/v2/files/",head,"multipart/related; boundary=\"foo_bar_baz\"",body,ssl,buff,sizeof(buff)));
169     PetscCall(PetscFree(body));
170     PetscCall(PetscSSLDestroyContext(ctx));
171     close(sock);
172     PetscCall(PetscStrstr(buff,"\"title\"",&title));
173     PetscCheck(title,PETSC_COMM_SELF,PETSC_ERR_LIB,"Upload of file %s failed",filename);
174   }
175   PetscFunctionReturn(0);
176 }
177 
178 #if defined(PETSC_HAVE_UNISTD_H)
179 #include <unistd.h>
180 #endif
181 
182 /*@C
183      PetscGoogleDriveAuthorize - Get authorization and refresh token for accessing Google drive from PETSc
184 
185    Not collective, only the first process in MPI_Comm does anything
186 
187    Input Parameters:
188 +  comm - the MPI communicator
189 -  tokensize - size of the token arrays
190 
191    Output Parameters:
192 +  access_token - can be used with PetscGoogleDriveUpload() for this one session
193 -  refresh_token - can be used for ever to obtain new access_tokens with PetscGoogleDriveRefresh(), guard this like a password
194                    it gives access to your Google Drive
195 
196    Notes:
197     This call requires stdout and stdin access from process 0 on the MPI communicator
198 
199    You can run src/sys/webclient/tutorials/googleobtainrefreshtoken to get a refresh token and then in the future pass it to
200    PETSc programs with -google_refresh_token XXX
201 
202    Level: intermediate
203 
204 .seealso: PetscGoogleDriveRefresh(), PetscGoogleDriveUpload(), PetscURLShorten()
205 
206 @*/
207 PetscErrorCode PetscGoogleDriveAuthorize(MPI_Comm comm,char access_token[],char refresh_token[],size_t tokensize)
208 {
209   SSL_CTX        *ctx;
210   SSL            *ssl;
211   int            sock;
212   PetscErrorCode ierr;
213   char           buff[8*1024],*ptr,body[1024];
214   PetscMPIInt    rank;
215   size_t         len;
216   PetscBool      found;
217 
218   PetscFunctionBegin;
219   PetscCallMPI(MPI_Comm_rank(comm,&rank));
220   if (rank == 0) {
221     PetscCheckFalse(!isatty(fileno(PETSC_STDOUT)),PETSC_COMM_SELF,PETSC_ERR_USER,"Requires users input/output");
222     ierr = PetscPrintf(comm,"Cut and paste the following into your browser:\n\n"
223                             "https://accounts.google.com/o/oauth2/auth?"
224                             "scope=https%%3A%%2F%%2Fwww.googleapis.com%%2Fauth%%2Fdrive.file&"
225                             "redirect_uri=urn:ietf:wg:oauth:2.0:oob&"
226                             "response_type=code&"
227                             "client_id="
228                             PETSC_GOOGLE_CLIENT_ID
229                             "\n\n");PetscCall(ierr);
230     PetscCall(PetscPrintf(comm,"Paste the result here:"));
231     ptr  = fgets(buff, 1024, stdin);
232     PetscCheck(ptr,PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Error reading from stdin: %d", errno);
233     PetscCall(PetscStrlen(buff,&len));
234     buff[len-1] = 0; /* remove carriage return at end of line */
235 
236     PetscCall(PetscSSLInitializeContext(&ctx));
237     PetscCall(PetscHTTPSConnect("accounts.google.com",443,ctx,&sock,&ssl));
238     PetscCall(PetscStrcpy(body,"code="));
239     PetscCall(PetscStrcat(body,buff));
240     PetscCall(PetscStrcat(body,"&client_id="));
241     PetscCall(PetscStrcat(body,PETSC_GOOGLE_CLIENT_ID));
242     PetscCall(PetscStrcat(body,"&client_secret="));
243     PetscCall(PetscStrcat(body,PETSC_GOOGLE_CLIENT_ST));
244     PetscCall(PetscStrcat(body,"&redirect_uri=urn:ietf:wg:oauth:2.0:oob&"));
245     PetscCall(PetscStrcat(body,"grant_type=authorization_code"));
246 
247     PetscCall(PetscHTTPSRequest("POST","accounts.google.com/o/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff)));
248     PetscCall(PetscSSLDestroyContext(ctx));
249     close(sock);
250 
251     PetscCall(PetscPullJSONValue(buff,"access_token",access_token,tokensize,&found));
252     PetscCheck(found,PETSC_COMM_SELF,PETSC_ERR_LIB,"Google drive did not return access_token");
253     PetscCall(PetscPullJSONValue(buff,"refresh_token",refresh_token,tokensize,&found));
254     PetscCheck(found,PETSC_COMM_SELF,PETSC_ERR_LIB,"Google drive did not return refresh_token");
255 
256     PetscCall(PetscPrintf(comm,"Here is your Google refresh token, save it in a save place, in the future you can run PETSc\n"));
257     PetscCall(PetscPrintf(comm,"programs with the option -google_refresh_token %s\n",refresh_token));
258     PetscCall(PetscPrintf(comm,"to access Google Drive automatically\n"));
259   }
260   PetscFunctionReturn(0);
261 }
262 
263 /*@C
264      PetscURLShorten - Uses Google's service to get a short url for a long url
265 
266     Input Parameters:
267 +    url - long URL you want shortened
268 -    lenshorturl - length of buffer to contain short URL
269 
270     Output Parameter:
271 .    shorturl - the shortened URL
272 
273    Level: intermediate
274 
275 .seealso: PetscGoogleDriveRefresh(), PetscGoogleDriveUpload(), PetscGoogleDriveAuthorize()
276 @*/
277 PetscErrorCode PetscURLShorten(const char url[],char shorturl[],size_t lenshorturl)
278 {
279   SSL_CTX        *ctx;
280   SSL            *ssl;
281   int            sock;
282   char           buff[1024],body[512],post[1024];
283   PetscBool      found;
284 
285   PetscFunctionBegin;
286   PetscCall(PetscSSLInitializeContext(&ctx));
287   PetscCall(PetscHTTPSConnect("www.googleapis.com",443,ctx,&sock,&ssl));
288   PetscCall(PetscStrcpy(body,"{"));
289   PetscCall(PetscPushJSONValue(body,"longUrl",url,sizeof(body)-2));
290   PetscCall(PetscStrcat(body,"}"));
291   PetscCall(PetscSNPrintf(post,sizeof(post),"www.googleapis.com/urlshortener/v1/url?key=%s",PETSC_GOOGLE_API_KEY));
292   PetscCall(PetscHTTPSRequest("POST",post,NULL,"application/json",body,ssl,buff,sizeof(buff)));
293   PetscCall(PetscSSLDestroyContext(ctx));
294   close(sock);
295 
296   PetscCall(PetscPullJSONValue(buff,"id",shorturl,lenshorturl,&found));
297   PetscCheck(found,PETSC_COMM_SELF,PETSC_ERR_LIB,"Google drive did not return short URL");
298   PetscFunctionReturn(0);
299 }
300