xref: /petsc/src/sys/webclient/google.c (revision f97672e55eacc8688507b9471cd7ec2664d7f203)
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   char           head[1024],buff[8*1024],*body,*title;
127   PetscMPIInt    rank;
128   struct stat    sb;
129   size_t         len,blen,rd;
130   FILE           *fd;
131   int            err;
132 
133   PetscFunctionBegin;
134   PetscCallMPI(MPI_Comm_rank(comm,&rank));
135   if (rank == 0) {
136     PetscCall(PetscStrcpy(head,"Authorization: Bearer "));
137     PetscCall(PetscStrcat(head,access_token));
138     PetscCall(PetscStrcat(head,"\r\n"));
139     PetscCall(PetscStrcat(head,"uploadType: multipart\r\n"));
140 
141     err = stat(filename,&sb);
142     PetscCheck(!err,PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Unable to stat file: %s",filename);
143     len = 1024 + sb.st_size;
144     PetscCall(PetscMalloc1(len,&body));
145     PetscCall(PetscStrcpy(body,"--foo_bar_baz\r\n"
146                                "Content-Type: application/json\r\n\r\n"
147                                "{"));
148     PetscCall(PetscPushJSONValue(body,"title",filename,len));
149     PetscCall(PetscStrcat(body,","));
150     PetscCall(PetscPushJSONValue(body,"mimeType","text.html",len));
151     PetscCall(PetscStrcat(body,","));
152     PetscCall(PetscPushJSONValue(body,"description","a file",len));
153     PetscCall(PetscStrcat(body,"}\r\n\r\n"
154                                "--foo_bar_baz\r\n"
155                                "Content-Type: text/html\r\n\r\n"));
156     PetscCall(PetscStrlen(body,&blen));
157     fd = fopen (filename, "r");
158     PetscCheck(fd,PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Unable to open file: %s",filename);
159     rd = fread (body+blen, sizeof (unsigned char), sb.st_size, fd);
160     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,sb.st_size);
161     fclose(fd);
162     body[blen + rd] = 0;
163     PetscCall(PetscStrcat(body,"\r\n\r\n"
164                                "--foo_bar_baz\r\n"));
165     PetscCall(PetscSSLInitializeContext(&ctx));
166     PetscCall(PetscHTTPSConnect("www.googleapis.com",443,ctx,&sock,&ssl));
167     PetscCall(PetscHTTPSRequest("POST","www.googleapis.com/upload/drive/v2/files/",head,"multipart/related; boundary=\"foo_bar_baz\"",body,ssl,buff,sizeof(buff)));
168     PetscCall(PetscFree(body));
169     PetscCall(PetscSSLDestroyContext(ctx));
170     close(sock);
171     PetscCall(PetscStrstr(buff,"\"title\"",&title));
172     PetscCheck(title,PETSC_COMM_SELF,PETSC_ERR_LIB,"Upload of file %s failed",filename);
173   }
174   PetscFunctionReturn(0);
175 }
176 
177 #if defined(PETSC_HAVE_UNISTD_H)
178 #include <unistd.h>
179 #endif
180 
181 /*@C
182      PetscGoogleDriveAuthorize - Get authorization and refresh token for accessing Google drive from PETSc
183 
184    Not collective, only the first process in MPI_Comm does anything
185 
186    Input Parameters:
187 +  comm - the MPI communicator
188 -  tokensize - size of the token arrays
189 
190    Output Parameters:
191 +  access_token - can be used with PetscGoogleDriveUpload() for this one session
192 -  refresh_token - can be used for ever to obtain new access_tokens with PetscGoogleDriveRefresh(), guard this like a password
193                    it gives access to your Google Drive
194 
195    Notes:
196     This call requires stdout and stdin access from process 0 on the MPI communicator
197 
198    You can run src/sys/webclient/tutorials/googleobtainrefreshtoken to get a refresh token and then in the future pass it to
199    PETSc programs with -google_refresh_token XXX
200 
201    Level: intermediate
202 
203 .seealso: `PetscGoogleDriveRefresh()`, `PetscGoogleDriveUpload()`, `PetscURLShorten()`
204 
205 @*/
206 PetscErrorCode PetscGoogleDriveAuthorize(MPI_Comm comm,char access_token[],char refresh_token[],size_t tokensize)
207 {
208   SSL_CTX        *ctx;
209   SSL            *ssl;
210   int            sock;
211   char           buff[8*1024],*ptr,body[1024];
212   PetscMPIInt    rank;
213   size_t         len;
214   PetscBool      found;
215 
216   PetscFunctionBegin;
217   PetscCallMPI(MPI_Comm_rank(comm,&rank));
218   if (rank == 0) {
219     PetscCheck(isatty(fileno(PETSC_STDOUT)),PETSC_COMM_SELF,PETSC_ERR_USER,"Requires users input/output");
220     PetscCall(PetscPrintf(comm,"Cut and paste the following into your browser:\n\n"
221                                "https://accounts.google.com/o/oauth2/auth?"
222                                "scope=https%%3A%%2F%%2Fwww.googleapis.com%%2Fauth%%2Fdrive.file&"
223                                "redirect_uri=urn:ietf:wg:oauth:2.0:oob&"
224                                "response_type=code&"
225                                "client_id="
226                                PETSC_GOOGLE_CLIENT_ID
227                                "\n\n"));
228     PetscCall(PetscPrintf(comm,"Paste the result here:"));
229     ptr  = fgets(buff, 1024, stdin);
230     PetscCheck(ptr,PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Error reading from stdin: %d", errno);
231     PetscCall(PetscStrlen(buff,&len));
232     buff[len-1] = 0; /* remove carriage return at end of line */
233 
234     PetscCall(PetscSSLInitializeContext(&ctx));
235     PetscCall(PetscHTTPSConnect("accounts.google.com",443,ctx,&sock,&ssl));
236     PetscCall(PetscStrcpy(body,"code="));
237     PetscCall(PetscStrcat(body,buff));
238     PetscCall(PetscStrcat(body,"&client_id="));
239     PetscCall(PetscStrcat(body,PETSC_GOOGLE_CLIENT_ID));
240     PetscCall(PetscStrcat(body,"&client_secret="));
241     PetscCall(PetscStrcat(body,PETSC_GOOGLE_CLIENT_ST));
242     PetscCall(PetscStrcat(body,"&redirect_uri=urn:ietf:wg:oauth:2.0:oob&"));
243     PetscCall(PetscStrcat(body,"grant_type=authorization_code"));
244 
245     PetscCall(PetscHTTPSRequest("POST","accounts.google.com/o/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff)));
246     PetscCall(PetscSSLDestroyContext(ctx));
247     close(sock);
248 
249     PetscCall(PetscPullJSONValue(buff,"access_token",access_token,tokensize,&found));
250     PetscCheck(found,PETSC_COMM_SELF,PETSC_ERR_LIB,"Google drive did not return access_token");
251     PetscCall(PetscPullJSONValue(buff,"refresh_token",refresh_token,tokensize,&found));
252     PetscCheck(found,PETSC_COMM_SELF,PETSC_ERR_LIB,"Google drive did not return refresh_token");
253 
254     PetscCall(PetscPrintf(comm,"Here is your Google refresh token, save it in a save place, in the future you can run PETSc\n"));
255     PetscCall(PetscPrintf(comm,"programs with the option -google_refresh_token %s\n",refresh_token));
256     PetscCall(PetscPrintf(comm,"to access Google Drive automatically\n"));
257   }
258   PetscFunctionReturn(0);
259 }
260 
261 /*@C
262      PetscURLShorten - Uses Google's service to get a short url for a long url
263 
264     Input Parameters:
265 +    url - long URL you want shortened
266 -    lenshorturl - length of buffer to contain short URL
267 
268     Output Parameter:
269 .    shorturl - the shortened URL
270 
271    Level: intermediate
272 
273 .seealso: `PetscGoogleDriveRefresh()`, `PetscGoogleDriveUpload()`, `PetscGoogleDriveAuthorize()`
274 @*/
275 PetscErrorCode PetscURLShorten(const char url[],char shorturl[],size_t lenshorturl)
276 {
277   SSL_CTX        *ctx;
278   SSL            *ssl;
279   int            sock;
280   char           buff[1024],body[512],post[1024];
281   PetscBool      found;
282 
283   PetscFunctionBegin;
284   PetscCall(PetscSSLInitializeContext(&ctx));
285   PetscCall(PetscHTTPSConnect("www.googleapis.com",443,ctx,&sock,&ssl));
286   PetscCall(PetscStrcpy(body,"{"));
287   PetscCall(PetscPushJSONValue(body,"longUrl",url,sizeof(body)-2));
288   PetscCall(PetscStrcat(body,"}"));
289   PetscCall(PetscSNPrintf(post,sizeof(post),"www.googleapis.com/urlshortener/v1/url?key=%s",PETSC_GOOGLE_API_KEY));
290   PetscCall(PetscHTTPSRequest("POST",post,NULL,"application/json",body,ssl,buff,sizeof(buff)));
291   PetscCall(PetscSSLDestroyContext(ctx));
292   close(sock);
293 
294   PetscCall(PetscPullJSONValue(buff,"id",shorturl,lenshorturl,&found));
295   PetscCheck(found,PETSC_COMM_SELF,PETSC_ERR_LIB,"Google drive did not return short URL");
296   PetscFunctionReturn(0);
297 }
298