xref: /petsc/src/sys/webclient/google.c (revision 68e695932dc3ba76353bc2baf983104ab033ae17) !
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],*access,*ctmp;
45   PetscMPIInt    rank;
46   char           *refreshtoken = (char*)refresh_token;
47 
48   PetscFunctionBegin;
49   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
50   if (!rank) {
51     if (!refresh_token) {
52       PetscBool set;
53       ierr = PetscMalloc1(512,&refreshtoken);CHKERRQ(ierr);
54       ierr = PetscOptionsGetString(NULL,"-google_refresh_token",refreshtoken,512,&set);CHKERRQ(ierr);
55       if (!set) {
56         ierr = PetscGoogleDriveAuthorize(comm,access_token,refreshtoken,512*sizeof(char));CHKERRQ(ierr);
57         ierr = PetscFree(refreshtoken);CHKERRQ(ierr);
58         PetscFunctionReturn(0);
59       }
60     }
61     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
62     ierr = PetscHTTPSConnect("accounts.google.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
63     ierr = PetscStrcpy(body,"client_id=");CHKERRQ(ierr);
64     ierr = PetscStrcat(body,PETSC_GOOGLE_CLIENT_ID);CHKERRQ(ierr);
65     ierr = PetscStrcat(body,"&client_secret=");CHKERRQ(ierr);
66     ierr = PetscStrcat(body,PETSC_GOOGLE_CLIENT_ST);CHKERRQ(ierr);
67     ierr = PetscStrcat(body,"&refresh_token=");CHKERRQ(ierr);
68     ierr = PetscStrcat(body,refreshtoken);CHKERRQ(ierr);
69     if (!refresh_token) {ierr = PetscFree(refreshtoken);CHKERRQ(ierr);}
70     ierr = PetscStrcat(body,"&grant_type=refresh_token");CHKERRQ(ierr);
71 
72     ierr = PetscHTTPSRequest("POST","accounts.google.com/o/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
73     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
74     close(sock);
75 
76     ierr   = PetscStrstr(buff,"\"access_token\" : \"",&access);CHKERRQ(ierr);
77     if (!access) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Did not receive access token from Google");
78     access += 18;
79     ierr   = PetscStrchr(access,'\"',&ctmp);CHKERRQ(ierr);
80     if (!ctmp) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Access token from Google is misformed");
81     *ctmp  = 0;
82     ierr   = PetscStrncpy(access_token,access,tokensize);CHKERRQ(ierr);
83     *ctmp  = '\"';
84   }
85   PetscFunctionReturn(0);
86 }
87 
88 #include <sys/stat.h>
89 
90 #undef __FUNCT__
91 #define __FUNCT__ "PetscGoogleDriveUpload"
92 /*@C
93      PetscGoogleDriveUpload - Loads a file to the Google Drive
94 
95      Not collective, only the first process in the MPI_Comm uploads the file
96 
97   Input Parameters:
98 +   comm - MPI communicator
99 .   access_token - obtained with PetscGoogleDriveRefresh(), pass NULL to have PETSc generate one
100 -   filename - file to upload; if you upload multiple times it will have different names each time on Google Drive
101 
102   Options Database:
103 .  -google_refresh_token   XXX
104 
105   Usage Patterns:
106     With PETSc option -google_refresh_token  XXX given
107     PetscGoogleDriveUpload(comm,NULL,filename);        will upload file with no user interaction
108 
109     Without PETSc option -google_refresh_token XXX given
110     PetscGoogleDriveUpload(comm,NULL,filename);        for first use will prompt user to authorize access to Google Drive with their processor
111 
112     With PETSc option -google_refresh_token  XXX given
113     PetscGoogleDriveRefresh(comm,NULL,access_token,sizeof(access_token));
114     PetscGoogleDriveUpload(comm,access_token,filename);
115 
116     With refresh token entered in some way by the user
117     PetscGoogleDriveRefresh(comm,refresh_token,access_token,sizeof(access_token));
118     PetscGoogleDriveUpload(comm,access_token,filename);
119 
120     PetscGoogleDriveAuthorize(comm,access_token,refresh_token,sizeof(access_token));
121     PetscGoogleDriveUpload(comm,access_token,filename);
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                          "{"
153                          "\"title\": \"");
154     ierr = PetscStrcat(body,filename);
155     ierr = PetscStrcat(body,"\","
156                          "\"mimeType\": \"text.html\","
157                          "\"description\": \" a file\""
158                          "}\r\n\r\n"
159                          "--foo_bar_baz\r\n"
160                          "Content-Type: text/html\r\n\r\n");
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");
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 .seealso: PetscGoogleDriveRefresh(), PetscGoogleDriveUpload(), PetscURLShorten()
208 
209 @*/
210 PetscErrorCode PetscGoogleDriveAuthorize(MPI_Comm comm,char access_token[],char refresh_token[],size_t tokensize)
211 {
212   SSL_CTX        *ctx;
213   SSL            *ssl;
214   int            sock;
215   PetscErrorCode ierr;
216   char           buff[8*1024],*ptr,body[1024],*access,*refresh,*ctmp;
217   PetscMPIInt    rank;
218   size_t         len;
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   = PetscStrstr(buff,"\"access_token\" : \"",&access);CHKERRQ(ierr);
254     if (!access) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Did not receive access token from Google");
255     access += 18;
256     ierr   = PetscStrchr(access,'\"',&ctmp);CHKERRQ(ierr);
257     if (!ctmp) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Access token from Google is misformed");
258     *ctmp  = 0;
259     ierr   = PetscStrncpy(access_token,access,tokensize);CHKERRQ(ierr);
260     *ctmp  = '\"';
261 
262     ierr   = PetscStrstr(buff,"\"refresh_token\" : \"",&refresh);CHKERRQ(ierr);
263     if (!refresh) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Did not receive refresh token from Google");
264     refresh += 19;
265     ierr   = PetscStrchr(refresh,'\"',&ctmp);CHKERRQ(ierr);
266     if (!ctmp) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Refresh token from Google is misformed");
267     *ctmp  = 0;
268     ierr = PetscStrncpy(refresh_token,refresh,tokensize);CHKERRQ(ierr);
269 
270     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);
271     ierr = PetscPrintf(comm,"programs with the option -google_refresh_token %s\n",refresh);CHKERRQ(ierr);
272     ierr = PetscPrintf(comm,"to access Google Drive automatically\n");CHKERRQ(ierr);
273   }
274   PetscFunctionReturn(0);
275 }
276 
277 
278 #undef __FUNCT__
279 #define __FUNCT__ "PetscURLShorten"
280 /*@C
281      PetscURLShorten - Uses Google's service to get a short url for a long url
282 
283     Input Parameters:
284 +    url - long URL you want shortened
285 -    lenshorturl - length of buffer to contain short URL
286 
287     Output Parameter:
288 .    shorturl - the shortened URL
289 
290 .seealso: PetscGoogleDriveRefresh(), PetscGoogleDriveUpload(), PetscGoogleDriveAuthorize()
291 @*/
292 PetscErrorCode PetscURLShorten(const char url[],char shorturl[],size_t lenshorturl)
293 {
294   SSL_CTX        *ctx;
295   SSL            *ssl;
296   int            sock;
297   PetscErrorCode ierr;
298   char           buff[1024],body[512],*sub1,*sub2;
299 
300   PetscFunctionBegin;
301   ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
302   ierr = PetscHTTPSConnect("www.googleapis.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
303   ierr = PetscSNPrintf(body,512,"{\"longUrl\": \"%s\"}",url);CHKERRQ(ierr);
304   ierr = PetscHTTPSRequest("POST","www.googleapis.com/urlshortener/v1/url",NULL,"application/json",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
305   ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
306   close(sock);
307   ierr = PetscStrstr(buff,"\"id\": \"",&sub1);CHKERRQ(ierr);
308   if (sub1) {
309     sub1 += 7;
310     ierr = PetscStrstr(sub1,"\"",&sub2);CHKERRQ(ierr);
311     if (!sub2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Google did not shorten URL");
312     sub2[0] = 0;
313     ierr = PetscStrncpy(shorturl,sub1,lenshorturl);CHKERRQ(ierr);
314   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Google did not shorten URL");
315   PetscFunctionReturn(0);
316 }
317 
318