Skip to content

Commit 0a37639

Browse files
committed
httpc: fix resource leak in httpcInit when svcCreateMemoryBlock fails
1 parent aba23eb commit 0a37639

File tree

1 file changed

+28
-12
lines changed

1 file changed

+28
-12
lines changed

libctru/source/services/httpc.c

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,9 @@ Result httpcInit(u32 sharedmem_size)
3737
{
3838
__httpc_sharedmem_size = sharedmem_size;
3939
__httpc_sharedmem_handle = 0;
40+
__httpc_sharedmem_addr = NULL;
4041

41-
if(__httpc_sharedmem_size)
42+
if (__httpc_sharedmem_size)
4243
{
4344
__httpc_sharedmem_addr = memalign(0x1000, __httpc_sharedmem_size);
4445
if(__httpc_sharedmem_addr==NULL)ret = -1;
@@ -51,18 +52,33 @@ Result httpcInit(u32 sharedmem_size)
5152
}
5253

5354
if (R_SUCCEEDED(ret))ret = HTTPC_Initialize(__httpc_servhandle, __httpc_sharedmem_size, __httpc_sharedmem_handle);
54-
if (R_FAILED(ret)) svcCloseHandle(__httpc_servhandle);
55+
56+
if (R_FAILED(ret))
57+
{
58+
svcCloseHandle(__httpc_servhandle);
59+
__httpc_servhandle = 0;
60+
}
5561
}
56-
if (R_FAILED(ret)) AtomicDecrement(&__httpc_refcount);
5762

58-
if (R_FAILED(ret) && __httpc_sharedmem_handle)
63+
if (R_FAILED(ret))
5964
{
60-
svcCloseHandle(__httpc_sharedmem_handle);
61-
__httpc_sharedmem_handle = 0;
62-
__httpc_sharedmem_size = 0;
65+
AtomicDecrement(&__httpc_refcount);
6366

64-
free(__httpc_sharedmem_addr);
65-
__httpc_sharedmem_addr = NULL;
67+
// Clean up shared memory block handle if it was created
68+
if (__httpc_sharedmem_handle)
69+
{
70+
svcCloseHandle(__httpc_sharedmem_handle);
71+
__httpc_sharedmem_handle = 0;
72+
}
73+
74+
// Always free the allocated buffer if it exists (it is possible that svcCreateMemoryBlock failed)
75+
if (__httpc_sharedmem_addr)
76+
{
77+
free(__httpc_sharedmem_addr);
78+
__httpc_sharedmem_addr = NULL;
79+
}
80+
81+
__httpc_sharedmem_size = 0;
6682
}
6783

6884
return ret;
@@ -98,14 +114,14 @@ Result httpcOpenContext(httpcContext *context, HTTPC_RequestMethod method, const
98114
if(R_FAILED(ret)) {
99115
HTTPC_CloseContext(__httpc_servhandle, context->httphandle);
100116
return ret;
101-
}
117+
}
102118

103119
ret = HTTPC_InitializeConnectionSession(context->servhandle, context->httphandle);
104120
if(R_FAILED(ret)) {
105121
svcCloseHandle(context->servhandle);
106122
HTTPC_CloseContext(__httpc_servhandle, context->httphandle);
107123
return ret;
108-
}
124+
}
109125

110126
if(use_defaultproxy==0)return 0;
111127

@@ -114,7 +130,7 @@ Result httpcOpenContext(httpcContext *context, HTTPC_RequestMethod method, const
114130
svcCloseHandle(context->servhandle);
115131
HTTPC_CloseContext(__httpc_servhandle, context->httphandle);
116132
return ret;
117-
}
133+
}
118134

119135
return 0;
120136
}

0 commit comments

Comments
 (0)