xref: /petsc/src/sys/webclient/google.c (revision bb04b57d8fc8b99a9ce04c03188cf4f575836949)
1 
2 #include <petscwebclient.h>
3 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
4 
5 /*
6    These variables identify the code as a PETSc application to Google.
7 
8    See -   http://stackoverflow.com/questions/4616553/using-oauth-in-free-open-source-software
9    Users can get their own application IDs - https://code.google.com/p/google-apps-manager/wiki/GettingAnOAuthConsoleKey
10 
11 */
12 #define PETSC_GOOGLE_CLIENT_ID  "521429262559-i19i57eek8tnt9ftpp4p91rcl0bo9ag5.apps.googleusercontent.com"
13 #define PETSC_GOOGLE_CLIENT_ST  "vOds_A71I3_S_aHMq_kZAI0t"
14 
15 
16 #undef __FUNCT__
17 #define __FUNCT__ "PetscGoogleDriveRefresh"
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 
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   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
52   if (!rank) {
53     if (!refresh_token) {
54       PetscBool set;
55       ierr = PetscMalloc1(512,&refreshtoken);CHKERRQ(ierr);
56       ierr = PetscOptionsGetString(NULL,"-google_refresh_token",refreshtoken,512,&set);CHKERRQ(ierr);
57       if (!set) {
58         ierr = PetscGoogleDriveAuthorize(comm,access_token,refreshtoken,512*sizeof(char));CHKERRQ(ierr);
59         ierr = PetscFree(refreshtoken);CHKERRQ(ierr);
60         PetscFunctionReturn(0);
61       }
62     }
63     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
64     ierr = PetscHTTPSConnect("accounts.google.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
65     ierr = PetscStrcpy(body,"client_id=");CHKERRQ(ierr);
66     ierr = PetscStrcat(body,PETSC_GOOGLE_CLIENT_ID);CHKERRQ(ierr);
67     ierr = PetscStrcat(body,"&client_secret=");CHKERRQ(ierr);
68     ierr = PetscStrcat(body,PETSC_GOOGLE_CLIENT_ST);CHKERRQ(ierr);
69     ierr = PetscStrcat(body,"&refresh_token=");CHKERRQ(ierr);
70     ierr = PetscStrcat(body,refreshtoken);CHKERRQ(ierr);
71     if (!refresh_token) {ierr = PetscFree(refreshtoken);CHKERRQ(ierr);}
72     ierr = PetscStrcat(body,"&grant_type=refresh_token");CHKERRQ(ierr);
73 
74     ierr = PetscHTTPSRequest("POST","accounts.google.com/o/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
75     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
76     close(sock);
77 
78     ierr   = PetscPullJSONValue(buff,"access_token",access_token,tokensize,&found);CHKERRQ(ierr);
79     if (!found) SETERRQ(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 #undef __FUNCT__
87 #define __FUNCT__ "PetscGoogleDriveUpload"
88 /*@C
89      PetscGoogleDriveUpload - Loads a file to the Google Drive
90 
91      Not collective, only the first process in the MPI_Comm uploads the file
92 
93   Input Parameters:
94 +   comm - MPI communicator
95 .   access_token - obtained with PetscGoogleDriveRefresh(), pass NULL to have PETSc generate one
96 -   filename - file to upload; if you upload multiple times it will have different names each time on Google Drive
97 
98   Options Database:
99 .  -google_refresh_token   XXX
100 
101   Usage Patterns:
102     With PETSc option -google_refresh_token  XXX given
103     PetscGoogleDriveUpload(comm,NULL,filename);        will upload file with no user interaction
104 
105     Without PETSc option -google_refresh_token XXX given
106     PetscGoogleDriveUpload(comm,NULL,filename);        for first use will prompt user to authorize access to Google Drive with their processor
107 
108     With PETSc option -google_refresh_token  XXX given
109     PetscGoogleDriveRefresh(comm,NULL,access_token,sizeof(access_token));
110     PetscGoogleDriveUpload(comm,access_token,filename);
111 
112     With refresh token entered in some way by the user
113     PetscGoogleDriveRefresh(comm,refresh_token,access_token,sizeof(access_token));
114     PetscGoogleDriveUpload(comm,access_token,filename);
115 
116     PetscGoogleDriveAuthorize(comm,access_token,refresh_token,sizeof(access_token));
117     PetscGoogleDriveUpload(comm,access_token,filename);
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 
134   PetscFunctionBegin;
135   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
136   if (!rank) {
137     ierr = PetscStrcpy(head,"Authorization: Bearer ");CHKERRQ(ierr);
138     ierr = PetscStrcat(head,access_token);CHKERRQ(ierr);
139     ierr = PetscStrcat(head,"\r\n");CHKERRQ(ierr);
140     ierr = PetscStrcat(head,"uploadType: multipart\r\n");CHKERRQ(ierr);
141 
142     ierr = stat(filename,&sb);
143     if (ierr) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Unable to stat file: %s",filename);
144     len = 1024 + sb.st_size;
145     ierr = PetscMalloc1(len,&body);CHKERRQ(ierr);
146     ierr = PetscStrcpy(body,"--foo_bar_baz\r\n"
147                             "Content-Type: application/json\r\n\r\n"
148                             "{");CHKERRQ(ierr);
149     ierr = PetscPushJSONValue(body,"title",filename,len);CHKERRQ(ierr);
150     ierr = PetscStrcat(body,",");CHKERRQ(ierr);
151     ierr = PetscPushJSONValue(body,"mimeType","text.html",len);CHKERRQ(ierr);
152     ierr = PetscStrcat(body,",");CHKERRQ(ierr);
153     ierr = PetscPushJSONValue(body,"description","a file",len);CHKERRQ(ierr);
154     ierr = PetscStrcat(body,"}\r\n\r\n"
155                             "--foo_bar_baz\r\n"
156                             "Content-Type: text/html\r\n\r\n");
157     ierr = PetscStrlen(body,&blen);CHKERRQ(ierr);
158     fd = fopen (filename, "r");
159     if (!fd) SETERRQ1(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     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);
162     fclose(fd);
163     body[blen + rd] = 0;
164     ierr = PetscStrcat(body,"\r\n\r\n"
165                             "--foo_bar_baz\r\n");
166     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
167     ierr = PetscHTTPSConnect("www.googleapis.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
168     ierr = PetscHTTPSRequest("POST","www.googleapis.com/upload/drive/v2/files/",head,"multipart/related; boundary=\"foo_bar_baz\"",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
169     ierr = PetscFree(body);CHKERRQ(ierr);
170     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
171     close(sock);
172     ierr   = PetscStrstr(buff,"\"title\"",&title);CHKERRQ(ierr);
173     if (!title) SETERRQ1(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 #undef __FUNCT__
183 #define __FUNCT__ "PetscGoogleDriveAuthorize"
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: This call requires stdout and stdin access from process 0 on the MPI communicator
199 
200    You can run src/sys/webclient/examples/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 .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   PetscErrorCode ierr;
212   char           buff[8*1024],*ptr,body[1024];
213   PetscMPIInt    rank;
214   size_t         len;
215   PetscBool      found;
216 
217   PetscFunctionBegin;
218   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
219   if (!rank) {
220     if (!isatty(fileno(PETSC_STDOUT))) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"Requires users input/output");
221     ierr = PetscPrintf(comm,"Cut and paste the following into your browser:\n\n"
222                             "https://accounts.google.com/o/oauth2/auth?"
223                             "scope=https%%3A%%2F%%2Fwww.googleapis.com%%2Fauth%%2Fdrive.file&"
224                             "redirect_uri=urn:ietf:wg:oauth:2.0:oob&"
225                             "response_type=code&"
226                             "client_id="
227                             PETSC_GOOGLE_CLIENT_ID
228                             "\n\n");CHKERRQ(ierr);
229     ierr = PetscPrintf(comm,"Paste the result here:");CHKERRQ(ierr);
230     ptr  = fgets(buff, 1024, stdin);
231     if (!ptr) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Error reading from stdin: %d", errno);
232     ierr = PetscStrlen(buff,&len);CHKERRQ(ierr);
233     buff[len-1] = 0; /* remove carriage return at end of line */
234 
235     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
236     ierr = PetscHTTPSConnect("accounts.google.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
237     ierr = PetscStrcpy(body,"code=");CHKERRQ(ierr);
238     ierr = PetscStrcat(body,buff);CHKERRQ(ierr);
239     ierr = PetscStrcat(body,"&client_id=");CHKERRQ(ierr);
240     ierr = PetscStrcat(body,PETSC_GOOGLE_CLIENT_ID);CHKERRQ(ierr);
241     ierr = PetscStrcat(body,"&client_secret=");CHKERRQ(ierr);
242     ierr = PetscStrcat(body,PETSC_GOOGLE_CLIENT_ST);CHKERRQ(ierr);
243     ierr = PetscStrcat(body,"&redirect_uri=urn:ietf:wg:oauth:2.0:oob&");CHKERRQ(ierr);
244     ierr = PetscStrcat(body,"grant_type=authorization_code");CHKERRQ(ierr);
245 
246     ierr = PetscHTTPSRequest("POST","accounts.google.com/o/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
247     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
248     close(sock);
249 
250     ierr   = PetscPullJSONValue(buff,"access_token",access_token,tokensize,&found);CHKERRQ(ierr);
251     if (!found) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Google drive did not return access_token");
252     ierr   = PetscPullJSONValue(buff,"refresh_token",refresh_token,tokensize,&found);CHKERRQ(ierr);
253     if (!found) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Google drive did not return refresh_token");
254 
255     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);
256     ierr = PetscPrintf(comm,"programs with the option -google_refresh_token %s\n",refresh_token);CHKERRQ(ierr);
257     ierr = PetscPrintf(comm,"to access Google Drive automatically\n");CHKERRQ(ierr);
258   }
259   PetscFunctionReturn(0);
260 }
261 
262 
263 #undef __FUNCT__
264 #define __FUNCT__ "PetscURLShorten"
265 /*@C
266      PetscURLShorten - Uses Google's service to get a short url for a long url
267 
268     Input Parameters:
269 +    url - long URL you want shortened
270 -    lenshorturl - length of buffer to contain short URL
271 
272     Output Parameter:
273 .    shorturl - the shortened URL
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   PetscErrorCode ierr;
283   char           buff[1024],body[512];
284   PetscBool      found;
285 
286   PetscFunctionBegin;
287   ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
288   ierr = PetscHTTPSConnect("www.googleapis.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
289   ierr = PetscStrcpy(body,"{");CHKERRQ(ierr);
290   ierr = PetscPushJSONValue(body,"longUrl",url,sizeof(body)-2);CHKERRQ(ierr);
291   ierr = PetscStrcat(body,"}");CHKERRQ(ierr);
292   ierr = PetscHTTPSRequest("POST","www.googleapis.com/urlshortener/v1/url",NULL,"application/json",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
293   ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
294   close(sock);
295 
296   ierr   = PetscPullJSONValue(buff,"id",shorturl,lenshorturl,&found);CHKERRQ(ierr);
297   if (!found) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Google drive did not return short URL");
298   PetscFunctionReturn(0);
299 }
300 
301