@@ -81,8 +81,6 @@ int swConnection_onSendfile(swConnection *conn, swBuffer_trunk *chunk)
81
81
if (task -> offset >= task -> filesize )
82
82
{
83
83
swBuffer_pop_trunk (conn -> out_buffer , chunk );
84
- close (task -> fd );
85
- sw_free (task );
86
84
87
85
#ifdef HAVE_TCP_NOPUSH
88
86
if (conn -> tcp_nopush )
@@ -210,6 +208,14 @@ int swConnection_get_port(swConnection *conn)
210
208
}
211
209
}
212
210
211
+ void swConnection_sendfile_destructor (swBuffer_trunk * chunk )
212
+ {
213
+ swTask_sendfile * task = chunk -> store .ptr ;
214
+ close (task -> fd );
215
+ sw_free (task -> filename );
216
+ sw_free (task );
217
+ }
218
+
213
219
int swConnection_sendfile (swConnection * conn , char * filename )
214
220
{
215
221
if (conn -> out_buffer == NULL )
@@ -221,6 +227,7 @@ int swConnection_sendfile(swConnection *conn, char *filename)
221
227
}
222
228
}
223
229
230
+ swBuffer_trunk error_chunk ;
224
231
swTask_sendfile * task = sw_malloc (sizeof (swTask_sendfile ));
225
232
if (task == NULL )
226
233
{
@@ -238,28 +245,29 @@ int swConnection_sendfile(swConnection *conn, char *filename)
238
245
swSysError ("open(%s) failed." , task -> filename );
239
246
return SW_ERR ;
240
247
}
248
+ task -> fd = file_fd ;
241
249
242
250
struct stat file_stat ;
243
251
if (fstat (file_fd , & file_stat ) < 0 )
244
252
{
245
- free (task -> filename );
246
- free (task );
247
253
swSysError ("fstat(%s) failed." , filename );
254
+ error_chunk .store .ptr = task ;
255
+ swConnection_sendfile_destructor (& error_chunk );
248
256
return SW_ERR ;
249
257
}
258
+ task -> filesize = file_stat .st_size ;
250
259
251
- swBuffer_trunk * trunk = swBuffer_new_trunk (conn -> out_buffer , SW_CHUNK_SENDFILE , 0 );
252
- if (trunk == NULL )
260
+ swBuffer_trunk * chunk = swBuffer_new_trunk (conn -> out_buffer , SW_CHUNK_SENDFILE , 0 );
261
+ if (chunk == NULL )
253
262
{
254
- free (task -> filename );
255
- free (task );
256
263
swWarn ("get out_buffer trunk failed." );
264
+ error_chunk .store .ptr = task ;
265
+ swConnection_sendfile_destructor (& error_chunk );
257
266
return SW_ERR ;
258
267
}
259
268
260
- task -> filesize = file_stat .st_size ;
261
- task -> fd = file_fd ;
262
- trunk -> store .ptr = (void * ) task ;
269
+ chunk -> store .ptr = (void * ) task ;
270
+ chunk -> destroy = swConnection_sendfile_destructor ;
263
271
264
272
return SW_OK ;
265
273
}
0 commit comments