xref: /petsc/src/sys/webclient/google.c (revision 0efc6a0385228cde9a68b4e67359bfe0b0532191)
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 .seealso: PetscURLShorten(), PetscGoogleDriveAuthorize(), PetscGoogleDriveUpload()
32 
33 @*/
34 PetscErrorCode PetscGoogleDriveRefresh(MPI_Comm comm,const char refresh_token[],char access_token[],size_t tokensize)
35 {
36   SSL_CTX        *ctx;
37   SSL            *ssl;
38   int            sock;
39   PetscErrorCode ierr;
40   char           buff[8*1024],body[1024],*access,*ctmp;
41   PetscMPIInt    rank;
42   char           *refreshtoken = (char*)refresh_token;
43 
44   PetscFunctionBegin;
45   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
46   if (!rank) {
47     if (!refresh_token) {
48       PetscBool set;
49       ierr = PetscMalloc1(512,&refreshtoken);CHKERRQ(ierr);
50       ierr = PetscOptionsGetString(NULL,"-refresh_token",refreshtoken,512,&set);CHKERRQ(ierr);
51       if (!set) {
52         ierr = PetscGoogleDriveAuthorize(comm,access_token,refreshtoken,512*sizeof(char));CHKERRQ(ierr);
53         ierr = PetscFree(refreshtoken);CHKERRQ(ierr);
54         PetscFunctionReturn(0);
55       }
56     }
57     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
58     ierr = PetscHTTPSConnect("accounts.google.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
59     ierr = PetscStrcpy(body,"&client_id=");CHKERRQ(ierr);
60     ierr = PetscStrcat(body,PETSC_GOOGLE_CLIENT_ID);CHKERRQ(ierr);
61     ierr = PetscStrcat(body,"&client_secret=");CHKERRQ(ierr);
62     ierr = PetscStrcat(body,PETSC_GOOGLE_CLIENT_ST);CHKERRQ(ierr);
63     ierr = PetscStrcat(body,"&refresh_token=");CHKERRQ(ierr);
64     ierr = PetscStrcat(body,refreshtoken);CHKERRQ(ierr);
65     if (!refresh_token) {ierr = PetscFree(refreshtoken);CHKERRQ(ierr);}
66     ierr = PetscStrcat(body,"&grant_type=refresh_token");CHKERRQ(ierr);
67 
68     ierr = PetscHTTPSRequest("POST","https://accounts.google.com/o/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
69     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
70     close(sock);
71 
72     ierr   = PetscStrstr(buff,"\"access_token\" : \"",&access);CHKERRQ(ierr);
73     if (!access) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Did not receive access token from Google");
74     access += 18;
75     ierr   = PetscStrchr(access,'\"',&ctmp);CHKERRQ(ierr);
76     if (!ctmp) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Access token from Google is misformed");
77     *ctmp  = 0;
78     ierr   = PetscStrncpy(access_token,access,tokensize);CHKERRQ(ierr);
79     *ctmp  = '\"';
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 .  -refresh_token   XXX
100 
101   Usage Patterns:
102     With PETSc option -refresh_token  XXX given
103     PetscGoogleDriveUpload(comm,NULL,filename);        will upload file with no user interaction
104 
105     Without PETSc option -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 -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                          "{"
149                          "\"title\": \"");
150     ierr = PetscStrcat(body,filename);
151     ierr = PetscStrcat(body,"\","
152                          "\"mimeType\": \"text.html\","
153                          "\"description\": \" a file\""
154                          "}\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 != 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","https://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 #undef __FUNCT__
179 #define __FUNCT__ "PetscGoogleDriveAuthorize"
180 /*@C
181      PetscGoogleDriveAuthorize - Get authorization and refresh token for accessing Google drive from PETSc
182 
183    Not collective, only the first process in MPI_Comm does anything
184 
185    Input Parameters:
186 +  comm - the MPI communicator
187 -  tokensize - size of the token arrays
188 
189    Output Parameters:
190 +  access_token - can be used with PetscGoogleDriveUpload() for this one session
191 -  refresh_token - can be used for ever to obtain new access_tokens with PetscGoogleDriveRefresh(), guard this like a password
192                    it gives access to your Google Drive
193 
194    Notes: This call requires stdout and stdin access from process 0 on the MPI communicator
195 
196    You can run src/sys/webclient/examples/tutorials/obtainrefreshtoken to get a refresh token and then in the future pass it to
197    PETSc programs with -refresh_token XXX
198 
199 .seealso: PetscGoogleDriveRefresh(), PetscGoogleDriveUpload(), PetscURLShorten()
200 
201 @*/
202 PetscErrorCode PetscGoogleDriveAuthorize(MPI_Comm comm,char access_token[],char refresh_token[],size_t tokensize)
203 {
204   SSL_CTX        *ctx;
205   SSL            *ssl;
206   int            sock;
207   PetscErrorCode ierr;
208   char           buff[8*1024],*ptr,body[1024],*access,*refresh,*ctmp;
209   PetscMPIInt    rank;
210   size_t         len;
211 
212   PetscFunctionBegin;
213   ierr = PetscPrintf(comm,"Cut and paste the following into your browser:\n"
214                           "https://accounts.google.com/o/oauth2/auth?"
215                           "scope=https%%3A%%2F%%2Fwww.googleapis.com%%2Fauth%%2Fdrive.file&"
216                           "redirect_uri=urn:ietf:wg:oauth:2.0:oob&"
217                           "response_type=code&"
218                           "client_id="
219                           PETSC_GOOGLE_CLIENT_ID
220                           "\n\n");CHKERRQ(ierr);
221   ierr = PetscPrintf(comm,"Paste the result here:");CHKERRQ(ierr);
222   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
223   if (!rank) {
224     ptr  = fgets(buff, 1024, stdin);
225     if (!ptr) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Error reading from stdin: %d", errno);
226     ierr = PetscStrlen(buff,&len);CHKERRQ(ierr);
227     buff[len-1] = 0; /* remove carriage return at end of line */
228 
229     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
230     ierr = PetscHTTPSConnect("accounts.google.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
231     ierr = PetscStrcpy(body,"code=");CHKERRQ(ierr);
232     ierr = PetscStrcat(body,buff);CHKERRQ(ierr);
233     ierr = PetscStrcat(body,"&client_id=");CHKERRQ(ierr);
234     ierr = PetscStrcat(body,PETSC_GOOGLE_CLIENT_ID);CHKERRQ(ierr);
235     ierr = PetscStrcat(body,"&client_secret=");CHKERRQ(ierr);
236     ierr = PetscStrcat(body,PETSC_GOOGLE_CLIENT_ST);CHKERRQ(ierr);
237     ierr = PetscStrcat(body,"&redirect_uri=urn:ietf:wg:oauth:2.0:oob&");CHKERRQ(ierr);
238     ierr = PetscStrcat(body,"grant_type=authorization_code");CHKERRQ(ierr);
239 
240     ierr = PetscHTTPSRequest("POST","https://accounts.google.com/o/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
241     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
242     close(sock);
243 
244     ierr   = PetscStrstr(buff,"\"access_token\" : \"",&access);CHKERRQ(ierr);
245     if (!access) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Did not receive access token from Google");
246     access += 18;
247     ierr   = PetscStrchr(access,'\"',&ctmp);CHKERRQ(ierr);
248     if (!ctmp) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Access token from Google is misformed");
249     *ctmp  = 0;
250     ierr   = PetscStrncpy(access_token,access,tokensize);CHKERRQ(ierr);
251     *ctmp  = '\"';
252 
253     ierr   = PetscStrstr(buff,"\"refresh_token\" : \"",&refresh);CHKERRQ(ierr);
254     if (!refresh) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Did not receive refresh token from Google");
255     refresh += 19;
256     ierr   = PetscStrchr(refresh,'\"',&ctmp);CHKERRQ(ierr);
257     if (!ctmp) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Refresh token from Google is misformed");
258     *ctmp  = 0;
259     ierr = PetscStrncpy(refresh_token,refresh,tokensize);CHKERRQ(ierr);
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 -refresh_token %d\n",refresh);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 .seealso: PetscGoogleDriveRefresh(), PetscGoogleDriveUpload(), PetscGoogleDriveAuthorize()
282 @*/
283 PetscErrorCode PetscURLShorten(const char url[],char shorturl[],size_t lenshorturl)
284 {
285   SSL_CTX        *ctx;
286   SSL            *ssl;
287   int            sock;
288   PetscErrorCode ierr;
289   char           buff[1024],body[512],*sub1,*sub2;
290 
291   PetscFunctionBegin;
292   ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
293   ierr = PetscHTTPSConnect("www.googleapis.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
294   ierr = PetscSNPrintf(body,512,"{\"longUrl\": \"%s\"}",url);CHKERRQ(ierr);
295   ierr = PetscHTTPSRequest("POST","https://www.googleapis.com/urlshortener/v1/url",NULL,"application/json",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
296   ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
297   close(sock);
298   ierr = PetscStrstr(buff,"\"id\": \"",&sub1);CHKERRQ(ierr);
299   if (sub1) {
300     sub1 += 7;
301     ierr = PetscStrstr(sub1,"\"",&sub2);CHKERRQ(ierr);
302     if (!sub2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Google did not shorten URL");
303     sub2[0] = 0;
304     ierr = PetscStrncpy(shorturl,sub1,lenshorturl);CHKERRQ(ierr);
305   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Google did not shorten URL");
306   PetscFunctionReturn(0);
307 }
308 
309