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