xref: /petsc/src/sys/webclient/box.c (revision 93e1d32f07e6327b6f25825b25eb764760ccd2b6)
1 
2 #include <petscwebclient.h>
3 
4 /*
5    These variables identify the code as a PETSc application to Box.
6 
7    See -   http://stackoverflow.com/questions/4616553/using-oauth-in-free-open-source-software
8    Users can get their own application IDs - goto https://developers.box.com
9 
10 */
11 #define PETSC_BOX_CLIENT_ID  "sse42nygt4zqgrdwi0luv79q1u1f0xza"
12 #define PETSC_BOX_CLIENT_ST  "A0Dy4KgOYLB2JIYZqpbze4EzjeIiX5k4"
13 
14 #include <mongoose.h>
15 
16 static volatile char *result = NULL;
17 
18 /*this is the main handler call. It switched based on what uri is in the request*/
19 static int PetscBoxWebServer_Private(struct mg_connection *conn)
20 {
21   const struct mg_request_info *request_info = mg_get_request_info(conn);
22   printf("Hi %s\n",request_info->uri);
23   printf("Hi %s\n",request_info->query_string);
24   result = (char*) request_info->query_string;
25 return 0;
26 }
27 
28 
29 static PetscErrorCode PetscBoxStartWebServer_Private(void)
30 {
31   PetscErrorCode      ierr;
32   int                 optionsLen = 5;
33   const char          *options[optionsLen];
34   struct mg_callbacks callbacks;
35   struct mg_context   *ctx;
36 
37   PetscFunctionBegin;
38   options[0] = "listening_ports";
39   options[1] = "8081s";
40   options[2] = "ssl_certificate";
41   options[3] = "/Users/barrysmith/Src/saws/saws.pem";
42   options[4] = NULL;
43 
44 
45   /* Prepare callbacks structure. We have only one callback, the rest are NULL. */
46   ierr = PetscMemzero(&callbacks, sizeof(callbacks));CHKERRQ(ierr);
47   callbacks.begin_request = PetscBoxWebServer_Private;
48   ctx = mg_start(&callbacks, NULL, options);
49   if (!ctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Unable to start up webserver");
50   while (!result) {};
51   PetscFunctionReturn(0);
52 }
53 
54 
55 #undef __FUNCT__
56 #define __FUNCT__ "PetscBoxAuthorize"
57 /*@C
58      PetscBoxAuthorize - Get authorization and refresh token for accessing Box drive from PETSc
59 
60    Not collective, only the first process in MPI_Comm does anything
61 
62    Input Parameters:
63 +  comm - the MPI communicator
64 -  tokensize - size of the token arrays
65 
66    Output Parameters:
67 +  access_token - can be used with PetscBoxUpload() for this one session
68 -  refresh_token - can be used for ever to obtain new access_tokens with PetscBoxRefresh(), guard this like a password
69                    it gives access to your Box Drive
70 
71    Notes: This call requires stdout and stdin access from process 0 on the MPI communicator
72 
73    You can run src/sys/webclient/examples/tutorials/obtainrefreshtoken to get a refresh token and then in the future pass it to
74    PETSc programs with -box_refresh_token XXX
75 
76 .seealso: PetscBoxRefresh(), PetscBoxUpload(), PetscURLShorten()
77 
78 @*/
79 PetscErrorCode PetscBoxAuthorize(MPI_Comm comm,char access_token[],char refresh_token[],size_t tokensize)
80 {
81   SSL_CTX        *ctx;
82   SSL            *ssl;
83   int            sock;
84   PetscErrorCode ierr;
85   char           buff[8*1024],body[1024],*access,*refresh,*ctmp;
86   PetscMPIInt    rank;
87   PetscBool      flg;
88 
89   PetscFunctionBegin;
90   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
91   if (!rank) {
92     ierr = PetscPrintf(comm,"Cut and paste the following into your browser:\n\n"
93                             "https://www.box.com/api/oauth2/authorize?"
94                             "response_type=code&"
95                             "client_id="
96                             PETSC_BOX_CLIENT_ID
97                             "&state=PETScState"
98                             "\n\n");CHKERRQ(ierr);
99     ierr = PetscBoxStartWebServer_Private();CHKERRQ(ierr);
100     ierr = PetscStrbeginswith((const char*)result,"state=PETScState&code=",&flg);CHKERRQ(ierr);
101     if (!flg) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Did not get expected string from Box got %s",result);
102     ierr = PetscStrncpy(buff,(const char*)result+22,sizeof(buff));CHKERRQ(ierr);
103 
104     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
105     ierr = PetscHTTPSConnect("www.box.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
106     ierr = PetscStrcpy(body,"code=");CHKERRQ(ierr);
107     ierr = PetscStrcat(body,buff);CHKERRQ(ierr);
108     ierr = PetscStrcat(body,"&client_id=");CHKERRQ(ierr);
109     ierr = PetscStrcat(body,PETSC_BOX_CLIENT_ID);CHKERRQ(ierr);
110     ierr = PetscStrcat(body,"&client_secret=");CHKERRQ(ierr);
111     ierr = PetscStrcat(body,PETSC_BOX_CLIENT_ST);CHKERRQ(ierr);
112     ierr = PetscStrcat(body,"&grant_type=authorization_code");CHKERRQ(ierr);
113 
114     ierr = PetscHTTPSRequest("POST","www.box.com/api/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
115     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
116     close(sock);
117 
118     ierr   = PetscStrstr(buff,"\"access_token\" : \"",&access);CHKERRQ(ierr);
119     if (!access) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Did not receive access token from Box");
120     access += 18;
121     ierr   = PetscStrchr(access,'\"',&ctmp);CHKERRQ(ierr);
122     if (!ctmp) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Access token from Box is misformed");
123     *ctmp  = 0;
124     ierr   = PetscStrncpy(access_token,access,tokensize);CHKERRQ(ierr);
125     *ctmp  = '\"';
126 
127     ierr   = PetscStrstr(buff,"\"refresh_token\" : \"",&refresh);CHKERRQ(ierr);
128     if (!refresh) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Did not receive refresh token from Box");
129     refresh += 19;
130     ierr   = PetscStrchr(refresh,'\"',&ctmp);CHKERRQ(ierr);
131     if (!ctmp) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Refresh token from Box is misformed");
132     *ctmp  = 0;
133     ierr = PetscStrncpy(refresh_token,refresh,tokensize);CHKERRQ(ierr);
134 
135     ierr = PetscPrintf(comm,"Here is your Box refresh token, save it in a save place, in the future you can run PETSc\n");CHKERRQ(ierr);
136     ierr = PetscPrintf(comm,"programs with the option -box_refresh_token %s\n",refresh);CHKERRQ(ierr);
137     ierr = PetscPrintf(comm,"to access Box Drive automatically\n");CHKERRQ(ierr);
138   }
139   PetscFunctionReturn(0);
140 }
141 
142 #undef __FUNCT__
143 #define __FUNCT__ "PetscBoxRefresh"
144 /*@C
145      PetscBoxRefresh - Get a new authorization token for accessing Box drive from PETSc from a refresh token
146 
147    Not collective, only the first process in the MPI_Comm does anything
148 
149    Input Parameters:
150 +   comm - MPI communicator
151 .   refresh token - obtained with PetscBoxAuthorize(), if NULL PETSc will first look for one in the options data
152                     if not found it will call PetscBoxAuthorize()
153 -   tokensize - size of the output string access_token
154 
155    Output Parameter:
156 +   access_token - token that can be passed to PetscBoxUpload()
157 -   new_refresh_token - the old refresh token is no longer valid, not this is different than Google where the same refresh_token is used forever
158 
159 .seealso: PetscURLShorten(), PetscBoxAuthorize(), PetscBoxUpload()
160 
161 @*/
162 PetscErrorCode PetscBoxRefresh(MPI_Comm comm,const char refresh_token[],char access_token[],char new_refresh_token[],size_t tokensize)
163 {
164   SSL_CTX        *ctx;
165   SSL            *ssl;
166   int            sock;
167   PetscErrorCode ierr;
168   char           buff[8*1024],body[1024],*access,*ctmp;
169   PetscMPIInt    rank;
170   char           *refreshtoken = (char*)refresh_token,*refresh;
171 
172   PetscFunctionBegin;
173   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
174   if (!rank) {
175     if (!refresh_token) {
176       PetscBool set;
177       ierr = PetscMalloc1(512,&refreshtoken);CHKERRQ(ierr);
178       ierr = PetscOptionsGetString(NULL,"-box_refresh_token",refreshtoken,512,&set);CHKERRQ(ierr);
179       if (!set) {
180         ierr = PetscBoxAuthorize(comm,access_token,refreshtoken,512*sizeof(char));CHKERRQ(ierr);
181         ierr = PetscFree(refreshtoken);CHKERRQ(ierr);
182         PetscFunctionReturn(0);
183       }
184     }
185     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
186     ierr = PetscHTTPSConnect("www.box.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
187     ierr = PetscStrcpy(body,"client_id=");CHKERRQ(ierr);
188     ierr = PetscStrcat(body,PETSC_BOX_CLIENT_ID);CHKERRQ(ierr);
189     ierr = PetscStrcat(body,"&client_secret=");CHKERRQ(ierr);
190     ierr = PetscStrcat(body,PETSC_BOX_CLIENT_ST);CHKERRQ(ierr);
191     ierr = PetscStrcat(body,"&refresh_token=");CHKERRQ(ierr);
192     ierr = PetscStrcat(body,refreshtoken);CHKERRQ(ierr);
193     if (!refresh_token) {ierr = PetscFree(refreshtoken);CHKERRQ(ierr);}
194     ierr = PetscStrcat(body,"&grant_type=refresh_token");CHKERRQ(ierr);
195 
196     ierr = PetscHTTPSRequest("POST","www.box.com/api/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
197     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
198     close(sock);
199 
200     ierr   = PetscStrstr(buff,"\"access_token\":\"",&access);CHKERRQ(ierr);
201     if (!access) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Did not receive access token from Box");
202     access += 16;
203     ierr   = PetscStrchr(access,'\"',&ctmp);CHKERRQ(ierr);
204     if (!ctmp) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Access token from Box is misformed");
205     *ctmp  = 0;
206     ierr   = PetscStrncpy(access_token,access,tokensize);CHKERRQ(ierr);
207     *ctmp  = '\"';
208 
209     ierr   = PetscStrstr(buff,"\"refresh_token\":\"",&refresh);CHKERRQ(ierr);
210     if (!refresh) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Did not receive refresh token from Box");
211     refresh += 17;
212     ierr   = PetscStrchr(refresh,'\"',&ctmp);CHKERRQ(ierr);
213     if (!ctmp) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Refresh token from Box is misformed");
214     *ctmp  = 0;
215     ierr = PetscStrncpy(new_refresh_token,refresh,tokensize);CHKERRQ(ierr);
216     ierr = PetscPrintf(comm,"Here is your new Box refresh token, save it in a save place, in the future you can run PETSc\n");CHKERRQ(ierr);
217     ierr = PetscPrintf(comm,"programs with the option -box_refresh_token %s\n",refresh);CHKERRQ(ierr);
218     ierr = PetscPrintf(comm,"to access Box Drive automatically\n");CHKERRQ(ierr);
219   }
220   PetscFunctionReturn(0);
221 }
222 
223 #include <sys/stat.h>
224 
225 #undef __FUNCT__
226 #define __FUNCT__ "PetscBoxUpload"
227 /*@C
228      PetscBoxUpload - Loads a file to the Box Drive
229 
230      This routine has not yet been written; it is just copied from Google Drive
231 
232      Not collective, only the first process in the MPI_Comm uploads the file
233 
234   Input Parameters:
235 +   comm - MPI communicator
236 .   access_token - obtained with PetscBoxRefresh(), pass NULL to have PETSc generate one
237 -   filename - file to upload; if you upload multiple times it will have different names each time on Box Drive
238 
239   Options Database:
240 .  -box_refresh_token   XXX
241 
242   Usage Patterns:
243     With PETSc option -box_refresh_token  XXX given
244     PetscBoxUpload(comm,NULL,filename);        will upload file with no user interaction
245 
246     Without PETSc option -box_refresh_token XXX given
247     PetscBoxUpload(comm,NULL,filename);        for first use will prompt user to authorize access to Box Drive with their processor
248 
249     With PETSc option -box_refresh_token  XXX given
250     PetscBoxRefresh(comm,NULL,access_token,sizeof(access_token));
251     PetscBoxUpload(comm,access_token,filename);
252 
253     With refresh token entered in some way by the user
254     PetscBoxRefresh(comm,refresh_token,access_token,sizeof(access_token));
255     PetscBoxUpload(comm,access_token,filename);
256 
257     PetscBoxAuthorize(comm,access_token,refresh_token,sizeof(access_token));
258     PetscBoxUpload(comm,access_token,filename);
259 
260 .seealso: PetscURLShorten(), PetscBoxAuthorize(), PetscBoxRefresh()
261 
262 @*/
263 PetscErrorCode PetscBoxUpload(MPI_Comm comm,const char access_token[],const char filename[])
264 {
265   SSL_CTX        *ctx;
266   SSL            *ssl;
267   int            sock;
268   PetscErrorCode ierr;
269   char           head[1024],buff[8*1024],*body,*title;
270   PetscMPIInt    rank;
271   struct stat    sb;
272   size_t         len,blen,rd;
273   FILE           *fd;
274 
275   PetscFunctionBegin;
276   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
277   if (!rank) {
278     ierr = PetscStrcpy(head,"Authorization: Bearer ");CHKERRQ(ierr);
279     ierr = PetscStrcat(head,access_token);CHKERRQ(ierr);
280     ierr = PetscStrcat(head,"\r\n");CHKERRQ(ierr);
281     ierr = PetscStrcat(head,"uploadType: multipart\r\n");CHKERRQ(ierr);
282 
283     ierr = stat(filename,&sb);
284     if (ierr) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Unable to stat file: %s",filename);
285     len = 1024 + sb.st_size;
286     ierr = PetscMalloc1(len,&body);CHKERRQ(ierr);
287     ierr = PetscStrcpy(body,"--foo_bar_baz\r\n"
288                          "Content-Type: application/json\r\n\r\n"
289                          "{"
290                          "\"title\": \"");
291     ierr = PetscStrcat(body,filename);
292     ierr = PetscStrcat(body,"\","
293                          "\"mimeType\": \"text.html\","
294                          "\"description\": \" a file\""
295                          "}\r\n\r\n"
296                          "--foo_bar_baz\r\n"
297                          "Content-Type: text/html\r\n\r\n");
298     ierr = PetscStrlen(body,&blen);CHKERRQ(ierr);
299     fd = fopen (filename, "r");
300     if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Unable to open file: %s",filename);
301     rd = fread (body+blen, sizeof (unsigned char), sb.st_size, fd);
302     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);
303     fclose(fd);
304     body[blen + rd] = 0;
305     ierr = PetscStrcat(body,"\r\n\r\n"
306                             "--foo_bar_baz\r\n");
307     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
308     ierr = PetscHTTPSConnect("www.boxapis.com",443,ctx,&sock,&ssl);CHKERRQ(ierr);
309     ierr = PetscHTTPSRequest("POST","www.boxapis.com/upload/drive/v2/files/",head,"multipart/related; boundary=\"foo_bar_baz\"",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
310     ierr = PetscFree(body);CHKERRQ(ierr);
311     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
312     close(sock);
313     ierr   = PetscStrstr(buff,"\"title\"",&title);CHKERRQ(ierr);
314     if (!title) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Upload of file %s failed",filename);
315   }
316   PetscFunctionReturn(0);
317 }
318 
319 
320