xref: /petsc/src/sys/webclient/google.c (revision 93e1d32f07e6327b6f25825b25eb764760ccd2b6)
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 != 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 #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/obtainrefreshtoken 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],*access,*refresh,*ctmp;
213   PetscMPIInt    rank;
214   size_t         len;
215 
216   PetscFunctionBegin;
217   ierr = PetscPrintf(comm,"Cut and paste the following into your browser:\n\n"
218                           "https://accounts.google.com/o/oauth2/auth?"
219                           "scope=https%%3A%%2F%%2Fwww.googleapis.com%%2Fauth%%2Fdrive.file&"
220                           "redirect_uri=urn:ietf:wg:oauth:2.0:oob&"
221                           "response_type=code&"
222                           "client_id="
223                           PETSC_GOOGLE_CLIENT_ID
224                           "\n\n");CHKERRQ(ierr);
225   ierr = PetscPrintf(comm,"Paste the result here:");CHKERRQ(ierr);
226   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
227   if (!rank) {
228     ptr  = fgets(buff, 1024, stdin);
229     if (!ptr) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Error reading from stdin: %d", errno);
230     ierr = PetscStrlen(buff,&len);CHKERRQ(ierr);
231     buff[len-1] = 0; /* remove carriage return at end of line */
232 
233     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
234     ierr = PetscHTTPSConnect("accounts.google.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
235     ierr = PetscStrcpy(body,"code=");CHKERRQ(ierr);
236     ierr = PetscStrcat(body,buff);CHKERRQ(ierr);
237     ierr = PetscStrcat(body,"&client_id=");CHKERRQ(ierr);
238     ierr = PetscStrcat(body,PETSC_GOOGLE_CLIENT_ID);CHKERRQ(ierr);
239     ierr = PetscStrcat(body,"&client_secret=");CHKERRQ(ierr);
240     ierr = PetscStrcat(body,PETSC_GOOGLE_CLIENT_ST);CHKERRQ(ierr);
241     ierr = PetscStrcat(body,"&redirect_uri=urn:ietf:wg:oauth:2.0:oob&");CHKERRQ(ierr);
242     ierr = PetscStrcat(body,"grant_type=authorization_code");CHKERRQ(ierr);
243 
244     ierr = PetscHTTPSRequest("POST","accounts.google.com/o/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
245     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
246     close(sock);
247 
248     ierr   = PetscStrstr(buff,"\"access_token\" : \"",&access);CHKERRQ(ierr);
249     if (!access) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Did not receive access token from Google");
250     access += 18;
251     ierr   = PetscStrchr(access,'\"',&ctmp);CHKERRQ(ierr);
252     if (!ctmp) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Access token from Google is misformed");
253     *ctmp  = 0;
254     ierr   = PetscStrncpy(access_token,access,tokensize);CHKERRQ(ierr);
255     *ctmp  = '\"';
256 
257     ierr   = PetscStrstr(buff,"\"refresh_token\" : \"",&refresh);CHKERRQ(ierr);
258     if (!refresh) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Did not receive refresh token from Google");
259     refresh += 19;
260     ierr   = PetscStrchr(refresh,'\"',&ctmp);CHKERRQ(ierr);
261     if (!ctmp) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Refresh token from Google is misformed");
262     *ctmp  = 0;
263     ierr = PetscStrncpy(refresh_token,refresh,tokensize);CHKERRQ(ierr);
264 
265     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);
266     ierr = PetscPrintf(comm,"programs with the option -google_refresh_token %d\n",refresh);CHKERRQ(ierr);
267     ierr = PetscPrintf(comm,"to access Google Drive automatically\n");CHKERRQ(ierr);
268   }
269   PetscFunctionReturn(0);
270 }
271 
272 
273 #undef __FUNCT__
274 #define __FUNCT__ "PetscURLShorten"
275 /*@C
276      PetscURLShorten - Uses Google's service to get a short url for a long url
277 
278     Input Parameters:
279 +    url - long URL you want shortened
280 -    lenshorturl - length of buffer to contain short URL
281 
282     Output Parameter:
283 .    shorturl - the shortened URL
284 
285 .seealso: PetscGoogleDriveRefresh(), PetscGoogleDriveUpload(), PetscGoogleDriveAuthorize()
286 @*/
287 PetscErrorCode PetscURLShorten(const char url[],char shorturl[],size_t lenshorturl)
288 {
289   SSL_CTX        *ctx;
290   SSL            *ssl;
291   int            sock;
292   PetscErrorCode ierr;
293   char           buff[1024],body[512],*sub1,*sub2;
294 
295   PetscFunctionBegin;
296   ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
297   ierr = PetscHTTPSConnect("www.googleapis.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
298   ierr = PetscSNPrintf(body,512,"{\"longUrl\": \"%s\"}",url);CHKERRQ(ierr);
299   ierr = PetscHTTPSRequest("POST","www.googleapis.com/urlshortener/v1/url",NULL,"application/json",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
300   ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
301   close(sock);
302   ierr = PetscStrstr(buff,"\"id\": \"",&sub1);CHKERRQ(ierr);
303   if (sub1) {
304     sub1 += 7;
305     ierr = PetscStrstr(sub1,"\"",&sub2);CHKERRQ(ierr);
306     if (!sub2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Google did not shorten URL");
307     sub2[0] = 0;
308     ierr = PetscStrncpy(shorturl,sub1,lenshorturl);CHKERRQ(ierr);
309   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Google did not shorten URL");
310   PetscFunctionReturn(0);
311 }
312 
313