xref: /petsc/src/sys/webclient/google.c (revision f15a11d28b36f01875e426cb22da92fd19b081e4)
1 
2 #include <petscwebclient.h>
3 
4 /*
5    These variables identify the code as a PETSc application to Google.
6 
7    See -   http://stackoverflow.com/questions/4616553/using-oauth-in-free-open-source-software
8    Users can get their own application IDs - https://code.google.com/p/google-apps-manager/wiki/GettingAnOAuthConsoleKey
9 
10 */
11 #define PETSC_GOOGLE_CLIENT_ID  "521429262559-i19i57eek8tnt9ftpp4p91rcl0bo9ag5.apps.googleusercontent.com"
12 #define PETSC_GOOGLE_CLIENT_ST  "vOds_A71I3_S_aHMq_kZAI0t"
13 
14 
15 #undef __FUNCT__
16 #define __FUNCT__ "PetscGoogleDriveRefresh"
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 
35 .seealso: PetscURLShorten(), PetscGoogleDriveAuthorize(), PetscGoogleDriveUpload()
36 
37 @*/
38 PetscErrorCode PetscGoogleDriveRefresh(MPI_Comm comm,const char refresh_token[],char access_token[],size_t tokensize)
39 {
40   SSL_CTX        *ctx;
41   SSL            *ssl;
42   int            sock;
43   PetscErrorCode ierr;
44   char           buff[8*1024],body[1024];
45   PetscMPIInt    rank;
46   char           *refreshtoken = (char*)refresh_token;
47   PetscBool      found;
48 
49   PetscFunctionBegin;
50   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
51   if (!rank) {
52     if (!refresh_token) {
53       PetscBool set;
54       ierr = PetscMalloc1(512,&refreshtoken);CHKERRQ(ierr);
55       ierr = PetscOptionsGetString(NULL,"-google_refresh_token",refreshtoken,512,&set);CHKERRQ(ierr);
56       if (!set) {
57         ierr = PetscGoogleDriveAuthorize(comm,access_token,refreshtoken,512*sizeof(char));CHKERRQ(ierr);
58         ierr = PetscFree(refreshtoken);CHKERRQ(ierr);
59         PetscFunctionReturn(0);
60       }
61     }
62     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
63     ierr = PetscHTTPSConnect("accounts.google.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
64     ierr = PetscStrcpy(body,"client_id=");CHKERRQ(ierr);
65     ierr = PetscStrcat(body,PETSC_GOOGLE_CLIENT_ID);CHKERRQ(ierr);
66     ierr = PetscStrcat(body,"&client_secret=");CHKERRQ(ierr);
67     ierr = PetscStrcat(body,PETSC_GOOGLE_CLIENT_ST);CHKERRQ(ierr);
68     ierr = PetscStrcat(body,"&refresh_token=");CHKERRQ(ierr);
69     ierr = PetscStrcat(body,refreshtoken);CHKERRQ(ierr);
70     if (!refresh_token) {ierr = PetscFree(refreshtoken);CHKERRQ(ierr);}
71     ierr = PetscStrcat(body,"&grant_type=refresh_token");CHKERRQ(ierr);
72 
73     ierr = PetscHTTPSRequest("POST","accounts.google.com/o/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
74     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
75     close(sock);
76 
77     ierr   = PetscPullJSONValue(buff,"access_token",access_token,tokensize,&found);CHKERRQ(ierr);
78     if (!found) SETERRQ(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 #undef __FUNCT__
86 #define __FUNCT__ "PetscGoogleDriveUpload"
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 processor
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 .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   PetscErrorCode ierr;
127   char           head[1024],buff[8*1024],*body,*title;
128   PetscMPIInt    rank;
129   struct stat    sb;
130   size_t         len,blen,rd;
131   FILE           *fd;
132 
133   PetscFunctionBegin;
134   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
135   if (!rank) {
136     ierr = PetscStrcpy(head,"Authorization: Bearer ");CHKERRQ(ierr);
137     ierr = PetscStrcat(head,access_token);CHKERRQ(ierr);
138     ierr = PetscStrcat(head,"\r\n");CHKERRQ(ierr);
139     ierr = PetscStrcat(head,"uploadType: multipart\r\n");CHKERRQ(ierr);
140 
141     ierr = stat(filename,&sb);
142     if (ierr) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Unable to stat file: %s",filename);
143     len = 1024 + sb.st_size;
144     ierr = PetscMalloc1(len,&body);CHKERRQ(ierr);
145     ierr = PetscStrcpy(body,"--foo_bar_baz\r\n"
146                             "Content-Type: application/json\r\n\r\n"
147                             "{");CHKERRQ(ierr);
148     ierr = PetscPushJSONValue(body,"title",filename,len);CHKERRQ(ierr);
149     ierr = PetscStrcat(body,",");CHKERRQ(ierr);
150     ierr = PetscPushJSONValue(body,"mimeType","text.html",len);CHKERRQ(ierr);
151     ierr = PetscStrcat(body,",");CHKERRQ(ierr);
152     ierr = PetscPushJSONValue(body,"description","a file",len);CHKERRQ(ierr);
153     ierr = PetscStrcat(body,"}\r\n\r\n"
154                             "--foo_bar_baz\r\n"
155                             "Content-Type: text/html\r\n\r\n");
156     ierr = PetscStrlen(body,&blen);CHKERRQ(ierr);
157     fd = fopen (filename, "r");
158     if (!fd) SETERRQ1(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     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);
161     fclose(fd);
162     body[blen + rd] = 0;
163     ierr = PetscStrcat(body,"\r\n\r\n"
164                             "--foo_bar_baz\r\n");
165     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
166     ierr = PetscHTTPSConnect("www.googleapis.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
167     ierr = PetscHTTPSRequest("POST","www.googleapis.com/upload/drive/v2/files/",head,"multipart/related; boundary=\"foo_bar_baz\"",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
168     ierr = PetscFree(body);CHKERRQ(ierr);
169     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
170     close(sock);
171     ierr   = PetscStrstr(buff,"\"title\"",&title);CHKERRQ(ierr);
172     if (!title) SETERRQ1(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 #undef __FUNCT__
182 #define __FUNCT__ "PetscGoogleDriveAuthorize"
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: This call requires stdout and stdin access from process 0 on the MPI communicator
198 
199    You can run src/sys/webclient/examples/tutorials/googleobtainrefreshtoken to get a refresh token and then in the future pass it to
200    PETSc programs with -google_refresh_token XXX
201 
202 .seealso: PetscGoogleDriveRefresh(), PetscGoogleDriveUpload(), PetscURLShorten()
203 
204 @*/
205 PetscErrorCode PetscGoogleDriveAuthorize(MPI_Comm comm,char access_token[],char refresh_token[],size_t tokensize)
206 {
207   SSL_CTX        *ctx;
208   SSL            *ssl;
209   int            sock;
210   PetscErrorCode ierr;
211   char           buff[8*1024],*ptr,body[1024];
212   PetscMPIInt    rank;
213   size_t         len;
214   PetscBool      found;
215 
216   PetscFunctionBegin;
217   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
218   if (!rank) {
219     if (!isatty(fileno(PETSC_STDOUT))) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"Requires users input/output");
220     ierr = 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");CHKERRQ(ierr);
228     ierr = PetscPrintf(comm,"Paste the result here:");CHKERRQ(ierr);
229     ptr  = fgets(buff, 1024, stdin);
230     if (!ptr) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Error reading from stdin: %d", errno);
231     ierr = PetscStrlen(buff,&len);CHKERRQ(ierr);
232     buff[len-1] = 0; /* remove carriage return at end of line */
233 
234     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
235     ierr = PetscHTTPSConnect("accounts.google.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
236     ierr = PetscStrcpy(body,"code=");CHKERRQ(ierr);
237     ierr = PetscStrcat(body,buff);CHKERRQ(ierr);
238     ierr = PetscStrcat(body,"&client_id=");CHKERRQ(ierr);
239     ierr = PetscStrcat(body,PETSC_GOOGLE_CLIENT_ID);CHKERRQ(ierr);
240     ierr = PetscStrcat(body,"&client_secret=");CHKERRQ(ierr);
241     ierr = PetscStrcat(body,PETSC_GOOGLE_CLIENT_ST);CHKERRQ(ierr);
242     ierr = PetscStrcat(body,"&redirect_uri=urn:ietf:wg:oauth:2.0:oob&");CHKERRQ(ierr);
243     ierr = PetscStrcat(body,"grant_type=authorization_code");CHKERRQ(ierr);
244 
245     ierr = PetscHTTPSRequest("POST","accounts.google.com/o/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
246     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
247     close(sock);
248 
249     ierr   = PetscPullJSONValue(buff,"access_token",access_token,tokensize,&found);CHKERRQ(ierr);
250     if (!found) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Google drive did not return access_token");
251     ierr   = PetscPullJSONValue(buff,"refresh_token",refresh_token,tokensize,&found);CHKERRQ(ierr);
252     if (!found) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Google drive did not return refresh_token");
253 
254     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);
255     ierr = PetscPrintf(comm,"programs with the option -google_refresh_token %s\n",refresh_token);CHKERRQ(ierr);
256     ierr = PetscPrintf(comm,"to access Google Drive automatically\n");CHKERRQ(ierr);
257   }
258   PetscFunctionReturn(0);
259 }
260 
261 
262 #undef __FUNCT__
263 #define __FUNCT__ "PetscURLShorten"
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 .seealso: PetscGoogleDriveRefresh(), PetscGoogleDriveUpload(), PetscGoogleDriveAuthorize()
275 @*/
276 PetscErrorCode PetscURLShorten(const char url[],char shorturl[],size_t lenshorturl)
277 {
278   SSL_CTX        *ctx;
279   SSL            *ssl;
280   int            sock;
281   PetscErrorCode ierr;
282   char           buff[1024],body[512];
283   PetscBool      found;
284 
285   PetscFunctionBegin;
286   ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
287   ierr = PetscHTTPSConnect("www.googleapis.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
288   ierr = PetscStrcpy(body,"{");CHKERRQ(ierr);
289   ierr = PetscPushJSONValue(body,"longUrl",url,sizeof(body)-2);CHKERRQ(ierr);
290   ierr = PetscStrcat(body,"}");CHKERRQ(ierr);
291   ierr = PetscHTTPSRequest("POST","www.googleapis.com/urlshortener/v1/url",NULL,"application/json",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
292   ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
293   close(sock);
294 
295   ierr   = PetscPullJSONValue(buff,"id",shorturl,lenshorturl,&found);CHKERRQ(ierr);
296   if (!found) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Google drive did not return short URL");
297   PetscFunctionReturn(0);
298 }
299 
300