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