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